/raida-folders

POST ASYNC

Performs file and directory operations on the RAIDA's distributed filesystem.

POST /api/v1/raida-folders
Alias: /manage-raida-filesystem

Description

This endpoint acts as a general-purpose command dispatcher for the RAIDA's distributed filesystem. Despite the name, it handles operations for both files and directories, including listing contents, creating directories, removing items, and uploading or downloading file data.

Asynchronous Operation

All commands are asynchronous. They return a task ID immediately, and the final result must be retrieved by polling the /tasks/{id} endpoint.


Request Body

ParameterTypeRequiredDescription
commandstringYesThe command to execute: "ls", "mkdir", "rm", "upload", "download".
pathstringYesThe full path on the RAIDA filesystem to target (e.g., "/usr/myname/file.txt").
datastringFor uploadBase64-encoded string of the file content. Required only for the "upload" command.

Response (in completed task `data`)

The response in the completed task's `data` field depends on the command that was executed.

Response for `ls`

pathstring
The directory path that was listed.
itemsarray
A list of file and directory objects.

Each object in the `items` array contains `name` (string), `size` (integer), and `type` ("file" or "directory").

Response for `download`

datastring
The base64-encoded content of the downloaded file.

Response for `mkdir`, `rm`, `upload`

A successful task will contain a simple confirmation object in its `data` field, such as {"status": "success"}, or it may be empty.


Examples

JavaScript: Manage RAIDA Filesystem

const apiHost = 'http://localhost:8006';

// Generic function to poll any task
async function pollTask(taskId, command) {
    const taskResponse = await fetch(`${apiHost}/api/v1/tasks/${taskId}`);
    const taskData = await taskResponse.json();
    const task = taskData.payload;

    console.log(`[${command}] Task ${taskId} progress: ${task.progress}% - ${task.message}`);

    if (task.status === 'completed') {
        console.log(`[${command}] Task finished successfully!`, task.data);
        return true; // Stop polling
    } else if (task.status === 'error') {
        console.error(`[${command}] Task failed:`, task.message);
        return true; // Stop polling
    }
    return false; // Continue polling
}

async function raidaFsCommand(payload) {
    try {
        const response = await fetch(`${apiHost}/api/v1/raida-folders`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });
        const taskInfo = await response.json();
        const taskId = taskInfo.payload.id;
        console.log(`[${payload.command}] Task created with ID: ${taskId}`);

        const pollInterval = setInterval(async () => {
            const isDone = await pollTask(taskId, payload.command);
            if (isDone) clearInterval(pollInterval);
        }, 2000); 
    } catch (error) {
        console.error(`Failed to start ${payload.command} task:`, error);
    }
}

// Example Usage:
// raidaFsCommand({ command: "ls", path: "/usr/myname/" });
// raidaFsCommand({ command: "upload", path: "/usr/myname/hello.txt", data: btoa("Hello RAIDA World") });
// raidaFsCommand({ command: "download", path: "/usr/myname/hello.txt" });

cURL: List Directory (ls)

# Step 1: Initiate the ls task
TASK_ID=$(curl -s -X POST "http://localhost:8006/api/v1/raida-folders" \
-H "Content-Type: application/json" \
-d '{"command":"ls", "path":"/usr/myname/"}' | jq -r '.payload.id')
echo "ls task started with ID: $TASK_ID"

# Step 2: Poll the task endpoint
while true; do
  RESPONSE=$(curl -s "http://localhost:8006/api/v1/tasks/$TASK_ID")
  STATUS=$(echo $RESPONSE | jq -r '.payload.status')
  echo "Polling task.. Status: $STATUS"; if [[ "$STATUS" == "completed" ]] || [[ "$STATUS" == "error" ]]; then
    echo "Final Response:"; echo $RESPONSE | jq; break
  fi; sleep 2
done

cURL: Upload File (upload)

# Step 1: Initiate the upload task
# Note: Base64 encode your file data. Here, "Hello" is encoded to "SGVsbG8="
TASK_ID=$(curl -s -X POST "http://localhost:8006/api/v1/raida-folders" \
-H "Content-Type: application/json" \
-d '{"command":"upload", "path":"/usr/myname/new.txt", "data":"SGVsbG8="}' | jq -r '.payload.id')
echo "upload task started with ID: $TASK_ID"

# Step 2: Poll the task endpoint
while true; do
  RESPONSE=$(curl -s "http://localhost:8006/api/v1/tasks/$TASK_ID")
  STATUS=$(echo $RESPONSE | jq -r '.payload.status')
  echo "Polling task.. Status: $STATUS"; if [[ "$STATUS" == "completed" ]] || [[ "$STATUS" == "error" ]]; then
    echo "Final Response:"; echo $RESPONSE | jq; break
  fi; sleep 2
done

Go: Manage RAIDA Filesystem

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"
)

const apiHost = "http://localhost:8006/api/v1"

// Type for the request
type RaidaFsRequest struct {
	Command string `json:"command"`
	Path    string `json:"path"`
    Data    string `json:"data,omitempty"`
}

// Type for the task response
type TaskResponse struct {
	Payload struct {
		ID       string      `json:"id"`
		Status   string      `json:"status"`
		Progress int         `json:"progress"`
		Message  string      `json:"message"`
		Data     interface{} `json:"data"`
	} `json:"payload"`
}

// pollTask polls a task until it is complete or fails.
func pollTask(taskId, command string) {
	for {
		resp, err := http.Get(fmt.Sprintf("%s/tasks/%s", apiHost, taskId))
		if err != nil {
			log.Printf("Error polling task: %v\n", err)
			return
		}
		var taskResp TaskResponse
		json.NewDecoder(resp.Body).Decode(&taskResp)
		resp.Body.Close()

		fmt.Printf("[%s] Polling... Status: %s\n", command, taskResp.Payload.Status)

		if taskResp.Payload.Status == "completed" {
			fmt.Printf("[%s] Task completed. Result: %+v\n", command, taskResp.Payload.Data)
			return
		} else if taskResp.Payload.Status == "error" {
			fmt.Printf("[%s] Task failed: %s\n", command, taskResp.Payload.Message)
			return
		}
		time.Sleep(2 * time.Second)
	}
}

// raidaFsCommand initiates a filesystem operation and polls for the result.
func raidaFsCommand(payload RaidaFsRequest) {
	requestBody, _ := json.Marshal(payload)

	resp, err := http.Post(fmt.Sprintf("%s/raida-folders", apiHost), "application/json", bytes.NewBuffer(requestBody))
	if err != nil {
		log.Fatalf("Failed to start %s task: %v", payload.Command, err)
	}
	defer resp.Body.Close()

	var taskResp TaskResponse
	json.NewDecoder(resp.Body).Decode(&taskResp)

	fmt.Printf("[%s] Task created with ID: %s\n", payload.Command, taskResp.Payload.ID)
	pollTask(taskResp.Payload.ID, payload.Command)
}

func main() {
    // Example 1: List a directory
	raidaFsCommand(RaidaFsRequest{Command: "ls", Path: "/usr/myname/"})
    
    // Example 2: Upload a file (data must be base64 encoded)
    // raidaFsCommand(RaidaFsRequest{Command: "upload", Path: "/usr/myname/hello.txt", Data: "SGVsbG8gR28h"})
}