@sanity/functions 1.8.0 → 1.9.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.
@@ -1,4 +1,25 @@
1
1
  import type { DurableHandler } from './types/durables.js';
2
+ /**
3
+ * Error type indicating an unrecoverable error in a durable function.
4
+ * Used to override the retry behavior in a durable step operation.
5
+ * @alpha Durable functions are an experimental feature and may change in the future.
6
+ * @hidden
7
+ * @example
8
+ * ```ts
9
+ * const handler = durableEventHandler(async ({step}) => {
10
+ * async step.run(async ({attempt}) => {
11
+ * // step.run code
12
+ * }, retry: {maxAttempts: 3})
13
+ * }).catch((err) => {
14
+ * if (err instanceof UserNotFound) {
15
+ * throw new UnrecoverableError(err)
16
+ * }
17
+ * })
18
+ * ```
19
+ */
20
+ export declare class UnrecoverableError extends Error {
21
+ name: string;
22
+ }
2
23
  /**
3
24
  * Durables creation function that can be called with or without a config object.
4
25
  * @alpha Durables are an experimental feature and may change in the future.
package/dist/durables.js CHANGED
@@ -1,3 +1,24 @@
1
+ /**
2
+ * Error type indicating an unrecoverable error in a durable function.
3
+ * Used to override the retry behavior in a durable step operation.
4
+ * @alpha Durable functions are an experimental feature and may change in the future.
5
+ * @hidden
6
+ * @example
7
+ * ```ts
8
+ * const handler = durableEventHandler(async ({step}) => {
9
+ * async step.run(async ({attempt}) => {
10
+ * // step.run code
11
+ * }, retry: {maxAttempts: 3})
12
+ * }).catch((err) => {
13
+ * if (err instanceof UserNotFound) {
14
+ * throw new UnrecoverableError(err)
15
+ * }
16
+ * })
17
+ * ```
18
+ */
19
+ export class UnrecoverableError extends Error {
20
+ name = 'UnrecoverableError';
21
+ }
1
22
  /**
2
23
  * Determine if `durableEventHandler({}, () => {})` or `durableEventHandler(() => {})`.
3
24
  * @param configOrHandler
@@ -1 +1 @@
1
- {"version":3,"file":"durables.js","sourceRoot":"","sources":["../src/durables.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,eAAe,GAAG,C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 export interface DurableLogger {
26
26
  export interface DurableStepCallbackContext {
27
27
  logger: DurableLogger;
28
28
  }
29
+ /**
30
+ * Context parameter passed to a branch method of a `step.fanout` execution.
31
+ * @alpha Using durables is considered experimental and may change in the future.
32
+ * @hidden
33
+ */
34
+ export interface DurableStepContext extends DurableStepCallbackContext {
35
+ step: DurableOperations;
36
+ }
37
+ export interface DurableFanoutBranchContext extends DurableStepContext {
38
+ }
39
+ /**
40
+ * Context parameter passed to the top-level `durableEventHandler` method.
41
+ * @alpha Using durables is considered experimental and may change in the future.
42
+ * @hidden
43
+ */
44
+ export interface DurableTopLevelContext extends DurableStepContext {
45
+ context: DurableContext;
46
+ event?: GenericEvent;
47
+ }
29
48
  /**
30
49
  * Arguments passed to callbacks that execute a durable attempt.
31
50
  * step.run & step.waitForCondition
@@ -57,94 +76,160 @@ export type DurableDuration = {
57
76
  } | {
58
77
  seconds: number;
59
78
  };
60
- /**
61
- * @alpha: Using durables is considered experimental and may change in the future.
62
- * @hidden
63
- */
64
- export type DurableJitterStrategy = 'none' | 'full' | 'half';
65
79
  /**
66
80
  * @alpha: Using durables is considered experimental and may change in the future.
67
81
  * @hidden
68
82
  */
69
83
  export interface DurableRetryStrategy {
70
84
  maxAttempts?: number;
71
- initialDelay?: DurableDuration;
72
- maxDelay?: DurableDuration;
73
- backoffRate?: number;
74
- jitter?: DurableJitterStrategy;
75
- retryableErrors?: (string | RegExp)[];
76
- retryableErrorTypes?: (new () => Error)[];
85
+ delay?: DurableDuration;
77
86
  }
78
87
  /**
79
- * @alpha: Using durables is considered experimental and may change in the future.
88
+ * @alpha Using durables is considered experimental and may change in the future.
80
89
  * @hidden
81
90
  */
82
- export type DurableStepSemantics = 'at-most-once-per-retry' | 'at-least-once-per-retry';
91
+ export type DurableWaitForConditionDecision = {
92
+ shouldRetry: true;
93
+ delay: DurableDuration;
94
+ } | {
95
+ shouldRetry: false;
96
+ };
83
97
  /**
84
- * @alpha: Using durables is considered experimental and may change in the future.
98
+ * @alpha Using durables is considered experimental and may change in the future.
85
99
  * @hidden
86
100
  */
87
- export interface DurableStepConfig {
88
- strategy?: DurableRetryStrategy;
89
- semantics?: DurableStepSemantics;
90
- }
101
+ export type DurableStepHandler<TArgs extends unknown[], TReturn> = (...args: TArgs) => TReturn;
91
102
  /**
92
- * Allowed operations in a retry code block
93
- * @alpha: Using durables is considered experimental and may change in the future.
103
+ * @alpha Using durables is considered experimental and may change in the future.
94
104
  * @hidden
95
105
  */
96
- export type DurableRetryOperations = Pick<DurableOperations, 'delegate' | 'waitForCallback' | 'waitForCondition'>;
106
+ export type DurableStepRunHandler<T = unknown> = DurableStepHandler<[context: DurableStepAttemptContext], T | Promise<T>>;
97
107
  /**
98
- * @alpha: Using durables is considered experimental and may change in the future.
108
+ * @alpha Using durables is considered experimental and may change in the future.
99
109
  * @hidden
100
110
  */
101
- export type DurableRetryBlock<T> = (envelope: {
102
- step: DurableRetryOperations;
103
- attempt: number;
104
- }) => Promise<T>;
111
+ export type DurableStepFanoutHandler<T = unknown> = DurableStepHandler<[context: DurableFanoutBranchContext], T | Promise<T>>;
105
112
  /**
106
- * @alpha: Using durables is considered experimental and may change in the future.
113
+ * @alpha Using durables is considered experimental and may change in the future.
107
114
  * @hidden
108
115
  */
109
- export type DurableRetry = <T>(name: string | undefined, config: DurableRetryStrategy, block: DurableRetryBlock<T>) => Promise<T>;
116
+ export type DurableStepWaitForCallbackHandler = DurableStepHandler<[callbackId: string, context: DurableStepCallbackContext], Promise<void>>;
110
117
  /**
111
118
  * @alpha Using durables is considered experimental and may change in the future.
112
119
  * @hidden
113
120
  */
114
- export type DurableWaitForConditionDecision = {
115
- shouldRetry: true;
116
- delay: DurableDuration;
117
- } | {
118
- shouldRetry: false;
119
- };
121
+ export type DurableWaitForConditionPoller<T = unknown> = DurableStepHandler<[state: T, context: DurableStepAttemptContext], Promise<T>>;
120
122
  /**
121
123
  * @alpha Using durables is considered experimental and may change in the future.
122
124
  * @hidden
123
125
  */
124
- export type DurableStepHandler<TArgs extends unknown[], TReturn> = (...args: TArgs) => TReturn;
126
+ export type DurableWaitForConditionNext<T = unknown> = DurableStepHandler<[
127
+ state: T,
128
+ context: Pick<DurableStepAttemptContext, 'attempt'>
129
+ ], DurableWaitForConditionDecision>;
125
130
  /**
126
131
  * @alpha Using durables is considered experimental and may change in the future.
127
132
  * @hidden
128
133
  */
129
- export type DurableStepRunHandler<T = unknown> = DurableStepHandler<[context: DurableStepAttemptContext], T | Promise<T>>;
134
+ export type BatchItemSucceededStatus = 'SUCCEEDED';
130
135
  /**
131
136
  * @alpha Using durables is considered experimental and may change in the future.
132
137
  * @hidden
133
138
  */
134
- export type DurableStepWaitForCallbackHandler = DurableStepHandler<[callbackId: string, context: DurableStepCallbackContext], Promise<void>>;
139
+ export type BatchItemFailedStatus = 'FAILED';
135
140
  /**
136
141
  * @alpha Using durables is considered experimental and may change in the future.
137
142
  * @hidden
138
143
  */
139
- export type DurableWaitForConditionPoller<T = unknown> = DurableStepHandler<[state: T, context: DurableStepAttemptContext], Promise<T>>;
144
+ export type BatchItemStartedStatus = 'STARTED';
140
145
  /**
141
146
  * @alpha Using durables is considered experimental and may change in the future.
142
147
  * @hidden
143
148
  */
144
- export type DurableWaitForConditionNext<T = unknown> = DurableStepHandler<[
145
- state: T,
146
- context: Pick<DurableStepAttemptContext, 'attempt'>
147
- ], DurableWaitForConditionDecision>;
149
+ export type BatchItemStatus = BatchItemSucceededStatus | BatchItemFailedStatus | BatchItemStartedStatus;
150
+ /**
151
+ * Reason why a batch operation (map, parallel, or concurrent execution)
152
+ * completed.
153
+ *
154
+ * - `ALL_COMPLETED`: every item finished.
155
+ * - `MIN_SUCCESSFUL_REACHED`: CompletionConfig.minSuccessful was reached.
156
+ * - `FAILURE_TOLERANCE_EXCEEDED`: a failure threshold was exceeded.
157
+ * - `CUSTOM_COMPLETION_SUCCEEDED`: a custom CompletionConfig.shouldComplete
158
+ * predicate signalled completion with a `SUCCEEDED` outcome before all items
159
+ * finished.
160
+ * - `CUSTOM_COMPLETION_FAILED`: a custom CompletionConfig.shouldComplete
161
+ * predicate signalled completion with a `FAILED` outcome before all items
162
+ * finished.
163
+ * @alpha Using durables is considered experimental and may change in the future.
164
+ * @hidden
165
+ * @remarks copied from AWS Durable Execution SDK
166
+ */
167
+ export type CompletionReason = 'ALL_COMPLETED' | 'MIN_SUCCESSFUL_REACHED' | 'FAILURE_TOLERANCE_EXCEEDED' | 'CUSTOM_COMPLETION_SUCCEEDED' | 'CUSTOM_COMPLETION_FAILED';
168
+ /**
169
+ * The result of a `step.fanout` branch.
170
+ * @alpha Using durables is considered experimental and may change in the future.
171
+ * @hidden
172
+ * @remarks copied from AWS Durable Execution SDK
173
+ */
174
+ export interface BatchItem<TResult> {
175
+ /** The result value if the item succeeded */
176
+ result?: TResult;
177
+ /** The error if the item failed */
178
+ error?: Error;
179
+ /** Index of the item in the original array */
180
+ index: number;
181
+ /** Status of the item execution */
182
+ status: BatchItemStatus;
183
+ }
184
+ /**
185
+ * @alpha Using durables is considered experimental and may change in the future.
186
+ * @hidden
187
+ * @remarks copied from AWS Durable Execution SDK
188
+ */
189
+ export interface BatchResult<TResult> {
190
+ /**
191
+ * All items in the batch with their results/errors.
192
+ */
193
+ all: Array<BatchItem<TResult>>;
194
+ /** Returns only the items that succeeded */
195
+ succeeded(): Array<BatchItem<TResult> & {
196
+ result: TResult;
197
+ }>;
198
+ /** Returns only the items that failed */
199
+ failed(): Array<BatchItem<TResult> & {
200
+ error: Error;
201
+ }>;
202
+ /**
203
+ * Returns only the items that are still in progress (STARTED) — items that
204
+ * were in flight when the batch completed early (e.g. via CompletionConfig.minSuccessful
205
+ * or a custom CompletionConfig.shouldComplete).
206
+ */
207
+ started(): Array<BatchItem<TResult> & {
208
+ status: BatchItemStartedStatus;
209
+ }>;
210
+ /** Overall status of the batch (SUCCEEDED if no failures, FAILED otherwise) */
211
+ status: BatchItemSucceededStatus | BatchItemFailedStatus;
212
+ /** Reason why the batch completed */
213
+ completionReason: CompletionReason;
214
+ /** Whether any item in the batch failed */
215
+ hasFailure: boolean;
216
+ /** Throws the first error if any item failed */
217
+ throwIfError(): void;
218
+ /** Returns array of all successful results */
219
+ getResults(): Array<TResult>;
220
+ /** Returns array of all errors */
221
+ getErrors(): Array<Error>;
222
+ /** Number of successful items */
223
+ successCount: number;
224
+ /** Number of failed items */
225
+ failureCount: number;
226
+ /**
227
+ * Number of started but not completed items. Not guaranteed to be stable across suspend/resume
228
+ */
229
+ startedCount: number;
230
+ /** Total number of items */
231
+ totalCount: number;
232
+ }
148
233
  /**
149
234
  * The interface defining the operations available to a durable function.
150
235
  * These operations are steps that delegate to other functions, and wait for external callbacks.
@@ -172,7 +257,7 @@ export type DurableOperations = {
172
257
  * step.run({
173
258
  * name: 'run-with-retry'
174
259
  * handler: () => { // handler code }
175
- * retry: { strategy: { maxAttempts: 2 } }
260
+ * retry: { maxAttempts: 2, delay: { seconds: 5 } }
176
261
  * })
177
262
  * ```
178
263
  * @param name - Step name
@@ -183,8 +268,57 @@ export type DurableOperations = {
183
268
  run<T>({ name, handler, retry }: {
184
269
  name?: string;
185
270
  handler: DurableStepRunHandler<T>;
186
- retry?: DurableStepConfig;
271
+ retry?: DurableRetryStrategy;
187
272
  }): Promise<T>;
273
+ /**
274
+ * Runs a set of steps, or branches, in parallel. Each branch contains its own child durable context, with all usual `step` operations available.
275
+ * @remarks By using the generic, you can set a single, homogeneous return type for all branches.
276
+ * @example
277
+ * ```ts
278
+ * step.fanout<string>({
279
+ * name: 'parallel-runs',
280
+ * branches: [async ({step, logger}) => {
281
+ * logger.log('Running first function in parallel')
282
+ * return 'first'
283
+ * }, async ({step, logger}) => {
284
+ * logger.log('Running second function in parallel')
285
+ * return 'second'
286
+ * }],
287
+ * })
288
+ * ```
289
+ * @param name - Step name
290
+ * @param branches - functions being executed in parallel
291
+ * @returns A batch result of values returned or errors thrown by all branches.
292
+ */
293
+ fanout<T>({ name, branches }: {
294
+ name?: string;
295
+ branches: DurableStepFanoutHandler<T>[];
296
+ }): Promise<BatchResult<T>>;
297
+ /**
298
+ * Runs a set of steps, or branches, in parallel. Each branch contains its own child durable context, with all usual `step` operations available.
299
+ * @remarks This overload provides automatic type inference for heterogeneous branch return types. When branches return different types, the result will be `BatchResult<T1 | T2 | ...>`.
300
+ * Use the explicit type parameter overloads above for strict homogeneous type checking.
301
+ * @example
302
+ * ```ts
303
+ * step.fanout<string>({
304
+ * name: 'parallel-runs',
305
+ * branches: [async ({step, logger}) => {
306
+ * logger.log('Running first function in parallel')
307
+ * return 'first'
308
+ * }, async ({step, logger}) => {
309
+ * logger.log('Running second function in parallel')
310
+ * return 'second'
311
+ * }],
312
+ * })
313
+ * ```
314
+ * @param name - Step name
315
+ * @param branches - functions being executed in parallel
316
+ * @returns A batch result of values returned or errors thrown by all branches.
317
+ */
318
+ fanout<Branches extends readonly unknown[]>({ name, branches, }: {
319
+ name?: string;
320
+ branches: Branches;
321
+ }): Promise<BatchResult<Branches[number] extends DurableStepFanoutHandler<infer ReturnType> ? ReturnType : never>>;
188
322
  /**
189
323
  * Calls another function and awaits its result.
190
324
  * similar to ctx.invoke()
@@ -218,6 +352,7 @@ export type DurableOperations = {
218
352
  name?: string;
219
353
  handler: string | BlueprintResource<`sanity.function.${string}`>;
220
354
  event?: unknown;
355
+ retry?: DurableRetryStrategy;
221
356
  }): Promise<T>;
222
357
  /**
223
358
  * Waits for an external callback
@@ -306,10 +441,4 @@ export type DurableOperations = {
306
441
  * @alpha Using durables is considered experimental and may change in the future.
307
442
  * @hidden
308
443
  */
309
- export type DurableHandler = (envelope: {
310
- context: DurableContext;
311
- event?: GenericEvent;
312
- step: DurableOperations;
313
- logger: DurableLogger;
314
- retry: DurableRetry;
315
- }) => unknown | Promise<unknown>;
444
+ export type DurableHandler = (envelope: DurableTopLevelContext) => unknown | Promise<unknown>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/functions",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "description": "Helper methods and type definitions for Sanity Functions",
5
5
  "keywords": [
6
6
  "sanity",
@@ -56,12 +56,12 @@
56
56
  "@aws-lite/sns-types": "^0.0.11",
57
57
  "@aws-lite/sqs": "^0.2.4",
58
58
  "@aws-lite/sqs-types": "^0.2.7",
59
- "@biomejs/biome": "2.5.8",
59
+ "@biomejs/biome": "2.5.15",
60
60
  "@types/node": "^22",
61
- "@vitest/coverage-v8": "4.1.10",
61
+ "@vitest/coverage-v8": "5.0.4",
62
62
  "rimraf": "^6.1.2",
63
63
  "typescript": "^7.0.2",
64
- "vitest": "4.1.10"
64
+ "vitest": "5.0.4"
65
65
  },
66
66
  "engines": {
67
67
  "node": ">=22"
package/src/durables.ts CHANGED
@@ -1,5 +1,27 @@
1
1
  import type {DurableHandler} from './types/durables.js'
2
2
 
3
+ /**
4
+ * Error type indicating an unrecoverable error in a durable function.
5
+ * Used to override the retry behavior in a durable step operation.
6
+ * @alpha Durable functions are an experimental feature and may change in the future.
7
+ * @hidden
8
+ * @example
9
+ * ```ts
10
+ * const handler = durableEventHandler(async ({step}) => {
11
+ * async step.run(async ({attempt}) => {
12
+ * // step.run code
13
+ * }, retry: {maxAttempts: 3})
14
+ * }).catch((err) => {
15
+ * if (err instanceof UserNotFound) {
16
+ * throw new UnrecoverableError(err)
17
+ * }
18
+ * })
19
+ * ```
20
+ */
21
+ export class UnrecoverableError extends Error {
22
+ override name = 'UnrecoverableError'
23
+ }
24
+
3
25
  /**
4
26
  * Determine if `durableEventHandler({}, () => {})` or `durableEventHandler(() => {})`.
5
27
  * @param configOrHandler
@@ -30,6 +30,26 @@ export interface DurableStepCallbackContext {
30
30
  logger: DurableLogger
31
31
  }
32
32
 
33
+ /**
34
+ * Context parameter passed to a branch method of a `step.fanout` execution.
35
+ * @alpha Using durables is considered experimental and may change in the future.
36
+ * @hidden
37
+ */
38
+ export interface DurableStepContext extends DurableStepCallbackContext {
39
+ step: DurableOperations
40
+ }
41
+ export interface DurableFanoutBranchContext extends DurableStepContext {}
42
+
43
+ /**
44
+ * Context parameter passed to the top-level `durableEventHandler` method.
45
+ * @alpha Using durables is considered experimental and may change in the future.
46
+ * @hidden
47
+ */
48
+ export interface DurableTopLevelContext extends DurableStepContext {
49
+ context: DurableContext
50
+ event?: GenericEvent
51
+ }
52
+
33
53
  /**
34
54
  * Arguments passed to callbacks that execute a durable attempt.
35
55
  * step.run & step.waitForCondition
@@ -53,98 +73,175 @@ export type DurableDuration =
53
73
  | {minutes: number; seconds?: number}
54
74
  | {seconds: number}
55
75
 
56
- /**
57
- * @alpha: Using durables is considered experimental and may change in the future.
58
- * @hidden
59
- */
60
- export type DurableJitterStrategy = 'none' | 'full' | 'half'
61
-
62
76
  /**
63
77
  * @alpha: Using durables is considered experimental and may change in the future.
64
78
  * @hidden
65
79
  */
66
80
  export interface DurableRetryStrategy {
67
81
  maxAttempts?: number
68
- initialDelay?: DurableDuration
69
- maxDelay?: DurableDuration
70
- backoffRate?: number
71
- jitter?: DurableJitterStrategy
72
- retryableErrors?: (string | RegExp)[]
73
- retryableErrorTypes?: (new () => Error)[]
82
+ // @todo: tie this to a string like "5s" or "1m" and normalize it to a duration object
83
+ delay?: DurableDuration
74
84
  }
75
85
 
76
86
  /**
77
- * @alpha: Using durables is considered experimental and may change in the future.
87
+ * @alpha Using durables is considered experimental and may change in the future.
78
88
  * @hidden
79
89
  */
80
- export type DurableStepSemantics = 'at-most-once-per-retry' | 'at-least-once-per-retry'
90
+ export type DurableWaitForConditionDecision = {shouldRetry: true; delay: DurableDuration} | {shouldRetry: false}
81
91
 
82
92
  /**
83
- * @alpha: Using durables is considered experimental and may change in the future.
93
+ * @alpha Using durables is considered experimental and may change in the future.
84
94
  * @hidden
85
95
  */
86
- export interface DurableStepConfig {
87
- strategy?: DurableRetryStrategy
88
- semantics?: DurableStepSemantics
89
- }
96
+ export type DurableStepHandler<TArgs extends unknown[], TReturn> = (...args: TArgs) => TReturn
90
97
 
91
98
  /**
92
- * Allowed operations in a retry code block
93
- * @alpha: Using durables is considered experimental and may change in the future.
99
+ * @alpha Using durables is considered experimental and may change in the future.
94
100
  * @hidden
95
101
  */
96
- export type DurableRetryOperations = Pick<DurableOperations, 'delegate' | 'waitForCallback' | 'waitForCondition'>
102
+ export type DurableStepRunHandler<T = unknown> = DurableStepHandler<[context: DurableStepAttemptContext], T | Promise<T>>
97
103
 
98
104
  /**
99
- * @alpha: Using durables is considered experimental and may change in the future.
105
+ * @alpha Using durables is considered experimental and may change in the future.
100
106
  * @hidden
101
107
  */
102
- export type DurableRetryBlock<T> = (envelope: {step: DurableRetryOperations; attempt: number}) => Promise<T>
108
+ export type DurableStepFanoutHandler<T = unknown> = DurableStepHandler<[context: DurableFanoutBranchContext], T | Promise<T>>
103
109
 
104
110
  /**
105
- * @alpha: Using durables is considered experimental and may change in the future.
111
+ * @alpha Using durables is considered experimental and may change in the future.
106
112
  * @hidden
107
113
  */
108
- export type DurableRetry = <T>(name: string | undefined, config: DurableRetryStrategy, block: DurableRetryBlock<T>) => Promise<T>
114
+ export type DurableStepWaitForCallbackHandler = DurableStepHandler<[callbackId: string, context: DurableStepCallbackContext], Promise<void>>
109
115
 
110
116
  /**
111
117
  * @alpha Using durables is considered experimental and may change in the future.
112
118
  * @hidden
113
119
  */
114
- export type DurableWaitForConditionDecision = {shouldRetry: true; delay: DurableDuration} | {shouldRetry: false}
120
+ export type DurableWaitForConditionPoller<T = unknown> = DurableStepHandler<[state: T, context: DurableStepAttemptContext], Promise<T>>
115
121
 
116
122
  /**
117
123
  * @alpha Using durables is considered experimental and may change in the future.
118
124
  * @hidden
119
125
  */
120
- export type DurableStepHandler<TArgs extends unknown[], TReturn> = (...args: TArgs) => TReturn
126
+ export type DurableWaitForConditionNext<T = unknown> = DurableStepHandler<
127
+ [state: T, context: Pick<DurableStepAttemptContext, 'attempt'>],
128
+ DurableWaitForConditionDecision
129
+ >
121
130
 
122
131
  /**
123
132
  * @alpha Using durables is considered experimental and may change in the future.
124
133
  * @hidden
125
134
  */
126
- export type DurableStepRunHandler<T = unknown> = DurableStepHandler<[context: DurableStepAttemptContext], T | Promise<T>>
127
-
135
+ export type BatchItemSucceededStatus = 'SUCCEEDED'
128
136
  /**
129
137
  * @alpha Using durables is considered experimental and may change in the future.
130
138
  * @hidden
131
139
  */
132
- export type DurableStepWaitForCallbackHandler = DurableStepHandler<[callbackId: string, context: DurableStepCallbackContext], Promise<void>>
133
-
140
+ export type BatchItemFailedStatus = 'FAILED'
134
141
  /**
135
142
  * @alpha Using durables is considered experimental and may change in the future.
136
143
  * @hidden
137
144
  */
138
- export type DurableWaitForConditionPoller<T = unknown> = DurableStepHandler<[state: T, context: DurableStepAttemptContext], Promise<T>>
139
-
145
+ export type BatchItemStartedStatus = 'STARTED'
140
146
  /**
141
147
  * @alpha Using durables is considered experimental and may change in the future.
142
148
  * @hidden
143
149
  */
144
- export type DurableWaitForConditionNext<T = unknown> = DurableStepHandler<
145
- [state: T, context: Pick<DurableStepAttemptContext, 'attempt'>],
146
- DurableWaitForConditionDecision
147
- >
150
+ export type BatchItemStatus = BatchItemSucceededStatus | BatchItemFailedStatus | BatchItemStartedStatus
151
+ /**
152
+ * Reason why a batch operation (map, parallel, or concurrent execution)
153
+ * completed.
154
+ *
155
+ * - `ALL_COMPLETED`: every item finished.
156
+ * - `MIN_SUCCESSFUL_REACHED`: CompletionConfig.minSuccessful was reached.
157
+ * - `FAILURE_TOLERANCE_EXCEEDED`: a failure threshold was exceeded.
158
+ * - `CUSTOM_COMPLETION_SUCCEEDED`: a custom CompletionConfig.shouldComplete
159
+ * predicate signalled completion with a `SUCCEEDED` outcome before all items
160
+ * finished.
161
+ * - `CUSTOM_COMPLETION_FAILED`: a custom CompletionConfig.shouldComplete
162
+ * predicate signalled completion with a `FAILED` outcome before all items
163
+ * finished.
164
+ * @alpha Using durables is considered experimental and may change in the future.
165
+ * @hidden
166
+ * @remarks copied from AWS Durable Execution SDK
167
+ */
168
+ export type CompletionReason =
169
+ | 'ALL_COMPLETED'
170
+ | 'MIN_SUCCESSFUL_REACHED'
171
+ | 'FAILURE_TOLERANCE_EXCEEDED'
172
+ | 'CUSTOM_COMPLETION_SUCCEEDED'
173
+ | 'CUSTOM_COMPLETION_FAILED'
174
+ /**
175
+ * The result of a `step.fanout` branch.
176
+ * @alpha Using durables is considered experimental and may change in the future.
177
+ * @hidden
178
+ * @remarks copied from AWS Durable Execution SDK
179
+ */
180
+ export interface BatchItem<TResult> {
181
+ /** The result value if the item succeeded */
182
+ result?: TResult
183
+ /** The error if the item failed */
184
+ error?: Error
185
+ /** Index of the item in the original array */
186
+ index: number
187
+ /** Status of the item execution */
188
+ status: BatchItemStatus
189
+ }
190
+ /**
191
+ * @alpha Using durables is considered experimental and may change in the future.
192
+ * @hidden
193
+ * @remarks copied from AWS Durable Execution SDK
194
+ */
195
+ export interface BatchResult<TResult> {
196
+ /**
197
+ * All items in the batch with their results/errors.
198
+ */
199
+ all: Array<BatchItem<TResult>>
200
+ /** Returns only the items that succeeded */
201
+ succeeded(): Array<
202
+ BatchItem<TResult> & {
203
+ result: TResult
204
+ }
205
+ >
206
+ /** Returns only the items that failed */
207
+ failed(): Array<
208
+ BatchItem<TResult> & {
209
+ error: Error
210
+ }
211
+ >
212
+ /**
213
+ * Returns only the items that are still in progress (STARTED) — items that
214
+ * were in flight when the batch completed early (e.g. via CompletionConfig.minSuccessful
215
+ * or a custom CompletionConfig.shouldComplete).
216
+ */
217
+ started(): Array<
218
+ BatchItem<TResult> & {
219
+ status: BatchItemStartedStatus
220
+ }
221
+ >
222
+ /** Overall status of the batch (SUCCEEDED if no failures, FAILED otherwise) */
223
+ status: BatchItemSucceededStatus | BatchItemFailedStatus
224
+ /** Reason why the batch completed */
225
+ completionReason: CompletionReason
226
+ /** Whether any item in the batch failed */
227
+ hasFailure: boolean
228
+ /** Throws the first error if any item failed */
229
+ throwIfError(): void
230
+ /** Returns array of all successful results */
231
+ getResults(): Array<TResult>
232
+ /** Returns array of all errors */
233
+ getErrors(): Array<Error>
234
+ /** Number of successful items */
235
+ successCount: number
236
+ /** Number of failed items */
237
+ failureCount: number
238
+ /**
239
+ * Number of started but not completed items. Not guaranteed to be stable across suspend/resume
240
+ */
241
+ startedCount: number
242
+ /** Total number of items */
243
+ totalCount: number
244
+ }
148
245
 
149
246
  /**
150
247
  * The interface defining the operations available to a durable function.
@@ -173,7 +270,7 @@ export type DurableOperations = {
173
270
  * step.run({
174
271
  * name: 'run-with-retry'
175
272
  * handler: () => { // handler code }
176
- * retry: { strategy: { maxAttempts: 2 } }
273
+ * retry: { maxAttempts: 2, delay: { seconds: 5 } }
177
274
  * })
178
275
  * ```
179
276
  * @param name - Step name
@@ -181,7 +278,58 @@ export type DurableOperations = {
181
278
  * @param retry - retry configuration
182
279
  * @returns The value returned by the executed function
183
280
  */
184
- run<T>({name, handler, retry}: {name?: string; handler: DurableStepRunHandler<T>; retry?: DurableStepConfig}): Promise<T>
281
+ run<T>({name, handler, retry}: {name?: string; handler: DurableStepRunHandler<T>; retry?: DurableRetryStrategy}): Promise<T>
282
+
283
+ /**
284
+ * Runs a set of steps, or branches, in parallel. Each branch contains its own child durable context, with all usual `step` operations available.
285
+ * @remarks By using the generic, you can set a single, homogeneous return type for all branches.
286
+ * @example
287
+ * ```ts
288
+ * step.fanout<string>({
289
+ * name: 'parallel-runs',
290
+ * branches: [async ({step, logger}) => {
291
+ * logger.log('Running first function in parallel')
292
+ * return 'first'
293
+ * }, async ({step, logger}) => {
294
+ * logger.log('Running second function in parallel')
295
+ * return 'second'
296
+ * }],
297
+ * })
298
+ * ```
299
+ * @param name - Step name
300
+ * @param branches - functions being executed in parallel
301
+ * @returns A batch result of values returned or errors thrown by all branches.
302
+ */
303
+ fanout<T>({name, branches}: {name?: string; branches: DurableStepFanoutHandler<T>[]}): Promise<BatchResult<T>>
304
+ /**
305
+ * Runs a set of steps, or branches, in parallel. Each branch contains its own child durable context, with all usual `step` operations available.
306
+ * @remarks This overload provides automatic type inference for heterogeneous branch return types. When branches return different types, the result will be `BatchResult<T1 | T2 | ...>`.
307
+ * Use the explicit type parameter overloads above for strict homogeneous type checking.
308
+ * @example
309
+ * ```ts
310
+ * step.fanout<string>({
311
+ * name: 'parallel-runs',
312
+ * branches: [async ({step, logger}) => {
313
+ * logger.log('Running first function in parallel')
314
+ * return 'first'
315
+ * }, async ({step, logger}) => {
316
+ * logger.log('Running second function in parallel')
317
+ * return 'second'
318
+ * }],
319
+ * })
320
+ * ```
321
+ * @param name - Step name
322
+ * @param branches - functions being executed in parallel
323
+ * @returns A batch result of values returned or errors thrown by all branches.
324
+ */
325
+ fanout<Branches extends readonly unknown[]>({
326
+ name,
327
+ branches,
328
+ }: {
329
+ name?: string
330
+ branches: Branches
331
+ }): Promise<BatchResult<Branches[number] extends DurableStepFanoutHandler<infer ReturnType> ? ReturnType : never>>
332
+
185
333
  /**
186
334
  * Calls another function and awaits its result.
187
335
  * similar to ctx.invoke()
@@ -219,6 +367,7 @@ export type DurableOperations = {
219
367
  name?: string
220
368
  handler: string | BlueprintResource<`sanity.function.${string}`>
221
369
  event?: unknown
370
+ retry?: DurableRetryStrategy
222
371
  }): Promise<T>
223
372
 
224
373
  /**
@@ -310,10 +459,4 @@ export type DurableOperations = {
310
459
  * @alpha Using durables is considered experimental and may change in the future.
311
460
  * @hidden
312
461
  */
313
- export type DurableHandler = (envelope: {
314
- context: DurableContext
315
- event?: GenericEvent
316
- step: DurableOperations
317
- logger: DurableLogger
318
- retry: DurableRetry
319
- }) => unknown | Promise<unknown>
462
+ export type DurableHandler = (envelope: DurableTopLevelContext) => unknown | Promise<unknown>