durability 2.1.0 → 3.0.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/dist/index.d.ts CHANGED
@@ -1,435 +1,10 @@
1
- /**
2
- * The context passed to a durable operation handler for each attempt.
3
- *
4
- * @example
5
- * ```ts
6
- * const sendEmail = async ({ id, payload, signal }: DurableCall<EmailPayload>) =>
7
- * fetch(payload.url, {
8
- * method: 'POST',
9
- * headers: { 'Idempotency-Key': id },
10
- * signal,
11
- * });
12
- * ```
13
- */
14
- export type DurableCall<Payload> = {
15
- /** The stable idempotency key supplied when the operation was registered. */
16
- id: string;
17
- /** The handler name used to register the operation. */
18
- operation: string;
19
- /** The JSON-serializable payload supplied when the operation was registered. */
20
- payload: Payload;
21
- /** The one-based attempt number. */
22
- attempt: number;
23
- /** Aborts when the attempt exceeds its configured timeout. */
24
- signal: AbortSignal;
25
- };
26
- /**
27
- * A function that executes one attempt of a durable operation.
28
- *
29
- * @example
30
- * ```ts
31
- * const resizeImage: DurableHandler<ResizeInput, string> = async ({
32
- * id,
33
- * payload,
34
- * }) => images.resize(payload.imageId, { idempotencyKey: id });
35
- * ```
36
- */
37
- export type DurableHandler<Payload, Result> = (call: DurableCall<Payload>) => Result | Promise<Result>;
38
- /**
39
- * Retry policy shared by all methods or overridden for one method.
40
- *
41
- * The delay callback owns the complete scheduling policy, so it can compose the
42
- * helpers exported from `durability/utils` or use an application-specific
43
- * strategy.
44
- *
45
- * @example
46
- * ```ts
47
- * import { exponential, jitter } from 'durability/utils';
48
- *
49
- * const retries: DurabilityRetryOptions = {
50
- * maxAttempts: 5,
51
- * delay: (attempt) => jitter(exponential(attempt)),
52
- * };
53
- * ```
54
- */
55
- export type DurabilityRetryOptions = {
56
- /** Returns the delay in milliseconds after a failed attempt. */
57
- delay?: (attempt: number) => number;
58
- /** The total number of attempts, including the initial attempt. Defaults to 5. */
59
- maxAttempts?: number;
60
- };
61
- type HandlerMap = Record<string, (...args: never[]) => unknown>;
62
- /** Information passed to a named alarm handler for one execution attempt. */
63
- export type DurableAlarmInfo = {
64
- /** Configured name of the logical alarm. */
65
- name: string;
66
- /** Timestamp originally passed to the named alarm method. */
67
- scheduledTime: number;
68
- /** One-based execution attempt for this scheduled occurrence. */
69
- attempt: number;
70
- /** Whether this scheduled occurrence has run before. */
71
- isRetry: boolean;
72
- /** Number of previous attempts for this scheduled occurrence. */
73
- retryCount: number;
74
- /** Stable key shared by every attempt of this scheduled occurrence. */
75
- idempotencyKey: string;
76
- /** Aborts when the attempt exceeds its configured timeout. */
77
- signal: AbortSignal;
78
- /** Invocation information for the shared physical Durable Object alarm. */
79
- platform: AlarmInvocationInfo | undefined;
80
- };
81
- /** A handler for one named logical alarm. */
82
- export type DurableAlarmHandler = (info: DurableAlarmInfo) => unknown | Promise<unknown>;
83
- /**
84
- * Execution policy overrides for one durable operation method.
85
- *
86
- * @example
87
- * ```ts
88
- * const resizePolicy: DurabilityMethodOptions = {
89
- * attemptTimeoutMs: 60_000,
90
- * retries: { maxAttempts: 2 },
91
- * };
92
- * ```
93
- */
94
- export type DurabilityMethodOptions = {
95
- /** Maximum duration of one attempt in milliseconds. */
96
- attemptTimeoutMs?: number;
97
- /** Retry policy overrides for this method. */
98
- retries?: DurabilityRetryOptions;
99
- };
100
- /** Execution policy overrides for one named alarm. */
101
- export type DurabilityAlarmMethodOptions = DurabilityMethodOptions & {
102
- /** Retry timed-out attempts only when their side effects are idempotent or reconciled. */
103
- retryTimeouts?: boolean;
104
- };
105
- /**
106
- * Configuration for a durability instance.
107
- *
108
- * Operation and named-alarm overrides replace global timeout and retry values
109
- * without changing the policy for other handlers.
110
- *
111
- * @example
112
- * ```ts
113
- * const options: DurabilityOptions<typeof handlers> = {
114
- * alarmConcurrency: 5,
115
- * attemptTimeoutMs: 30_000,
116
- * retries: { maxAttempts: 5 },
117
- * methods: {
118
- * resizeImage: {
119
- * attemptTimeoutMs: 60_000,
120
- * retries: { maxAttempts: 2 },
121
- * },
122
- * },
123
- * };
124
- * ```
125
- */
126
- type SerializedError = {
127
- name: string;
128
- message: string;
129
- };
130
- type OperationLifecycleEntity = {
131
- entityKind: 'operation';
132
- operation: string;
133
- id: string;
134
- generation: string;
135
- };
136
- type AlarmLifecycleEntity = {
137
- entityKind: 'named_alarm';
138
- alarm: string;
139
- id: string;
140
- generation: string;
141
- };
142
- type LifecycleEntity = OperationLifecycleEntity | AlarmLifecycleEntity;
143
- /** Best-effort metrics signal for queue lifecycle changes. */
144
- export type DurabilityLifecycleEvent = (OperationLifecycleEntity & {
145
- type: 'registered';
146
- timestamp: number;
147
- attempt: 0;
148
- }) | (AlarmLifecycleEntity & {
149
- type: 'scheduled';
150
- timestamp: number;
151
- attempt: 0;
152
- scheduledTime: number;
153
- }) | (LifecycleEntity & {
154
- type: 'attempt_started';
155
- timestamp: number;
156
- attempt: number;
157
- }) | (LifecycleEntity & {
158
- type: 'attempt_settled';
159
- timestamp: number;
160
- attempt: number;
161
- durationMs: number;
162
- outcome: 'completed';
163
- }) | (LifecycleEntity & {
164
- type: 'attempt_settled';
165
- timestamp: number;
166
- attempt: number;
167
- durationMs: number;
168
- outcome: 'retry_scheduled';
169
- error: SerializedError;
170
- nextAttemptAt: number;
171
- }) | (LifecycleEntity & {
172
- type: 'attempt_settled';
173
- timestamp: number;
174
- attempt: number;
175
- durationMs: number;
176
- outcome: 'failed';
177
- error: SerializedError;
178
- }) | (LifecycleEntity & {
179
- type: 'terminal';
180
- timestamp: number;
181
- attempt: number;
182
- reason: 'attempts_exhausted';
183
- error: SerializedError;
184
- }) | {
185
- type: 'purged';
186
- entityKind: 'durability';
187
- timestamp: number;
188
- before: number;
189
- operations: number;
190
- namedAlarms: number;
191
- total: number;
192
- };
193
- export type DurabilityOptions<Handlers extends HandlerMap = HandlerMap, AlarmNames extends string = never> = {
194
- /** Named logical alarms sharing the Durable Object's physical alarm. */
195
- alarms?: Record<AlarmNames, DurableAlarmHandler>;
196
- /** Execution policy overrides keyed by named alarm. */
197
- alarmMethods?: [AlarmNames] extends [never] ? never : Partial<Record<NoInfer<AlarmNames>, DurabilityAlarmMethodOptions>>;
198
- /** Maximum handlers shared by eager operations and alarm work. Defaults to 10. */
199
- alarmConcurrency?: number;
200
- /** Time before a running alarm hands unfinished work to a new alarm. Defaults to 14 minutes. */
201
- alarmHandoffMs?: number;
202
- /** Maximum duration of one handler attempt. Defaults to 5 minutes. */
203
- attemptTimeoutMs?: number;
204
- /** Execution policy overrides keyed by handler name. */
205
- methods?: Partial<Record<Extract<keyof Handlers, string>, DurabilityMethodOptions>>;
206
- /** Retry policy shared by handlers without a method-level override. */
207
- retries?: DurabilityRetryOptions;
208
- /** Receives best-effort, non-durable lifecycle metrics events. */
209
- onLifecycleEvent?: (event: DurabilityLifecycleEvent) => void | Promise<void>;
210
- };
211
- type HandlerPayload<Handler> = Handler extends (call: DurableCall<infer Payload>) => unknown ? Payload : never;
212
- type DurableOperationInput<Handler> = {
213
- /** Stable idempotency key used to deduplicate the operation. */
214
- id: string;
215
- /** JSON-serializable input passed to the operation handler. */
216
- payload: HandlerPayload<Handler>;
217
- };
218
- type HandlerResult<Handler> = Handler extends (...args: never[]) => infer Result ? Awaited<Result> : never;
219
- /**
220
- * The persisted state and result of a durable operation.
221
- *
222
- * Operation methods only wait for durable registration, not handler completion.
223
- * Call `getResult` later and narrow on `status` before reading a result or error.
224
- *
225
- * @example
226
- * ```ts
227
- * const state = await durability.resizeImage.getResult('resize:image-1');
228
- *
229
- * if (state.status === 'completed') {
230
- * console.log(state.result);
231
- * } else if (state.status === 'failed') {
232
- * console.error(state.error.name, state.error.message);
233
- * }
234
- * ```
235
- */
236
- export type DurableOperationResult<Result> = {
237
- /** No operation exists for the supplied idempotency key. */
238
- status: 'not_found';
239
- } | {
240
- /** The operation is waiting to run or retry. */
241
- status: 'pending';
242
- /** The number of attempts already started. */
243
- attempt: number;
244
- /** Unix timestamp in milliseconds when the next attempt becomes eligible. */
245
- nextAttemptAt: number;
246
- /** The previous attempt's error message, or null before the first attempt. */
247
- lastError: string | null;
248
- } | {
249
- /** The operation exhausted its attempts or failed with a non-retryable error. */
250
- status: 'failed';
251
- /** The number of attempts that were started. */
252
- attempt: number;
253
- /** The terminal error's serialized name and message. */
254
- error: {
255
- name: string;
256
- message: string;
257
- };
258
- } | {
259
- /** The operation completed successfully. */
260
- status: 'completed';
261
- /** The handler's persisted return value. */
262
- result: Result;
263
- };
264
- /** Registers calls for one handler and reads their persisted results. */
265
- type DurableOperation<Handler> = ((input: DurableOperationInput<Handler>) => Promise<void>) & {
266
- /** Reads the persisted state for an idempotency key. */
267
- getResult: (idempotencyKey: string) => Promise<DurableOperationResult<HandlerResult<Handler>>>;
268
- };
269
- /**
270
- * Typed operation methods and alarm handler created from a handler map.
271
- *
272
- * Each handler key becomes a registration method. The Durable Object must also
273
- * forward its alarm callback so pending retries survive object eviction.
274
- *
275
- * @example
276
- * ```ts
277
- * declare const durability: Durability<typeof handlers>;
278
- *
279
- * await durability.resizeImage({
280
- * id: 'resize:image-1',
281
- * payload: { imageId: 'image-1' },
282
- * });
283
- *
284
- * const alarm = (info: AlarmInvocationInfo) => durability.alarm(info);
285
- * ```
286
- */
287
- type DurableNamedAlarm = (scheduledTime: number) => Promise<void>;
288
- type DurabilityAlarm<AlarmNames extends string> = ((alarmInfo?: AlarmInvocationInfo) => Promise<void>) & Record<AlarmNames, DurableNamedAlarm>;
289
- /** Aggregate counts returned by a destructive purge. */
290
- export type DurablePurgeResult = {
291
- operations: number;
292
- namedAlarms: number;
293
- total: number;
294
- };
295
- export type Durability<Handlers extends HandlerMap, AlarmNames extends string = never> = {
296
- /** Processes due work and exposes methods for scheduling named alarms. */
297
- alarm: DurabilityAlarm<AlarmNames>;
298
- /** Destructively removes all queue records created before a timestamp. */
299
- purgeBefore: (timestamp: number) => Promise<DurablePurgeResult>;
300
- } & {
301
- [Operation in keyof Handlers]: DurableOperation<Handlers[Operation]>;
302
- };
303
- /**
304
- * Ordered SQLite migrations for the tables owned by durability.
305
- *
306
- * Every SQLite-backed Durable Object instance has an independent database, so
307
- * the durability schema must exist in each instance before calls can be stored.
308
- * {@link createDurability} applies these migrations automatically on instance
309
- * initialization. They are tracked in the namespaced `durability_migrations`
310
- * table so they can coexist with application-owned migrations in the same
311
- * database.
312
- *
313
- * The list is exported so migration names can be inspected before an explicit
314
- * rollback with {@link migrateDurability}. Most consumers should not execute
315
- * the SQL directly.
316
- *
317
- * @example
318
- * ```ts
319
- * const currentTarget = durabilityMigrations.at(-1)?.name ?? null;
320
- * migrateDurability(this.ctx, currentTarget);
321
- * ```
322
- */
323
- export declare const durabilityMigrations: {
324
- name: string;
325
- up: string;
326
- down: string;
327
- }[];
328
- /**
329
- * Migration names changed by a call to {@link migrateDurability}.
330
- *
331
- * @example
332
- * ```ts
333
- * const { applied, rolledBack } = migrateDurability(this.ctx);
334
- * console.log({ applied, rolledBack });
335
- * ```
336
- */
337
- export type DurabilityMigrationResult = {
338
- /** Migrations applied in ascending order. */
339
- applied: string[];
340
- /** Migrations reverted in descending order. */
341
- rolledBack: string[];
342
- };
343
- /**
344
- * Moves the durability schema in one Durable Object instance to a target.
345
- *
346
- * {@link createDurability} calls this with the latest target automatically. Call
347
- * it directly only for explicit schema management, especially rollbacks. Passing
348
- * `null` removes every durability table and permanently deletes stored calls.
349
- *
350
- * @example Apply all pending durability migrations.
351
- * ```ts
352
- * migrateDurability(this.ctx);
353
- * ```
354
- *
355
- * @example Roll back to a specific version, then remove the schema entirely.
356
- * ```ts
357
- * migrateDurability(this.ctx, 'durability_0001_create_calls');
358
- * migrateDurability(this.ctx, null);
359
- * ```
360
- *
361
- * @param context Durable Object context containing SQLite-backed storage.
362
- * @param target Migration name to migrate to, or null to roll back all migrations.
363
- */
364
- export declare const migrateDurability: (context: Pick<DurableObjectState, "storage">, target?: string | null) => DurabilityMigrationResult;
365
- /**
366
- * Marks a handler failure as terminal so it is persisted without another retry.
367
- *
368
- * Use this for permanent failures such as invalid input. Transient errors should
369
- * be thrown normally so the configured retry policy can handle them.
370
- *
371
- * @example
372
- * ```ts
373
- * if (!recipient.isValid) {
374
- * throw new NonRetryableError('Recipient is invalid');
375
- * }
376
- * ```
377
- */
378
- export declare class NonRetryableError extends Error {
379
- constructor(message: string);
380
- }
381
- /**
382
- * Error recorded when a handler attempt exceeds its configured timeout.
383
- *
384
- * Durability creates this error and aborts the attempt's signal; consumers do
385
- * not need to throw it themselves. Timeout failures follow the normal retry
386
- * policy and are exposed by `getResult` if they become terminal.
387
- *
388
- * @example
389
- * ```ts
390
- * const state = await durability.resizeImage.getResult('resize:image-1');
391
- * if (
392
- * state.status === 'failed' &&
393
- * state.error.name === 'DurableAttemptTimeoutError'
394
- * ) {
395
- * console.error('Resize timed out');
396
- * }
397
- * ```
398
- */
399
- export declare class DurableAttemptTimeoutError extends Error {
400
- constructor(operation: string, timeoutMs: number);
401
- }
402
- /** Error recorded when a named alarm attempt exceeds its configured timeout. */
403
- export declare class DurableAlarmTimeoutError extends Error {
404
- constructor(name: string, timeoutMs: number);
405
- }
406
- /** Error persisted when retry-delay evaluation fails or is unsafe. */
407
- export declare class DurableRetryPolicyError extends Error {
408
- constructor(entity: string, reason?: unknown);
409
- }
410
- /** Error persisted when a successful result cannot be JSON-serialized. */
411
- export declare class DurableResultSerializationError extends Error {
412
- constructor(operation: string, reason?: unknown);
413
- }
414
- /** Error persisted when pending work has already reached its attempt limit. */
415
- export declare class DurableAttemptsExhaustedError extends Error {
416
- constructor(entity: 'operation' | 'named alarm', name: string, max: number);
417
- }
418
- /**
419
- * Error thrown when an idempotency key is reused for another operation.
420
- *
421
- * A call ID permanently identifies its original operation so `getResult` cannot
422
- * return a value with the wrong inferred type.
423
- *
424
- * @example
425
- * ```ts
426
- * await durability.resizeImage({ id: 'job:1', payload: resizeInput });
427
- * await durability.sendEmail({ id: 'job:1', payload: emailInput });
428
- * // Throws DuplicateDurableCallError because job:1 belongs to resizeImage.
429
- * ```
430
- */
431
- export declare class DuplicateDurableCallError extends Error {
432
- constructor(id: string, existingOperation: string, requestedOperation: string);
433
- }
434
- export declare const createDurability: <Handlers extends HandlerMap, const AlarmNames extends string = never>(context: Pick<DurableObjectState, "storage"> & Partial<Pick<DurableObjectState, "waitUntil">>, handlers: Handlers, options?: DurabilityOptions<Handlers, AlarmNames>) => Durability<Handlers, AlarmNames>;
435
- export {};
1
+ export { Durability, type DurabilityConfig, type DurabilityConstructor, type DurabilityOptions, type DurableCall, type DurableHandler, type DurableOperation, type DurableOperationResult, type HandlerMap, } from './durability.js';
2
+ export { DurabilityAlarms, type DurabilityAlarmsConfig, type DurabilityAlarmsConstructor, type DurabilityAlarmsOptions, type DurableAlarmHandler, type DurableAlarmInfo, type DurableNamedAlarm, } from './durability-alarms.js';
3
+ export { DurabilityFanout, type DurabilityFanoutConfig, type DurabilityFanoutMessage, type FanoutInput, type FanoutTarget, type FanoutEnqueueOptions, } from './fanout.js';
4
+ export { RoutingLoad, type EnqueueResult, type LoadSnapshot, type ProcessingLoad, } from './load.js';
5
+ export type { MessageWrite, StoredMessage } from './stored-message.js';
6
+ export { DurabilityScheduler, type DurabilityContext, type DurabilitySchedulerConfig, type DurabilitySchedulerOptions, type DurabilityStorageBackend, type SchedulerAttachment, } from './scheduler.js';
7
+ export { DuplicateDurableCallError, DurableAlarmTimeoutError, DurableAttemptsExhaustedError, DurableAttemptTimeoutError, DurableResultSerializationError, DurableRetryPolicyError, NonRetryableError, FanoutTimeoutError, FanoutSettlementError, FanoutEnqueueError, RoutingError, } from './errors.js';
8
+ export type { DurabilityLifecycleEvent } from './lifecycle.js';
9
+ export { durabilityNamedAlarmMigrations, durabilityOperationMigrations, durabilityFanoutMigrations, type DurabilityMigrationResult, type MigrationCapability, } from './migrations.js';
10
+ export type { DurabilityAlarmMethodOptions, DurabilityMethodOptions, DurabilityRetryOptions, } from './policy.js';