@temporalio/workflow 1.0.0-rc.0 → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,91 @@
1
+ /**
2
+ * This library provides tools required for authoring workflows.
3
+ *
4
+ * ## Usage
5
+ * See the {@link https://docs.temporal.io/typescript/hello-world#workflows | tutorial} for writing your first workflow.
6
+ *
7
+ * ### Timers
8
+ *
9
+ * The recommended way of scheduling timers is by using the {@link sleep} function. We've replaced `setTimeout` and
10
+ * `clearTimeout` with deterministic versions so these are also usable but have a limitation that they don't play well
11
+ * with {@link https://docs.temporal.io/typescript/workflow-scopes-and-cancellation | cancellation scopes}.
12
+ *
13
+ * <!--SNIPSTART typescript-sleep-workflow-->
14
+ * <!--SNIPEND-->
15
+ *
16
+ * ### Activities
17
+ *
18
+ * To schedule Activities, use {@link proxyActivities} to obtain an Activity function and call.
19
+ *
20
+ * <!--SNIPSTART typescript-schedule-activity-workflow-->
21
+ * <!--SNIPEND-->
22
+ *
23
+ * ### Signals and Queries
24
+ *
25
+ * To add signal handlers to a Workflow, add a signals property to the exported `workflow` object. Signal handlers can
26
+ * return either `void` or `Promise<void>`, you may schedule activities and timers from a signal handler.
27
+ *
28
+ * To add query handlers to a Workflow, add a queries property to the exported `workflow` object. Query handlers must
29
+ * **not** mutate any variables or generate any commands (like Activities or Timers), they run synchronously and thus
30
+ * **must** return a `Promise`.
31
+ *
32
+ * #### Implementation
33
+ *
34
+ * <!--SNIPSTART typescript-workflow-signal-implementation-->
35
+ * <!--SNIPEND-->
36
+ *
37
+ * ### Deterministic built-ins
38
+ * It is safe to call `Math.random()` and `Date()` in workflow code as they are replaced with deterministic versions. We
39
+ * also provide a deterministic {@link uuid4} function for convenience.
40
+ *
41
+ * ### [Cancellation and scopes](https://docs.temporal.io/typescript/workflow-scopes-and-cancellation)
42
+ * - {@link CancellationScope}
43
+ * - {@link Trigger}
44
+ *
45
+ * ### [Sinks](https://docs.temporal.io/typescript/sinks)
46
+ * - {@link Sinks}
47
+ *
48
+ * @module
49
+ */
50
+
51
+ export {
52
+ ActivityFailure,
53
+ ApplicationFailure,
54
+ CancelledFailure,
55
+ ChildWorkflowFailure,
56
+ defaultPayloadConverter,
57
+ PayloadConverter,
58
+ rootCause,
59
+ ServerFailure,
60
+ TemporalFailure,
61
+ TerminatedFailure,
62
+ TimeoutFailure,
63
+ } from '@temporalio/common';
64
+ export {
65
+ ActivityCancellationType,
66
+ ActivityFunction,
67
+ ActivityInterface, // eslint-disable-line deprecation/deprecation
68
+ ActivityOptions,
69
+ RetryPolicy,
70
+ UntypedActivities,
71
+ } from '@temporalio/internal-workflow-common';
72
+ export * from '@temporalio/internal-workflow-common/lib/errors';
73
+ export * from '@temporalio/internal-workflow-common/lib/interfaces';
74
+ export * from '@temporalio/internal-workflow-common/lib/workflow-handle';
75
+ export * from '@temporalio/internal-workflow-common/lib/workflow-options';
76
+ export { AsyncLocalStorage, CancellationScope, CancellationScopeOptions, ROOT_SCOPE } from './cancellation-scope';
77
+ export * from './errors';
78
+ export * from './interceptors';
79
+ export {
80
+ ChildWorkflowCancellationType,
81
+ ChildWorkflowOptions,
82
+ ContinueAsNew,
83
+ ContinueAsNewOptions,
84
+ ParentClosePolicy,
85
+ ParentWorkflowInfo,
86
+ WorkflowInfo,
87
+ } from './interfaces';
88
+ export { Sink, SinkCall, SinkFunction, Sinks } from './sinks';
89
+ export { Trigger } from './trigger';
90
+ export * from './workflow';
91
+ export { ChildWorkflowHandle, ExternalWorkflowHandle } from './workflow-handle';
@@ -0,0 +1,239 @@
1
+ /**
2
+ * Type definitions and generic helpers for interceptors.
3
+ *
4
+ * The Workflow specific interceptors are defined here.
5
+ *
6
+ * @module
7
+ */
8
+
9
+ import { WorkflowExecution } from '@temporalio/common';
10
+ import { ActivityOptions, Headers, LocalActivityOptions, Next, Timestamp } from '@temporalio/internal-workflow-common';
11
+ import type { coresdk } from '@temporalio/proto';
12
+ import { ChildWorkflowOptionsWithDefaults, ContinueAsNewOptions } from './interfaces';
13
+
14
+ export { Next, Headers };
15
+
16
+ /** Input for WorkflowInboundCallsInterceptor.execute */
17
+ export interface WorkflowExecuteInput {
18
+ readonly args: unknown[];
19
+ readonly headers: Headers;
20
+ }
21
+
22
+ /** Input for WorkflowInboundCallsInterceptor.handleSignal */
23
+ export interface SignalInput {
24
+ readonly signalName: string;
25
+ readonly args: unknown[];
26
+ readonly headers: Headers;
27
+ }
28
+
29
+ /** Input for WorkflowInboundCallsInterceptor.handleQuery */
30
+ export interface QueryInput {
31
+ readonly queryId: string;
32
+ readonly queryName: string;
33
+ readonly args: unknown[];
34
+ readonly headers: Headers;
35
+ }
36
+
37
+ /**
38
+ * Implement any of these methods to intercept Workflow inbound calls like execution, and signal and query handling.
39
+ */
40
+ export interface WorkflowInboundCallsInterceptor {
41
+ /**
42
+ * Called when Workflow execute method is called
43
+ *
44
+ * @return result of the Workflow execution
45
+ */
46
+ execute?: (input: WorkflowExecuteInput, next: Next<this, 'execute'>) => Promise<unknown>;
47
+
48
+ /** Called when signal is delivered to a Workflow execution */
49
+ handleSignal?: (input: SignalInput, next: Next<this, 'handleSignal'>) => Promise<void>;
50
+
51
+ /**
52
+ * Called when a Workflow is queried
53
+ *
54
+ * @return result of the query
55
+ */
56
+ handleQuery?: (input: QueryInput, next: Next<this, 'handleQuery'>) => Promise<unknown>;
57
+ }
58
+
59
+ /** Input for WorkflowOutboundCallsInterceptor.scheduleActivity */
60
+ export interface ActivityInput {
61
+ readonly activityType: string;
62
+ readonly args: unknown[];
63
+ readonly options: ActivityOptions;
64
+ readonly headers: Headers;
65
+ readonly seq: number;
66
+ }
67
+
68
+ /** Input for WorkflowOutboundCallsInterceptor.scheduleLocalActivity */
69
+ export interface LocalActivityInput {
70
+ readonly activityType: string;
71
+ readonly args: unknown[];
72
+ readonly options: LocalActivityOptions;
73
+ readonly headers: Headers;
74
+ readonly seq: number;
75
+ readonly originalScheduleTime?: Timestamp;
76
+ readonly attempt: number;
77
+ }
78
+
79
+ /** Input for WorkflowOutboundCallsInterceptor.startChildWorkflowExecution */
80
+ export interface StartChildWorkflowExecutionInput {
81
+ readonly workflowType: string;
82
+ readonly options: ChildWorkflowOptionsWithDefaults;
83
+ readonly headers: Headers;
84
+ readonly seq: number;
85
+ }
86
+
87
+ /** Input for WorkflowOutboundCallsInterceptor.startTimer */
88
+ export interface TimerInput {
89
+ readonly durationMs: number;
90
+ readonly seq: number;
91
+ }
92
+
93
+ /**
94
+ * Same as ContinueAsNewOptions but workflowType must be defined
95
+ */
96
+ export type ContinueAsNewInputOptions = ContinueAsNewOptions & Required<Pick<ContinueAsNewOptions, 'workflowType'>>;
97
+
98
+ /** Input for WorkflowOutboundCallsInterceptor.continueAsNew */
99
+ export interface ContinueAsNewInput {
100
+ readonly args: unknown[];
101
+ readonly headers: Headers;
102
+ readonly options: ContinueAsNewInputOptions;
103
+ }
104
+
105
+ /** Input for WorkflowOutboundCallsInterceptor.signalWorkflow */
106
+ export interface SignalWorkflowInput {
107
+ readonly seq: number;
108
+ readonly signalName: string;
109
+ readonly args: unknown[];
110
+ readonly headers: Headers;
111
+ readonly target:
112
+ | {
113
+ readonly type: 'external';
114
+ readonly workflowExecution: WorkflowExecution;
115
+ }
116
+ | {
117
+ readonly type: 'child';
118
+ readonly childWorkflowId: string;
119
+ };
120
+ }
121
+
122
+ /**
123
+ * Implement any of these methods to intercept Workflow code calls to the Temporal APIs, like scheduling an activity and starting a timer
124
+ */
125
+ export interface WorkflowOutboundCallsInterceptor {
126
+ /**
127
+ * Called when Workflow schedules an Activity
128
+ *
129
+ * @return result of the activity execution
130
+ */
131
+ scheduleActivity?: (input: ActivityInput, next: Next<this, 'scheduleActivity'>) => Promise<unknown>;
132
+
133
+ /**
134
+ * Called when Workflow schedules a local Activity
135
+ *
136
+ * @return result of the activity execution
137
+ */
138
+ scheduleLocalActivity?: (input: LocalActivityInput, next: Next<this, 'scheduleLocalActivity'>) => Promise<unknown>;
139
+
140
+ /**
141
+ * Called when Workflow starts a timer
142
+ */
143
+ startTimer?: (input: TimerInput, next: Next<this, 'startTimer'>) => Promise<void>;
144
+
145
+ /**
146
+ * Called when Workflow calls continueAsNew
147
+ */
148
+ continueAsNew?: (input: ContinueAsNewInput, next: Next<this, 'continueAsNew'>) => Promise<never>;
149
+
150
+ /**
151
+ * Called when Workflow signals a child or external Workflow
152
+ */
153
+ signalWorkflow?: (input: SignalWorkflowInput, next: Next<this, 'signalWorkflow'>) => Promise<void>;
154
+
155
+ /**
156
+ * Called when Workflow starts a child workflow execution, the interceptor function returns 2 promises:
157
+ *
158
+ * - The first resolves with the `runId` when the child workflow has started or rejects if failed to start.
159
+ * - The second resolves with the workflow result when the child workflow completes or rejects on failure.
160
+ */
161
+ startChildWorkflowExecution?: (
162
+ input: StartChildWorkflowExecutionInput,
163
+ next: Next<this, 'startChildWorkflowExecution'>
164
+ ) => Promise<[Promise<string>, Promise<unknown>]>;
165
+ }
166
+
167
+ /** Input for WorkflowInternalsInterceptor.concludeActivation */
168
+ export interface ConcludeActivationInput {
169
+ commands: coresdk.workflow_commands.IWorkflowCommand[];
170
+ }
171
+
172
+ /** Output for WorkflowInternalsInterceptor.concludeActivation */
173
+ export type ConcludeActivationOutput = ConcludeActivationInput;
174
+
175
+ /** Input for WorkflowInternalsInterceptor.activate */
176
+ export interface ActivateInput {
177
+ activation: coresdk.workflow_activation.IWorkflowActivation;
178
+ batchIndex: number;
179
+ }
180
+
181
+ /** Input for WorkflowInternalsInterceptor.dispose */
182
+ // eslint-disable-next-line @typescript-eslint/no-empty-interface
183
+ export interface DisposeInput {}
184
+
185
+ /**
186
+ * Interceptor for the internals of the Workflow runtime.
187
+ *
188
+ * Use to manipulate or trace Workflow activations.
189
+ *
190
+ * @experimental
191
+ */
192
+ export interface WorkflowInternalsInterceptor {
193
+ /**
194
+ * Called when the Workflow runtime runs a WorkflowActivationJob.
195
+ */
196
+ activate?(input: ActivateInput, next: Next<this, 'activate'>): void;
197
+
198
+ /**
199
+ * Called after all `WorkflowActivationJob`s have been processed for an activation.
200
+ *
201
+ * Can manipulate the commands generated by the Workflow
202
+ */
203
+ concludeActivation?(input: ConcludeActivationInput, next: Next<this, 'concludeActivation'>): ConcludeActivationOutput;
204
+
205
+ /**
206
+ * Called before disposing the Workflow isolate context.
207
+ *
208
+ * Implement this method to perform any resource cleanup.
209
+ */
210
+ dispose?(input: DisposeInput, next: Next<this, 'dispose'>): Promise<void>;
211
+ }
212
+
213
+ /**
214
+ * A mapping from interceptor type to an optional list of interceptor implementations
215
+ */
216
+ export interface WorkflowInterceptors {
217
+ inbound?: WorkflowInboundCallsInterceptor[];
218
+ outbound?: WorkflowOutboundCallsInterceptor[];
219
+ internals?: WorkflowInternalsInterceptor[];
220
+ }
221
+
222
+ /**
223
+ * A function that returns {@link WorkflowInterceptors} and takes no arguments.
224
+ *
225
+ * Workflow interceptor modules should export an `interceptors` function of this type.
226
+ *
227
+ * @example
228
+ *
229
+ * ```ts
230
+ * export function interceptors(): WorkflowInterceptors {
231
+ * return {
232
+ * inbound: [], // Populate with list of interceptor implementations
233
+ * outbound: [], // Populate with list of interceptor implementations
234
+ * internals: [], // Populate with list of interceptor implementations
235
+ * };
236
+ * }
237
+ * ```
238
+ */
239
+ export type WorkflowInterceptorsFactory = () => WorkflowInterceptors;
@@ -0,0 +1,272 @@
1
+ import { RetryPolicy, TemporalFailure } from '@temporalio/common';
2
+ import { checkExtends, CommonWorkflowOptions, SearchAttributes } from '@temporalio/internal-workflow-common';
3
+ import type { coresdk } from '@temporalio/proto';
4
+
5
+ /**
6
+ * Workflow Execution information
7
+ */
8
+ export interface WorkflowInfo {
9
+ /**
10
+ * ID of the Workflow, this can be set by the client during Workflow creation.
11
+ * A single Workflow may run multiple times e.g. when scheduled with cron.
12
+ */
13
+ workflowId: string;
14
+
15
+ /**
16
+ * ID of a single Workflow run
17
+ */
18
+ runId: string;
19
+
20
+ /**
21
+ * Workflow function's name
22
+ */
23
+ workflowType: string;
24
+
25
+ /**
26
+ * Indexed information attached to the Workflow Execution
27
+ */
28
+ searchAttributes: SearchAttributes;
29
+
30
+ /**
31
+ * Non-indexed information attached to the Workflow Execution
32
+ */
33
+ memo?: Record<string, unknown>;
34
+
35
+ /**
36
+ * Parent Workflow info (present if this is a Child Workflow)
37
+ */
38
+ parent?: ParentWorkflowInfo;
39
+
40
+ /**
41
+ * Result from the previous Run (present if this is a Cron Workflow or was Continued As New).
42
+ *
43
+ * An array of values, since other SDKs may return multiple values from a Workflow.
44
+ */
45
+ lastResult?: unknown;
46
+
47
+ /**
48
+ * Failure from the previous Run (present when this Run is a retry, or the last Run of a Cron Workflow failed)
49
+ */
50
+ lastFailure?: TemporalFailure;
51
+
52
+ /**
53
+ * Task queue this Workflow is executing on
54
+ */
55
+ taskQueue: string;
56
+
57
+ /**
58
+ * Namespace this Workflow is executing in
59
+ */
60
+ namespace: string;
61
+
62
+ /**
63
+ * Run Id of the first Run in this Execution Chain
64
+ */
65
+ firstExecutionRunId: string;
66
+
67
+ /**
68
+ * The last Run Id in this Execution Chain
69
+ */
70
+ continuedFromExecutionRunId?: string;
71
+
72
+ // TODO expose from Core
73
+ /**
74
+ * Time at which the Workflow Run started
75
+ */
76
+ // startTime: Date;
77
+
78
+ /**
79
+ * Milliseconds after which the Workflow Execution is automatically terminated by Temporal Server. Set via {@link WorkflowOptions.workflowExecutionTimeout}.
80
+ */
81
+ executionTimeoutMs?: number;
82
+
83
+ /**
84
+ * Time at which the Workflow Execution expires
85
+ */
86
+ executionExpirationTime?: Date;
87
+
88
+ /**
89
+ * Milliseconds after which the Workflow Run is automatically terminated by Temporal Server. Set via {@link WorkflowOptions.workflowRunTimeout}.
90
+ */
91
+ runTimeoutMs?: number;
92
+
93
+ /**
94
+ * Maximum execution time of a Workflow Task in milliseconds. Set via {@link WorkflowOptions.workflowTaskTimeout}.
95
+ */
96
+ taskTimeoutMs: number;
97
+
98
+ /**
99
+ * Retry Policy for this Execution. Set via {@link WorkflowOptions.retry}.
100
+ */
101
+ retryPolicy?: RetryPolicy;
102
+
103
+ /**
104
+ * Starts at 1 and increments for every retry if there is a `retryPolicy`
105
+ */
106
+ attempt: number;
107
+
108
+ /**
109
+ * Cron Schedule for this Execution. Set via {@link WorkflowOptions.cronSchedule}.
110
+ */
111
+ cronSchedule?: string;
112
+
113
+ /**
114
+ * Milliseconds between Cron Runs
115
+ */
116
+ cronScheduleToScheduleInterval?: number;
117
+ }
118
+
119
+ export interface ParentWorkflowInfo {
120
+ workflowId: string;
121
+ runId: string;
122
+ namespace: string;
123
+ }
124
+
125
+ /**
126
+ * Not an actual error, used by the Workflow runtime to abort execution when {@link continueAsNew} is called
127
+ */
128
+ export class ContinueAsNew extends Error {
129
+ public readonly name = 'ContinueAsNew';
130
+
131
+ constructor(public readonly command: coresdk.workflow_commands.IContinueAsNewWorkflowExecution) {
132
+ super('Workflow continued as new');
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Options for continuing a Workflow as new
138
+ */
139
+ export interface ContinueAsNewOptions {
140
+ /**
141
+ * A string representing the Workflow type name, e.g. the filename in the Node.js SDK or class name in Java
142
+ */
143
+ workflowType?: string;
144
+ /**
145
+ * Task queue to continue the Workflow in
146
+ */
147
+ taskQueue?: string;
148
+ /**
149
+ * Timeout for the entire Workflow run
150
+ * @format {@link https://www.npmjs.com/package/ms | ms} formatted string
151
+ */
152
+ workflowRunTimeout?: string;
153
+ /**
154
+ * Timeout for a single Workflow task
155
+ * @format {@link https://www.npmjs.com/package/ms | ms} formatted string
156
+ */
157
+ workflowTaskTimeout?: string;
158
+ /**
159
+ * Non-searchable attributes to attach to next Workflow run
160
+ */
161
+ memo?: Record<string, any>;
162
+ /**
163
+ * Searchable attributes to attach to next Workflow run
164
+ */
165
+ searchAttributes?: SearchAttributes;
166
+ }
167
+
168
+ /**
169
+ * Specifies:
170
+ * - whether cancellation requests are sent to the Child
171
+ * - whether and when a {@link CanceledFailure} is thrown from {@link executeChild} or
172
+ * {@link ChildWorkflowHandle.result}
173
+ *
174
+ * @default {@link ChildWorkflowCancellationType.WAIT_CANCELLATION_COMPLETED}
175
+ */
176
+ export enum ChildWorkflowCancellationType {
177
+ /**
178
+ * Don't send a cancellation request to the Child.
179
+ */
180
+ ABANDON = 0,
181
+
182
+ /**
183
+ * Send a cancellation request to the Child. Immediately throw the error.
184
+ */
185
+ TRY_CANCEL = 1,
186
+
187
+ /**
188
+ * Send a cancellation request to the Child. The Child may respect cancellation, in which case an error will be thrown
189
+ * when cancellation has completed, and {@link isCancellation}(error) will be true. On the other hand, the Child may
190
+ * ignore the cancellation request, in which case an error might be thrown with a different cause, or the Child may
191
+ * complete successfully.
192
+ *
193
+ * @default
194
+ */
195
+ WAIT_CANCELLATION_COMPLETED = 2,
196
+
197
+ /**
198
+ * Send a cancellation request to the Child. Throw the error once the Server receives the Child cancellation request.
199
+ */
200
+ WAIT_CANCELLATION_REQUESTED = 3,
201
+ }
202
+
203
+ checkExtends<coresdk.child_workflow.ChildWorkflowCancellationType, ChildWorkflowCancellationType>();
204
+
205
+ /**
206
+ * How a Child Workflow reacts to the Parent Workflow reaching a Closed state.
207
+ *
208
+ * @see {@link https://docs.temporal.io/concepts/what-is-a-parent-close-policy/ | Parent Close Policy}
209
+ */
210
+ export enum ParentClosePolicy {
211
+ /**
212
+ * If a `ParentClosePolicy` is set to this, or is not set at all, the server default value will be used.
213
+ */
214
+ PARENT_CLOSE_POLICY_UNSPECIFIED = 0,
215
+
216
+ /**
217
+ * When the Parent is Closed, the Child is Terminated.
218
+ *
219
+ * @default
220
+ */
221
+ PARENT_CLOSE_POLICY_TERMINATE = 1,
222
+
223
+ /**
224
+ * When the Parent is Closed, nothing is done to the Child.
225
+ */
226
+ PARENT_CLOSE_POLICY_ABANDON = 2,
227
+
228
+ /**
229
+ * When the Parent is Closed, the Child is Cancelled.
230
+ */
231
+ PARENT_CLOSE_POLICY_REQUEST_CANCEL = 3,
232
+ }
233
+
234
+ checkExtends<coresdk.child_workflow.ParentClosePolicy, ParentClosePolicy>();
235
+
236
+ export interface ChildWorkflowOptions extends CommonWorkflowOptions {
237
+ /**
238
+ * Workflow id to use when starting. If not specified a UUID is generated. Note that it is
239
+ * dangerous as in case of client side retries no deduplication will happen based on the
240
+ * generated id. So prefer assigning business meaningful ids if possible.
241
+ */
242
+ workflowId?: string;
243
+
244
+ /**
245
+ * Task queue to use for Workflow tasks. It should match a task queue specified when creating a
246
+ * `Worker` that hosts the Workflow code.
247
+ */
248
+ taskQueue?: string;
249
+
250
+ /**
251
+ * Specifies:
252
+ * - whether cancellation requests are sent to the Child
253
+ * - whether and when an error is thrown from {@link executeChild} or
254
+ * {@link ChildWorkflowHandle.result}
255
+ *
256
+ * @default {@link ChildWorkflowCancellationType.WAIT_CANCELLATION_COMPLETED}
257
+ */
258
+ cancellationType?: ChildWorkflowCancellationType;
259
+
260
+ /**
261
+ * Specifies how the Child reacts to the Parent Workflow reaching a Closed state.
262
+ *
263
+ * @default {@link ParentClosePolicy.PARENT_CLOSE_POLICY_TERMINATE}
264
+ */
265
+ parentClosePolicy?: ParentClosePolicy;
266
+ }
267
+
268
+ export type RequiredChildWorkflowOptions = Required<Pick<ChildWorkflowOptions, 'workflowId' | 'cancellationType'>> & {
269
+ args: unknown[];
270
+ };
271
+
272
+ export type ChildWorkflowOptionsWithDefaults = ChildWorkflowOptions & RequiredChildWorkflowOptions;