Skip to content

Latest commit

 

History

History
521 lines (428 loc) · 11.3 KB

API_DOCUMENTATION.md

File metadata and controls

521 lines (428 loc) · 11.3 KB

API Documentation - New Endpoints

Overview

This document describes the new file operation and comparison endpoints added to make Grid Transit production-ready.


File Operation Endpoints

1. Set File Status

Endpoint: POST /api/file/status

Changes the status of a file in the system.

Request

{
  "filePath": "src/components/Button.tsx",
  "newStatus": "modified_local"
}

Parameters

  • filePath (string, required): Relative path to the file
  • newStatus (string, required): One of:
    • synced
    • new_local
    • new_remote
    • modified_local
    • modified_remote
    • deleted_local
    • deleted_remote
    • conflict
    • conflict_deleted_remote
    • conflict_deleted_local

Response (Success)

{
  "success": true,
  "message": "File status updated to modified_local"
}

Response (Error)

{
  "error": "Missing filePath or newStatus"
}

Status Code

  • 200 - Status updated successfully
  • 400 - Missing or invalid parameters
  • 500 - Server error

2. Delete File

Endpoint: POST /api/file/delete

Marks a file for deletion or removes it from specified location.

Request

{
  "filePath": "src/old-file.ts",
  "deleteWhat": "both"
}

Parameters

  • filePath (string, required): Relative path to the file
  • deleteWhat (string, required): One of:
    • "both" - Delete from local and remote
    • "local" - Delete from local client only
    • "remote" - Delete from remote server only

Response (Success)

{
  "success": true,
  "message": "File deleted from both"
}

Response (Error)

{
  "error": "Missing filePath or deleteWhat"
}

Status Code

  • 200 - File deleted successfully
  • 400 - Missing or invalid parameters
  • 500 - Server error

3. Rename File

Endpoint: POST /api/file/rename

Renames a file on both local and remote locations.

Request

{
  "oldPath": "src/OldName.tsx",
  "newPath": "src/NewName.tsx"
}

Parameters

  • oldPath (string, required): Current relative path
  • newPath (string, required): New relative path (can include directory changes)

Response (Success)

{
  "success": true,
  "message": "File renamed from src/OldName.tsx to src/NewName.tsx"
}

Response (Error)

{
  "error": "Missing oldPath or newPath"
}

Status Code

  • 200 - File renamed successfully
  • 400 - Missing or invalid parameters
  • 500 - Server error (target exists, permission denied, etc.)

Comparison Endpoints

4. Compare (Modified for Two-Phase Loading)

Endpoint: POST /api/compare

Initiates file comparison with immediate return + background processing.

Request

{
  "profile": {
    "id": "conn-123",
    "name": "Production Server",
    "type": "SFTP",
    "host": "sftp.example.com",
    "port": 22,
    "username": "deploy",
    "password": "secret",
    "authType": "password",
    "localRoot": "local_dir",
    "remoteRoot": "/var/www/html"
  },
  "phase": "auto"
}

Parameters

  • profile (object, required): Connection profile
  • phase (string, optional): "auto" (default) or "immediate" (for polling)

Response (Immediate - Phase 1)

{
  "success": true,
  "localDir": "local_dir",
  "remoteDir": "/var/www/html",
  "isComparing": true,
  "items": [
    {
      "key": "src/main.ts",
      "path": "src/main.ts",
      "status": "synced",
      "suggestedAction": "already_synced",
      "localFile": {
        "path": "src/main.ts",
        "size": 256,
        "mtime": 1704067200000,
        "hash": "abc123def456",
        "type": "file"
      },
      "remoteFile": {
        "path": "src/main.ts",
        "size": 256,
        "mtime": 1704067200000,
        "hash": "abc123def456",
        "type": "file"
      },
      "priority": 1704067200000,
      "isComparingStatus": true
    }
  ]
}

Response Fields

  • success (boolean): Operation success
  • localDir (string): Local directory path
  • remoteDir (string): Remote directory path
  • isComparing (boolean): NEW - Indicates background comparison is running
  • items (array): Array of SyncItem objects

SyncItem Object (Updated)

{
  key: string;                    // Unique identifier
  path: string;                   // Relative file path
  status: string;                 // Current sync status
  suggestedAction: string;        // Recommended action
  localFile?: SyncFile | null;    // Local file info
  remoteFile?: SyncFile | null;   // Remote file info
  priority: number;               // Sort priority
  isComparingStatus?: boolean;    // NEW - Status still being compared
}

Client-Side Behavior

  1. Immediate (< 500ms): Receive file list with isComparing: true
  2. Background: Status comparison runs on server
  3. Polling: Client calls /api/compare-status every 1 second
  4. Update: When comparison complete, receive full results with real statuses

Status Code

  • 200 - Success (may still be comparing in background)
  • 400 - Invalid connection profile
  • 500 - Server error during scanning

5. Get Comparison Status (NEW)

Endpoint: GET /api/compare-status

Polls for completion of background file status comparison.

Request

GET /api/compare-status

No parameters needed.

Response (Comparison Complete)

{
  "success": true,
  "isComparing": false,
  "timestamp": 1704067200000,
  "localDir": "local_dir",
  "remoteDir": "/var/www/html",
  "items": [
    {
      "key": "src/main.ts",
      "path": "src/main.ts",
      "status": "modified_local",
      "suggestedAction": "upload",
      "localFile": { ... },
      "remoteFile": { ... },
      "priority": 1704067200000
    }
  ]
}

Response (Still Comparing)

{
  "success": false,
  "isComparing": true
}

Status Code

  • 200 - Status returned (may still be comparing)

Polling Strategy

// Client code
async function pollComparison() {
  let attempts = 0;
  const interval = setInterval(async () => {
    attempts++;
    const res = await fetch('/api/compare-status');
    const data = await res.json();
    
    if (data.success && !data.isComparing) {
      // Comparison complete
      updateUI(data.items);
      clearInterval(interval);
    } else if (attempts > 30) {
      // Timeout after 30 seconds
      clearInterval(interval);
    }
  }, 1000); // Poll every second
}

Integration Examples

JavaScript/Fetch

Change File Status

async function changeFileStatus(filePath, newStatus) {
  const response = await fetch('/api/file/status', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ filePath, newStatus })
  });
  const data = await response.json();
  if (data.success) {
    console.log('Status updated:', data.message);
  } else {
    console.error('Error:', data.error);
  }
}

// Usage
await changeFileStatus('src/app.tsx', 'synced');

Delete File

async function deleteFile(filePath, deleteWhat) {
  const response = await fetch('/api/file/delete', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ filePath, deleteWhat })
  });
  const data = await response.json();
  return data.success;
}

// Usage
await deleteFile('src/old-file.ts', 'remote');

Run Comparison with Polling

async function compareWithPolling(profile) {
  // Phase 1: Get immediate results
  const compareRes = await fetch('/api/compare', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ profile })
  });
  const data = await compareRes.json();
  
  // Display files immediately
  displayFiles(data.items);
  
  // Phase 2: Poll if still comparing
  if (data.isComparing) {
    let attempts = 0;
    const pollInterval = setInterval(async () => {
      attempts++;
      const statusRes = await fetch('/api/compare-status');
      const statusData = await statusRes.json();
      
      if (statusData.success && !statusData.isComparing) {
        // Update with real statuses
        updateFileStatuses(statusData.items);
        clearInterval(pollInterval);
      } else if (attempts > 30) {
        clearInterval(pollInterval); // Timeout
      }
    }, 1000);
  }
}

Error Handling

Common Errors

400 - Bad Request

{
  "error": "Missing filePath or newStatus"
}

Fix: Ensure all required parameters are provided

404 - File Not Found

{
  "error": "File not found in snapshot"
}

Fix: Path may have changed or file may have been deleted

409 - Conflict

{
  "error": "Target file already exists at new path"
}

Fix: Choose a different name or location

500 - Server Error

{
  "error": "Failed to update status: Permission denied"
}

Fix: Check file permissions, retry operation


Rate Limiting

Currently, no rate limiting is implemented. Recommended:

  • Limit polling to 1 second intervals
  • Maximum 30 polling attempts (30 seconds timeout)
  • Batch file operations when possible

Security Considerations

While Implementing

  1. Validate paths - Ensure paths don't escape working directories
  2. Check permissions - Verify user has access to target locations
  3. Sanitize input - Remove special characters from file operations
  4. Log operations - Track all file mutations for audit trail
  5. CSRF protection - Implement if needed for production

Request/Response

  • All credentials handled securely in connection profile
  • File operations logged to history
  • No sensitive data in responses

Backward Compatibility

✅ Fully Compatible

  • Existing /api/compare calls still work
  • Old clients ignore isComparing and isComparingStatus fields
  • New fields are optional and don't break parsing

Version History

v2.0 (Current)

  • Added two-phase comparison with background processing
  • Added file operation endpoints (status, delete, rename)
  • Added polling endpoint for completion tracking
  • Enhanced SyncItem interface with metadata flag

v1.0 (Previous)

  • Original single-phase comparison
  • Limited file operations
  • File must wait for full comparison

Future Enhancements

Potential additions for v3.0:

  • WebSocket support for real-time status updates
  • Batch operations endpoint
  • File preview endpoint
  • Advanced filtering API
  • Sync scheduling API
  • Webhook support for external integrations

Testing the API

Using cURL

# Check file status
curl -X POST http://localhost:3000/api/file/status \
  -H "Content-Type: application/json" \
  -d '{"filePath":"src/main.ts","newStatus":"synced"}'

# Delete file
curl -X POST http://localhost:3000/api/file/delete \
  -H "Content-Type: application/json" \
  -d '{"filePath":"src/old.ts","deleteWhat":"both"}'

# Poll comparison status  
curl http://localhost:3000/api/compare-status

Using Postman

  1. Create POST request to http://localhost:3000/api/file/status
  2. Headers: Content-Type: application/json
  3. Body (JSON):
    {
      "filePath": "src/main.ts",
      "newStatus": "modified_local"
    }
  4. Send and check response

Support & Questions

For API questions, refer to:

  1. Implementation: src/server/api-router.ts
  2. Types: src/server/api-router.ts (SyncItem interface)
  3. Client usage: src/stores/sync-store.ts