Skip to main content

Namespace: workflow

This library provides tools required for authoring workflows.

Usage#

See the tutorial for writing your first workflow.

Timers#

The recommended way of scheduling timers is by using the sleep function. We've replaced setTimeout and clearTimeout with deterministic versions so these are also usable but have a limitation that they don't play well with cancellation scopes.

import { sleep } from '@temporalio/workflow';
export async function sleeper(ms = 100): Promise<void> {  await sleep(ms);  console.log('slept');}

Activities#

To schedule Activities, use createActivityHandle to obtain an Activity function and call.

import { createActivityHandle } from '@temporalio/workflow';import type * as activities from '../activities';
const { httpGet } = createActivityHandle<typeof activities>({  startToCloseTimeout: '1 minute',});
export async function http(): Promise<string> {  return await httpGet('https://temporal.io');}

Signals and Queries#

To add signal handlers to a Workflow, add a signals property to the exported workflow object. Signal handlers can return either void or Promise<void>, you may schedule activities and timers from a signal handler.

To add query handlers to a Workflow, add a queries property to the exported workflow object. Query handlers must not mutate any variables or generate any commands (like Activities or Timers), they run synchronously and thus must return a Promise.

Interface#

Implementation#

import { defineSignal, setListener } from '@temporalio/workflow';
export const interruptSignal = defineSignal<[string]>('interrupt');
export async function interruptableWorkflow(): Promise<void> {  // When this Promise is rejected Workflow execution will fail  await new Promise<never>((_resolve, reject) => {    setListener(interruptSignal, (reason) => reject(new Error(reason)));  });}

Deterministic built-ins#

It is safe to call Math.random() and Date() in workflow code as they are replaced with deterministic versions. We also provide a deterministic uuid4 function for convenience.

Cancellation and scopes#

External dependencies#

Classes#

Interfaces#

References#

ActivityCancellationType#

Re-exports: ActivityCancellationType


ActivityFailure#

Re-exports: ActivityFailure


ActivityFunction#

Re-exports: ActivityFunction


ActivityInterface#

Re-exports: ActivityInterface


ActivityOptions#

Re-exports: ActivityOptions


ApplicationFailure#

Re-exports: ApplicationFailure


CancelledFailure#

Re-exports: CancelledFailure


ChildWorkflowFailure#

Re-exports: ChildWorkflowFailure


DataConverter#

Re-exports: DataConverter


Headers#

Re-exports: Headers


IllegalStateError#

Re-exports: IllegalStateError


Next#

Re-exports: Next


RetryOptions#

Re-exports: RetryOptions


ServerFailure#

Re-exports: ServerFailure


TemporalFailure#

Re-exports: TemporalFailure


TerminatedFailure#

Re-exports: TerminatedFailure


TimeoutFailure#

Re-exports: TimeoutFailure


ValueError#

Re-exports: ValueError


Workflow#

Re-exports: Workflow


WorkflowIdReusePolicy#

Re-exports: WorkflowIdReusePolicy


WorkflowResultType#

Re-exports: WorkflowResultType


defaultDataConverter#

Re-exports: defaultDataConverter


rootCause#

Re-exports: rootCause

Type aliases#

ChildWorkflowCancellationType#

Ƭ ChildWorkflowCancellationType: ChildWorkflowCancellationType


ConcludeActivationOutput#

Ƭ ConcludeActivationOutput: ConcludeActivationInput

Output for WorkflowInternalsInterceptor.concludeActivation


ExternalDependencies#

Ƭ ExternalDependencies: Record<string, ExternalDependency>

Workflow dependencies are a mapping of name to ExternalDependency


ExternalDependency#

Ƭ ExternalDependency: Record<string, ExternalDependencyFunction>

A mapping of name to function, defines a single external dependency (e.g. logger)


ExternalDependencyFunction#

Ƭ ExternalDependencyFunction: (...args: any[]) => void

Type declaration#

▸ (...args): void

Any function signature can be used for dependency functions as long as the return type is void.

When calling a dependency function, arguments and return value are copied between the Workflow isolate and the Node.js. This constrains the argument types to primitives (excluding Symbols).

Parameters#
NameType
...argsany[]
Returns#

void


InternalActivityFunction#

Ƭ InternalActivityFunction<P, R>: ActivityFunction<P, R> & ActivityInfo

Type parameters#

NameType
Pextends any[]
RR

Listener#

Ƭ Listener<Ret, Args, T>: T extends SignalDefinition<infer A> ? (...args: A) => void | Promise<void> : T extends QueryDefinition<infer R, infer A> ? (...args: A) => R : never

A listener function capable of accepting the arguments for a given SignalDefinition or QueryDefinition.

Type parameters#

NameType
RetRet
Argsextends any[]
Textends SignalDefinition<Args> | QueryDefinition<Ret, Args>

ParentClosePolicy#

Ƭ ParentClosePolicy: ParentClosePolicy


WorkflowInterceptorsFactory#

Ƭ WorkflowInterceptorsFactory: () => WorkflowInterceptors

Type declaration#

▸ (): WorkflowInterceptors

A function that returns WorkflowInterceptors and takes no arguments.

Workflow interceptor modules should export an interceptors function of this type.

Returns#

WorkflowInterceptors

Variables#

ChildWorkflowCancellationType#

ChildWorkflowCancellationType: typeof ChildWorkflowCancellationType


ParentClosePolicy#

ParentClosePolicy: typeof ParentClosePolicy


ROOT_SCOPE#

Const ROOT_SCOPE: RootCancellationScope

There can only be one of these

Functions#

addDefaultWorkflowOptions#

addDefaultWorkflowOptions(opts): ChildWorkflowOptionsWithDefaults

Adds default values to workflowId and workflowIdReusePolicy to given workflow options.

Parameters#

NameType
optsChildWorkflowOptions

Returns#

ChildWorkflowOptionsWithDefaults


condition#

condition(timeout, fn): Promise<boolean>

Returns a Promise that resolves when fn evaluates to true or timeout expires.

Parameters#

NameTypeDescription
timeoutnumber | stringms formatted string or number of milliseconds
fn() => boolean-

Returns#

Promise<boolean>

a boolean indicating whether the condition was true before the timeout expires

condition(fn): Promise<void>

Returns a Promise that resolves when fn evaluates to true.

Parameters#

NameType
fn() => boolean

Returns#

Promise<void>


continueAsNew#

continueAsNew<F>(...args): Promise<never>

Continues current Workflow execution as new with default options.

Shorthand for makeContinueAsNewFunc<F>()(...args).

example

import { continueAsNew } from '@temporalio/workflow';
export function myWorkflow(n: number) {  return {    async execute() {      // ... Workflow logic      await continueAsNew<typeof myWorkflow>(n + 1);    }  };}

Type parameters#

NameType
Fextends Workflow

Parameters#

NameType
...argsParameters<F>

Returns#

Promise<never>


createActivityHandle#

createActivityHandle<A>(options): A

Configure Activity functions with given ActivityOptions.

This method may be called multiple times to setup Activities with different options.

example

import { createActivityHandle, ActivityInterface } from '@temporalio/workflow';import * as activities from '../activities';
// Setup Activities from module exportsconst { httpGet, otherActivity } = createActivityHandle<typeof activities>({  startToCloseTimeout: '30 minutes',});
// Setup Activities from an explicit interface (e.g. when defined by another SDK)interface JavaActivities extends ActivityInterface {  httpGetFromJava(url: string): Promise<string>  someOtherJavaActivity(arg1: number, arg2: string): Promise<string>;}
const {  httpGetFromJava,  someOtherJavaActivity} = createActivityHandle<JavaActivities>({  taskQueue: 'java-worker-taskQueue',  startToCloseTimeout: '5m',});
export function execute(): Promise<void> {  const response = await httpGet('http://example.com');  // ...}

Type parameters#

NameTypeDescription
Aextends Record<string, ActivityFunction<any, any>>An ActivityInterface - mapping of name to function

Parameters#

NameType
optionsActivityOptions

Returns#

A

a Proxy for which each attribute is a callable Activity function


createChildWorkflowHandle#

createChildWorkflowHandle<T>(workflowType, options?): ChildWorkflowHandle<T>

Returns a client-side handle that implements a child Workflow interface. Takes a child Workflow type and optional child Workflow options as arguments. Workflow options may be needed to override the timeouts and task queue if they differ from the parent Workflow.

A child Workflow supports starting, awaiting completion, signaling and cancellation via CancellationScopes. In order to query the child, use a WorkflowClient from an Activity.

Type parameters#

NameType
Textends Workflow

Parameters#

NameType
workflowTypestring
options?ChildWorkflowOptions

Returns#

ChildWorkflowHandle<T>

createChildWorkflowHandle<T>(workflowFunc, options?): ChildWorkflowHandle<T>

Returns a client-side handle that implements a child Workflow interface. Deduces the Workflow interface from provided Workflow function. Workflow options may be needed to override the timeouts and task queue if they differ from the parent Workflow.

A child Workflow supports starting, awaiting completion, signaling and cancellation via CancellationScopes. In order to query the child, use a WorkflowClient from an Activity.

Type parameters#

NameType
Textends Workflow

Parameters#

NameType
workflowFuncT
options?ChildWorkflowOptions

Returns#

ChildWorkflowHandle<T>


createExternalWorkflowHandle#

createExternalWorkflowHandle(workflowId, runId?): ExternalWorkflowHandle

Returns a client-side handle that can be used to signal and cancel an existing Workflow execution. It takes a Workflow ID and optional run ID.

Parameters#

NameType
workflowIdstring
runId?string

Returns#

ExternalWorkflowHandle


defineQuery#

defineQuery<Ret, Args>(name): QueryDefinition<Ret, Args>

Define a query method for a Workflow.

Definitions are used to register listeners in the Workflow via setListener and to query Workflows using a WorkflowHandle. Definitions can be reused in multiple Workflows.

Type parameters#

NameType
RetRet
Argsextends any[][]

Parameters#

NameType
namestring

Returns#

QueryDefinition<Ret, Args>


defineSignal#

defineSignal<Args>(name): SignalDefinition<Args>

Define a signal method for a Workflow.

Definitions are used to register listeners in the Workflow via setListener and to signal Workflows using a WorkflowHandle, ChildWorkflowHandle or ExternalWorkflowHandle. Definitions can be reused in multiple Workflows.

Type parameters#

NameType
Argsextends any[][]

Parameters#

NameType
namestring

Returns#

SignalDefinition<Args>


dependencies#

dependencies<T>(): T

Get a reference to injected external dependencies.

example

import { dependencies, ExternalDependencies } from '@temporalio/workflow';
interface MyDependencies extends ExternalDependencies {  logger: {    info(message: string): void;    error(message: string): void;  };}
const { logger } = dependencies<MyDependencies>();logger.info('setting up');
export function myWorkflow() {  return {    async execute() {      logger.info('hey ho');      logger.error('lets go');    }  };}

Type parameters#

NameType
Textends ExternalDependencies

Returns#

T


deprecatePatch#

deprecatePatch(patchId): void

Indicate that a patch is being phased out.

See docs page for info.

Workflows with this call may be deployed alongside workflows with a patched call, but they must not be deployed while any workers still exist running old code without a patched call, or any runs with histories produced by such workers exist. If either kind of worker encounters a history produced by the other, their behavior is undefined.

Once all live workflow runs have been produced by workers with this call, you can deploy workers which are free of either kind of patch call for this ID. Workers with and without this call may coexist, as long as they are both running the "new" code.

Parameters#

NameTypeDescription
patchIdstringAn identifier that should be unique to this patch. It is OK to use multiple calls with the same ID, which means all such calls will always return the same value.

Returns#

void


isCancellation#

isCancellation(err): boolean

Returns whether provided err is caused by cancellation

Parameters#

NameType
errunknown

Returns#

boolean


makeContinueAsNewFunc#

makeContinueAsNewFunc<F>(options?): (...args: Parameters<F>) => Promise<never>

Returns a function f that will cause the current Workflow to ContinueAsNew when called.

f takes the same arguments as the Workflow execute function supplied to typeparam F.

Once f is called, Workflow execution immediately completes.

Type parameters#

NameType
Fextends Workflow

Parameters#

NameType
options?ContinueAsNewOptions

Returns#

fn

▸ (...args): Promise<never>

Returns a function f that will cause the current Workflow to ContinueAsNew when called.

f takes the same arguments as the Workflow execute function supplied to typeparam F.

Once f is called, Workflow execution immediately completes.

Parameters#
NameType
...argsParameters<F>
Returns#

Promise<never>


patched#

patched(patchId): boolean

Patch or upgrade workflow code by checking or stating that this workflow has a certain patch.

See docs page for info.

If the workflow is replaying an existing history, then this function returns true if that history was produced by a worker which also had a patched call with the same patchId. If the history was produced by a worker without such a call, then it will return false.

If the workflow is not currently replaying, then this call always returns true.

Your workflow code should run the "new" code if this returns true, if it returns false, you should run the "old" code. By doing this, you can maintain determinism.

Parameters#

NameTypeDescription
patchIdstringAn identifier that should be unique to this patch. It is OK to use multiple calls with the same ID, which means all such calls will always return the same value.

Returns#

boolean


setListener#

setListener<Ret, Args, T>(def, listener): void

Set a listener function for a Workflow query or signal.

If this function is called multiple times for a given signal or query name the last listener will overwrite any previous calls.

Type parameters#

NameType
RetRet
Argsextends any[]
Textends SignalDefinition<Args> | QueryDefinition<Ret, Args>

Parameters#

NameTypeDescription
defTa SignalDefinition or QueryDefinition as returned by defineSignal or defineQuery respectively.
listenerListener<Ret, Args, T>a compatible listener function for the given definition.

Returns#

void


sleep#

sleep(ms): Promise<void>

Asynchronous sleep.

Schedules a timer on the Temporal service.

Parameters#

NameTypeDescription
msnumber | stringsleep duration - ms formatted string or number of milliseconds. If given a negative number, value will be set to 1.

Returns#

Promise<void>


uuid4#

uuid4(): string

Generate an RFC compliant V4 uuid. Uses the workflow's deterministic PRNG making it safe for use within a workflow. This function is cryptographically insecure. See the stackoverflow discussion.

Returns#

string


workflowInfo#

workflowInfo(): WorkflowInfo

Get information about the current Workflow

Returns#

WorkflowInfo