XYLEX Group

Activities

Defining business logic with Activities

Activities

Activities encapsulate business logic with automatic retry, exponential backoff, timeout handling, and heartbeat monitoring.

Defining Activities

import { activity } from 'worlds-engine';

const myActivity = activity('my-activity', async (ctx, input) => {
  // Business logic here
  return { result: 'success' };
});

Configuration

Activities can be configured globally or per-workflow execution.

const myActivity = activity('name', handler, {
  retry: {
    maxAttempts: 5,
    backoff: 'exponential',
    initialInterval: 1000,
    maxInterval: 30000,
    multiplier: 2
  },
  timeout: '5m',
  heartbeatTimeout: '30s',
  taskQueue: 'default'
});

Activity Context

The context object passed to the handler provides utilities for the running activity.

Heartbeats

Signal liveness for long-running operations:

const processFile = activity('process-file', async (ctx, file) => {
  const lines = file.split('\n');
  for (let i = 0; i < lines.length; i++) {
    processLine(lines[i]);
    
    // Send heartbeat every 100 lines
    if (i % 100 === 0) {
      ctx.heartbeat(`Processed ${i}/${lines.length} lines`);
    }
  }
});

Cancellation

Check if the activity has been cancelled:

const longTask = activity('long-task', async (ctx, input) => {
  while (shouldContinue()) {
    if (ctx.isCancelled()) {
      // Clean up resources
      await cleanup();
      return;
    }
    
    await doWork();
  }
});

Metadata

Access activity metadata:

console.log(ctx.activityId);   // Unique ID
console.log(ctx.workflowId);   // Parent workflow ID
console.log(ctx.attempt);      // Current retry attempt (1-based)

Best Practices

  1. Idempotency: Activities may be retried. Ensure they are safe to run multiple times.
  2. Heartbeats: Use heartbeats for any operation longer than the heartbeat timeout (default 30s).
  3. Input/Output: Keep inputs and outputs serializable (JSON) and reasonably sized.
  4. Timeouts: Set appropriate timeouts to prevent stuck activities.