durability 2.0.0 → 3.0.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/dist/index.d.ts CHANGED
@@ -1,350 +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
- /**
63
- * Execution policy overrides for one durable operation method.
64
- *
65
- * @example
66
- * ```ts
67
- * const resizePolicy: DurabilityMethodOptions = {
68
- * attemptTimeoutMs: 60_000,
69
- * retries: { maxAttempts: 2 },
70
- * };
71
- * ```
72
- */
73
- export type DurabilityMethodOptions = {
74
- /** Maximum duration of one attempt in milliseconds. */
75
- attemptTimeoutMs?: number;
76
- /** Retry policy overrides for this method. */
77
- retries?: DurabilityRetryOptions;
78
- };
79
- /**
80
- * Configuration for a durability instance.
81
- *
82
- * Method-level values override global timeout and retry values without changing
83
- * the policy for other handlers.
84
- *
85
- * @example
86
- * ```ts
87
- * const options: DurabilityOptions<typeof handlers> = {
88
- * alarmConcurrency: 5,
89
- * attemptTimeoutMs: 30_000,
90
- * retries: { maxAttempts: 5 },
91
- * methods: {
92
- * resizeImage: {
93
- * attemptTimeoutMs: 60_000,
94
- * retries: { maxAttempts: 2 },
95
- * },
96
- * },
97
- * };
98
- * ```
99
- */
100
- export type DurabilityOptions<Handlers extends HandlerMap = HandlerMap> = {
101
- /** Maximum immediate operations executed concurrently by an alarm. Defaults to 10. */
102
- alarmConcurrency?: number;
103
- /** Time before a running alarm hands unfinished work to a new alarm. Defaults to 14 minutes. */
104
- alarmHandoffMs?: number;
105
- /** Maximum duration of one handler attempt. Defaults to 5 minutes. */
106
- attemptTimeoutMs?: number;
107
- /** Execution policy overrides keyed by handler name. */
108
- methods?: Partial<Record<Extract<keyof Handlers, string>, DurabilityMethodOptions>>;
109
- /** Retry policy shared by handlers without a method-level override. */
110
- retries?: DurabilityRetryOptions;
111
- };
112
- type HandlerPayload<Handler> = Handler extends (call: DurableCall<infer Payload>) => unknown ? Payload : never;
113
- type DurableOperationInput<Handler> = {
114
- /** Stable idempotency key used to deduplicate the operation. */
115
- id: string;
116
- /** JSON-serializable input passed to the operation handler. */
117
- payload: HandlerPayload<Handler>;
118
- };
119
- type HandlerResult<Handler> = Handler extends (...args: never[]) => infer Result ? Awaited<Result> : never;
120
- /**
121
- * The persisted state and result of a durable operation.
122
- *
123
- * Operation methods only wait for durable registration, not handler completion.
124
- * Call `getResult` later and narrow on `status` before reading a result or error.
125
- *
126
- * @example
127
- * ```ts
128
- * const state = await durability.resizeImage.getResult('resize:image-1');
129
- *
130
- * if (state.status === 'completed') {
131
- * console.log(state.result);
132
- * } else if (state.status === 'failed') {
133
- * console.error(state.error.name, state.error.message);
134
- * }
135
- * ```
136
- */
137
- export type DurableOperationResult<Result> = {
138
- /** No operation exists for the supplied idempotency key. */
139
- status: 'not_found';
140
- } | {
141
- /** The operation is waiting to run or retry. */
142
- status: 'pending';
143
- /** The number of attempts already started. */
144
- attempt: number;
145
- /** Unix timestamp in milliseconds when the next attempt becomes eligible. */
146
- nextAttemptAt: number;
147
- /** The previous attempt's error message, or null before the first attempt. */
148
- lastError: string | null;
149
- } | {
150
- /** The operation exhausted its attempts or failed with a non-retryable error. */
151
- status: 'failed';
152
- /** The number of attempts that were started. */
153
- attempt: number;
154
- /** The terminal error's serialized name and message. */
155
- error: {
156
- name: string;
157
- message: string;
158
- };
159
- } | {
160
- /** The operation completed successfully. */
161
- status: 'completed';
162
- /** The handler's persisted return value. */
163
- result: Result;
164
- };
165
- /** Registers calls for one handler and reads their persisted results. */
166
- type DurableOperation<Handler> = ((input: DurableOperationInput<Handler>) => Promise<void>) & {
167
- /** Reads the persisted state for an idempotency key. */
168
- getResult: (idempotencyKey: string) => Promise<DurableOperationResult<HandlerResult<Handler>>>;
169
- };
170
- /**
171
- * Typed operation methods and alarm handler created from a handler map.
172
- *
173
- * Each handler key becomes a registration method. The Durable Object must also
174
- * forward its alarm callback so pending retries survive object eviction.
175
- *
176
- * @example
177
- * ```ts
178
- * declare const durability: Durability<typeof handlers>;
179
- *
180
- * await durability.resizeImage({
181
- * id: 'resize:image-1',
182
- * payload: { imageId: 'image-1' },
183
- * });
184
- *
185
- * const alarm = (info: AlarmInvocationInfo) => durability.alarm(info);
186
- * ```
187
- */
188
- export type Durability<Handlers extends HandlerMap> = {
189
- /** Processes due operations. Forward the Durable Object's alarm handler here. */
190
- alarm: (alarmInfo?: AlarmInvocationInfo) => Promise<void>;
191
- } & {
192
- [Operation in keyof Handlers]: DurableOperation<Handlers[Operation]>;
193
- };
194
- /**
195
- * Ordered SQLite migrations for the tables owned by durability.
196
- *
197
- * Every SQLite-backed Durable Object instance has an independent database, so
198
- * the durability schema must exist in each instance before calls can be stored.
199
- * {@link createDurability} applies these migrations automatically on instance
200
- * initialization. They are tracked in the namespaced `durability_migrations`
201
- * table so they can coexist with application-owned migrations in the same
202
- * database.
203
- *
204
- * The list is exported so migration names can be inspected before an explicit
205
- * rollback with {@link migrateDurability}. Most consumers should not execute
206
- * the SQL directly.
207
- *
208
- * @example
209
- * ```ts
210
- * const currentTarget = durabilityMigrations.at(-1)?.name ?? null;
211
- * migrateDurability(this.ctx, currentTarget);
212
- * ```
213
- */
214
- export declare const durabilityMigrations: {
215
- name: string;
216
- up: string;
217
- down: string;
218
- }[];
219
- /**
220
- * Migration names changed by a call to {@link migrateDurability}.
221
- *
222
- * @example
223
- * ```ts
224
- * const { applied, rolledBack } = migrateDurability(this.ctx);
225
- * console.log({ applied, rolledBack });
226
- * ```
227
- */
228
- export type DurabilityMigrationResult = {
229
- /** Migrations applied in ascending order. */
230
- applied: string[];
231
- /** Migrations reverted in descending order. */
232
- rolledBack: string[];
233
- };
234
- /**
235
- * Moves the durability schema in one Durable Object instance to a target.
236
- *
237
- * {@link createDurability} calls this with the latest target automatically. Call
238
- * it directly only for explicit schema management, especially rollbacks. Passing
239
- * `null` removes every durability table and permanently deletes stored calls.
240
- *
241
- * @example Apply all pending durability migrations.
242
- * ```ts
243
- * migrateDurability(this.ctx);
244
- * ```
245
- *
246
- * @example Roll back to a specific version, then remove the schema entirely.
247
- * ```ts
248
- * migrateDurability(this.ctx, 'durability_0001_create_calls');
249
- * migrateDurability(this.ctx, null);
250
- * ```
251
- *
252
- * @param context Durable Object context containing SQLite-backed storage.
253
- * @param target Migration name to migrate to, or null to roll back all migrations.
254
- */
255
- export declare const migrateDurability: (context: Pick<DurableObjectState, "storage">, target?: string | null) => DurabilityMigrationResult;
256
- /**
257
- * Marks a handler failure as terminal so it is persisted without another retry.
258
- *
259
- * Use this for permanent failures such as invalid input. Transient errors should
260
- * be thrown normally so the configured retry policy can handle them.
261
- *
262
- * @example
263
- * ```ts
264
- * if (!recipient.isValid) {
265
- * throw new NonRetryableError('Recipient is invalid');
266
- * }
267
- * ```
268
- */
269
- export declare class NonRetryableError extends Error {
270
- constructor(message: string);
271
- }
272
- /**
273
- * Error recorded when a handler attempt exceeds its configured timeout.
274
- *
275
- * Durability creates this error and aborts the attempt's signal; consumers do
276
- * not need to throw it themselves. Timeout failures follow the normal retry
277
- * policy and are exposed by `getResult` if they become terminal.
278
- *
279
- * @example
280
- * ```ts
281
- * const state = await durability.resizeImage.getResult('resize:image-1');
282
- * if (
283
- * state.status === 'failed' &&
284
- * state.error.name === 'DurableAttemptTimeoutError'
285
- * ) {
286
- * console.error('Resize timed out');
287
- * }
288
- * ```
289
- */
290
- export declare class DurableAttemptTimeoutError extends Error {
291
- constructor(operation: string, timeoutMs: number);
292
- }
293
- /**
294
- * Error thrown when an idempotency key is reused for another operation.
295
- *
296
- * A call ID permanently identifies its original operation so `getResult` cannot
297
- * return a value with the wrong inferred type.
298
- *
299
- * @example
300
- * ```ts
301
- * await durability.resizeImage({ id: 'job:1', payload: resizeInput });
302
- * await durability.sendEmail({ id: 'job:1', payload: emailInput });
303
- * // Throws DuplicateDurableCallError because job:1 belongs to resizeImage.
304
- * ```
305
- */
306
- export declare class DuplicateDurableCallError extends Error {
307
- constructor(id: string, existingOperation: string, requestedOperation: string);
308
- }
309
- /**
310
- * Creates typed, alarm-backed durable methods from an operation handler map.
311
- *
312
- * Registered calls persist before execution and are deduplicated by their IDs.
313
- * Generated methods resolve after registration; read handler results with each
314
- * method's `getResult` function.
315
- *
316
- * The Durable Object class must use SQLite storage, and its `alarm` method must
317
- * delegate to the returned alarm handler. External side effects should use the
318
- * call ID as an idempotency key because a crash can occur after a side effect but
319
- * before the completion record commits.
320
- *
321
- * @example
322
- * ```ts
323
- * class ImageJobs extends DurableObject<Env> {
324
- * private readonly durability = createDurability(this.ctx, {
325
- * resizeImage: async ({ id, payload, signal }) =>
326
- * this.env.IMAGES.resize(payload.imageId, {
327
- * idempotencyKey: id,
328
- * signal,
329
- * }),
330
- * });
331
- *
332
- * resize(imageId: string) {
333
- * return this.durability.resizeImage({
334
- * id: `resize:${imageId}`,
335
- * payload: { imageId },
336
- * });
337
- * }
338
- *
339
- * alarm(info: AlarmInvocationInfo) {
340
- * return this.durability.alarm(info);
341
- * }
342
- * }
343
- * ```
344
- *
345
- * @param context Durable Object context containing SQLite-backed storage.
346
- * @param handlers Operation handlers keyed by their public method names.
347
- * @param options Concurrency, timeout, and retry policy configuration.
348
- */
349
- export declare const createDurability: <Handlers extends HandlerMap>(context: Pick<DurableObjectState, "storage">, handlers: Handlers, options?: DurabilityOptions<Handlers>) => Durability<Handlers>;
350
- 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';