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
Type Aliases
ActivityFunctionWithOptions
ActivityFunctionWithOptions<
T> =T&object
Type Parameters
T
T extends ActivityFunction
Type Declaration
executeWithOptions()
executeWithOptions(
options,args):Promise<Awaited<ReturnType<T>>>
Experimental
Execute the activity, overriding its existing options with the provided options.
Parameters
options
ActivityOptions
args
Parameters<T>
list of arguments
Returns
Promise<Awaited<ReturnType<T>>>
return value of the activity
executeWithOptions is a new method to provide call-site options and is subject to change
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.
Type Parameters
T
T
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)
ChildWorkflowCancellationType
ChildWorkflowCancellationType = typeof
ChildWorkflowCancellationType[keyof typeofChildWorkflowCancellationType]
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
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&object
Type Parameters
T
T extends ActivityFunction
Type Declaration
executeWithOptions()
executeWithOptions(
options,args):Promise<Awaited<ReturnType<T>>>
Experimental
Run the local activity, overriding its existing options with the provided options.
Parameters
options
LocalActivityOptions
args
Parameters<T>
list of arguments
Returns
Promise<Awaited<ReturnType<T>>>
return value of the activity
executeWithOptions is a new method to provide call-site options and is subject to change
LocalActivityInterfaceFor
LocalActivityInterfaceFor<
T> ={ [K in keyof T]: T[K] extends ActivityFunction ? LocalActivityFunctionWithOptions<T[K]> : typeof NotAnActivityMethod }
The local activity counterpart to ActivityInterfaceFor
Type Parameters
T
T
NexusOperationCancellationType
NexusOperationCancellationType = typeof
NexusOperationCancellationType[keyof typeofNexusOperationCancellationType]
Determines:
- whether cancellation requests should be propagated from the Workflow to the Nexus Operation
- whether and when should the Operation's cancellation be reported back to the Workflow
(i.e. at which moment should the operation's result promise fail with a
NexusOperationFailure, withcauseset to aCancelledFailure).
Note that this setting only applies to cancellation originating from an external request for the
Workflow itself, or from internal cancellation of the CancellationScope in which the
Operation call was made.
ParentClosePolicy
ParentClosePolicy = typeof
ParentClosePolicy[keyof typeofParentClosePolicy]
How a Child Workflow reacts to the Parent Workflow reaching a Closed state.
See
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; } |object&Parameters<WorkflowFn> extends [any,...(...)[]] ?object:object& {signal:string;signalArgs?:ReadonlyArray<unknown>; } |object&SignalArgsextends [any,...(...)[]] ?object:object>
Experimental
This API is experimental and subject to change.
Type Parameters
WorkflowFn
WorkflowFn extends (...args) => Promise<any> = (...args) => Promise<any>
SignalValue
SignalValue extends SignalDefinition<any[]> = SignalDefinition<any[]>
SignalArgs
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) =>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).
Parameters
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.
Returns
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
};
}
Variables
AsyncLocalStorage
constAsyncLocalStorage: <T>() =>ALS<T>
Returns
ALS<T>
ChildWorkflowCancellationType
constChildWorkflowCancellationType: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.
Type Declaration
ABANDON
readonlyABANDON:"ABANDON"
Do not propagate cancellation requests to the Child, and immediately report cancellation to the caller.
TRY_CANCEL
readonlyTRY_CANCEL:"TRY_CANCEL"
Propagate cancellation request from the Parent Workflow to the Child, yet immediately report cancellation to the caller, i.e. without waiting for the server to confirm the cancellation request.
Note that this cancellation type provides no guarantee, from the Parent-side, that the cancellation request will actually be atomically added to the Child workflow's history. In particular, the Child may complete (either successfully or uncessfully) before the cancellation is delivered, resulting in a situation where the Parent workflow thinks its child was cancelled, but the child actually completed successfully.
To guarantee that the Child will eventually be notified of the cancellation request, use WAIT_CANCELLATION_REQUESTED.
WAIT_CANCELLATION_COMPLETED
readonlyWAIT_CANCELLATION_COMPLETED:"WAIT_CANCELLATION_COMPLETED"
Propagate cancellation request from the Parent Workflow to the Child, then wait for completion of the Child Workflow.
The Child may respect cancellation, in which case the Parent's executeChild or
ChildWorkflowHandle.result promise will fail with a ChildWorkflowFailure, with cause
set to a CancelledFailure. On the other hand, the Child may ignore the cancellation request,
in which case the corresponding promise will either resolve with a result (if Child completed
successfully) or reject with a different cause (if Child completed uncessfully).
Default
WAIT_CANCELLATION_REQUESTED
readonlyWAIT_CANCELLATION_REQUESTED:"WAIT_CANCELLATION_REQUESTED"
Propagate cancellation request from the Parent Workflow to the Child, then wait for the server to confirm that the Child Workflow cancellation request was recorded in its history.
This cancellation type guarantees that the Child will eventually be notified of the cancellation request (that is, unless the Child terminates inbetween due to unexpected causes).
Default
ChildWorkflowCancellationType.WAIT_CANCELLATION_COMPLETED
enhancedStackTraceQuery
constenhancedStackTraceQuery:QueryDefinition<EnhancedStackTrace, [],string>
log
constlog:WorkflowLogger
Default workflow logger.
This logger is replay-aware and will omit log messages on workflow replay. Messages emitted by this logger are funnelled through a sink that forwards them to the logger registered on Runtime.logger.
Attributes from the current Workflow Execution context are automatically included as metadata on every log
entries. An extra sdkComponent metadata attribute is also added, with value workflow; this can be used for
fine-grained filtering of log entries further downstream.
To customize log attributes, register a WorkflowOutboundCallsInterceptor that intercepts the
getLogAttributes() method.
Notice that since sinks are used to power this logger, any log attributes must be transferable via the postMessage API.
NOTE: Specifying a custom logger through defaultSink or by manually registering a sink named
defaultWorkerLogger has been deprecated. Please use Runtime.logger instead.
metricMeter
constmetricMeter:MetricMeter
Experimental
A MetricMeter that can be used to emit metrics from within a Workflow.
The Metric API is an experimental feature and may be subject to change.
NexusOperationCancellationType
constNexusOperationCancellationType:object
Determines:
- whether cancellation requests should be propagated from the Workflow to the Nexus Operation
- whether and when should the Operation's cancellation be reported back to the Workflow
(i.e. at which moment should the operation's result promise fail with a
NexusOperationFailure, withcauseset to aCancelledFailure).
Note that this setting only applies to cancellation originating from an external request for the
Workflow itself, or from internal cancellation of the CancellationScope in which the
Operation call was made.
Type Declaration
ABANDON
readonlyABANDON:"ABANDON"
Do not propagate cancellation requests to the Nexus Operation, and immediately report cancellation to the caller.
TRY_CANCEL
readonlyTRY_CANCEL:"TRY_CANCEL"
Initiate a cancellation request for the Nexus operation and immediately report cancellation to the caller. Note that it doesn't guarantee that cancellation is delivered to the operation if calling workflow exits before the delivery is done. If you want to ensure that cancellation is delivered to the operation, use WAIT_CANCELLATION_REQUESTED.
Propagate cancellation request from the Workflow to the Operation, yet immediately report cancellation to the caller, i.e. without waiting for the server to confirm the cancellation request.
Note that this cancellation type provides no guarantee, from the Workflow-side, that the cancellation request will be delivered to the Operation Handler. In particular, either the Operation or the Workflow may complete (either successfully or uncessfully) before the cancellation request is delivered, resulting in a situation where the Operation completed successfully, but the Workflow thinks it was cancelled.
To guarantee that the Operation will eventually be notified of the cancellation request, use WAIT_CANCELLATION_REQUESTED.
WAIT_CANCELLATION_COMPLETED
readonlyWAIT_CANCELLATION_COMPLETED:"WAIT_CANCELLATION_COMPLETED"
Propagate cancellation request from the Workflow to the Operation, then wait for completion of the Operation.
WAIT_CANCELLATION_REQUESTED
readonlyWAIT_CANCELLATION_REQUESTED:"WAIT_CANCELLATION_REQUESTED"
Propagate cancellation request from the Workflow to the Operation, then wait for the server to confirm that the Operation cancellation request was delivered to the Operation Handler.
NotAnActivityMethod
constNotAnActivityMethod: uniquesymbol
Symbol used in the return type of proxy methods to mark that an attribute on the source type is not a method.
See
ParentClosePolicy
constParentClosePolicy:object
How a Child Workflow reacts to the Parent Workflow reaching a Closed state.
Type Declaration
ABANDON
readonlyABANDON:"ABANDON"
When the Parent is Closed, nothing is done to the Child.
PARENT_CLOSE_POLICY_ABANDON
readonlyPARENT_CLOSE_POLICY_ABANDON:"ABANDON"
When the Parent is Closed, nothing is done to the Child.
Deprecated
Use ParentClosePolicy.ABANDON instead.
PARENT_CLOSE_POLICY_REQUEST_CANCEL
readonlyPARENT_CLOSE_POLICY_REQUEST_CANCEL:"REQUEST_CANCEL"
When the Parent is Closed, the Child is Cancelled.
Deprecated
Use ParentClosePolicy.REQUEST_CANCEL instead.
PARENT_CLOSE_POLICY_TERMINATE
readonlyPARENT_CLOSE_POLICY_TERMINATE:"TERMINATE"
When the Parent is Closed, the Child is Terminated.
Deprecated
Use ParentClosePolicy.TERMINATE instead.
PARENT_CLOSE_POLICY_UNSPECIFIED
readonlyPARENT_CLOSE_POLICY_UNSPECIFIED:undefined
If a ParentClosePolicy is set to this, or is not set at all, the server default value will be used.
Deprecated
Either leave property undefined, or set an explicit policy instead.
REQUEST_CANCEL
readonlyREQUEST_CANCEL:"REQUEST_CANCEL"
When the Parent is Closed, the Child is Cancelled.
TERMINATE
readonlyTERMINATE:"TERMINATE"
When the Parent is Closed, the Child is Terminated.
Default
See
stackTraceQuery
conststackTraceQuery:QueryDefinition<string, [],string>
workflowMetadataQuery
constworkflowMetadataQuery:QueryDefinition<IWorkflowMetadata, [],string>
workflowRandom
constworkflowRandom:WorkflowRandomStream
Experimental
The default deterministic random stream for the current workflow execution.
This exposes the same underlying sequence used by workflow-level Math.random()
when no named override is active. It can be useful for plugin/interceptor code
that wants an explicit handle to the main workflow random stream, including from
inside a temporary named scope established by another WorkflowRandomStream.
This API may be removed or changed in the future.
Functions
addDefaultWorkflowOptions()
addDefaultWorkflowOptions<
T>(opts):ChildWorkflowOptionsWithDefaults
Adds default values of workflowId and cancellationType to given workflow options.
Type Parameters
T
T extends Workflow
Parameters
opts
WithWorkflowArgs<T, ChildWorkflowOptions>
Returns
ChildWorkflowOptionsWithDefaults
allHandlersFinished()
allHandlersFinished():
boolean
Whether update and signal handlers have finished executing.
Consider waiting on this condition before workflow return or continue-as-new, to prevent interruption of in-progress handlers by workflow exit:
await workflow.condition(workflow.allHandlersFinished)
Returns
boolean
true if there are no in-progress update or signal handler executions.
condition()
Call Signature
condition(
fn,timeout,options):Promise<boolean>
Experimental
Returns a Promise that resolves when fn evaluates to true or timeout expires, providing
options to configure the timer (i.e. provide metadata)
Parameters
fn
() => boolean
timeout
number of milliseconds or ms-formatted string
options
Returns
Promise<boolean>
a boolean indicating whether the condition was true before the timeout expires
TimerOptions is a new addition and subject to change
Call Signature
condition(
fn,timeout):Promise<boolean>
Returns a Promise that resolves when fn evaluates to true or timeout expires.
Parameters
fn
() => boolean
timeout
number of milliseconds or ms-formatted string
Returns
Promise<boolean>
a boolean indicating whether the condition was true before the timeout expires
Call Signature
condition(
fn):Promise<void>
Returns a Promise that resolves when fn evaluates to true.
Parameters
fn
() => boolean
Returns
Promise<void>
continueAsNew()
continueAsNew<
F>(...args):Promise<never>
Continues-As-New the current Workflow Execution with default options.
Shorthand for makeContinueAsNewFunc<F>()(...args). (See: makeContinueAsNewFunc.)
Type Parameters
F
F extends Workflow
Parameters
args
...Parameters<F>
Returns
Promise<never>
Example
import { continueAsNew } from '@temporalio/workflow';
import { SearchAttributeType } from '@temporalio/common';
export async function myWorkflow(n: number): Promise<void> {
// ... Workflow logic
await continueAsNew<typeof myWorkflow>(n + 1);
}
createEventGroup()
createEventGroup(
id,options?):EventGroup
Experimental
Create an Event Group that can be attached to commands scheduled by this Workflow.
Attach the returned group via command eventGroups options, or via EventGroup.withScope.
Parameters
id
string
non-empty group identity. Commands with the same id belong to the same group.
The user-provided ID is stored as plain text in the workflow history and should
therefore not contain sensitive information.
options?
label?
string
optional non-empty display text for the UI / CLI. If provided, it is persisted to history as a codec-encoded Payload.
Event Groups is an experimental API and may change without notice.
Returns
createNexusServiceClient()
createNexusServiceClient<
T>(options):NexusServiceClient<T>
Create a Nexus client for invoking Nexus Operations from a Workflow.
Type Parameters
T
T extends ServiceDefinition<OperationMap>
Parameters
options
Returns
currentUpdateInfo()
currentUpdateInfo():
UpdateInfo|undefined
Get information about the current update if any.
Returns
UpdateInfo | undefined
Info for the current update handler the code calling this is executing within if any.
defineQuery()
defineQuery<
Ret,Args,Name>(name,options?):QueryDefinition<Ret,Args,Name>
Define a query method for a Workflow.
A definition is used to register a handler in the Workflow via setHandler and to query a Workflow using a WorkflowHandle. A definition can be reused in multiple Workflows.
Type Parameters
Ret
Ret
Args
Args extends any[] = []
Name
Name extends string = string
Parameters
name
Name
options?
Returns
QueryDefinition<Ret, Args, Name>
defineSignal()
defineSignal<
Args,Name>(name,options?):SignalDefinition<Args,Name>
Define a signal method for a Workflow.
A definition is used to register a handler in the Workflow via setHandler and to signal a Workflow using a WorkflowHandle, ChildWorkflowHandle or ExternalWorkflowHandle. A definition can be reused in multiple Workflows.
Type Parameters
Args
Args extends any[] = []
Name
Name extends string = string
Parameters
name
Name
options?
optional type information used to convert Signal arguments
Returns
SignalDefinition<Args, Name>
defineUpdate()
defineUpdate<
Ret,Args,Name>(name,options?):UpdateDefinition<Ret,Args,Name>
Define an update method for a Workflow.
A definition is used to register a handler in the Workflow via setHandler and to update a Workflow using a WorkflowHandle, ChildWorkflowHandle or ExternalWorkflowHandle. A definition can be reused in multiple Workflows.
Type Parameters
Ret
Ret
Args
Args extends any[] = []
Name
Name extends string = string
Parameters
name
Name
options?
Returns
UpdateDefinition<Ret, Args, Name>
defineWorkflowOptions()
defineWorkflowOptions<
A,RT>(fn,config):void
Experimental
Attach per-execution options and static metadata to a Workflow function.
Static options are available before the Workflow function's arguments are decoded.
Type Parameters
A
A extends any[]
RT
RT
Parameters
fn
(...args) => Promise<RT>
config
Returns
void
deprecatePatch()
deprecatePatch(
patchId,options?):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
patchId
string
An 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.
options?
Returns
void
executeChild()
Call Signature
executeChild<
T>(workflowType,options):Promise<WorkflowResultType<T>>
Start a child Workflow execution and await its completion.
- By default, a child will be scheduled on the same task queue as its parent.
- This operation is cancellable using CancellationScopes.
Type Parameters
T
T extends Workflow
Parameters
workflowType
string
options
WithWorkflowArgs<T, ChildWorkflowOptions>
Returns
Promise<WorkflowResultType<T>>
The result of the child Workflow.
Call Signature
executeChild<
T>(workflowFunc,options):Promise<WorkflowResultType<T>>
Start a child Workflow execution and await its completion.
- By default, a child will be scheduled on the same task queue as its parent.
- Deduces the Workflow type and signature from provided Workflow function.
- This operation is cancellable using CancellationScopes.
Type Parameters
T
T extends Workflow
Parameters
workflowFunc
T
options
WithWorkflowArgs<T, ChildWorkflowDefinitionOptions>
Returns
Promise<WorkflowResultType<T>>
The result of the child Workflow.
Call Signature
executeChild<
T>(workflowType):Promise<WorkflowResultType<T>>
Start a child Workflow execution and await its completion.
Override for Workflows that accept no arguments.
- The child will be scheduled on the same task queue as its parent.
- This operation is cancellable using CancellationScopes.
Type Parameters
T
T extends () => WorkflowReturnType
Parameters
workflowType
string
Returns
Promise<WorkflowResultType<T>>
The result of the child Workflow.
Call Signature
executeChild<
T>(workflowFunc):Promise<WorkflowResultType<T>>
Start a child Workflow execution and await its completion.
Override for Workflows that accept no arguments.
- The child will be scheduled on the same task queue as its parent.
- Deduces the Workflow type and signature from provided Workflow function.
- This operation is cancellable using CancellationScopes.
Type Parameters
T
T extends () => WorkflowReturnType
Parameters
workflowFunc
T
Returns
Promise<WorkflowResultType<T>>
The result of the child Workflow.
getCurrentDetails()
getCurrentDetails():
string
Returns
string
getExternalWorkflowHandle()
getExternalWorkflowHandle(
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
workflowId
string
runId?
string
Returns
getRandomStream()
getRandomStream(
name):WorkflowRandomStream
Experimental
Get a named deterministic random stream for the current workflow execution.
Named streams are derived from the workflow seed and a stable stream name,
without consuming the workflow's default Math.random() stream. Repeated
calls with the same name within a workflow execution refer to the same
logical stream state, including across activations.
This is the preferred entry point for workflow plugins and interceptors that
need their own deterministic entropy. Use stable package- or module-style
names so the stream identity remains replay-safe, then keep the returned
WorkflowRandomStream around and call its methods directly.
This API may be removed or changed in the future.
Parameters
name
string
Returns
inWorkflowContext()
inWorkflowContext():
boolean
Returns whether or not code is executing in workflow context
Returns
boolean
isCancellation()
isCancellation(
err):boolean
Returns whether provided err is caused by cancellation
Parameters
err
unknown
Returns
boolean
makeContinueAsNewFunc()
makeContinueAsNewFunc<
F>(options?): (...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 function supplied to typeparam F.
Once f is called, Workflow Execution immediately completes.
Type Parameters
F
F extends Workflow
Parameters
options?
Returns
(...args) => Promise<never>
patched()
patched(
patchId,options?):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
patchId
string
An 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.
options?
Returns
boolean
proxyActivities()
proxyActivities<
A>(options):ActivityInterfaceFor<A>
Configure Activity functions with given ActivityOptions.
This method may be called multiple times to setup Activities with different options.
Type Parameters
A
Parameters
options
Returns
a Proxy for which each attribute is a callable Activity function
Example
import { proxyActivities } from '@temporalio/workflow';
import * as activities from '../activities';
// Setup Activities from module exports
const { httpGet, otherActivity } = proxyActivities<typeof activities>({
startToCloseTimeout: '30 minutes',
});
// Use activities with default options
const result1 = await httpGet('http://example.com');
// Override options for specific activity calls
const result2 = await httpGet.executeWithOptions({
staticSummary: 'Fetches data from external API',
scheduleToCloseTimeout: '5m'
}, ['http://api.example.com']);
const result3 = await otherActivity.executeWithOptions({
staticSummary: 'Processes the fetched data',
taskQueue: 'special-task-queue'
}, [data]);
// Setup Activities from an explicit interface (e.g. when defined by another SDK)
interface JavaActivities {
httpGetFromJava(url: string): Promise<string>
someOtherJavaActivity(arg1: number, arg2: string): Promise<string>;
}
const {
httpGetFromJava,
someOtherJavaActivity
} = proxyActivities<JavaActivities>({
taskQueue: 'java-worker-taskQueue',
startToCloseTimeout: '5m',
});
export function execute(): Promise<void> {
const response = await httpGet("http://example.com");
// Or with custom options:
const response2 = await httpGetFromJava.executeWithOptions({
staticSummary: 'Java HTTP call with timeout override',
startToCloseTimeout: '2m'
}, ["http://fast-api.example.com"]);
// ...
}
proxyLocalActivities()
proxyLocalActivities<
A>(options):LocalActivityInterfaceFor<A>
Configure Local Activity functions with given LocalActivityOptions.
This method may be called multiple times to setup Activities with different options.
Type Parameters
A
Parameters
options
Returns
a Proxy for which each attribute is a callable Activity function
See
proxyActivities for examples
proxySinks()
proxySinks<
T>():T
Get a reference to Sinks for exporting data out of the Workflow.
These Sinks must be registered with the Worker in order for this mechanism to work.
Type Parameters
T
T extends Sinks
Returns
T
Example
import { proxySinks, Sinks } from '@temporalio/workflow';
interface MySinks extends Sinks {
logger: {
info(message: string): void;
error(message: string): void;
};
}
const { logger } = proxySinks<MyDependencies>();
logger.info('setting up');
export function myWorkflow() {
return {
async execute() {
logger.info("hey ho");
logger.error("lets go");
}
};
}
setCurrentDetails()
setCurrentDetails(
details):void
Parameters
details
string
Returns
void
setDefaultQueryHandler()
setDefaultQueryHandler(
handler):void
Set a query handler function that will handle query calls for non-registered query names.
Queries are dispatched to the default query handler in the order that they were accepted by the server.
If this function is called multiple times for a given query name the last handler will overwrite any previous calls.
Parameters
handler
DefaultQueryHandler | undefined
a function that will handle queries for non-registered query names, or undefined to unset the handler.
Returns
void
setDefaultSignalHandler()
setDefaultSignalHandler(
handler):void
Set a signal handler function that will handle signals calls for non-registered signal names.
Signals are dispatched to the default signal handler in the order that they were accepted by the server.
If this function is called multiple times for a given signal name the last handler will overwrite any previous calls.
Parameters
handler
DefaultSignalHandler | undefined
a function that will handle signals for non-registered signal names, or undefined to unset the handler.
Returns
void
setDefaultUpdateHandler()
setDefaultUpdateHandler(
handler):void
Set a update handler function that will handle updates calls for non-registered update names.
Updates are dispatched to the default update handler in the order that they were accepted by the server.
If this function is called multiple times for a given update name the last handler will overwrite any previous calls.
Parameters
handler
DefaultUpdateHandler | undefined
a function that will handle updates for non-registered update names, or undefined to unset the handler.
Returns
void
setHandler()
Call Signature
setHandler<
Ret,Args,T>(def,handler,options?):void
Set a handler function for a Workflow update, signal, or query.
If this function is called multiple times for a given update, signal, or query name the last handler will overwrite any previous calls.
Type Parameters
Ret
Ret
Args
Args extends any[]
T
T extends QueryDefinition<Ret, Args, string>
Parameters
def
T
an UpdateDefinition, SignalDefinition, or QueryDefinition as returned by defineUpdate, defineSignal, or defineQuery respectively.
handler
Handler<Ret, Args, T> | undefined
a compatible handler function for the given definition or undefined to unset the handler.
options?
QueryHandlerOptions
an optional description of the handler and an optional update validator function.
Returns
void
Call Signature
setHandler<
Ret,Args,T>(def,handler,options?):void
Set a handler function for a Workflow update, signal, or query.
If this function is called multiple times for a given update, signal, or query name the last handler will overwrite any previous calls.
Type Parameters
Ret
Ret
Args
Args extends any[]
T
T extends SignalDefinition<Args, string>
Parameters
def
T
an UpdateDefinition, SignalDefinition, or QueryDefinition as returned by defineUpdate, defineSignal, or defineQuery respectively.
handler
Handler<Ret, Args, T> | undefined
a compatible handler function for the given definition or undefined to unset the handler.
options?
SignalHandlerOptions
an optional description of the handler and an optional update validator function.
Returns
void
Call Signature
setHandler<
Ret,Args,T>(def,handler,options?):void
Set a handler function for a Workflow update, signal, or query.
If this function is called multiple times for a given update, signal, or query name the last handler will overwrite any previous calls.
Type Parameters
Ret
Ret
Args
Args extends any[]
T
T extends UpdateDefinition<Ret, Args, string>
Parameters
def
T
an UpdateDefinition, SignalDefinition, or QueryDefinition as returned by defineUpdate, defineSignal, or defineQuery respectively.
handler
Handler<Ret, Args, T> | undefined
a compatible handler function for the given definition or undefined to unset the handler.
options?
UpdateHandlerOptions<Args>
an optional description of the handler and an optional update validator function.
Returns
void
setWorkflowOptions()
setWorkflowOptions<
A,RT>(options,fn):void
Can be used to alter workflow functions with certain options specified at definition time.
Prefer defineWorkflowOptions for new code, especially when setting static workflow metadata such as type information.
Type Parameters
A
A extends any[]
RT
RT
Parameters
options
WorkflowDefinitionOptionsOrGetter
Options for the workflow defintion, or a function that returns options. If a function is provided, it will be called once just before the workflow function is called for the first time. It is safe to call workflowInfo inside such a function.
fn
(...args) => Promise<RT>
The workflow function.
Returns
void
Examples
For example:
setWorkflowOptions({
versioningBehavior: 'PINNED',
failureExceptionTypes: [CustomWorkflowError]
}, myWorkflow);
export async function myWorkflow(): Promise<string> {
// Workflow code here
return "hi";
}
To annotate a default or dynamic workflow:
export default async function (): Promise<string> {
// Workflow code here
return "hi";
}
setWorkflowOptions({
versioningBehavior: 'PINNED',
failureExceptionTypes: [CustomWorkflowError]
}, module.exports.default);
signalWithStartWorkflow()
signalWithStartWorkflow<
WorkflowFn,SignalValue>(requestInput):Promise<ExternalWorkflowHandle>
Experimental
Signal a workflow, starting it first if needed.
Type Parameters
WorkflowFn
WorkflowFn extends (...args) => Promise<any> = (...args) => Promise<any>
SignalValue
SignalValue extends SignalDefinition<any[], string> = SignalDefinition<any[], string>
Parameters
requestInput
SignalWithStartWorkflowInput<WorkflowFn, SignalValue>
Returns
Promise<ExternalWorkflowHandle>
A workflow handle to the started workflow. This API is experimental and subject to change.
sleep()
sleep(
ms,options?):Promise<void>
Asynchronous sleep.
Schedules a timer on the Temporal service.
Parameters
ms
sleep duration - number of milliseconds or ms-formatted string. If given a negative number or 0, value will be set to 1.
options?
optional timer options for additional configuration
Returns
Promise<void>
startChild()
Call Signature
startChild<
T>(workflowType,options):Promise<ChildWorkflowHandle<T>>
Start a child Workflow execution
- Returns a client-side handle that implements a child Workflow interface.
- By default, a child will be scheduled on the same task queue as its parent.
A child Workflow handle supports awaiting completion, signaling and cancellation via CancellationScopes. In order to query the child, use a WorkflowClient from an Activity.
Type Parameters
T
T extends Workflow
Parameters
workflowType
string
options
WithWorkflowArgs<T, ChildWorkflowOptions>
Returns
Promise<ChildWorkflowHandle<T>>
Call Signature
startChild<
T>(workflowFunc,options):Promise<ChildWorkflowHandle<T>>
Start a child Workflow execution
- Returns a client-side handle that implements a child Workflow interface.
- Deduces the Workflow type and signature from provided Workflow function.
- By default, a child will be scheduled on the same task queue as its parent.
A child Workflow handle supports awaiting completion, signaling and cancellation via CancellationScopes. In order to query the child, use a WorkflowClient from an Activity.
Type Parameters
T
T extends Workflow
Parameters
workflowFunc
T
options
WithWorkflowArgs<T, ChildWorkflowDefinitionOptions>
Returns
Promise<ChildWorkflowHandle<T>>
Call Signature
startChild<
T>(workflowType):Promise<ChildWorkflowHandle<T>>
Start a child Workflow execution
Override for Workflows that accept no arguments.
- Returns a client-side handle that implements a child Workflow interface.
- The child will be scheduled on the same task queue as its parent.
A child Workflow handle supports awaiting completion, signaling and cancellation via CancellationScopes. In order to query the child, use a WorkflowClient from an Activity.
Type Parameters
T
T extends () => Promise<any>
Parameters
workflowType
string
Returns
Promise<ChildWorkflowHandle<T>>
Call Signature
startChild<
T>(workflowFunc):Promise<ChildWorkflowHandle<T>>
Start a child Workflow execution
Override for Workflows that accept no arguments.
- Returns a client-side handle that implements a child Workflow interface.
- Deduces the Workflow type and signature from provided Workflow function.
- The child will be scheduled on the same task queue as its parent.
A child Workflow handle supports awaiting completion, signaling and cancellation via CancellationScopes. In order to query the child, use a WorkflowClient from an Activity.
Type Parameters
T
T extends () => Promise<any>
Parameters
workflowFunc
T
Returns
Promise<ChildWorkflowHandle<T>>
upsertMemo()
upsertMemo(
memo,options?):void
Updates this Workflow's Memos by merging the provided memo with existing
Memos (as returned by workflowInfo().memo).
New memo is merged by replacing properties of the same name at the first
level only. Setting a property to value undefined or null clears that
key from the Memo.
For example:
upsertMemo({
key1: value,
key3: { subkey1: value }
key4: value,
});
upsertMemo({
key2: value
key3: { subkey2: value }
key4: undefined,
});
would result in the Workflow having these Memo:
{
key1: value,
key2: value,
key3: { subkey2: value } // Note this object was completely replaced
// Note that key4 was completely removed
}
Parameters
memo
Record<string, unknown>
The Record to merge.
options?
Returns
void
upsertSearchAttributes()
upsertSearchAttributes(
searchAttributes,options?):void
Updates this Workflow's Search Attributes by merging the provided searchAttributes with the existing Search
Attributes, workflowInfo().searchAttributes.
Search attributes can be upserted using either SearchAttributes (deprecated) or SearchAttributeUpdatePair[] (preferred)
Upserting a workflow's search attributes using SearchAttributeUpdatePair[]:
const intKey = defineSearchKey('CustomIntField', 'INT');
const boolKey = defineSearchKey('CustomBoolField', 'BOOL');
const keywordListKey = defineSearchKey('CustomKeywordField', 'KEYWORD_LIST');
upsertSearchAttributes([
defineSearchAttribute(intKey, 1),
defineSearchAttribute(boolKey, true)
]);
upsertSearchAttributes([
defineSearchAttribute(intKey, 42),
defineSearchAttribute(keywordListKey, ['durable code', 'is great'])
]);
Would result in the Workflow having these Search Attributes:
{
CustomIntField: [42],
CustomBoolField: [true],
CustomKeywordField: ['durable code', 'is great']
}
Parameters
searchAttributes
SearchAttributes | SearchAttributeUpdatePair[]
The Record to merge. If using SearchAttributeUpdatePair[] (preferred), set a value to null to remove the search attribute. If using SearchAttributes (deprecated), set a value to undefined or an empty list to remove the search attribute.
options?
Returns
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.
WARNING: This function returns a frozen copy of WorkflowInfo, at the point where this method has been called. Changes happening at later point in workflow execution will not be reflected in the returned object.
For this reason, we recommend calling workflowInfo() on every access to WorkflowInfo's fields,
rather than caching the WorkflowInfo object (or part of it) in a local variable. For example:
// GOOD
function myWorkflow() {
doSomething(workflowInfo().searchAttributes)
...
doSomethingElse(workflowInfo().searchAttributes)
}
vs
// BAD
function myWorkflow() {
const attributes = workflowInfo().searchAttributes
doSomething(attributes)
...
doSomethingElse(attributes)
}
Returns
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
AutoUpgradeVersioningOverride
Re-exports AutoUpgradeVersioningOverride
BaseWorkflowHandle
Re-exports BaseWorkflowHandle
BaseWorkflowOptions
Re-exports BaseWorkflowOptions
CancelledFailure
Re-exports CancelledFailure
ChildWorkflowFailure
Re-exports ChildWorkflowFailure
CommonWorkflowOptions
Re-exports CommonWorkflowOptions
CompleteAsyncError
Re-exports CompleteAsyncError
decodeWorkflowIdConflictPolicy
Re-exports decodeWorkflowIdConflictPolicy
decodeWorkflowIdReusePolicy
Re-exports decodeWorkflowIdReusePolicy
defaultPayloadConverter
Re-exports defaultPayloadConverter
encodeWorkflowIdConflictPolicy
Re-exports encodeWorkflowIdConflictPolicy
encodeWorkflowIdReusePolicy
Re-exports encodeWorkflowIdReusePolicy
ExternalStorageDriverError
Re-exports ExternalStorageDriverError
ExternalStorageError
Re-exports ExternalStorageError
ExternalStorageNotConfiguredError
Re-exports ExternalStorageNotConfiguredError
ExternalStorageReferenceError
Re-exports ExternalStorageReferenceError
ExternalStorageUnregisteredDriverError
Re-exports ExternalStorageUnregisteredDriverError
extractWorkflowType
Re-exports extractWorkflowType
extractWorkflowTypeAndConfig
Re-exports extractWorkflowTypeAndConfig
Headers
Re-exports Headers
IllegalStateError
Re-exports IllegalStateError
InvalidVersioningOverrideError
Re-exports InvalidVersioningOverrideError
NamespaceNotFoundError
Re-exports NamespaceNotFoundError
Next
Re-exports Next
OneTimeVersioningOverride
Re-exports OneTimeVersioningOverride
Payload
Re-exports Payload
PayloadConverter
Re-exports PayloadConverter
PayloadConverterError
Re-exports PayloadConverterError
PinnedVersioningOverride
Re-exports PinnedVersioningOverride
QueryDefinition
Re-exports QueryDefinition
RetryPolicy
Re-exports RetryPolicy
rootCause
Re-exports rootCause
SearchAttributes
Re-exports SearchAttributes
SearchAttributeValue
Re-exports SearchAttributeValue
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
VersioningOverride
Re-exports VersioningOverride
WithWorkflowArgs
Re-exports WithWorkflowArgs
WorkerDeploymentVersion
Re-exports WorkerDeploymentVersion
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