### Task Routing Examples in TypeScript Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Demonstrates task routing mechanisms where workers can be assigned to specific queues for specialized processing, or left unassigned to handle tasks from any queue. This ensures efficient task distribution based on worker specialization. ```typescript const worker = new Worker('critical-queue') ``` ```typescript const task = await getTask('critical-queue') ``` ```typescript const worker = new Worker() ``` -------------------------------- ### Metrics Collector Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Details on the metrics collector for tracking counts and rates with rolling windows. ```APIDOC ## Metrics Collector ### Description Tracks workflow and activity counts and rates using rolling windows. ### Counters - **workflowsQueued**: number - **workflowsRunning**: number - **workflowsCompleted**: number - **workflowsFailed**: number - **activitiesCompleted**: number - **activitiesFailed**: number ### Recording Methods - **recordWorkflowQueued()**: void - **recordWorkflowStarted()**: void - **recordWorkflowCompleted()**: void - **recordWorkflowFailed()**: void - **recordActivityCompleted()**: void - **recordActivityFailed()**: void ### Metrics Calculation The `getMetrics` method calculates various metrics including uptime, throughput (per minute and per hour), and workload. ```typescript getMetrics(workerStats): WorldMetrics { const now = Date.now(); const uptime = now - this.startTime; this.cleanOldMetrics(); const recentCompletions = this.workflowCompletions.length; const perMinute = recentCompletions; const perHour = (recentCompletions / this.windowSize) * 3600000; const workload = workerStats.total > 0 ? workerStats.busy / workerStats.total : 0; return { uptime, workers, workflows, throughput, workload }; } ``` ### Cleanup Old Metrics The `cleanOldMetrics` method removes metrics older than the defined `windowSize` (defaulting to 60000ms or 1 minute). ``` -------------------------------- ### Schedule Management API Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md APIs for creating, pausing, resuming, and deleting recurring and one-time schedules. ```APIDOC ## POST /schedule ### Description Creates a recurring schedule for a workflow. ### Method POST ### Endpoint /schedule ### Parameters #### Path Parameters - **id** (string) - Required - Unique identifier for the schedule. - **workflowName** (string) - Required - The name of the workflow to schedule. - **input** (any | () => any) - Required - The input data for the workflow, can be a value or a function that returns a value. - **cronExpression** (string) - Required - The cron expression defining the schedule's recurrence. ### Request Example ```json { "id": "schedule-123", "workflowName": "my-workflow", "input": { "data": "value" }, "cronExpression": "0 0 * * *" } ``` ### Response #### Success Response (200) - **void** - Indicates the schedule was created successfully. ## POST /scheduleOnce ### Description Creates a one-time schedule for a workflow to execute at a specific time. ### Method POST ### Endpoint /scheduleOnce ### Parameters #### Path Parameters - **workflowName** (string) - Required - The name of the workflow to schedule. - **input** (any) - Required - The input data for the workflow. - **executeAt** (number) - Required - Unix timestamp in milliseconds when the workflow should execute. ### Request Example ```json { "workflowName": "one-time-workflow", "input": { "data": "specific" }, "executeAt": 1678886400000 } ``` ### Response #### Success Response (200) - **string** - The ID of the one-time schedule. ## POST /pause ### Description Pauses a previously created schedule. ### Method POST ### Endpoint /pause ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the schedule to pause. ### Response #### Success Response (200) - **void** - Indicates the schedule was paused successfully. ## POST /resume ### Description Resumes a paused schedule. ### Method POST ### Endpoint /resume ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the schedule to resume. ### Response #### Success Response (200) - **void** - Indicates the schedule was resumed successfully. ## DELETE /delete ### Description Deletes a schedule. ### Method DELETE ### Endpoint /delete ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the schedule to delete. ### Response #### Success Response (200) - **void** - Indicates the schedule was deleted successfully. ``` -------------------------------- ### Logger Implementation Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Details on the logger system, including writing logs, log entry format, and level filtering. ```APIDOC ## Logger System ### Description Implements a logger that writes to console and file with support for level filtering. ### Log Methods - **debug**(category: string, message: string, metadata?: object): void - **info**(category: string, message: string, metadata?: object): void - **warn**(category: string, message: string, metadata?: object): void - **error**(category: string, message: string, metadata?: object): void ### Log Entry Format ```json { "timestamp": 1234567890, "level": "info", "category": "workflow", "message": "workflow started", "metadata": { "workflowId": "wf-123" } } ``` ### File Format Newline delimited JSON. ### Flush Mechanism - Entries are queued in an in-memory array. - Flushed every 2 seconds via an interval timer. - Batched writes to a file using `appendFile`. - Console output is immediate. ### Level Filtering Logs are filtered based on a `minLevel` configuration using the following order: ```typescript const levelOrder = { debug: 0, info: 1, warn: 2, error: 3 }; if (levelOrder[level] < levelOrder[minLevel]) return; ``` ``` -------------------------------- ### Running the Example Project Source: https://github.com/xylex-group/worlds-engine/blob/main/examples/retry-patterns/README.md Provides the necessary npm commands to install dependencies and run the retry patterns example project. Assumes Node.js and npm are installed. ```bash npm install npm start ``` -------------------------------- ### Heartbeat Monitor Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Information on the heartbeat monitor for tracking liveness through periodic signals. ```APIDOC ## Heartbeat Monitor ### Description Monitors the liveness of entities by tracking periodic heartbeat signals. ### Heartbeat Entry ```json { "id": "string", "lastBeat": 1234567890, "message": "optional string" } ``` ### Operations - **beat(id: string, message?: string): void**: Records or updates a heartbeat for a given ID. - **check(id: string): boolean**: Returns `true` if the entity with the given ID is considered alive (heartbeat within the timeout period), `false` otherwise. - **findDead(): string[]**: Returns an array of IDs for entities that have missed their heartbeat within the timeout period. ``` -------------------------------- ### Install Worlds Engine using npm Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md This command installs the worlds-engine package using npm. It requires Node.js version 18 or higher and automatically installs dependencies like blessed, chalk, cron-parser, and uuid. ```bash npm install worlds-engine ``` -------------------------------- ### Time Skipper Installation and Advancement (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md A class that allows for manual control over JavaScript's Date.now and setTimeout functions. It intercepts these calls to simulate time passage and execute timers accurately. ```typescript class TimeSkipper { private currentTime: number private timers: Timer[] = [] install(): void { Date.now = () => this.currentTime global.setTimeout = (cb delay) => { const id = this.nextId++ this.timers.push({ id cb executeAt: this.currentTime + delay }) return id } } advance(ms: number): void { const target = this.currentTime + ms while (this.currentTime < target) { const next = this.timers .filter(t => t.executeAt <= target) .sort((a b) => a.executeAt - b.executeAt)[0] if (!next) { this.currentTime = target break } this.currentTime = next.executeAt next.cb() if (next.interval) { next.executeAt = this.currentTime + next.interval } else { this.timers = this.timers.filter(t => t.id !== next.id) } } } } ``` -------------------------------- ### Test Harness Creation (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Creates a test harness for the Worlds Engine, including a memory-based world instance and time control utilities. It allows for advancing time and running workflows. ```typescript function createTestHarness(config?: TestHarnessConfig): TestHarness { const world = new World({ persistence: 'memory' minWorkers: 1 maxWorkers: 1 }) let currentTime = config?.initialTime || Date.now() return { world currentTime async advance(ms: number): Promise async advanceTo(timestamp: number): Promise async runUntilComplete(workflowId: string timeout?: number): Promise } } ``` -------------------------------- ### Example World Initialization - TypeScript Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/api-reference.md Demonstrates initializing a World instance with specific configurations for worker management, persistence, and failure handling, then registering workflows and starting the engine. ```typescript const world = new World({ minWorkers: 2, maxWorkers: 10, scaleThreshold: 0.7, persistence: 'hybrid', persistencePath: '.worlds-engine', failureStrategy: 'retry' }); world.register(orderWorkflow, chargePayment, refundPayment); await world.start(); const handle = await world.execute('process-order', order, { workflowId: `order-${order.id}` }); ``` -------------------------------- ### Configure and Run a Workflow in Worlds-Engine Source: https://context7.com/xylex-group/worlds-engine/llms.txt This snippet demonstrates the core setup and execution of a workflow using worlds-engine. It includes configuring the World with parameters like worker counts and persistence, defining an activity and a workflow, registering them, starting the world, executing a workflow, and retrieving its result. Dependencies include 'worlds-engine'. Inputs are configuration options and workflow parameters. Outputs include workflow execution results. Limitations: Assumes a local setup for persistence and execution. ```typescript import { World, workflow, activity } from 'worlds-engine' const world = new World({ minWorkers: 2, maxWorkers: 10, scaleThreshold: 0.7, scaleDownThreshold: 0.3, persistence: 'hybrid', persistencePath: '.worlds-engine', failureStrategy: 'compensate', heartbeatInterval: 5000, heartbeatTimeout: 30000 }) const greetActivity = activity('greet', async (ctx, { name }) => { ctx.heartbeat('processing greeting') return { message: `Hello, ${name}!`, greeted: true } }, { retry: { maxAttempts: 3, backoff: 'exponential', initialInterval: 1000 } }) const greetWorkflow = workflow('greet-workflow', async (ctx, { name }) => { const result = await ctx.run(greetActivity, { name }) return { success: true, ...result } }) world.register(greetWorkflow, greetActivity) await world.start() const handle = await world.execute('greet-workflow', { name: 'Alice' }) const result = await handle.result() console.log(result) // { success: true, message: 'Hello, Alice!', greeted: true } await world.shutdown() ``` -------------------------------- ### Example Workflow Creation - TypeScript Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/api-reference.md An example demonstrating how to create a workflow named 'process-order'. It includes a handler that runs a 'chargePayment' activity and adds a compensation for 'refundPayment'. ```typescript const orderWorkflow = workflow('process-order', async (ctx, order) => { const payment = await ctx.run(chargePayment, order); ctx.addCompensation(() => ctx.run(refundPayment, payment)); return { orderId: order.id, status: 'completed' }; }, { failureStrategy: 'compensate', timeout: 60000 }); ``` -------------------------------- ### Example Activity Creation - TypeScript Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/api-reference.md An example demonstrating the creation of a 'send-email' activity. It includes heartbeat calls for progress reporting and retry and timeout configurations. ```typescript const sendEmail = activity('send-email', async (ctx, email) => { ctx.heartbeat('connecting to smtp'); await smtp.connect(); ctx.heartbeat('sending email'); await smtp.send(email); return { messageId: '123', success: true }; }, { retry: { maxAttempts: 3, backoff: 'exponential', initialInterval: 1000, maxInterval: 30000 }, timeout: 60000, heartbeatTimeout: 10000 }); ``` -------------------------------- ### Basic Workflow Execution Example Source: https://github.com/xylex-group/worlds-engine/blob/main/README.md Demonstrates the basic execution of a workflow. It involves defining an activity, defining a workflow that uses the activity, registering them with a World instance, starting the world, executing the workflow, and retrieving its result. ```typescript import { World workflow activity } from 'worlds-engine' const myActivity = activity('name' async (ctx input) => { return { result: input.value * 2 } }) const myWorkflow = workflow('name' async (ctx input) => { const result = await ctx.run(myActivity input) return result }) const world = new World() world.register(myWorkflow myActivity) await world.start() const handle = await world.execute('name' { value: 5 }) const result = await handle.result() ``` -------------------------------- ### Logger Implementation: File Format Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Specifies that log entries are written to files in a newline-delimited JSON format. Each line in the log file represents a single, complete log entry. ```json {"timestamp":1234567890,"level":"info","category":"workflow","message":"started"} {"timestamp":1234567891,"level":"error","category":"activity","message":"failed"} ``` -------------------------------- ### Metrics Collector: Recording Methods Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Provides methods to record specific events, such as workflow queuing, starting, completion, and failure, as well as activity completion and failure. These methods update the internal counters and time-based arrays. ```typescript recordWorkflowQueued(): void recordWorkflowStarted(): void recordWorkflowCompleted(): void recordWorkflowFailed(): void recordActivityCompleted(): void recordActivityFailed(): void ``` -------------------------------- ### File Store Directory Structure Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Illustrates the directory structure for the file store implementation of worlds-engine. It shows dedicated directories for workflows, schedules, the queue file, logs, and state. Each workflow and schedule is stored as a separate JSON file. ```bash .worlds-engine/ workflows/ workflow-id-1.json workflow-id-2.json schedules/ schedule-id-1.json queue.json logs/ 2025-12-01.log state/ ``` -------------------------------- ### Custom World Implementation Example (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/README.md Provides an example of extending the `World` class to create a custom world implementation. This allows developers to integrate custom infrastructure for storage, queuing, etc. ```typescript import { World, type WorldConfig } from 'worlds-engine' class MyCustomWorld extends World { constructor(config: WorldConfig) { super(config) } async initialize(): Promise { await this.storage.initialize() } async shutdown(): Promise { await this.storage.shutdown() } } ``` -------------------------------- ### Logger Implementation: Log Entry Format Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Defines the structure of a single log entry. Each entry includes a timestamp, level, category, message, and optional metadata. This format ensures consistent logging data. ```typescript { timestamp: 1234567890, level: 'info', category: 'workflow', message: 'workflow started', metadata: { workflowId: 'wf-123' } } ``` -------------------------------- ### Worker Lifecycle Management in TypeScript Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md This section details the operations for managing the lifecycle of worker processes. It includes functions for spawning new workers, handling their initialization and task execution, and killing idle workers. It also outlines the steps for graceful shutdown. ```typescript async spawnWorker(taskQueue?: string): Promise { const worker = new Worker(taskQueue heartbeatInterval) this.workers.push(worker) worker.start( async (queue) => await this.taskQueue.dequeue(queue) async (task) => await this.executeTask(task) (workerId) => this.heartbeat.beat(workerId) ) } ``` ```typescript async killWorker(): Promise { const idleWorker = this.workers.find(d => d.isIdle()) if (!idleWorker) return idleWorker.stop() this.workers = this.workers.filter(d => d.id !== idleWorker.id) } ``` -------------------------------- ### Test Harness Time Control (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Provides methods to control time within a test environment, allowing advancement by milliseconds or to a specific timestamp. It also includes a function to run a workflow until completion or timeout. ```typescript async advance(ms: number): Promise { currentTime += ms await sleep(100) } async advanceTo(timestamp: number): Promise { if (timestamp < currentTime) throw new Error('cannot go back') await this.advance(timestamp - currentTime) } async runUntilComplete(workflowId: string timeout = 30000): Promise { const start = Date.now() while (true) { const state = await world.query(workflowId) if (state.status === 'completed' || state.status === 'failed') break if (Date.now() - start > timeout) throw new Error('timeout') await sleep(100) } } ``` -------------------------------- ### Cron Expressions for Billing Cycles (N/A) Source: https://github.com/xylex-group/worlds-engine/blob/main/examples/recurring-invoice/README.md Provides example cron expressions for different billing cycles: weekly, quarterly, and annual. These are standard cron syntax and do not depend on specific project code. ```typescript // weekly billing '0 9 * * 1' ``` ```typescript // quarterly billing '0 9 1 */3 *' ``` ```typescript // annual billing '0 9 1 1 *' ``` -------------------------------- ### Logger Implementation: Log Methods Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Provides methods for logging messages at different severity levels: debug, info, warn, and error. Each method accepts a category, a message, and optional metadata. These methods are used to record events within the system. ```typescript debug(category: string, message: string, metadata?: object): void info(category: string, message: string, metadata?: object): void warn(category: string, message: string, metadata?: object): void error(category: string, message: string, metadata?: object): void ``` -------------------------------- ### Predefined Retry Patterns (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Offers predefined retry configurations for common scenarios such as API calls, database operations, network requests, and quick retries. These patterns encapsulate commonly used retry settings, simplifying the application of retry logic for standard tasks. ```typescript retryPatterns.api retryPatterns.database retryPatterns.network retryPatterns.quick ``` -------------------------------- ### Using Predefined Retry Patterns with Worlds Engine Source: https://github.com/xylex-group/worlds-engine/blob/main/examples/retry-patterns/README.md Demonstrates the usage of predefined retry patterns (API, Database, Network) from worlds-engine's `retryPatterns` object. These patterns offer common configurations for specific service types, simplifying setup. ```typescript import { withRetry, retryPatterns } from 'worlds-engine' // api pattern: 5 attempts, exponential backoff await withRetry(apiCall, retryPatterns.api) // database pattern: 3 attempts, shorter intervals await withRetry(dbQuery, retryPatterns.database) // network pattern: 5 attempts, longer intervals await withRetry(networkOp, retryPatterns.network) ``` -------------------------------- ### Workflow Querying System in TypeScript Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md This TypeScript code defines the structure for filtering workflow queries and outlines the execution logic. It allows fetching workflows based on various criteria like status, name, and time range, and includes pagination. ```typescript { status?: WorkflowStatus | WorkflowStatus[] workflowName?: string parentId?: string startedAfter?: number startedBefore?: number limit?: number offset?: number } ``` ```typescript async queryWorkflows(filters: WorkflowQueryFilter): Promise { let results = await this.getAllWorkflows() results = results.filter(wf => this.matchesFilter(wf filters)) results.sort((a b) => b.startedAt - a.startedAt) if (filters.offset) { results = results.slice(filters.offset) } if (filters.limit) { results = results.slice(0 filters.limit) } return results } ``` ```typescript matchesFilter(workflow: WorkflowState filters: WorkflowQueryFilter): boolean { if (filters.status) { const statuses = Array.isArray(filters.status) ? filters.status : [filters.status] if (!statuses.includes(workflow.status)) return false } if (filters.workflowName && !workflow.workflowId.includes(filters.workflowName)) { return false } if (filters.parentId && workflow.parentId !== filters.parentId) { return false } if (filters.startedAfter && workflow.startedAt < filters.startedAfter) { return false } if (filters.startedBefore && workflow.startedAt > filters.startedBefore) { return false } return true } ``` -------------------------------- ### Initialize Runtime with World Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/api-reference.md Connects the Worlds Engine runtime to a specific World instance. This function must be called before starting any workflows. After initialization, you can use the `start` function to initiate workflows. ```typescript import { initializeRuntime } from 'worlds-engine' const world = new World(config) initializeRuntime(world) await world.start() const handle = await start('workflow' input) ``` -------------------------------- ### Parse Cron Expression Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md This TypeScript code demonstrates parsing a cron expression using the 'cron-parser' library. It shows how to get the next execution time from a parsed cron expression. ```typescript const parsed = parseExpression(cronExpression) const next = parsed.next() schedule.nextExecution = next.getTime() ``` -------------------------------- ### Define Child Workflow Events Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md This TypeScript code defines the event structures for child workflow interactions within the event sourcing system. It includes events for starting and completing child workflows. ```typescript { type: 'child_workflow_started' timestamp: number childId: string name: string } { type: 'child_workflow_completed' timestamp: number childId: string result: any } ``` -------------------------------- ### Define Workflow Lifecycle Events Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md This TypeScript code defines the structure for various workflow lifecycle events used in event sourcing. It includes events for starting, completing, failing, and cancelling workflows. ```typescript { type: 'workflow_started' timestamp: number input: any } { type: 'workflow_completed' timestamp: number result: any } { type: 'workflow_failed' timestamp: number error: string } { type: 'workflow_cancelled' timestamp: number } ``` -------------------------------- ### CustomWorld Implementation Example Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/api-reference.md An example demonstrating how to extend the `World` interface to create a custom world implementation. This allows you to integrate with specific infrastructure or services. You need to override `initialize` and `shutdown` methods for custom logic. ```typescript import { World type WorldConfig } from 'worlds-engine' class CustomWorld extends World { constructor(config: WorldConfig) { super(config) } async initialize(): Promise { // custom initialization } async shutdown(): Promise { // custom cleanup } } ``` -------------------------------- ### Define Activity Lifecycle Events Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md This TypeScript code defines the structure for activity lifecycle events within the event sourcing system. It covers scheduling, starting, completion, failure, retries, and heartbeats for activities. ```typescript { type: 'activity_scheduled' timestamp: number activityId: string name: string input: any } { type: 'activity_started' timestamp: number activityId: string } { type: 'activity_completed' timestamp: number activityId: string result: any } { type: 'activity_failed' timestamp: number activityId: string error: string attempt: number } { type: 'activity_retry' timestamp: number activityId: string attempt: number delayMs: number } { type: 'activity_heartbeat' timestamp: number activityId: string message?: string } ``` -------------------------------- ### Example ctx.run Usage - TypeScript Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/api-reference.md Shows how to use `ctx.run` within a workflow to execute the 'sendEmail' activity with specific input, and obtain its result. ```typescript const result = await ctx.run(sendEmail, { to: 'user@example.com', subject: 'hello' }); ``` -------------------------------- ### Activity Timeout Enforcement with Promise.race (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Implements a timeout for a set of asynchronous activities represented by promises. It races the activity promises against a timeout promise. ```typescript const promises = [handler(ctx input)] if (timeoutMs) { promises.push( new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')) timeoutMs) ) ) } return await Promise.race(promises) ``` -------------------------------- ### Heartbeat Monitor: Heartbeat Entry Format Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Specifies the structure for a heartbeat entry, which includes a unique ID, the timestamp of the last received beat, and an optional message. ```typescript { id: string, lastBeat: number, message?: string } ``` -------------------------------- ### Activity Context Methods Example (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/README.md Shows the available methods and properties on the activity context object passed to activity functions. These allow activities to signal progress, check for cancellation, and access execution details. ```typescript ctx.heartbeat(message?: string): void ctx.isCancelled(): boolean ctx.activityId: string ctx.workflowId: string ctx.attempt: number ``` -------------------------------- ### Activity Configuration Object Example (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/README.md Defines the structure for configuring activity execution parameters in Worlds Engine. This includes settings for retries, timeouts, and task queuing. ```typescript { retry: { maxAttempts: number, backoff: 'linear' | 'exponential' | 'constant', initialInterval: number, maxInterval: number, multiplier: number }, timeout: string | number, heartbeatTimeout: string | number, taskQueue: string } ``` -------------------------------- ### Schedule Management API: Delete Schedule Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Deletes a schedule identified by its ID. This operation removes the schedule from the storage. It returns a Promise that resolves once the deletion is complete. ```typescript async delete(id: string): Promise { await store.deleteSchedule(id) } ``` -------------------------------- ### Workflow Dev Kit API with Hooks and Webhooks in TypeScript Source: https://context7.com/xylex-group/worlds-engine/llms.txt Demonstrates how to use the Worlds Engine API to create workflows that interact with external systems via hooks and webhooks. This includes creating hooks, waiting for hook responses, creating webhook endpoints, and waiting for webhook requests. It also shows how to initiate a workflow and resume a hook externally. ```typescript import { World, workflow, activity, initializeRuntime, start, resumeHook, getRun } from 'worlds-engine' import { sleep, createHook, createWebhook, getWritable, getWorkflowMetadata } from 'worlds-engine' const approvalWorkflow = workflow('approval-workflow', async (ctx, input) => { console.log('Creating approval hook...') // Create a hook that external systems can call const hook = await ctx.createHook() console.log(`Hook token: ${hook.token}`) console.log('Send approval payload to this token to continue workflow') // Workflow suspends here until hook receives data const approval = await hook.wait() console.log(`Approval received: ${approval.approved}`) if (!approval.approved) { throw new Error('workflow rejected') } return { status: 'approved', approver: approval.approver } }) const webhookWorkflow = workflow('webhook-workflow', async (ctx, input) => { console.log('Creating webhook...') // Create a webhook endpoint const webhook = await ctx.createWebhook() console.log(`Webhook URL: ${webhook.url}`) console.log('Send POST request to this URL to continue workflow') // Workflow suspends until webhook receives request const request = await webhook.wait() console.log(`Webhook received ${request.method} request`) return { status: 'webhook received', url: webhook.url } }) const streamingWorkflow = workflow('streaming-workflow', async (ctx, input) => { const stream = ctx.getWritable() const writer = stream.getWriter() for (let i = 0; i < input.items.length; i++) { await ctx.sleep(500) // Stream progress updates await writer.write({ progress: ((i + 1) / input.items.length) * 100, currentItem: input.items[i], timestamp: Date.now() }) } await writer.close() return { processed: input.items.length } }) const world = new World({ minWorkers: 2, maxWorkers: 5, persistence: 'hybrid' }) world.register(approvalWorkflow, webhookWorkflow, streamingWorkflow) initializeRuntime(world) await world.start() // Start workflow with hook const handle = await start('approval-workflow', { userId: 'user-123' }) // Simulate external approval system setTimeout(async () => { const state = await getRun(handle.workflowId) if (state.hooks && state.hooks.length > 0) { const hookToken = state.hooks[0].token await resumeHook(hookToken, { approved: true, approver: 'admin' }) } }, 2000) const result = await handle.result() console.log('Workflow result:', result) ``` -------------------------------- ### Define Compensation Events Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md This TypeScript code defines the event structures for compensation actions within the event sourcing implementation. It includes events for adding, executing, and failing compensations. ```typescript { type: 'compensation_added' timestamp: number compensationId: string } { type: 'compensation_executed' timestamp: number compensationId: string } { type: 'compensation_failed' timestamp: number compensationId: string error: string } ``` -------------------------------- ### Test Activities Directly with Mock Context (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/activities.md Provides an example of how to test an activity function directly, bypassing the normal workflow execution. It involves importing the `activity` utility, defining a simple activity, creating a mock `context` object, and then calling the activity's `handler` with the mock context and input. Assertions can then be made on the result. ```typescript import { activity } from 'worlds-engine' const myActivity = activity('test', async (ctx, input) => { return { value: input.x * 2 } }) // create a mock context const mockContext = { activityId: 'test-1', workflowId: 'workflow-1', attempt: 1, heartbeat: () => {}, isCancelled: () => false } const result = await myActivity.handler(mockContext, { x: 5 }) expect(result.value).toBe(10) ``` -------------------------------- ### Cron Schedule Explanation Source: https://github.com/xylex-group/worlds-engine/blob/main/examples/recurring-invoice/README.md Provides a visual breakdown of the cron expression '0 9 1 * *', explaining each field (minute, hour, day of month, month, day of week). This helps in understanding how to configure scheduled job timings. ```plaintext 0 9 1 * * │ │ │ │ │ │ │ │ │ └─ day of week any │ │ │ └─ month any │ │ └─ day 1 │ └─ hour 9 └─ minute 0 ``` -------------------------------- ### Parse Timeout String to Milliseconds (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Parses a timeout string (e.g., '10s', '5m') into milliseconds. It handles units like ms, s, m, and h. Throws an error for invalid formats. ```typescript function parseTimeout(timeout: string | number): number { if (typeof timeout === 'number') return timeout const match = timeout.match(/^(\d+)(ms|s|m|h)$/) if (!match) throw new Error('invalid timeout format') const value = parseInt(match[1] 10) const unit = match[2] switch (unit) { case 'ms': return value case 's': return value * 1000 case 'm': return value * 60 * 1000 case 'h': return value * 60 * 60 * 1000 } } ``` -------------------------------- ### Test Harness Usage: Executing and Monitoring Workflows (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/workflows.md Demonstrates how to use the `createTestHarness` utility for testing workflows. It covers setting up the harness, registering workflows and activities, executing a workflow, advancing time, and waiting for completion. Allows querying the final state of a workflow. ```typescript import { createTestHarness } from 'worlds-engine/testing' const harness = createTestHarness() await harness.world.start() harness.world.register(myWorkflow myActivity) const handle = await harness.world.execute('my-workflow' input) await harness.advance(60000) await harness.runUntilComplete(handle.workflowId) const state = await handle.query() ``` -------------------------------- ### Worker Class Definition in TypeScript Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Defines the structure of a Worker class in TypeScript. It includes properties for tracking worker status, current task, task execution times, heartbeat information, and completed tasks. The `start` method is asynchronous and takes callbacks for task retrieval, task execution, and heartbeating. ```typescript class Worker { id: string status: WorkerStatus currentTask?: Task taskStartedAt?: number lastHeartbeat: number tasksCompleted: number async start( getTask: (queue?: string) => Promise executeTask: (task: Task) => Promise onHeartbeat: (id: string) => void ): Promise } ``` -------------------------------- ### Example ctx.addCompensation Usage - TypeScript Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/api-reference.md Demonstrates registering a compensation function using `ctx.addCompensation` after successfully charging a card, ensuring a refund can be processed if necessary. ```typescript const payment = await ctx.run(chargeCard, amount); ctx.addCompensation(() => ctx.run(refundCard, payment)); ``` -------------------------------- ### Enforce Promise Timeout with Promise.race (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Ensures a promise-returning function completes within a specified timeout. It uses Promise.race to either resolve the function's promise or reject with a timeout error. ```typescript async function withTimeout( fn: () => Promise timeoutMs: number ): Promise { return Promise.race([ fn() new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')) timeoutMs) ) ]) } ``` -------------------------------- ### Schedule Management API: Pause Schedule Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Pauses an existing schedule identified by its ID. This operation marks the schedule as paused and persists the change. It returns a Promise that resolves upon successful pausing. ```typescript async pause(id: string): Promise { schedule.paused = true await store.saveSchedule(schedule) } ``` -------------------------------- ### Deterministic Testing: Initializing Test Environment with Specific Time (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/workflows.md Demonstrates how to ensure deterministic test runs by providing an `initialTime` when creating the test harness. This sets a fixed starting point for time, making tests repeatable and predictable, especially when dealing with time-sensitive operations or scheduling. ```typescript const harness = createTestHarness({ initialTime: 1000000 }) ``` -------------------------------- ### Activity Options Configuration in TypeScript Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/activities.md Provides a comprehensive example of configuring various options for an activity, including detailed retry strategies (max attempts, backoff type, intervals, multiplier), execution timeout, heartbeat timeout, and task queue routing. ```typescript activity('name', handler, { retry: { maxAttempts: 3, backoff: 'exponential', // 'linear' | 'exponential' | 'constant' initialInterval: 1000, // first retry delay (ms) maxInterval: 60000, // cap on retry delay multiplier: 2, // for exponential backoff }, timeout: '30s', // max execution time ('30s', '5m', '1h') heartbeatTimeout: '10s', // max time between heartbeats taskQueue: 'critical', // route to specific workers }) ``` -------------------------------- ### Implement Compensation Strategy Flow Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md This code snippet demonstrates the implementation of the compensation strategy flow in TypeScript. It uses `saga.executeCompensations` to add 'compensation_executed' or 'compensation_failed' events to the history based on the outcome of compensation attempts. ```typescript await saga.executeCompensations( (id) => addEvent({ type: 'compensation_executed' compensationId: id }) (id error) => addEvent({ type: 'compensation_failed' compensationId: id error }) ) ``` -------------------------------- ### Basic Retry with Worlds Engine Source: https://github.com/xylex-group/worlds-engine/blob/main/examples/retry-patterns/README.md Illustrates a basic retry mechanism for an asynchronous function using default settings provided by worlds-engine. It requires importing the `withRetry` utility. ```typescript import { withRetry } from 'worlds-engine' const result = await withRetry( () => fetch('https://api.example.com/data'), { maxAttempts: 3, backoff: 'exponential' } ) ``` -------------------------------- ### Heartbeat Monitor: Class Definition Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Defines a HeartbeatMonitor class used to track the liveness of various components through periodic signals. It stores heartbeat information and uses a configurable timeout to determine if a component is considered 'dead'. ```typescript class HeartbeatMonitor { private heartbeats: Map private timeout: number } ``` -------------------------------- ### Example ctx.executeChild Usage - TypeScript Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/api-reference.md Illustrates spawning a child workflow named 'process-item' with given input and then retrieving its result using the returned handle. ```typescript const child = await ctx.executeChild('process-item', item); const childResult = await child.result(); ``` -------------------------------- ### RetryOptions Structure for withRetry (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Defines the structure for configuring the retry behavior of the `withRetry` function. It includes parameters for maximum attempts, backoff strategy, interval settings, timeouts, and custom retry logic callbacks. ```typescript { maxAttempts?: number backoff?: 'linear' | 'exponential' | 'constant' initialInterval?: number maxInterval?: number multiplier?: number timeout?: string | number onRetry?: (attempt: number error: Error delayMs: number) => void shouldRetry?: (error: Error) => boolean } ``` -------------------------------- ### LocalWorld Initialization (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/README.md Shows how to instantiate and configure `LocalWorld`, the default implementation for development environments in Worlds Engine. It requires setting a `webhookBaseUrl`. ```typescript import { LocalWorld } from 'worlds-engine' const world = new LocalWorld({ webhookBaseUrl: 'http://localhost:3000/webhooks' }) // Note: The second 'world' assignment is likely a typo in the original source. // const world = new World(config, world) ``` -------------------------------- ### Task Queue Coordination in TypeScript Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md This TypeScript code defines the structure of a task and provides operations for enqueueing and dequeueing tasks with priority sorting and queue filtering. It ensures tasks are processed in the correct order and can be routed efficiently. ```typescript { id: string type: 'workflow' | 'activity' | 'compensation' workflowId: string name: string input: any options: WorkflowOptions | ActivityOptions priority?: number scheduledAt: number taskQueue?: string } ``` ```typescript async enqueue(task: Task): Promise { this.queue.push(task) this.queue.sort((a b) => { if (a.priority !== b.priority) { return (b.priority || 0) - (a.priority || 0) } return a.scheduledAt - b.scheduledAt }) await this.persist() } ``` ```typescript async dequeue(taskQueue?: string): Promise { if (taskQueue) { const idx = this.queue.findIndex(t => t.taskQueue === taskQueue || !t.taskQueue ) if (idx >= 0) { const task = this.queue.splice(idx 1)[0] await this.persist() return task } return undefined } const task = this.queue.shift() if (task) await this.persist() return task } ``` -------------------------------- ### Heartbeat Monitor: Operations Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Provides methods to manage heartbeats: `beat` to record a new heartbeat signal, `check` to verify if a component is still alive within the timeout period, and `findDead` to identify all components that have missed their heartbeats. ```typescript beat(id: string, message?: string): void { this.heartbeats.set(id, { id, lastBeat: Date.now(), message }) } check(id: string): boolean { const entry = this.heartbeats.get(id) if (!entry) return false return Date.now() - entry.lastBeat < this.timeout } findDead(): string[] { const now = Date.now() return Array.from(this.heartbeats.entries()) .filter(([_, entry]) => now - entry.lastBeat >= this.timeout) .map(([id, _]) => id) } ``` -------------------------------- ### Manual Workflow Execution - TypeScript Source: https://github.com/xylex-group/worlds-engine/blob/main/examples/recurring-invoice/README.md Demonstrates how to manually trigger a workflow ('batch-invoices') with specific parameters using `world.execute`. It also shows how to wait for the workflow to complete and retrieve its result. ```typescript const handle = await world.execute('batch-invoices', { customerIds: ['cust-1', 'cust-2'], month: 12, year: 2025 }); const result = await handle.result(); ``` -------------------------------- ### Metrics Collector: Cleanup Old Metrics Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Removes outdated metric data points that fall outside the defined rolling window. This ensures that calculations are based only on recent events, maintaining the accuracy of real-time performance reporting. ```typescript cleanOldMetrics(): void { const cutoff = Date.now() - this.windowSize this.workflowCompletions = this.workflowCompletions.filter(t => t > cutoff) this.workflowFailures = this.workflowFailures.filter(t => t > cutoff) } ``` -------------------------------- ### Monitoring Retries with Worlds Engine Source: https://github.com/xylex-group/worlds-engine/blob/main/examples/retry-patterns/README.md Demonstrates how to monitor retry attempts using the `onRetry` callback within `withRetry` from worlds-engine. This callback provides details about the attempt number, error, and delay, enabling logging or integration with monitoring services. ```typescript await withRetry(operation, { onRetry: (attempt, error, delayMs) => { console.log(`retry ${attempt} after ${delayMs}ms: ${error.message}`) // or send to your monitoring service } }) ``` -------------------------------- ### Compensation Registration during Workflow Execution (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Demonstrates how to register a compensation function during the execution of a workflow activity. The `ctx.addCompensation` method is used to associate a rollback action with the primary activity, ensuring that if the workflow fails, the compensation can be triggered. ```typescript const result = await ctx.run(activity input) ctx.addCompensation(async () => { await ctx.run(undoActivity result.id) }) ``` -------------------------------- ### Compensation Structure Definition (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md Defines the structure for a single compensation item within the saga pattern. Each compensation has a unique ID, a function to execute for rollback, and flags to track whether it has been executed and if any errors occurred during execution. ```typescript { id: string fn: () => Promise executed: boolean error?: string } ``` -------------------------------- ### POST /api/process Source: https://context7.com/xylex-group/worlds-engine/llms.txt Initiates a new image processing workflow by accepting an array of image URLs. It returns a workflow ID for status tracking. ```APIDOC ## POST /api/process ### Description Initiates a new image processing workflow by accepting an array of image URLs. It returns a workflow ID for status tracking. ### Method POST ### Endpoint /api/process #### Request Body - **urls** (array of strings) - Required - An array of image URLs to process. ### Request Example ```json { "urls": [ "http://example.com/image1.jpg", "http://example.com/image2.jpg" ] } ``` ### Response #### Success Response (200) - **workflowId** (string) - The unique identifier for the executed workflow. - **status** (string) - The initial status of the workflow, typically 'queued'. #### Response Example ```json { "workflowId": "unique-workflow-id", "status": "queued" } ``` ``` -------------------------------- ### Initialize Runtime API with World Instance (TypeScript) Source: https://github.com/xylex-group/worlds-engine/blob/main/README.md Connects the runtime API to a World instance using `initializeRuntime`. This setup is crucial for the engine to interact with the underlying infrastructure defined by the World. ```typescript const world = new World(config) initializeRuntime(world) await world.start() ``` -------------------------------- ### Scaling Evaluation Logic in TypeScript Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md This TypeScript function evaluates the current workload and determines whether to scale workers up or down. It adjusts the worker count incrementally to prevent oscillation. Dependencies include 'scaleThreshold', 'maxWorkers', 'minWorkers', 'spawnWorker', and 'killWorker'. ```typescript async checkScaling(): Promise { const metrics = this.getMetrics() const workload = metrics.workload if (workload >= scaleThreshold && workers.length < maxWorkers) { const needed = Math.min( Math.ceil((maxWorkers - workers.length) / 2) maxWorkers - workers.length ) for (let i = 0; i < needed; i++) { await spawnWorker() } } if (workload <= scaleDownThreshold && workers.length > minWorkers) { const toKill = Math.min( Math.floor((workers.length - minWorkers) / 2) workers.length - minWorkers ) for (let i = 0; i < toKill; i++) { await killWorker() } } } ``` -------------------------------- ### Implement Cascade Strategy Flow Cancellation Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/getting-started.md This TypeScript code implements the recursive cancellation logic for the cascade strategy flow. The `cancel` function recursively calls itself for child workflows after updating the current workflow's status to 'cancelled'. ```typescript async cascade(workflowId: string) { await this.cancel(workflowId) } async cancel(workflowId: string) { const state = await store.getWorkflow(workflowId) state.status = 'cancelled' for (const childId of state.childIds) { await this.cancel(childId) } await store.saveWorkflow(state) } ``` -------------------------------- ### TypeScript: Querying Compensated Workflows Source: https://github.com/xylex-group/worlds-engine/blob/main/docs/failure-strategies.md Demonstrates how to query workflows that have completed their compensation phase in TypeScript. This is useful for auditing or verifying cleanup operations. ```typescript const compensated = await world.queryWorkflows({ status: 'compensated', limit: 10 }) ```