Reference

TypeScript SDK


The ORCHER TypeScript SDK (@orcher/sdk) lets you write workflows and tasks as plain async TypeScript. It offers two ways to define them, and you can mix them in one worker:

  • Functional: task({ ... }) and workflow({ ... }) return typed references, with no classes.
  • Decorators: @Tasks()/@Task() on a class whose constructor dependencies are injected, and @Workflow({ name }) on a class with a run() method.

Both register what they define in the process when the module is imported, and a worker started in that process serves everything registered. Task references carry their input and output types, so ctx.executeTask() is checked by the compiler.


Installation

1
npm install @orcher/sdk

Requirements

  • Node.js 22 or later.
  • A supported platform. The SDK runs on a native core, shipped prebuilt for macOS (arm64 and x64) and Linux (x64 and arm64, with glibc or musl). npm installs the one that matches your machine. Windows is not supported.
  • Legacy decorators. The decorators need experimentalDecorators, and constructor injection needs emitDecoratorMetadata:
1
{
2
"compilerOptions": {
3
"target": "ES2022",
4
"module": "commonjs",
5
"strict": true,
6
"experimentalDecorators": true,
7
"emitDecoratorMetadata": true
8
}
9
}

Quick Start

1. Define Tasks

Tasks are where side effects go: API calls, database writes, emails. A functional task:

1
import { task, type TaskContext } from '@orcher/sdk';
2
3
export interface ChargeInput {
4
orderId: string;
5
amount: number;
6
}
7
8
export interface Charge {
9
chargeId: string;
10
amount: number;
11
}
12
13
export const chargePayment = task({
14
name: 'chargePayment',
15
timeout: 30_000, // milliseconds per attempt
16
execute: async (_ctx: TaskContext, input: ChargeInput): Promise<Charge> => {
17
// Call your payment provider here, with input.orderId as the idempotency key.
18
return { chargeId: `ch_${input.orderId}`, amount: input.amount };
19
},
20
});

Or a class of tasks, when they share injected services. Each @Task() method is a task named after the method, and createTaskRefs() gives you typed references to them:

1
import { Injectable, Task, Tasks, createTaskRefs } from '@orcher/sdk';
2
3
@Injectable()
4
export class InventoryService {
5
async reserve(orderId: string): Promise<string> {
6
// Call your inventory system here.
7
return `res_${orderId}`;
8
}
9
}
10
11
@Tasks()
12
export class OrderTasks {
13
// Constructor parameters are resolved from the worker's container.
14
constructor(private readonly inventory: InventoryService) {}
15
16
@Task()
17
async reserveInventory(_ctx: TaskContext, orderId: string): Promise<string> {
18
return this.inventory.reserve(orderId);
19
}
20
21
@Task()
22
async sendConfirmation(_ctx: TaskContext, orderId: string): Promise<void> {
23
// Call your email provider here.
24
console.log(`confirmation sent for ${orderId}`);
25
}
26
}
27
28
// Typed references to the tasks, keyed by method name.
29
export const orderTasks = createTaskRefs(OrderTasks);

2. Define a Workflow

A workflow orchestrates tasks. Its code must be deterministic: it is replayed from its journal after a restart, and must make the same calls in the same order each time. Functional:

1
export const processOrder = workflow({
2
name: 'processOrder',
3
run: async (ctx: WorkflowContext, input: OrderInput): Promise<OrderOutput> => {
4
const charge = await ctx.executeTask(chargePayment, input);
5
const reservationId = await ctx.executeTask(orderTasks.reserveInventory, input.orderId);
6
await ctx.executeTask(orderTasks.sendConfirmation, input.orderId);
7
return { orderId: input.orderId, chargeId: charge.chargeId, reservationId };
8
},
9
});

Or as a class. @Workflow() requires a name, and the class must have a run() method:

1
@Workflow({ name: 'processOrderClass' })
2
export class ProcessOrder {
3
async run(ctx: WorkflowContext, input: OrderInput): Promise<OrderOutput> {
4
const charge = await ctx.executeTask(chargePayment, input);
5
const reservationId = await ctx.executeTask(orderTasks.reserveInventory, input.orderId);
6
await ctx.executeTask(orderTasks.sendConfirmation, input.orderId);
7
return { orderId: input.orderId, chargeId: charge.chargeId, reservationId };
8
}
9
}

3. Run a Worker

1
import { Worker } from '@orcher/sdk';
2
// Importing the modules runs their decorators and task()/workflow() calls,
3
// which register them for the worker.
4
import './tasks';
5
import './workflows';
6
7
async function main(): Promise<void> {
8
const worker = await Worker.builder()
9
.serverUrl(process.env.ORCHER_URL ?? 'http://localhost:50051')
10
.namespace('default')
11
.taskQueue('orders')
12
.build();
13
14
// Resolves once the worker is polling; it keeps polling until shutdown().
15
await worker.run();
16
17
process.once('SIGTERM', () => {
18
void worker.shutdown();
19
});
20
}
21
22
main().catch((err) => {
23
console.error(err);
24
process.exit(1);
25
});

4. Start a Workflow (Client)

1
import { Client } from '@orcher/sdk';
2
import type { OrderInput, OrderOutput } from './workflows';
3
4
async function main(): Promise<void> {
5
const client = new Client({
6
serverUrl: process.env.ORCHER_URL ?? 'http://localhost:50051',
7
namespace: 'default',
8
});
9
await client.connect();
10
11
const input: OrderInput = { orderId: 'ord_123', amount: 9999 };
12
const handle = await client.startWorkflow<OrderOutput>({
13
workflowType: 'processOrder',
14
workflowId: `order-${input.orderId}`,
15
taskQueue: 'orders',
16
args: [input],
17
});
18
19
const result = await handle.result();
20
console.log('order completed:', result);
21
22
client.close();
23
}
24
25
main().catch((err) => {
26
console.error(err);
27
process.exit(1);
28
});

Next Steps

  • Workflows: the WorkflowContext API, timers, child workflows, events, queries
  • Tasks: task options, retries, heartbeats, cancellation, injection
  • Client: starting workflows, handles, errors, authentication
  • Worker: worker options, registration, shutdown
  • Actors: virtual actors with server-side state
  • Sessions: pinning a series of tasks to one worker
  • Testing: running workflows in memory with mocked tasks
  • Patterns: sagas, fan-out, approvals, batching