Reference

Client API


The Client connects to the ORCHER engine over gRPC. Use it to start workflows, wait for their results, send them events, query them, and cancel or terminate them.


Connecting

1
const client = new Client({
2
serverUrl: 'http://localhost:50051',
3
namespace: 'default',
4
});
5
await client.connect();
6
7
// ... start workflows, send events, read results ...
8
9
client.close();

serverUrl and namespace are required. Call connect() before anything else; every other method throws a ClientError on a client that is not connected.

API keys and TLS

An engine that requires authentication rejects requests without a valid API key. Pass it as apiKey; it is sent as authorization: Bearer <key> on every request. The SDK doesn't read ORCHER_API_KEY or any other variable for the client, so read it yourself:

1
// An https:// URL turns TLS on, verified against the system trust store.
2
const client = new Client({
3
serverUrl: 'https://orcher.example.com',
4
namespace: 'payments',
5
apiKey: process.env.ORCHER_API_KEY,
6
});
7
await client.connect();

TLS follows the URL scheme. An https:// URL connects over TLS and verifies the engine against the system trust store, with no other setting. An http:// URL connects in plaintext, so use https:// whenever the engine expects TLS. The tls option adds certificates: a CA certificate to trust a private or self-signed authority, and a client certificate and key for mutual TLS. Setting tls at all turns TLS on:

1
const client = new Client({
2
serverUrl: 'https://orcher.internal:50051',
3
namespace: 'payments',
4
tls: {
5
caPath: '/etc/orcher/ca.pem', // only for a private certificate authority
6
certPath: '/etc/orcher/client.pem',
7
keyPath: '/etc/orcher/client-key.pem',
8
},
9
});
10
await client.connect();
tls fieldDescription
caPathPEM file of a private CA to trust. Omit it for a publicly trusted certificate.
certPath / keyPathPEM files of the client certificate and key, for mutual TLS. Set both.
rejectUnauthorizedVerification cannot be turned off: false is rejected. Trust a development certificate through caPath instead.

Starting Workflows

1
const handle = await client.startWorkflow<OrderOutput>({
2
workflowType: 'processOrder',
3
workflowId: 'order-123',
4
taskQueue: 'orders',
5
args: [{ orderId: '123', amount: 9999 }],
6
});
7
8
console.log(`started ${handle.workflowId} (run ${handle.runId})`);

startWorkflow() resolves as soon as the engine has accepted the workflow, with a WorkflowHandle for it. The type parameter is the type handle.result() resolves to.

OptionDefaultDescription
workflowType(required)The name the workflow was registered under: workflow({ name }) or @Workflow({ name })
workflowIda random UUIDIdentifies the workflow within the namespace; see duplicate starts
taskQueue'default'The queue whose workers run it
argsnoneThe input, as a one-element array: args: [input]. Only the first element is sent.
workflowExecutionTimeoutnoneBounds the whole workflow, retries included
workflowRunTimeoutnoneBounds a single run
workflowTaskTimeoutnoneBounds the processing of one workflow activation
workflowIdReusePolicyengine defaultWhether workflowId may be reused; see below
retryPolicynoneRetry a failed workflow as a fresh run (opt-in)
cronSchedulenoneStart the workflow on a cron schedule
memo, searchAttributesNot supported yet: passing either throws a ClientError

Timeouts take a Duration or a number of milliseconds. Prefer Duration, which states its unit where you write it.

Timeouts and Retries

1
const handle = await client.startWorkflow<OrderOutput>({
2
workflowType: 'processOrder',
3
workflowId: `order-${order.orderId}`,
4
taskQueue: 'orders',
5
args: [order],
6
// Bounds the whole workflow, retries included.
7
workflowExecutionTimeout: Duration.fromMinutes(30),
8
// Opt-in: retry a failed workflow as a fresh run.
9
retryPolicy: { maxAttempts: 3, initialInterval: 10_000 },
10
});

Without workflowExecutionTimeout a workflow runs until it finishes, however long that takes. Without retryPolicy a failed workflow is not retried; with one, each retry is a new run with its own journal. The retry policy fields are the same as for tasks (see retry policy).

On a Schedule

1
await client.startWorkflow({
2
workflowType: 'nightlyReport',
3
workflowId: 'nightly-report',
4
taskQueue: 'reports',
5
cronSchedule: '0 2 * * *', // every day at 02:00
6
});

Starting a Workflow Once

A workflow id names at most one open run. Starting a workflow whose id belongs to a run that is still open is refused with a WorkflowError whose code is WORKFLOW_ALREADY_EXISTS, and whose details.runId names the open run when the engine reports it. That holds under every workflowIdReusePolicy except TerminateIfRunning. The policies differ in what they allow once the earlier run has closed:

WorkflowIdReusePolicyA new start with the same id is allowed
AllowDuplicateonce the earlier run has closed, however it ended
AllowDuplicateFailedOnlyonce the earlier run has closed without completing (failed, canceled, terminated or timed out)
RejectDuplicatenever
TerminateIfRunningalways: an open run is terminated first

Leaving the policy unset lets the engine decide, which allows a new run once the previous one has closed. Use the workflow id as an idempotency key for the work it stands for, so a repeated request finds the run that is already going:

1
// Start the order's workflow once. A second call for the same order, say a
2
// retried webhook, gets the run that is already going instead of a new one.
3
async function startOnce(client: Client, order: OrderInput): Promise<WorkflowHandle<OrderOutput>> {
4
const workflowId = `order-${order.orderId}`;
5
try {
6
return await client.startWorkflow<OrderOutput>({
7
workflowType: 'processOrder',
8
workflowId,
9
taskQueue: 'orders',
10
args: [order],
11
workflowIdReusePolicy: WorkflowIdReusePolicy.RejectDuplicate,
12
});
13
} catch (err) {
14
if (err instanceof WorkflowError && err.code === ExecutionErrorCode.WORKFLOW_ALREADY_EXISTS) {
15
// details.runId names the run holding the id, when the server reports it.
16
return client.getWorkflowHandle<OrderOutput>({ workflowId, runId: err.details?.runId });
17
}
18
throw err;
19
}
20
}

Payload Size

A default engine refuses any single payload larger than 8 MiB: a workflow input, a task input or result, an event, a workflow result. Starting a workflow with a larger input rejects with an InvalidArgumentError saying so. A task or workflow whose own result is too large fails with the failure type PayloadTooLarge, which is not retried, because the same code would produce the same result. The operator can change the limit. Workers and clients send and receive gRPC messages of up to 32 MiB. Keep large data in your own storage and pass a reference to it.


WorkflowHandle

startWorkflow() returns a handle; getWorkflowHandle() makes one for a workflow by id.

1
// Wait for the result.
2
const result = await handle.result();
3
4
// Wait at most 5 seconds; the workflow keeps running either way.
5
const soon = await handle.resultWithTimeout(5_000);
6
7
// Status and a fuller description.
8
const status = await handle.status(); // WorkflowStatus.Running, .Completed, ...
9
const description = await handle.describe();
10
11
// Deliver an event to ctx.waitForEvent('approval') in the workflow.
12
await handle.sendEvent('approval', { approved: true });
13
14
// Ask a query handler the workflow registered.
15
const progress = await handle.query<{ done: number; total: number }>('progress');
16
17
// Ask the workflow to stop, or stop it outright.
18
await handle.cancel();
19
await handle.terminate('opened by mistake');

Getting a Handle by Id

1
const handle = client.getWorkflowHandle<OrderOutput>({ workflowId: 'order-123' });
2
const result = await handle.result();

Without a runId, the handle addresses the workflow's latest run.

How a Workflow Ended

handle.result() resolves with the workflow's return value. A workflow that ended without a result rejects with a subclass of WorkflowOutcomeError that says how it ended:

ErrorCodeThe workflow
WorkflowFailedErrorWORKFLOW_EXECUTION_FAILEDthrew, or a task failed after its retries; failure holds the recorded message
WorkflowCanceledErrorWORKFLOW_CANCELEDwas canceled, for example with handle.cancel()
WorkflowTerminatedErrorWORKFLOW_TERMINATEDwas terminated with handle.terminate()
WorkflowTimedOutErrorWORKFLOW_TIMEOUTran past its workflowExecutionTimeout

All four carry workflowId and runId, and all are WorkflowErrors and OrcherErrors, so broader instanceof checks still match.

1
try {
2
return await handle.result();
3
} catch (err) {
4
if (err instanceof WorkflowFailedError) {
5
// The workflow threw, or a task failed after its retries.
6
console.error(`order failed: ${err.failure}`);
7
} else if (err instanceof WorkflowCanceledError) {
8
console.warn(`order ${err.workflowId} was canceled`);
9
} else if (err instanceof WorkflowTerminatedError) {
10
console.warn(`order ${err.workflowId} was terminated`);
11
} else if (err instanceof WorkflowTimedOutError) {
12
console.warn(`order ${err.workflowId} ran past its execution timeout`);
13
} else {
14
throw err; // not an ending: the result could not be read
15
}
16
return undefined;
17
}

resultWithTimeout(ms) bounds only how long the call waits. When it gives up it throws a TimeoutError, which is not a workflow outcome: the workflow keeps running.

1
try {
2
await handle.resultWithTimeout(10_000);
3
} catch (err) {
4
if (err instanceof TimeoutError) {
5
// This call gave up; the workflow is still running.
6
} else if (err instanceof WorkflowOutcomeError) {
7
// The workflow ended without a result.
8
} else {
9
throw err;
10
}
11
}

Other failures arrive as OrcherError subclasses named after the cause, such as ConnectionError, UnauthenticatedError, PermissionDeniedError and InvalidArgumentError. A workflow id that does not exist gives a WorkflowError with code WORKFLOW_NOT_FOUND.

Canceling and Terminating

handle.cancel() asks the workflow to stop; handle.terminate(reason?) ends it at once, with no further workflow code running. Running tasks learn of either through their heartbeats; see cancellation. cancel() takes a cleanupTimeout, a Duration or a number of milliseconds: how long the workflow may take to end after the request before the engine terminates it. Without one there is no limit. Engines from before cancellation cleanup ignore it and end the run as canceled at once.

1
// Ask the workflow to stop, and give it at most 30 seconds to finish before
2
// the engine terminates it.
3
await handle.cancel({ cleanupTimeout: Duration.fromSeconds(30) });

Resetting a Workflow

Reset replays a workflow's journal up to an event and runs on from there, making fresh decisions after that point. Use it to recover runs that failed because of a bug, once the fix is deployed:

1
const handle = client.getWorkflowHandle({ workflowId: 'order-12345' });
2
3
// Keep journal events up to and including 5; replay them, then run on from there.
4
const newExecutionId = await handle.reset(5, 'bad deployment caused failures');
5
console.log(`new execution: ${newExecutionId}`);

Client Reference

MethodDescription
new Client(config)Create a client: serverUrl, namespace, and optionally apiKey, tls, identity
client.connect()Connect to the engine
client.startWorkflow<T>(options)Start a workflow; resolves with a WorkflowHandle<T>
client.getWorkflowHandle<T>({ workflowId, runId? })A handle for an existing workflow
client.listWorkflows(options?)List workflows, filtered by type, queue or status
client.actorRef(ActorClass, key)A typed reference to an actor; see Actors
client.close()Close the connection

WorkflowHandle

MemberDescription
handle.workflowId / handle.runIdThe workflow id, and the run the handle names (if any)
handle.result()Wait for the result; rejects with a WorkflowOutcomeError subclass if there is none
handle.resultWithTimeout(ms)The same, giving up with a TimeoutError after ms milliseconds
handle.status()The current WorkflowStatus
handle.describe()Status, timing, journal length and configuration
handle.sendEvent(name, payload?)Send an event to ctx.waitForEvent(name)
handle.query<T>(name, args?)Call a query handler the workflow registered
handle.cancel(options?)Ask the workflow to stop; cleanupTimeout bounds how long it may take
handle.terminate(reason?)Stop the workflow at once, without cleanup
handle.reset(eventId, reason?)Reset to a journal event; resolves with the new execution id

Next Steps