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 proxyActivities to obtain an Activity function and call.
import { proxyActivities } from '@temporalio/workflow';
import type * as activities from './activities';
const { sendEmail } = proxyActivities<typeof activities>({
startToCloseTimeout: '1 minute',
});
export async function sampleWorkflow(): Promise<string> {
await sendEmail("to@example.com","Hello, Temporal!");
}
Updates, Signals and Queries
Use setHandler to set handlers for Updates, Signals, and Queries.
Update and Signal handlers can be either async or non-async functions. Update handlers may return a value, but signal
handlers may not (return void or Promise<void>). You may use Activities, Timers, child Workflows, etc in Update
and Signal handlers, but this should be done cautiously: for example, note that if you await async operations such as
these in an Update or Signal handler, then you are responsible for ensuring that the workflow does not complete first.
Query handlers may not be async functions, and may not mutate any variables or use Activities, Timers, child Workflows, etc.
Implementation
export const incrementSignal = wf.defineSignal<[number]>('increment');
export const getValueQuery = wf.defineQuery<number>('getValue');
export const incrementAndGetValueUpdate = wf.defineUpdate<number, [number]>('incrementAndGetValue');
export async function counterWorkflow(initialValue: number): Promise<void> {
let count = initialValue;
wf.setHandler(incrementSignal, (arg: number) => {
count += arg;
});
wf.setHandler(getValueQuery, () => count);
wf.setHandler(incrementAndGetValueUpdate, (arg: number): number => {
count += arg;
return count;
});
await wf.condition(() => false);
}
More
Classes
- CancellationScope
- ContinueAsNew
- DeterminismViolationError
- LocalActivityDoBackoff
- Trigger
- WorkflowError
Interfaces
- ActivateInput
- ActivityInput
- ActivityOptions
- ActivityProxyOptions
- CancellationScopeOptions
- ChildWorkflowHandle
- ChildWorkflowOptions
- ConcludeActivationInput
- ContinueAsNewInput
- ContinueAsNewOptions
- DisposeInput
- EnhancedStackTrace
- EventGroup
- EventGroupsOptions
- ExternalWorkflowHandle
- LocalActivityInput
- LocalActivityOptions
- LocalActivityProxyOptions
- LoggerSinks
- NexusOperationHandle
- NexusServiceClient
- NexusServiceClientOptions
- ParentWorkflowInfo
- QueryInput
- RootWorkflowInfo
- SignalInput
- SignalWithStartWorkflowResponse
- SignalWorkflowInput
- SinkCall
- StackTrace
- StackTraceFileLocation
- StackTraceFileSlice
- StackTraceSDKInfo
- StartChildWorkflowExecutionInput
- StartNexusOperationInput
- StartNexusOperationOptions
- StartNexusOperationOutput
- TimerInput
- TimerOptions
- UnsafeRandomSource
- UnsafeWorkflowInfo
- UpdateInput
- WorkflowExecuteInput
- WorkflowInboundCallsInterceptor
- WorkflowInfo
- WorkflowInterceptors
- WorkflowInternalsInterceptor
- WorkflowOutboundCallsInterceptor
- WorkflowRandomStream
References
ActivityCancellationType
Re-exports ActivityCancellationType
ActivityFailure
Re-exports ActivityFailure
ActivityFunction
Re-exports ActivityFunction
ActivityInterface
Re-exports ActivityInterface
ActivityTypeInfoMap
Re-exports ActivityTypeInfoMap
ApplicationFailure
Re-exports ApplicationFailure
BaseWorkflowHandle
Re-exports BaseWorkflowHandle
BaseWorkflowOptions
Re-exports BaseWorkflowOptions
CancelledFailure
Re-exports CancelledFailure
ChildWorkflowFailure
Re-exports ChildWorkflowFailure
CommonWorkflowOptions
Re-exports CommonWorkflowOptions
CompleteAsyncError
Re-exports CompleteAsyncError
ExternalStorageDriverError
Re-exports ExternalStorageDriverError
ExternalStorageError
Re-exports ExternalStorageError
ExternalStorageNotConfiguredError
Re-exports ExternalStorageNotConfiguredError
ExternalStorageReferenceError
Re-exports ExternalStorageReferenceError
ExternalStorageUnregisteredDriverError
Re-exports ExternalStorageUnregisteredDriverError
Headers
Re-exports Headers
IllegalStateError
Re-exports IllegalStateError
NamespaceNotFoundError
Re-exports NamespaceNotFoundError
Next
Re-exports Next
Payload
Re-exports Payload
PayloadConverter
Re-exports PayloadConverter
PayloadConverterError
Re-exports PayloadConverterError
QueryDefinition
Re-exports QueryDefinition
RetryPolicy
Re-exports RetryPolicy
SearchAttributeValue
Re-exports SearchAttributeValue
SearchAttributes
Re-exports SearchAttributes
ServerFailure
Re-exports ServerFailure
SignalDefinition
Re-exports SignalDefinition
TemporalFailure
Re-exports TemporalFailure
TerminatedFailure
Re-exports TerminatedFailure
TimeoutFailure
Re-exports TimeoutFailure
UntypedActivities
Re-exports UntypedActivities
ValueError
Re-exports ValueError
WithWorkflowArgs
Re-exports WithWorkflowArgs
Workflow
Re-exports Workflow
WorkflowDurationOptions
Re-exports WorkflowDurationOptions
WorkflowIdConflictPolicy
Re-exports WorkflowIdConflictPolicy
WorkflowIdReusePolicy
Re-exports WorkflowIdReusePolicy
WorkflowNotFoundError
Re-exports WorkflowNotFoundError
WorkflowQueryOptions
Re-exports WorkflowQueryOptions
WorkflowQueryType
Re-exports WorkflowQueryType
WorkflowResultType
Re-exports WorkflowResultType
WorkflowReturnType
Re-exports WorkflowReturnType
WorkflowSignalOptions
Re-exports WorkflowSignalOptions
WorkflowSignalType
Re-exports WorkflowSignalType
WorkflowTypeOptions
Re-exports WorkflowTypeOptions
decodeWorkflowIdConflictPolicy
Re-exports decodeWorkflowIdConflictPolicy
decodeWorkflowIdReusePolicy
Re-exports decodeWorkflowIdReusePolicy
defaultPayloadConverter
Re-exports defaultPayloadConverter
encodeWorkflowIdConflictPolicy
Re-exports encodeWorkflowIdConflictPolicy
encodeWorkflowIdReusePolicy
Re-exports encodeWorkflowIdReusePolicy
extractWorkflowType
Re-exports extractWorkflowType
extractWorkflowTypeAndConfig
Re-exports extractWorkflowTypeAndConfig
rootCause
Re-exports rootCause
Type Aliases
ActivityFunctionWithOptions
Ƭ ActivityFunctionWithOptions<T>: T & { executeWithOptions: (options: ActivityOptions, args: Parameters<T>) => Promise<Awaited<ReturnType<T>>> }
Type parameters
| Name | Type |
|---|---|
T | extends ActivityFunction |
ActivityInterfaceFor
Ƭ ActivityInterfaceFor<T>: { [K in keyof T]: T[K] extends ActivityFunction ? ActivityFunctionWithOptions<T[K]> : typeof NotAnActivityMethod }
Type helper that takes a type T and transforms attributes that are not ActivityFunction to
NotAnActivityMethod.
Example
Used by proxyActivities to get this compile-time error:
interface MyActivities {
valid(input: number): Promise<number>;
invalid(input: number): number;
}
const act = proxyActivities<MyActivities>({ startToCloseTimeout: '5m' });
await act.valid(true);
await act.invalid();
// ^ TS complains with:
// (property) invalidDefinition: typeof NotAnActivityMethod
// This expression is not callable.
// Type 'Symbol' has no call signatures.(2349)
Type parameters
| Name |
|---|
T |
ChildWorkflowCancellationType
Ƭ ChildWorkflowCancellationType: typeof ChildWorkflowCancellationType[keyof typeof ChildWorkflowCancellationType]
ConcludeActivationOutput
Ƭ ConcludeActivationOutput: ConcludeActivationInput
Output for WorkflowInternalsInterceptor.concludeActivation
ContinueAsNewInputOptions
Ƭ ContinueAsNewInputOptions: ContinueAsNewOptions & Required<Pick<ContinueAsNewOptions, "workflowType">>
Input for WorkflowOutboundCallsInterceptor.continueAsNew.
GetLogAttributesInput
Ƭ GetLogAttributesInput: Record<string, unknown>
Input for WorkflowOutboundCallsInterceptor.getLogAttributes.
GetMetricTagsInput
Ƭ GetMetricTagsInput: MetricTags
Input for WorkflowOutboundCallsInterceptor.getMetricTags.
LocalActivityFunctionWithOptions
Ƭ LocalActivityFunctionWithOptions<T>: T & { executeWithOptions: (options: LocalActivityOptions, args: Parameters<T>) => Promise<Awaited<ReturnType<T>>> }
Type parameters
| Name | Type |
|---|---|
T | extends ActivityFunction |
LocalActivityInterfaceFor
Ƭ LocalActivityInterfaceFor<T>: { [K in keyof T]: T[K] extends ActivityFunction ? LocalActivityFunctionWithOptions<T[K]> : typeof NotAnActivityMethod }
The local activity counterpart to ActivityInterfaceFor
Type parameters
| Name |
|---|
T |
NexusOperationCancellationType
Ƭ NexusOperationCancellationType: typeof NexusOperationCancellationType[keyof typeof NexusOperationCancellationType]
ParentClosePolicy
Ƭ ParentClosePolicy: typeof ParentClosePolicy[keyof typeof ParentClosePolicy]
SignalWithStartWorkflowRequest
Ƭ SignalWithStartWorkflowRequest<WorkflowFn, SignalValue, SignalArgs>: ReplaceSignalWithStartWorkflowRequest<{ args?: ReadonlyArray<unknown> | Readonly<Parameters<WorkflowFn>> ; cronSchedule?: string ; executionTimeout?: Duration ; headers?: Record<string, unknown> ; id: string ; idConflictPolicy?: WorkflowIdConflictPolicy ; idReusePolicy?: WorkflowIdReusePolicy ; memo?: Record<string, unknown> ; namespace: string ; priority?: Priority ; retryPolicy?: RetryPolicy ; runTimeout?: Duration ; searchAttributes?: TypedSearchAttributes ; signal: string | SignalValue ; signalArgs?: ReadonlyArray<unknown> | Readonly<SignalArgs> ; startDelay?: Duration ; staticDetails?: string ; staticSummary?: string ; taskQueue: string ; taskTimeout?: Duration ; versioningOverride?: VersioningOverride ; workflow: string | WorkflowFn }, { args?: ReadonlyArray<unknown> ; workflow: string } | { workflow: WorkflowFn } & Parameters<WorkflowFn> extends [any, ...(...)[]] ? { args: Parameters<...> | Readonly<...> } : { args?: Parameters<...> | Readonly<...> } & { signal: string ; signalArgs?: ReadonlyArray<unknown> } | { signal: SignalValue } & SignalArgs extends [any, ...(...)[]] ? { signalArgs: SignalArgs | Readonly<...> } : { signalArgs?: SignalArgs | Readonly<...> }>
This API is experimental and subject to change.
Type parameters
| Name | Type |
|---|---|
WorkflowFn | extends (...args: any[]) => Promise<any> = (...args: any[]) => Promise<any> |
SignalValue | extends SignalDefinition<any[]> = SignalDefinition<any[]> |
SignalArgs | extends any[] = SignalValue extends SignalDefinition<infer Args, any> ? Args : never |
Sink
Ƭ Sink: Record<string, SinkFunction>
A mapping of name to function, defines a single sink (e.g. logger)
SinkFunction
Ƭ SinkFunction: (...args: any[]) => void
Any function signature can be used for Sink functions as long as the return type is void.
When calling a Sink function, arguments are copied from the Workflow isolate to the Node.js environment using postMessage.
This constrains the argument types to primitives (excluding Symbols).
Type declaration
▸ (...args): void
Parameters
| Name | Type |
|---|---|
...args | any[] |
Returns
void
Sinks
Ƭ Sinks: Record<string, Sink>
Workflow Sink are a mapping of name to Sink
WorkflowInterceptorsFactory
Ƭ WorkflowInterceptorsFactory: () => WorkflowInterceptors
A function that instantiates WorkflowInterceptors.
Workflow interceptor modules should export an interceptors function of this type.
Example
export function interceptors(): WorkflowInterceptors {
return {
inbound: [], // Populate with list of inbound interceptor implementations
outbound: [], // Populate with list of outbound interceptor implementations
internals: [], // Populate with list of internals interceptor implementations
};
}
Type declaration
▸ (): WorkflowInterceptors
Returns
Variables
AsyncLocalStorage
• Const AsyncLocalStorage: <T>() => ALS<T>
Type declaration
• <T>(): ALS<T>
Type parameters
| Name |
|---|
T |
Returns
ALS<T>
ChildWorkflowCancellationType
• Const ChildWorkflowCancellationType: Object
Determines:
- whether cancellation requests should be propagated from the Parent Workflow to the Child, and
- whether and when should the Child's cancellation be reported back to the Parent Workflow
(i.e. at which moment should the executeChild's or ChildWorkflowHandle.result's
promise fail with a
ChildWorkflowFailure, withcauseset to aCancelledFailure).
Note that this setting only applies to cancellation originating from an external request for the
Parent Workflow itself, or from internal cancellation of the CancellationScope in which the
Child Workflow call was made. Eventual Cancellation of a Child Workflow on completion of the
Parent Workflow is controlled by the ParentClosePolicy setting.
Default
ChildWorkflowCancellationType.WAIT_CANCELLATION_COMPLETED