@temporalio/workflow 1.8.6 → 1.9.0-rc.0

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/errors.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { ActivityFailure, CancelledFailure, ChildWorkflowFailure } from '@temporalio/common';
2
2
  import { SymbolBasedInstanceOfError } from '@temporalio/common/lib/type-helpers';
3
+ import { coresdk } from '@temporalio/proto';
3
4
 
4
5
  /**
5
6
  * Base class for all workflow errors
@@ -13,6 +14,16 @@ export class WorkflowError extends Error {}
13
14
  @SymbolBasedInstanceOfError('DeterminismViolationError')
14
15
  export class DeterminismViolationError extends WorkflowError {}
15
16
 
17
+ /**
18
+ * A class that acts as a marker for this special result type
19
+ */
20
+ @SymbolBasedInstanceOfError('LocalActivityDoBackoff')
21
+ export class LocalActivityDoBackoff extends Error {
22
+ constructor(public readonly backoff: coresdk.activity_result.IDoBackoff) {
23
+ super();
24
+ }
25
+ }
26
+
16
27
  /**
17
28
  * Returns whether provided `err` is caused by cancellation
18
29
  */
@@ -1,3 +1,6 @@
1
+ import { IllegalStateError } from '@temporalio/common';
2
+ import { type Activator } from './internals';
3
+
1
4
  export function maybeGetActivatorUntyped(): unknown {
2
5
  return (globalThis as any).__TEMPORAL_ACTIVATOR__;
3
6
  }
@@ -5,3 +8,21 @@ export function maybeGetActivatorUntyped(): unknown {
5
8
  export function setActivatorUntyped(activator: unknown): void {
6
9
  (globalThis as any).__TEMPORAL_ACTIVATOR__ = activator;
7
10
  }
11
+
12
+ export function maybeGetActivator(): Activator | undefined {
13
+ return maybeGetActivatorUntyped() as Activator | undefined;
14
+ }
15
+
16
+ export function assertInWorkflowContext(message: string): Activator {
17
+ const activator = maybeGetActivator();
18
+ if (activator == null) throw new IllegalStateError(message);
19
+ return activator;
20
+ }
21
+
22
+ export function getActivator(): Activator {
23
+ const activator = maybeGetActivator();
24
+ if (activator === undefined) {
25
+ throw new IllegalStateError('Workflow uninitialized');
26
+ }
27
+ return activator;
28
+ }
package/src/index.ts CHANGED
@@ -20,18 +20,21 @@
20
20
  * <!--SNIPSTART typescript-schedule-activity-workflow-->
21
21
  * <!--SNIPEND-->
22
22
  *
23
- * ### Signals and Queries
23
+ * ### Updates, Signals and Queries
24
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.
25
+ * Use {@link setHandler} to set handlers for Updates, Signals, and Queries.
27
26
  *
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`.
27
+ * Update and Signal handlers can be either async or non-async functions. Update handlers may return a value, but signal
28
+ * handlers may not (return `void` or `Promise<void>`). You may use Activities, Timers, child Workflows, etc in Update
29
+ * and Signal handlers, but this should be done cautiously: for example, note that if you await async operations such as
30
+ * these in an Update or Signal handler, then you are responsible for ensuring that the workflow does not complete first.
31
+ *
32
+ * Query handlers may **not** be async functions, and may **not** mutate any variables or use Activities, Timers,
33
+ * child Workflows, etc.
31
34
  *
32
35
  * #### Implementation
33
36
  *
34
- * <!--SNIPSTART typescript-workflow-signal-implementation-->
37
+ * <!--SNIPSTART typescript-workflow-update-signal-query-example-->
35
38
  * <!--SNIPEND-->
36
39
  *
37
40
  * ### More
@@ -98,7 +101,20 @@ export {
98
101
  UnsafeWorkflowInfo,
99
102
  WorkflowInfo,
100
103
  } from './interfaces';
101
- export { LoggerSinks, Sink, SinkCall, SinkFunction, Sinks } from './sinks';
104
+ export { proxySinks, Sink, SinkCall, SinkFunction, Sinks } from './sinks';
105
+ export { log } from './logs';
102
106
  export { Trigger } from './trigger';
103
107
  export * from './workflow';
104
108
  export { ChildWorkflowHandle, ExternalWorkflowHandle } from './workflow-handle';
109
+
110
+ // Anything below this line is deprecated
111
+
112
+ export {
113
+ /**
114
+ * @deprecated Do not use LoggerSinks directly. To log from Workflow code, use the `log` object
115
+ * exported by the `@temporalio/workflow` package. To capture log messages emitted
116
+ * by Workflow code, set the {@link Runtime.logger} property.
117
+ */
118
+ // eslint-disable-next-line deprecation/deprecation
119
+ LoggerSinksDeprecated as LoggerSinks,
120
+ } from './logs';
@@ -18,6 +18,15 @@ export interface WorkflowExecuteInput {
18
18
  readonly headers: Headers;
19
19
  }
20
20
 
21
+ /** Input for WorkflowInboundCallsInterceptor.handleUpdate and
22
+ * WorkflowInboundCallsInterceptor.validateUpdate */
23
+ export interface UpdateInput {
24
+ readonly updateId: string;
25
+ readonly name: string;
26
+ readonly args: unknown[];
27
+ readonly headers: Headers;
28
+ }
29
+
21
30
  /** Input for WorkflowInboundCallsInterceptor.handleSignal */
22
31
  export interface SignalInput {
23
32
  readonly signalName: string;
@@ -44,6 +53,15 @@ export interface WorkflowInboundCallsInterceptor {
44
53
  */
45
54
  execute?: (input: WorkflowExecuteInput, next: Next<this, 'execute'>) => Promise<unknown>;
46
55
 
56
+ /** Called when Update handler is called
57
+ *
58
+ * @return result of the Update
59
+ */
60
+ handleUpdate?: (input: UpdateInput, next: Next<this, 'handleUpdate'>) => Promise<unknown>;
61
+
62
+ /** Called when update validator called */
63
+ validateUpdate?: (input: UpdateInput, next: Next<this, 'validateUpdate'>) => void;
64
+
47
65
  /** Called when signal is delivered to a Workflow execution */
48
66
  handleSignal?: (input: SignalInput, next: Next<this, 'handleSignal'>) => Promise<void>;
49
67
 
package/src/interfaces.ts CHANGED
@@ -5,6 +5,7 @@ import {
5
5
  CommonWorkflowOptions,
6
6
  SearchAttributes,
7
7
  SignalDefinition,
8
+ UpdateDefinition,
8
9
  QueryDefinition,
9
10
  Duration,
10
11
  VersioningIntent,
@@ -20,46 +21,46 @@ export interface WorkflowInfo {
20
21
  * ID of the Workflow, this can be set by the client during Workflow creation.
21
22
  * A single Workflow may run multiple times e.g. when scheduled with cron.
22
23
  */
23
- workflowId: string;
24
+ readonly workflowId: string;
24
25
 
25
26
  /**
26
27
  * ID of a single Workflow run
27
28
  */
28
- runId: string;
29
+ readonly runId: string;
29
30
 
30
31
  /**
31
32
  * Workflow function's name
32
33
  */
33
- workflowType: string;
34
+ readonly workflowType: string;
34
35
 
35
36
  /**
36
37
  * Indexed information attached to the Workflow Execution
37
38
  *
38
39
  * This value may change during the lifetime of an Execution.
39
40
  */
40
- searchAttributes: SearchAttributes;
41
+ readonly searchAttributes: SearchAttributes;
41
42
 
42
43
  /**
43
44
  * Non-indexed information attached to the Workflow Execution
44
45
  */
45
- memo?: Record<string, unknown>;
46
+ readonly memo?: Record<string, unknown>;
46
47
 
47
48
  /**
48
49
  * Parent Workflow info (present if this is a Child Workflow)
49
50
  */
50
- parent?: ParentWorkflowInfo;
51
+ readonly parent?: ParentWorkflowInfo;
51
52
 
52
53
  /**
53
54
  * Result from the previous Run (present if this is a Cron Workflow or was Continued As New).
54
55
  *
55
56
  * An array of values, since other SDKs may return multiple values from a Workflow.
56
57
  */
57
- lastResult?: unknown;
58
+ readonly lastResult?: unknown;
58
59
 
59
60
  /**
60
61
  * Failure from the previous Run (present when this Run is a retry, or the last Run of a Cron Workflow failed)
61
62
  */
62
- lastFailure?: TemporalFailure;
63
+ readonly lastFailure?: TemporalFailure;
63
64
 
64
65
  /**
65
66
  * Length of Workflow history up until the current Workflow Task.
@@ -68,7 +69,7 @@ export interface WorkflowInfo {
68
69
  *
69
70
  * You may safely use this information to decide when to {@link continueAsNew}.
70
71
  */
71
- historyLength: number;
72
+ readonly historyLength: number;
72
73
 
73
74
  /**
74
75
  * Size of Workflow history in bytes until the current Workflow Task.
@@ -79,7 +80,7 @@ export interface WorkflowInfo {
79
80
  *
80
81
  * You may safely use this information to decide when to {@link continueAsNew}.
81
82
  */
82
- historySize: number;
83
+ readonly historySize: number;
83
84
 
84
85
  /**
85
86
  * A hint provided by the current WorkflowTaskStarted event recommending whether to
@@ -89,79 +90,79 @@ export interface WorkflowInfo {
89
90
  *
90
91
  * Supported only on Temporal Server 1.20+, always `false` on older servers.
91
92
  */
92
- continueAsNewSuggested: boolean;
93
+ readonly continueAsNewSuggested: boolean;
93
94
 
94
95
  /**
95
96
  * Task queue this Workflow is executing on
96
97
  */
97
- taskQueue: string;
98
+ readonly taskQueue: string;
98
99
 
99
100
  /**
100
101
  * Namespace this Workflow is executing in
101
102
  */
102
- namespace: string;
103
+ readonly namespace: string;
103
104
 
104
105
  /**
105
106
  * Run Id of the first Run in this Execution Chain
106
107
  */
107
- firstExecutionRunId: string;
108
+ readonly firstExecutionRunId: string;
108
109
 
109
110
  /**
110
111
  * The last Run Id in this Execution Chain
111
112
  */
112
- continuedFromExecutionRunId?: string;
113
+ readonly continuedFromExecutionRunId?: string;
113
114
 
114
115
  /**
115
116
  * Time at which this [Workflow Execution Chain](https://docs.temporal.io/workflows#workflow-execution-chain) was started
116
117
  */
117
- startTime: Date;
118
+ readonly startTime: Date;
118
119
 
119
120
  /**
120
121
  * Time at which the current Workflow Run started
121
122
  */
122
- runStartTime: Date;
123
+ readonly runStartTime: Date;
123
124
 
124
125
  /**
125
126
  * Milliseconds after which the Workflow Execution is automatically terminated by Temporal Server. Set via {@link WorkflowOptions.workflowExecutionTimeout}.
126
127
  */
127
- executionTimeoutMs?: number;
128
+ readonly executionTimeoutMs?: number;
128
129
 
129
130
  /**
130
131
  * Time at which the Workflow Execution expires
131
132
  */
132
- executionExpirationTime?: Date;
133
+ readonly executionExpirationTime?: Date;
133
134
 
134
135
  /**
135
136
  * Milliseconds after which the Workflow Run is automatically terminated by Temporal Server. Set via {@link WorkflowOptions.workflowRunTimeout}.
136
137
  */
137
- runTimeoutMs?: number;
138
+ readonly runTimeoutMs?: number;
138
139
 
139
140
  /**
140
141
  * Maximum execution time of a Workflow Task in milliseconds. Set via {@link WorkflowOptions.workflowTaskTimeout}.
141
142
  */
142
- taskTimeoutMs: number;
143
+ readonly taskTimeoutMs: number;
143
144
 
144
145
  /**
145
146
  * Retry Policy for this Execution. Set via {@link WorkflowOptions.retry}.
146
147
  */
147
- retryPolicy?: RetryPolicy;
148
+ readonly retryPolicy?: RetryPolicy;
148
149
 
149
150
  /**
150
151
  * Starts at 1 and increments for every retry if there is a `retryPolicy`
151
152
  */
152
- attempt: number;
153
+ readonly attempt: number;
153
154
 
154
155
  /**
155
156
  * Cron Schedule for this Execution. Set via {@link WorkflowOptions.cronSchedule}.
156
157
  */
157
- cronSchedule?: string;
158
+ readonly cronSchedule?: string;
158
159
 
159
160
  /**
160
161
  * Milliseconds between Cron Runs
161
162
  */
162
- cronScheduleToScheduleInterval?: number;
163
+ readonly cronScheduleToScheduleInterval?: number;
163
164
 
164
- unsafe: UnsafeWorkflowInfo;
165
+ readonly unsafe: UnsafeWorkflowInfo;
165
166
  }
166
167
 
167
168
  /**
@@ -176,9 +177,9 @@ export interface UnsafeWorkflowInfo {
176
177
  * The safe version of time is `new Date()` and `Date.now()`, which are set on the first invocation of a Workflow
177
178
  * Task and stay constant for the duration of the Task and during replay.
178
179
  */
179
- now(): number;
180
+ readonly now: () => number;
180
181
 
181
- isReplaying: boolean;
182
+ readonly isReplaying: boolean;
182
183
  }
183
184
 
184
185
  export interface ParentWorkflowInfo {
@@ -231,6 +232,8 @@ export interface ContinueAsNewOptions {
231
232
  * When using the Worker Versioning feature, specifies whether this Workflow should
232
233
  * Continue-as-New onto a worker with a compatible Build Id or not. See {@link VersioningIntent}.
233
234
  *
235
+ * @default 'COMPATIBLE'
236
+ *
234
237
  * @experimental
235
238
  */
236
239
  versioningIntent?: VersioningIntent;
@@ -341,6 +344,8 @@ export interface ChildWorkflowOptions extends CommonWorkflowOptions {
341
344
  * When using the Worker Versioning feature, specifies whether this Child Workflow should run on
342
345
  * a worker with a compatible Build Id or not. See {@link VersioningIntent}.
343
346
  *
347
+ * @default 'COMPATIBLE'
348
+ *
344
349
  * @experimental
345
350
  */
346
351
  versioningIntent?: VersioningIntent;
@@ -428,19 +433,26 @@ export interface WorkflowCreateOptionsInternal extends WorkflowCreateOptions {
428
433
  }
429
434
 
430
435
  /**
431
- * A handler function capable of accepting the arguments for a given SignalDefinition or QueryDefinition.
436
+ * A handler function capable of accepting the arguments for a given UpdateDefinition, SignalDefinition or QueryDefinition.
432
437
  */
433
438
  export type Handler<
434
439
  Ret,
435
440
  Args extends any[],
436
- T extends SignalDefinition<Args> | QueryDefinition<Ret, Args>
437
- > = T extends SignalDefinition<infer A>
441
+ T extends UpdateDefinition<Ret, Args> | SignalDefinition<Args> | QueryDefinition<Ret, Args>
442
+ > = T extends UpdateDefinition<infer R, infer A>
443
+ ? (...args: A) => R | Promise<R>
444
+ : T extends SignalDefinition<infer A>
438
445
  ? (...args: A) => void | Promise<void>
439
446
  : T extends QueryDefinition<infer R, infer A>
440
447
  ? (...args: A) => R
441
448
  : never;
442
449
 
443
450
  /**
444
- * A handler function accepting signals calls for non-registered signal names.
451
+ * A handler function accepting signal calls for non-registered signal names.
445
452
  */
446
453
  export type DefaultSignalHandler = (signalName: string, ...args: unknown[]) => void | Promise<void>;
454
+
455
+ /**
456
+ * A validation function capable of accepting the arguments for a given UpdateDefinition.
457
+ */
458
+ export type UpdateValidator<Args extends any[]> = (...args: Args) => void;