Check Background Jobs

Monitor the status of asynchronous operations such as role assignments, knowledge deletion, and bulk operations.

Endpoint

POST /v1/workspaces/{workspaceId}/background-jobs

Authentication

Requires API key authentication with a valid access token.

Request

curl -X POST \
  'https://api.sharely.ai/v1/workspaces/{workspaceId}/background-jobs' \
  -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
  -H 'Content-Type: application/json' \
  -H 'organizationid: your-organization-id' \
  -d '{
    "jobIds": ["job-uuid-1", "job-uuid-2"]
  }'

Path Parameters

ParameterTypeRequiredDescription
workspaceIdstring (UUID)YesThe unique identifier of the workspace

Headers

HeaderTypeRequiredDescription
AuthorizationstringYesBearer token with access token
organizationidstring (UUID)YesYour organization ID
Content-TypestringYesMust be application/json

Body Parameters

ParameterTypeRequiredDescription
jobIdsarray of stringsYesArray of background job UUIDs to check

Response

Success Response (200 OK)

{
  "jobs": [
    {
      "id": "job-uuid-1",
      "status": "COMPLETED",
      "type": "ROLE_ASSIGNMENT",
      "createdAt": "2024-11-14T15:30:00Z",
      "completedAt": "2024-11-14T15:30:05Z",
      "result": {
        "assignedCount": 150,
        "knowledgeId": "knowledge-uuid"
      }
    },
    {
      "id": "job-uuid-2",
      "status": "RUNNING",
      "type": "ROLE_DELETION",
      "createdAt": "2024-11-14T15:31:00Z",
      "progress": 65
    },
    {
      "id": "job-uuid-3",
      "status": "FAILED",
      "type": "KNOWLEDGE_UPLOAD",
      "createdAt": "2024-11-14T15:29:00Z",
      "failedAt": "2024-11-14T15:29:10Z",
      "error": {
        "code": "PROCESSING_ERROR",
        "message": "Failed to extract text from PDF"
      }
    }
  ]
}

Response Fields

FieldTypeDescription
jobsarrayArray of job status objects
jobs[].idstring (UUID)Job unique identifier
jobs[].statusstringJob status: RUNNING, COMPLETED, FAILED, CANCELLED
jobs[].typestringType of operation (e.g., ROLE_ASSIGNMENT, ROLE_DELETION)
jobs[].createdAtstring (ISO 8601)Job creation timestamp
jobs[].completedAtstring (ISO 8601)Job completion timestamp (if completed)
jobs[].failedAtstring (ISO 8601)Job failure timestamp (if failed)
jobs[].progressnumberCompletion percentage (0-100) for running jobs
jobs[].resultobjectResult data for completed jobs
jobs[].errorobjectError details for failed jobs

Job Statuses

RUNNING

The job is currently being processed. Check the progress field for completion percentage.

COMPLETED

The job finished successfully. The result field contains operation details.

FAILED

The job encountered an error. The error field contains failure details.

CANCELLED

The job was cancelled before completion.

Common Job Types

TypeDescriptionTypical Duration
ROLE_ASSIGNMENTAssigning roles to knowledge items2-10 seconds
ROLE_UNASSIGNMENTRemoving role assignments2-10 seconds
ROLE_DELETIONDeleting a role and its relationships5-30 seconds
KNOWLEDGE_UPLOADProcessing uploaded files10-60 seconds
KNOWLEDGE_DELETIONDeleting knowledge with children2-15 seconds

Example Usage

Node.js - Polling Pattern

const fetch = require('node-fetch');
 
async function waitForJobs(workspaceId, jobIds, accessToken, organizationId) {
  const maxAttempts = 30;
  const pollInterval = 2000; // 2 seconds
 
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    const response = await fetch(
      `https://api.sharely.ai/v1/workspaces/${workspaceId}/background-jobs`,
      {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${accessToken}`,
          'Content-Type': 'application/json',
          'organizationid': organizationId
        },
        body: JSON.stringify({ jobIds })
      }
    );
 
    const data = await response.json();
 
    // Check if all jobs are done
    const allDone = data.jobs.every(job =>
      ['COMPLETED', 'FAILED', 'CANCELLED'].includes(job.status)
    );
 
    if (allDone) {
      return data.jobs;
    }
 
    // Wait before next poll
    await new Promise(resolve => setTimeout(resolve, pollInterval));
  }
 
  throw new Error('Jobs did not complete within timeout');
}

Python - With Exponential Backoff

import requests
import time
 
def check_background_jobs(workspace_id, job_ids, access_token, organization_id):
    max_attempts = 30
    base_interval = 1  # Start with 1 second
 
    for attempt in range(max_attempts):
        response = requests.post(
            f'https://api.sharely.ai/v1/workspaces/{workspace_id}/background-jobs',
            headers={
                'Authorization': f'Bearer {access_token}',
                'Content-Type': 'application/json',
                'organizationid': organization_id
            },
            json={'jobIds': job_ids}
        )
 
        response.raise_for_status()
        data = response.json()
 
        # Check if all jobs are complete
        all_done = all(
            job['status'] in ['COMPLETED', 'FAILED', 'CANCELLED']
            for job in data['jobs']
        )
 
        if all_done:
            return data['jobs']
 
        # Exponential backoff
        wait_time = min(base_interval * (2 ** attempt), 30)
        time.sleep(wait_time)
 
    raise TimeoutError('Jobs did not complete within timeout')

Best Practices

  1. Poll Interval: Start with 1-2 second intervals, increase with exponential backoff
  2. Timeout: Set a reasonable timeout (30-60 seconds for most operations)
  3. Batch Checking: Check multiple job IDs in a single request
  4. Error Handling: Always handle FAILED status and inspect error details
  5. Result Validation: Verify the result field matches expected outcomes

Related Endpoints