Reference

Tasks


Tasks do the work that touches the outside world: API calls, database writes, file operations. A workflow schedules a task, any worker polling the queue runs it, and its result is journaled. A failed attempt is retried according to the task's retry policy.

There are two ways to define tasks, and both give the same kind of TaskReference for ctx.executeTask():

  • Functional: task({ name, execute }), for tasks with no shared dependencies.
  • Class-based: @Tasks() on a class and @Task() on its methods, when tasks need injected services.

Functional Tasks

1
export const sendEmail = task({
2
name: 'sendEmail',
3
execute: async (_ctx: TaskContext, input: { to: string; subject: string }): Promise<boolean> => {
4
// Call your email provider here.
5
console.log(`sending "${input.subject}" to ${input.to}`);
6
return true;
7
},
8
});

task() returns a typed reference: sendEmail is a TaskReference<{ to: string; subject: string }, boolean>. The function receives a TaskContext first and the task's input second.

task() optionDescription
name(required) The task's name, unique in the process
execute(required) async (ctx, input) => result
timeoutHow long one attempt may run, in milliseconds. 5 minutes when no timeout is set here or on the call.
heartbeatTimeoutHow long an attempt may go without a heartbeat, in milliseconds
retryPolicyHow failed attempts are retried; see below

Class-Based Tasks

1
import { Injectable, Task, Tasks, createTaskRefs, type TaskContext } from '@orcher/sdk';
2
3
// A service: one instance per worker (the default scope, 'singleton').
4
@Injectable()
5
export class PaymentGateway {
6
async charge(orderId: string, amount: number, idempotencyKey: string): Promise<string> {
7
// Call your payment provider here.
8
console.log(`charging ${amount} for ${orderId} (${idempotencyKey})`);
9
return `ch_${orderId}`;
10
}
11
12
async refund(chargeId: string): Promise<void> {
13
// Call your payment provider here.
14
console.log(`refunding ${chargeId}`);
15
}
16
}
17
18
// A task class: a new instance for each task it runs, built by the worker's
19
// container, which injects the constructor parameters.
20
@Tasks()
21
export class PaymentTasks {
22
constructor(private readonly gateway: PaymentGateway) {}
23
24
// The method name is the task name: this registers 'charge'.
25
@Task({ timeout: 30_000, retryPolicy: { maxAttempts: 3 } })
26
async charge(_ctx: TaskContext, input: { orderId: string; amount: number }): Promise<string> {
27
return this.gateway.charge(input.orderId, input.amount, `charge-${input.orderId}`);
28
}
29
30
@Task()
31
async refund(_ctx: TaskContext, chargeId: string): Promise<void> {
32
await this.gateway.refund(chargeId);
33
}
34
}
35
36
// Typed references, keyed by method name:
37
// paymentTasks.charge is TaskReference<{ orderId: string; amount: number }, string>
38
export const paymentTasks = createTaskRefs(PaymentTasks);
  • The method name is the task name. Don't pass name: to @Task(): it would register the task under that name, while createTaskRefs() types the reference by method name, so the reference you call and the task the worker registered would no longer line up.
  • Use createTaskRefs(Class) for references. @Task() attaches each reference to the class, but TypeScript cannot see what a decorator adds; createTaskRefs() returns the same references with their input and result types.
  • Task methods take (ctx, input). The worker always passes the TaskContext first.
  • Names are global within the process. Two classes with a charge method register two tasks named charge, and the second replaces the first (with a warning). Give methods names that are unique across the process.

@Task() takes timeout and retryPolicy, with the same meaning as for task(). To set a heartbeat timeout for a class-based task, pass heartbeatTimeout on the call (see per-call options).

Dependency Injection

The worker's container builds a new instance of the task class for every task it runs. Constructor parameters are resolved by their type, which requires emitDecoratorMetadata, and each must be a class marked @Injectable(). A service is shared by the whole worker (scope: 'singleton', the default) unless declared otherwise:

1
// A fresh instance wherever it is injected.
2
@Injectable({ scope: 'transient' })
3
export class RequestTimer {
4
readonly startedAt = Date.now();
5
}
ScopeInstances
'singleton' (default)One per worker
'transient'A new one wherever it is injected

Workflows get no injection: they must be deterministic, so services belong in tasks.

When to Use Which

Use caseChoose
A stateless task (send an email, call an API)task({ ... })
Tasks that share a client, pool or configuration@Tasks() with @Injectable() services
Several related operations on one service@Tasks() class

Retry Policy

When an attempt throws, the engine schedules another after a backoff, until the policy runs out of attempts. Then the task fails, and ctx.executeTask() throws in the workflow.

1
export const chargeCard = task({
2
name: 'chargeCard',
3
timeout: 30_000, // per attempt, in milliseconds
4
heartbeatTimeout: 10_000, // fail the attempt after 10 s without a heartbeat
5
retryPolicy: {
6
maxAttempts: 5, // attempts in total, the first included
7
initialInterval: 1_000, // milliseconds before the first retry
8
backoffCoefficient: 2, // each wait is twice the one before
9
maxInterval: 60_000, // ...up to a minute
10
nonRetryableErrorTypes: ['CardDeclinedError'],
11
},
12
execute: async (ctx: TaskContext, input: ChargeInput): Promise<string> => {
13
// The same key on every attempt, so a retried charge is not taken twice.
14
const idempotencyKey = `charge-${input.orderId}`;
15
console.log(`attempt ${ctx.attempt()} with key ${idempotencyKey}`);
16
// Call your payment provider here; throw CardDeclinedError on a decline.
17
return `ch_${input.orderId}`;
18
},
19
});
FieldDefault (when a policy is given)Description
maxAttempts3Attempts in total, the first included
initialInterval1000Milliseconds before the first retry
backoffCoefficient2Each wait is the previous one times this
maxInterval60000The longest wait between attempts, in milliseconds
nonRetryableErrorTypes[]Error types that fail the task at once

The engine works in whole seconds, so intervals below a second are rounded down. A task with no retryPolicy uses the engine's default policy. ctx.attempt() in the task counts attempts from 1.

Errors That Should Not Be Retried

An error's type is its name, or its class name when name is left as 'Error'. List the types that retrying cannot fix in nonRetryableErrorTypes:

1
// The engine matches nonRetryableErrorTypes against the error's name
2
// (or, when name is left as 'Error', its class name).
3
export class CardDeclinedError extends Error {
4
override name = 'CardDeclinedError';
5
}

Or mark one error as final, whatever the policy says, by setting nonRetryable: true on it:

1
export const validateAddress = task({
2
name: 'validateAddress',
3
execute: async (_ctx: TaskContext, postcode: string): Promise<string> => {
4
if (postcode.trim() === '') {
5
// Any error with nonRetryable set is final, whatever the retry policy says.
6
throw Object.assign(new Error('postcode is empty'), { nonRetryable: true });
7
}
8
return postcode.toUpperCase();
9
},
10
});

Idempotency

Tasks run at least once: an attempt can do its work and then fail to report it, and run again. Results are journaled once, but side effects need an idempotency key that is the same on every attempt. Build it from the business identity of the work, as chargeCard above does with the order id, and pass it to the service you call.


Heartbeats

The worker heartbeats every task it runs, on its own, for as long as the task runs. A long task needs no heartbeat code to stay alive, and if its worker dies the heartbeats stop, the attempt times out after its heartbeat timeout, and the engine runs it again.

ctx.heartbeat() and ctx.heartbeatWithDetails(details) are optional. Call them to record how far the task has got, and to learn that it was canceled: both throw a TaskError with code TASK_CANCELED once it has been.

1
@Task()
2
async importRows(ctx: TaskContext, { rows }: { rows: string[] }): Promise<number> {
3
for (let i = 0; i < rows.length; i++) {
4
await importRow(rows[i]!);
5
if (i % 100 === 0) {
6
// Optional: the worker already heartbeats the task on its own.
7
// This also records how far it got, and throws once the task is canceled.
8
await ctx.heartbeatWithDetails({ done: i + 1, total: rows.length });
9
}
10
}
11
return rows.length;
12
}

ctx.heartbeatTimeout() returns the heartbeat timeout the attempt is judged by, in milliseconds.


Cancellation

When the workflow is canceled or terminated, the engine answers the worker's next heartbeat with a request to stop, and the task's cancellation token is set. ctx.isCancelled() then returns true. Check it between units of work:

1
@Task()
2
async reindex(ctx: TaskContext, { shards }: { shards: number[] }): Promise<number> {
3
let done = 0;
4
for (const shard of shards) {
5
if (ctx.isCancelled()) {
6
// Clean up here, then stop.
7
throw new Error(`reindex canceled after ${done} shards`);
8
}
9
console.log(`reindexing shard ${shard}`);
10
done += 1;
11
}
12
return done;
13
}

Or wait on the cancellation token, for example to abort a request in flight:

1
@Task()
2
async download(ctx: TaskContext, url: string): Promise<string> {
3
const controller = new AbortController();
4
void ctx.cancellationToken().waitForCancellation().then(() => controller.abort());
5
6
const response = await fetch(url, { signal: controller.signal });
7
return response.text();
8
}

Task Metadata and Logging

1
@Task()
2
async inspect(ctx: TaskContext): Promise<void> {
3
const log = ctx.logger(); // adds the workflow id, task type and attempt to each line
4
log.info(`workflow ${ctx.workflowId()}, task ${ctx.taskType()}`);
5
if (ctx.isRetry()) {
6
log.warn(`attempt ${ctx.attempt()}`); // attempts count from 1
7
}
8
const limit = ctx.heartbeatTimeout(); // milliseconds, or undefined
9
log.debug(`heartbeat timeout: ${limit ?? 'none'}`);
10
}

TaskContext Reference

MethodDescription
ctx.attempt()The attempt number, from 1
ctx.isRetry()Whether this is not the first attempt
ctx.workflowId()The workflow that scheduled the task
ctx.taskType()The task's registered name
ctx.heartbeatTimeout()The heartbeat timeout in milliseconds, or undefined
ctx.heartbeat()Record a heartbeat; throws once the task is canceled
ctx.heartbeatWithDetails(details)The same, with JSON-serializable progress details
ctx.isCancelled()Whether the engine has asked the attempt to stop
ctx.cancellationToken()A token with isCancelled and waitForCancellation()
ctx.logger()A logger that prefixes each line with the task's metadata
ctx.taskId() / ctx.runId()The task's id and its run's id

Next Steps

  • Workflows: calling tasks, per-call options, failures
  • Worker: worker configuration
  • Testing: mocking tasks in tests