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({ ... })andworkflow({ ... })return typed references, with no classes. - Decorators:
@Tasks()/@Task()on a class whose constructor dependencies are injected, and@Workflow({ name })on a class with arun()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
1npm install @orcher/sdkRequirements
- 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 needsemitDecoratorMetadata:
1{2 "compilerOptions": {3 "target": "ES2022",4 "module": "commonjs",5 "strict": true,6 "experimentalDecorators": true,7 "emitDecoratorMetadata": true8 }9}Quick Start
1. Define Tasks
Tasks are where side effects go: API calls, database writes, emails. A functional task:
1import { task, type TaskContext } from '@orcher/sdk';23export interface ChargeInput {4 orderId: string;5 amount: number;6}78export interface Charge {9 chargeId: string;10 amount: number;11}1213export const chargePayment = task({14 name: 'chargePayment',15 timeout: 30_000, // milliseconds per attempt16 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:
1import { Injectable, Task, Tasks, createTaskRefs } from '@orcher/sdk';23@Injectable()4export class InventoryService {5 async reserve(orderId: string): Promise<string> {6 // Call your inventory system here.7 return `res_${orderId}`;8 }9}1011@Tasks()12export class OrderTasks {13 // Constructor parameters are resolved from the worker's container.14 constructor(private readonly inventory: InventoryService) {}1516 @Task()17 async reserveInventory(_ctx: TaskContext, orderId: string): Promise<string> {18 return this.inventory.reserve(orderId);19 }2021 @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}2728// Typed references to the tasks, keyed by method name.29export 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:
1export 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' })2export 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
1import { Worker } from '@orcher/sdk';2// Importing the modules runs their decorators and task()/workflow() calls,3// which register them for the worker.4import './tasks';5import './workflows';67async 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();1314 // Resolves once the worker is polling; it keeps polling until shutdown().15 await worker.run();1617 process.once('SIGTERM', () => {18 void worker.shutdown();19 });20}2122main().catch((err) => {23 console.error(err);24 process.exit(1);25});4. Start a Workflow (Client)
1import { Client } from '@orcher/sdk';2import type { OrderInput, OrderOutput } from './workflows';34async 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();1011 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 });1819 const result = await handle.result();20 console.log('order completed:', result);2122 client.close();23}2425main().catch((err) => {26 console.error(err);27 process.exit(1);28});A workflow and a task each take one input: an object, an array, or a single string, number or boolean. Pass several values as one object; several arguments are refused.
Next Steps
- Workflows: the
WorkflowContextAPI, 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