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.
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
Enumerations
Classes
- CancellationScope
- ContinueAsNew
- DeterminismViolationError
- LocalActivityDoBackoff
- Trigger
- WorkflowError
Interfaces
- ActivateInput
- ActivityInput
- CancellationScopeOptions
- ChildWorkflowHandle
- ChildWorkflowOptions
- ConcludeActivationInput
- ContinueAsNewInput
- ContinueAsNewOptions
- DisposeInput
- EnhancedStackTrace
- ExternalWorkflowHandle
- LocalActivityInput
- LoggerSinks
- ParentWorkflowInfo
- QueryInput
- SignalInput
- SignalWorkflowInput
- SinkCall
- StackTrace
- StackTraceFileLocation
- StackTraceFileSlice
- StackTraceSDKInfo
- StartChildWorkflowExecutionInput
- TimerInput
- UnsafeWorkflowInfo
- UpdateInput
- WorkflowExecuteInput
- WorkflowInboundCallsInterceptor
- WorkflowInfo
- WorkflowInterceptors
- WorkflowInternalsInterceptor
- WorkflowOutboundCallsInterceptor
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
BaseWorkflowHandle
Re-exports BaseWorkflowHandle
BaseWorkflowOptions
Re-exports BaseWorkflowOptions
CancelledFailure
Re-exports CancelledFailure
ChildWorkflowFailure
Re-exports ChildWorkflowFailure
CommonWorkflowOptions
Re-exports CommonWorkflowOptions
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
WorkflowIdReusePolicy
Re-exports WorkflowIdReusePolicy
WorkflowNotFoundError
Re-exports WorkflowNotFoundError
WorkflowQueryType
Re-exports WorkflowQueryType
WorkflowResultType
Re-exports WorkflowResultType
WorkflowReturnType
Re-exports WorkflowReturnType
WorkflowSignalType
Re-exports WorkflowSignalType
defaultPayloadConverter
Re-exports defaultPayloadConverter
extractWorkflowType
Re-exports extractWorkflowType
rootCause
Re-exports rootCause
Type Aliases
ActivityInterfaceFor
Ƭ ActivityInterfaceFor<T
>: { [K in keyof T]: T[K] extends ActivityFunction ? 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 |
ConcludeActivationOutput
Ƭ ConcludeActivationOutput: ConcludeActivationInput
Output for WorkflowInternalsInterceptor.concludeActivation
ContinueAsNewInputOptions
Ƭ ContinueAsNewInputOptions: ContinueAsNewOptions
& Required
<Pick
<ContinueAsNewOptions
, "workflowType"
>>
Same as ContinueAsNewOptions but workflowType must be defined
GetLogAttributesInput
Ƭ GetLogAttributesInput: Record
<string
, unknown
>
Input for WorkflowOutboundCallsInterceptor.getLogAttributes
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 returns WorkflowInterceptors and takes no arguments.
Workflow interceptor modules should export an interceptors
function of this type.
Example
export function interceptors(): WorkflowInterceptors {
return {
inbound: [], // Populate with list of interceptor implementations
outbound: [], // Populate with list of interceptor implementations
internals: [], // Populate with list of 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
>
NotAnActivityMethod
• Const
NotAnActivityMethod: unique symbol
Symbol used in the return type of proxy methods to mark that an attribute on the source type is not a method.
See
enhancedStackTraceQuery
• Const
enhancedStackTraceQuery: QueryDefinition
<EnhancedStackTrace
, [], string
>
log
• Const
log: 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.
stackTraceQuery
• Const
stackTraceQuery: QueryDefinition
<string
, [], string
>
workflowMetadataQuery
• Const
workflowMetadataQuery: QueryDefinition
<IWorkflowMetadata
, [], string
>
Functions
addDefaultWorkflowOptions
▸ addDefaultWorkflowOptions<T
>(opts
): ChildWorkflowOptionsWithDefaults
Adds default values of workflowId
and cancellationType
to given workflow options.
Type parameters
Name | Type |
---|---|
T | extends Workflow |
Parameters
Name | Type |
---|---|
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
▸ condition(fn
, timeout
): Promise
<boolean
>
Returns a Promise that resolves when fn
evaluates to true
or timeout
expires.
Parameters
Name | Type | Description |
---|---|---|
fn | () => boolean | - |
timeout | Duration | number of milliseconds or ms-formatted string |
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
Name | Type |
---|---|
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
Name | Type |
---|---|
F | extends Workflow |
Parameters
Name | Type |
---|---|
...args | Parameters <F > |
Returns
Promise
<never
>
Example
import { continueAsNew } from '@temporalio/workflow';
export async function myWorkflow(n: number): Promise<void> {
// ... Workflow logic
await continueAsNew<typeof myWorkflow>(n + 1);
}
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
): 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
Name | Type |
---|---|
Ret | Ret |
Args | extends any [] = [] |
Name | extends string = string |
Parameters
Name | Type |
---|---|
name | Name |
Returns
QueryDefinition
<Ret
, Args
, Name
>
defineSignal
▸ defineSignal<Args
, Name
>(name
): 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
Name | Type |
---|---|
Args | extends any [] = [] |
Name | extends string = string |
Parameters
Name | Type |
---|---|
name | Name |
Returns
SignalDefinition
<Args
, Name
>
defineUpdate
▸ defineUpdate<Ret
, Args
, Name
>(name
): 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
Name | Type |
---|---|
Ret | Ret |
Args | extends any [] = [] |
Name | extends string = string |
Parameters
Name | Type |
---|---|
name | Name |
Returns
UpdateDefinition
<Ret
, Args
, Name
>
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
Name | Type | Description |
---|---|---|
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. |
Returns
void
executeChild
▸ 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
Name | Type |
---|---|
T | extends Workflow |
Parameters
Name | Type |
---|---|
workflowType | string |
options | WithWorkflowArgs <T , ChildWorkflowOptions > |
Returns
Promise
<WorkflowResultType
<T
>>
The result of the child Workflow.
▸ 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
Name | Type |
---|---|
T | extends Workflow |
Parameters
Name | Type |
---|---|
workflowFunc | T |
options | WithWorkflowArgs <T , ChildWorkflowOptions > |
Returns
Promise
<WorkflowResultType
<T
>>
The result of the child Workflow.
▸ 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
Name | Type |
---|---|
T | extends () => WorkflowReturnType |
Parameters
Name | Type |
---|---|
workflowType | string |
Returns
Promise
<WorkflowResultType
<T
>>
The result of the child Workflow.
▸ 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
Name | Type |
---|---|
T | extends () => WorkflowReturnType |
Parameters
Name | Type |
---|---|
workflowFunc | T |
Returns
Promise
<WorkflowResultType
<T
>>
The result of the child Workflow.
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
Name | Type |
---|---|
workflowId | string |
runId? | 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
Name | Type |
---|---|
err | unknown |
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 function supplied to typeparam F
.
Once f
is called, Workflow Execution immediately completes.
Type parameters
Name | Type |
---|---|
F | extends Workflow |
Parameters
Name | Type |
---|---|
options? | ContinueAsNewOptions |
Returns
fn
▸ (...args
): Promise
<never
>
Parameters
Name | Type |
---|---|
...args | Parameters <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
Name | Type | Description |
---|---|---|
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. |
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
Name | Type |
---|---|
A | UntypedActivities |
Parameters
Name | Type |
---|---|
options | ActivityOptions |
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',
});
// 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");
// ...
}
proxyLocalActivities
▸ proxyLocalActivities<A
>(options
): ActivityInterfaceFor
<A
>
Configure Local Activity functions with given LocalActivityOptions.
This method may be called multiple times to setup Activities with different options.
Type parameters
Name | Type |
---|---|
A | UntypedActivities |
Parameters
Name | Type |
---|---|
options | LocalActivityOptions |
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
Name | Type |
---|---|
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");
}
};
}
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 or query name the last handler will overwrite any previous calls.
Parameters
Name | Type | Description |
---|---|---|
handler | undefined | DefaultSignalHandler | a function that will handle signals for non-registered signal names, or undefined to unset the handler. |
Returns
void
setHandler
▸ 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
Name | Type |
---|---|
Ret | Ret |
Args | extends any [] |
T | extends QueryDefinition <Ret , Args , string > |
Parameters
Name | Type | Description |
---|---|---|
def | T | an UpdateDefinition, SignalDefinition, or QueryDefinition as returned by defineUpdate, defineSignal, or defineQuery respectively. |
handler | undefined | Handler <Ret , Args , T > | 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
▸ setHandler<Ret
, Args
, T
>(def
, handler
, options?
): void
Type parameters
Name | Type |
---|---|
Ret | Ret |
Args | extends any [] |
T | extends SignalDefinition <Args , string > |
Parameters
Name | Type |
---|---|
def | T |
handler | undefined | Handler <Ret , Args , T > |
options? | SignalHandlerOptions |
Returns
void
▸ setHandler<Ret
, Args
, T
>(def
, handler
, options?
): void
Type parameters
Name | Type |
---|---|
Ret | Ret |
Args | extends any [] |
T | extends UpdateDefinition <Ret , Args , string > |
Parameters
Name | Type |
---|---|
def | T |
handler | undefined | Handler <Ret , Args , T > |
options? | UpdateHandlerOptions <Args > |
Returns
void
sleep
▸ sleep(ms
): Promise
<void
>
Asynchronous sleep.
Schedules a timer on the Temporal service.
Parameters
Name | Type | Description |
---|---|---|
ms | Duration | sleep duration - number of milliseconds or ms-formatted string. If given a negative number or 0, value will be set to 1. |
Returns
Promise
<void
>
startChild
▸ 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
Name | Type |
---|---|
T | extends Workflow |
Parameters
Name | Type |
---|---|
workflowType | string |
options | WithWorkflowArgs <T , ChildWorkflowOptions > |
Returns
Promise
<ChildWorkflowHandle
<T
>>
▸ 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
Name | Type |
---|---|
T | extends Workflow |
Parameters
Name | Type |
---|---|
workflowFunc | T |
options | WithWorkflowArgs <T , ChildWorkflowOptions > |
Returns
Promise
<ChildWorkflowHandle
<T
>>
▸ 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
Name | Type |
---|---|
T | extends () => Promise <any > |
Parameters
Name | Type |
---|---|
workflowType | string |
Returns
Promise
<ChildWorkflowHandle
<T
>>
▸ 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
Name | Type |
---|---|
T | extends () => Promise <any > |
Parameters
Name | Type |
---|---|
workflowFunc | T |
Returns
Promise
<ChildWorkflowHandle
<T
>>
upsertMemo
▸ upsertMemo(memo
): 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
Name | Type | Description |
---|---|---|
memo | Record <string , unknown > | The Record to merge. |
Returns
void
upsertSearchAttributes
▸ upsertSearchAttributes(searchAttributes
): void
Updates this Workflow's Search Attributes by merging the provided searchAttributes
with the existing Search
Attributes, workflowInfo().searchAttributes
.
For example, this Workflow code:
upsertSearchAttributes({
CustomIntField: [1],
CustomBoolField: [true]
});
upsertSearchAttributes({
CustomIntField: [42],
CustomKeywordField: ['durable code', 'is great']
});
would result in the Workflow having these Search Attributes:
{
CustomIntField: [42],
CustomBoolField: [true],
CustomKeywordField: ['durable code', 'is great']
}
Parameters
Name | Type | Description |
---|---|---|
searchAttributes | SearchAttributes | The Record to merge. Use a value of [] to clear a Search Attribute. |
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)
}