durability 1.0.0 → 2.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/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 Andre Venceslau
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,148 @@
1
+ # Durability
2
+
3
+ Alarm-backed, effectively-once operation execution for Cloudflare Durable Objects.
4
+
5
+ The package registers each operation and the first alarm in one Durable Object storage transaction. It only creates an alarm when none exists. Generated operation methods return `Promise<void>` after registration commits; they do not wait for the handler result. An alarm firing during execution attaches to the same in-memory promise. Failed calls are retried from later alarms, and a stable call ID deduplicates completed and concurrent calls. SQLite access and schema migrations are managed through `workers-qb`.
6
+
7
+ ```ts
8
+ import { DurableObject } from 'cloudflare:workers';
9
+ import { createDurability, type DurableHandler } from 'durability';
10
+
11
+ type ResizeInput = { imageId: string };
12
+
13
+ export class ImageJobs extends DurableObject<Env> {
14
+ private readonly durability = createDurability(this.ctx, {
15
+ resizeImage: (async ({ id, payload }) => {
16
+ return this.env.IMAGES.resize(payload.imageId, { idempotencyKey: id });
17
+ }) satisfies DurableHandler<ResizeInput, string>,
18
+ });
19
+
20
+ resize(imageId: string) {
21
+ return this.durability.resizeImage({
22
+ id: `resize:${imageId}`,
23
+ payload: { imageId },
24
+ });
25
+ }
26
+
27
+ alarm(alarmInfo?: AlarmInvocationInfo) {
28
+ return this.durability.alarm(alarmInfo);
29
+ }
30
+ }
31
+ ```
32
+
33
+ ## SQLite requirement
34
+
35
+ The Durable Object class must use SQLite storage:
36
+
37
+ ```jsonc
38
+ {
39
+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ImageJobs"] }],
40
+ }
41
+ ```
42
+
43
+ `createDurability` migrates to the latest schema and stores calls in the `durability_calls` table. Each package migration has `up` and `down` SQL and is tracked in the namespaced `durability_migrations` table.
44
+
45
+ Rollbacks are explicit because rolling back the initial migration deletes durable call records:
46
+
47
+ ```ts
48
+ import { migrateDurability } from 'durability';
49
+
50
+ migrateDurability(this.ctx, 'durability_0001_create_calls');
51
+ migrateDurability(this.ctx, null); // roll back every durability migration
52
+ ```
53
+
54
+ Passing a migration name moves the schema to that exact version, applying or reverting migrations as needed. Payloads and results must be JSON-serializable.
55
+
56
+ ## Reading results
57
+
58
+ Results are read through the same typed operation using its idempotency key:
59
+
60
+ ```ts
61
+ const result = await this.durability.resizeImage.getResult(`resize:${imageId}`);
62
+
63
+ switch (result.status) {
64
+ case 'not_found':
65
+ break;
66
+ case 'pending':
67
+ console.log(result.attempt, result.nextAttemptAt, result.lastError);
68
+ break;
69
+ case 'failed':
70
+ console.error(result.error.name, result.error.message);
71
+ break;
72
+ case 'completed':
73
+ console.log(result.result);
74
+ break;
75
+ }
76
+ ```
77
+
78
+ The completed result type is inferred from the operation handler. Looking up a key belonging to another operation throws `DuplicateDurableCallError` rather than returning a result with the wrong type.
79
+
80
+ ## Retries, timeouts, and terminal failures
81
+
82
+ Attempts use exponential backoff with equal jitter, stop after five attempts, and time out after five minutes by default. The retry `delay` function fully controls scheduling and can be overridden globally or per operation. The package exports the default delay building blocks for custom policies:
83
+
84
+ ```ts
85
+ import { exponential, jitter } from 'durability/utils';
86
+
87
+ const durability = createDurability(this.ctx, handlers, {
88
+ attemptTimeoutMs: 60_000,
89
+ retries: {
90
+ maxAttempts: 5,
91
+ delay: (attempt) => jitter(exponential(attempt)),
92
+ },
93
+ methods: {
94
+ resizeImage: {
95
+ attemptTimeoutMs: 10 * 60_000,
96
+ retries: {
97
+ maxAttempts: 2,
98
+ delay: (attempt) => exponential(attempt, 500, 30_000),
99
+ },
100
+ },
101
+ },
102
+ });
103
+ ```
104
+
105
+ Each attempt receives its own `AbortSignal`:
106
+
107
+ ```ts
108
+ const handlers = {
109
+ sendEmail: async ({ payload, signal }: DurableCall<EmailPayload>) =>
110
+ fetch(payload.url, { method: 'POST', signal }),
111
+ };
112
+ ```
113
+
114
+ A timed-out attempt aborts its signal and follows the normal retry policy. Abort-aware APIs stop promptly; arbitrary handler code cannot be forcibly terminated.
115
+
116
+ Throw `NonRetryableError` to move a call directly to `failed` without another attempt:
117
+
118
+ ```ts
119
+ import { NonRetryableError } from 'durability';
120
+
121
+ throw new NonRetryableError('Recipient permanently rejected');
122
+ ```
123
+
124
+ Errors created by `NonRetryableError` from `cloudflare:workflows` are also recognized.
125
+
126
+ ## Delivery semantics
127
+
128
+ Calls are delivered at least once and deduplicated by ID after completion. Arbitrary external side effects cannot be made strictly exactly-once: a process can stop after the side effect succeeds but before its completion record commits. Pass the call ID to external services as an idempotency key to obtain effectively-once behavior.
129
+
130
+ Completion records are retained indefinitely so IDs remain deduplicated. The helper owns the Durable Object's alarm; compose unrelated scheduled work through the same alarm handler instead of independently replacing its alarm.
131
+
132
+ ## Durable Object-to-Object coordination
133
+
134
+ When an operation spans multiple Durable Objects, a durability-enabled coordinator can retry each step after a crash, while durability-enabled participants deduplicate those retries using stable operation IDs. This supports sagas and other two-phase coordination scenarios with eventual consistency; it does not create one atomic storage transaction across the objects.
135
+
136
+ Intermediate states may be visible until every participant completes. Persist the coordination state, propagate stable IDs to every participant, and explicitly handle terminal failures or compensating operations when the operation can be aborted.
137
+
138
+ ## Long-running alarm calls
139
+
140
+ Alarm invocations have a 15-minute wall-time limit. If a handler is still pending after 14 minutes, the helper retains its promise in memory, arms an immediate alarm, and returns from the current invocation. The next alarm attaches to the same promise instead of starting the handler again:
141
+
142
+ ```ts
143
+ const durability = createDurability(this.ctx, handlers, {
144
+ alarmHandoffMs: 14 * 60_000,
145
+ });
146
+ ```
147
+
148
+ This handoff can keep a call running beyond one alarm invocation while the Durable Object remains in memory. It is intentionally backed by the persisted pending call: if Cloudflare evicts or restarts the object during a handoff, the next alarm reconstructs and executes the call again. External side effects still require the stable call ID as an idempotency key.
@@ -0,0 +1,350 @@
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 {};
package/dist/index.js ADDED
@@ -0,0 +1,551 @@
1
+ import { z } from 'zod';
2
+ import { DOQB } from 'workers-qb';
3
+ import { exponential, jitter } from './utils.js';
4
+ const tableName = 'durability_calls';
5
+ const migrationTableName = 'durability_migrations';
6
+ const storedValueSchema = z.discriminatedUnion('kind', [
7
+ z.object({ kind: z.literal('value'), value: z.json() }),
8
+ z.object({ kind: z.literal('undefined') }),
9
+ ]);
10
+ /**
11
+ * Ordered SQLite migrations for the tables owned by durability.
12
+ *
13
+ * Every SQLite-backed Durable Object instance has an independent database, so
14
+ * the durability schema must exist in each instance before calls can be stored.
15
+ * {@link createDurability} applies these migrations automatically on instance
16
+ * initialization. They are tracked in the namespaced `durability_migrations`
17
+ * table so they can coexist with application-owned migrations in the same
18
+ * database.
19
+ *
20
+ * The list is exported so migration names can be inspected before an explicit
21
+ * rollback with {@link migrateDurability}. Most consumers should not execute
22
+ * the SQL directly.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * const currentTarget = durabilityMigrations.at(-1)?.name ?? null;
27
+ * migrateDurability(this.ctx, currentTarget);
28
+ * ```
29
+ */
30
+ export const durabilityMigrations = [
31
+ {
32
+ name: 'durability_0001_create_calls',
33
+ up: `
34
+ CREATE TABLE IF NOT EXISTS durability_calls (
35
+ id TEXT PRIMARY KEY,
36
+ operation TEXT NOT NULL,
37
+ payload TEXT NOT NULL,
38
+ status TEXT NOT NULL CHECK (status IN ('pending', 'completed', 'failed')),
39
+ result TEXT,
40
+ attempt INTEGER NOT NULL DEFAULT 0,
41
+ next_attempt_at INTEGER NOT NULL,
42
+ last_error TEXT,
43
+ last_error_name TEXT,
44
+ completed_at INTEGER
45
+ );
46
+ `,
47
+ down: 'DROP TABLE IF EXISTS durability_calls;',
48
+ },
49
+ {
50
+ name: 'durability_0002_pending_index',
51
+ up: `
52
+ CREATE INDEX IF NOT EXISTS durability_calls_pending_idx
53
+ ON durability_calls (status, next_attempt_at);
54
+ `,
55
+ down: 'DROP INDEX IF EXISTS durability_calls_pending_idx;',
56
+ },
57
+ ];
58
+ /**
59
+ * Moves the durability schema in one Durable Object instance to a target.
60
+ *
61
+ * {@link createDurability} calls this with the latest target automatically. Call
62
+ * it directly only for explicit schema management, especially rollbacks. Passing
63
+ * `null` removes every durability table and permanently deletes stored calls.
64
+ *
65
+ * @example Apply all pending durability migrations.
66
+ * ```ts
67
+ * migrateDurability(this.ctx);
68
+ * ```
69
+ *
70
+ * @example Roll back to a specific version, then remove the schema entirely.
71
+ * ```ts
72
+ * migrateDurability(this.ctx, 'durability_0001_create_calls');
73
+ * migrateDurability(this.ctx, null);
74
+ * ```
75
+ *
76
+ * @param context Durable Object context containing SQLite-backed storage.
77
+ * @param target Migration name to migrate to, or null to roll back all migrations.
78
+ */
79
+ export const migrateDurability = (context, target = durabilityMigrations[durabilityMigrations.length - 1]
80
+ ?.name ?? null) => {
81
+ const targetIndex = target === null
82
+ ? -1
83
+ : durabilityMigrations.findIndex((migration) => migration.name === target);
84
+ if (target !== null && targetIndex === -1) {
85
+ throw new Error(`Unknown durability migration target "${target}"`);
86
+ }
87
+ const qb = new DOQB(context.storage.sql);
88
+ const workersQbMigrations = durabilityMigrations.map(({ name, up }) => ({ name, sql: up }));
89
+ const migrationBuilder = qb.migrations({
90
+ migrations: workersQbMigrations,
91
+ tableName: 'durability_migrations',
92
+ });
93
+ const appliedNames = new Set(migrationBuilder.getApplied().map((migration) => migration.name));
94
+ const rolledBack = [];
95
+ for (let index = durabilityMigrations.length - 1; index > targetIndex; index--) {
96
+ const migration = durabilityMigrations[index];
97
+ if (!migration || !appliedNames.has(migration.name)) {
98
+ continue;
99
+ }
100
+ qb.raw({
101
+ query: `${migration.down}\nDELETE FROM ${migrationTableName} WHERE name = '${migration.name}';`,
102
+ }).execute();
103
+ rolledBack.push(migration.name);
104
+ }
105
+ const applied = qb
106
+ .migrations({
107
+ migrations: workersQbMigrations.slice(0, targetIndex + 1),
108
+ tableName: 'durability_migrations',
109
+ })
110
+ .apply()
111
+ .map((migration) => migration.name);
112
+ return { applied, rolledBack };
113
+ };
114
+ /**
115
+ * Marks a handler failure as terminal so it is persisted without another retry.
116
+ *
117
+ * Use this for permanent failures such as invalid input. Transient errors should
118
+ * be thrown normally so the configured retry policy can handle them.
119
+ *
120
+ * @example
121
+ * ```ts
122
+ * if (!recipient.isValid) {
123
+ * throw new NonRetryableError('Recipient is invalid');
124
+ * }
125
+ * ```
126
+ */
127
+ export class NonRetryableError extends Error {
128
+ constructor(message) {
129
+ super(message);
130
+ this.name = 'NonRetryableError';
131
+ }
132
+ }
133
+ /**
134
+ * Error recorded when a handler attempt exceeds its configured timeout.
135
+ *
136
+ * Durability creates this error and aborts the attempt's signal; consumers do
137
+ * not need to throw it themselves. Timeout failures follow the normal retry
138
+ * policy and are exposed by `getResult` if they become terminal.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * const state = await durability.resizeImage.getResult('resize:image-1');
143
+ * if (
144
+ * state.status === 'failed' &&
145
+ * state.error.name === 'DurableAttemptTimeoutError'
146
+ * ) {
147
+ * console.error('Resize timed out');
148
+ * }
149
+ * ```
150
+ */
151
+ export class DurableAttemptTimeoutError extends Error {
152
+ constructor(operation, timeoutMs) {
153
+ super(`Durable operation "${operation}" timed out after ${timeoutMs}ms`);
154
+ this.name = 'DurableAttemptTimeoutError';
155
+ }
156
+ }
157
+ /**
158
+ * Error thrown when an idempotency key is reused for another operation.
159
+ *
160
+ * A call ID permanently identifies its original operation so `getResult` cannot
161
+ * return a value with the wrong inferred type.
162
+ *
163
+ * @example
164
+ * ```ts
165
+ * await durability.resizeImage({ id: 'job:1', payload: resizeInput });
166
+ * await durability.sendEmail({ id: 'job:1', payload: emailInput });
167
+ * // Throws DuplicateDurableCallError because job:1 belongs to resizeImage.
168
+ * ```
169
+ */
170
+ export class DuplicateDurableCallError extends Error {
171
+ constructor(id, existingOperation, requestedOperation) {
172
+ super(`Durable call "${id}" already belongs to operation "${existingOperation}", not "${requestedOperation}"`);
173
+ this.name = 'DuplicateDurableCallError';
174
+ }
175
+ }
176
+ /**
177
+ * Creates typed, alarm-backed durable methods from an operation handler map.
178
+ *
179
+ * Registered calls persist before execution and are deduplicated by their IDs.
180
+ * Generated methods resolve after registration; read handler results with each
181
+ * method's `getResult` function.
182
+ *
183
+ * The Durable Object class must use SQLite storage, and its `alarm` method must
184
+ * delegate to the returned alarm handler. External side effects should use the
185
+ * call ID as an idempotency key because a crash can occur after a side effect but
186
+ * before the completion record commits.
187
+ *
188
+ * @example
189
+ * ```ts
190
+ * class ImageJobs extends DurableObject<Env> {
191
+ * private readonly durability = createDurability(this.ctx, {
192
+ * resizeImage: async ({ id, payload, signal }) =>
193
+ * this.env.IMAGES.resize(payload.imageId, {
194
+ * idempotencyKey: id,
195
+ * signal,
196
+ * }),
197
+ * });
198
+ *
199
+ * resize(imageId: string) {
200
+ * return this.durability.resizeImage({
201
+ * id: `resize:${imageId}`,
202
+ * payload: { imageId },
203
+ * });
204
+ * }
205
+ *
206
+ * alarm(info: AlarmInvocationInfo) {
207
+ * return this.durability.alarm(info);
208
+ * }
209
+ * }
210
+ * ```
211
+ *
212
+ * @param context Durable Object context containing SQLite-backed storage.
213
+ * @param handlers Operation handlers keyed by their public method names.
214
+ * @param options Concurrency, timeout, and retry policy configuration.
215
+ */
216
+ export const createDurability = (context, handlers, options = {}) => {
217
+ migrateDurability(context);
218
+ const qb = new DOQB(context.storage.sql);
219
+ const active = new Map();
220
+ const alarmConcurrency = options.alarmConcurrency ?? 10;
221
+ const alarmHandoffMs = options.alarmHandoffMs ?? 14 * 60000;
222
+ const defaultAttemptTimeoutMs = options.attemptTimeoutMs ?? 5 * 60000;
223
+ const defaultRetryDelay = options.retries?.delay ??
224
+ ((attempt) => jitter(exponential(attempt)));
225
+ const defaultMaxAttempts = options.retries?.maxAttempts ?? 5;
226
+ if (!Number.isInteger(alarmConcurrency) || alarmConcurrency < 1) {
227
+ throw new RangeError('alarmConcurrency must be a positive integer');
228
+ }
229
+ if (!Number.isInteger(defaultAttemptTimeoutMs) ||
230
+ defaultAttemptTimeoutMs < 1) {
231
+ throw new RangeError('attemptTimeoutMs must be a positive integer');
232
+ }
233
+ if (!Number.isInteger(defaultMaxAttempts) || defaultMaxAttempts < 1) {
234
+ throw new RangeError('retries.maxAttempts must be a positive integer');
235
+ }
236
+ const methodOptions = (options.methods ?? {});
237
+ for (const [operation, method] of Object.entries(methodOptions)) {
238
+ if (method?.attemptTimeoutMs !== undefined &&
239
+ (!Number.isInteger(method.attemptTimeoutMs) ||
240
+ method.attemptTimeoutMs < 1)) {
241
+ throw new RangeError(`methods.${operation}.attemptTimeoutMs must be a positive integer`);
242
+ }
243
+ if (method?.retries?.maxAttempts !== undefined &&
244
+ (!Number.isInteger(method.retries.maxAttempts) ||
245
+ method.retries.maxAttempts < 1)) {
246
+ throw new RangeError(`methods.${operation}.retries.maxAttempts must be a positive integer`);
247
+ }
248
+ }
249
+ const executionPolicy = (operation) => {
250
+ const method = methodOptions[operation];
251
+ return {
252
+ attemptTimeoutMs: method?.attemptTimeoutMs ?? defaultAttemptTimeoutMs,
253
+ delay: method?.retries?.delay ?? defaultRetryDelay,
254
+ maxAttempts: method?.retries?.maxAttempts ?? defaultMaxAttempts,
255
+ };
256
+ };
257
+ const isNonRetryable = (error) => {
258
+ if (error instanceof NonRetryableError) {
259
+ return true;
260
+ }
261
+ if (typeof error !== 'object' || error === null) {
262
+ return false;
263
+ }
264
+ const value = error;
265
+ return (value.name === 'NonRetryableError' ||
266
+ value.constructor?.name === 'NonRetryableError');
267
+ };
268
+ const serialize = (value) => JSON.stringify(value === undefined
269
+ ? { kind: 'undefined' }
270
+ : { kind: 'value', value: z.json().parse(value) });
271
+ const deserialize = (value) => {
272
+ const parsed = JSON.parse(value);
273
+ const stored = storedValueSchema.parse(parsed);
274
+ return stored.kind === 'undefined' ? undefined : stored.value;
275
+ };
276
+ const getCall = (id) => qb
277
+ .fetchOne({
278
+ tableName,
279
+ where: { conditions: 'id = ?', params: [id] },
280
+ })
281
+ .execute().results;
282
+ const getResult = (operation, idempotencyKey) => {
283
+ const call = getCall(idempotencyKey);
284
+ if (!call) {
285
+ return { status: 'not_found' };
286
+ }
287
+ assertOperation(idempotencyKey, call.operation, operation);
288
+ if (call.status === 'pending') {
289
+ return {
290
+ status: 'pending',
291
+ attempt: call.attempt,
292
+ nextAttemptAt: call.next_attempt_at,
293
+ lastError: call.last_error,
294
+ };
295
+ }
296
+ if (call.status === 'failed') {
297
+ return {
298
+ status: 'failed',
299
+ attempt: call.attempt,
300
+ error: {
301
+ name: call.last_error_name ?? 'Error',
302
+ message: call.last_error ?? 'Durable operation failed',
303
+ },
304
+ };
305
+ }
306
+ if (call.result === null) {
307
+ throw new Error(`Completed durable call "${idempotencyKey}" has no result`);
308
+ }
309
+ return { status: 'completed', result: deserialize(call.result) };
310
+ };
311
+ const listDueIds = (now, limit) => (qb
312
+ .fetchAll({
313
+ tableName,
314
+ fields: 'id',
315
+ where: {
316
+ conditions: "status = 'pending' AND next_attempt_at <= ?",
317
+ params: [now],
318
+ },
319
+ orderBy: 'next_attempt_at ASC',
320
+ limit,
321
+ })
322
+ .execute().results ?? []).map((call) => call.id);
323
+ const getNextPendingAt = () => qb
324
+ .fetchOne({
325
+ tableName,
326
+ fields: 'next_attempt_at',
327
+ where: { conditions: "status = 'pending'" },
328
+ orderBy: 'next_attempt_at ASC',
329
+ })
330
+ .execute().results?.next_attempt_at;
331
+ const runConcurrent = async (items, concurrency, worker) => {
332
+ let nextIndex = 0;
333
+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, async () => {
334
+ while (nextIndex < items.length) {
335
+ const item = items[nextIndex++];
336
+ if (item !== undefined) {
337
+ // eslint-disable-next-line no-await-in-loop
338
+ await worker(item);
339
+ }
340
+ }
341
+ }));
342
+ };
343
+ const assertOperation = (id, existingOperation, requestedOperation) => {
344
+ if (existingOperation !== requestedOperation) {
345
+ throw new DuplicateDurableCallError(id, existingOperation, requestedOperation);
346
+ }
347
+ };
348
+ const armIfMissing = async (timestamp) => {
349
+ const currentAlarm = await context.storage.getAlarm();
350
+ if (currentAlarm === null) {
351
+ await context.storage.setAlarm(timestamp);
352
+ }
353
+ };
354
+ let alarmRefresh;
355
+ const scheduleNextAlarm = () => {
356
+ if (alarmRefresh) {
357
+ return alarmRefresh;
358
+ }
359
+ alarmRefresh = context.storage
360
+ .transaction(async (transaction) => {
361
+ const nextAttemptAt = getNextPendingAt();
362
+ const currentAlarm = await transaction.getAlarm();
363
+ if (nextAttemptAt === undefined) {
364
+ if (currentAlarm !== null) {
365
+ await transaction.deleteAlarm();
366
+ }
367
+ }
368
+ else if (currentAlarm === null) {
369
+ await transaction.setAlarm(nextAttemptAt);
370
+ }
371
+ })
372
+ .finally(() => {
373
+ alarmRefresh = undefined;
374
+ });
375
+ return alarmRefresh;
376
+ };
377
+ const execute = (id) => {
378
+ const running = active.get(id);
379
+ if (running) {
380
+ return running;
381
+ }
382
+ const execution = (async () => {
383
+ const call = getCall(id);
384
+ if (!call) {
385
+ return undefined;
386
+ }
387
+ if (call.status === 'completed') {
388
+ if (call.result === null) {
389
+ throw new Error(`Completed durable call "${id}" has no result`);
390
+ }
391
+ return deserialize(call.result);
392
+ }
393
+ if (call.status === 'failed') {
394
+ return undefined;
395
+ }
396
+ const handler = handlers[call.operation];
397
+ const attempt = call.attempt + 1;
398
+ const policy = executionPolicy(call.operation);
399
+ qb.update({
400
+ tableName,
401
+ data: { attempt },
402
+ where: { conditions: 'id = ?', params: [id] },
403
+ }).execute();
404
+ let timeout;
405
+ try {
406
+ if (!handler) {
407
+ throw new NonRetryableError(`No handler registered for operation "${call.operation}"`);
408
+ }
409
+ const controller = new AbortController();
410
+ const handlerResult = Promise.resolve().then(() => handler({
411
+ id,
412
+ operation: call.operation,
413
+ payload: deserialize(call.payload),
414
+ attempt,
415
+ signal: controller.signal,
416
+ }));
417
+ const timeoutResult = new Promise((_resolve, reject) => {
418
+ timeout = setTimeout(() => {
419
+ const error = new DurableAttemptTimeoutError(call.operation, policy.attemptTimeoutMs);
420
+ controller.abort(error);
421
+ reject(error);
422
+ }, policy.attemptTimeoutMs);
423
+ });
424
+ const result = await Promise.race([handlerResult, timeoutResult]);
425
+ qb.update({
426
+ tableName,
427
+ data: {
428
+ status: 'completed',
429
+ result: serialize(result),
430
+ last_error: null,
431
+ last_error_name: null,
432
+ completed_at: Date.now(),
433
+ },
434
+ where: { conditions: 'id = ?', params: [id] },
435
+ }).execute();
436
+ return result;
437
+ }
438
+ catch (error) {
439
+ const terminal = isNonRetryable(error) || attempt >= policy.maxAttempts;
440
+ const baseDelay = terminal ? 0 : policy.delay(attempt);
441
+ if (!Number.isFinite(baseDelay) || baseDelay < 0) {
442
+ throw new RangeError(`Retry delay for operation "${call.operation}" must be a non-negative finite number`);
443
+ }
444
+ const nextAttemptAt = Date.now() + Math.round(baseDelay);
445
+ await context.storage.transaction(async (transaction) => {
446
+ qb.update({
447
+ tableName,
448
+ data: {
449
+ status: terminal ? 'failed' : 'pending',
450
+ attempt,
451
+ next_attempt_at: nextAttemptAt,
452
+ last_error: error instanceof Error ? error.message : String(error),
453
+ last_error_name: error instanceof Error ? error.name : 'Error',
454
+ },
455
+ where: { conditions: 'id = ?', params: [id] },
456
+ }).execute();
457
+ if (!terminal && (await transaction.getAlarm()) === null) {
458
+ await transaction.setAlarm(nextAttemptAt);
459
+ }
460
+ });
461
+ throw error;
462
+ }
463
+ finally {
464
+ if (timeout !== undefined) {
465
+ clearTimeout(timeout);
466
+ }
467
+ }
468
+ })();
469
+ active.set(id, execution);
470
+ void execution.finally(() => active.delete(id)).catch(() => undefined);
471
+ return execution;
472
+ };
473
+ const run = async (input) => {
474
+ const existing = getCall(input.id);
475
+ if (existing) {
476
+ assertOperation(input.id, existing.operation, input.operation);
477
+ if (existing.status === 'completed' || existing.status === 'failed') {
478
+ return;
479
+ }
480
+ await context.storage.transaction(async (transaction) => {
481
+ if ((await transaction.getAlarm()) === null) {
482
+ await transaction.setAlarm(existing.next_attempt_at);
483
+ }
484
+ });
485
+ }
486
+ else {
487
+ const now = Date.now();
488
+ await context.storage.transaction(async (transaction) => {
489
+ qb.insert({
490
+ tableName,
491
+ data: {
492
+ id: input.id,
493
+ operation: input.operation,
494
+ payload: serialize(input.payload),
495
+ status: 'pending',
496
+ attempt: 0,
497
+ next_attempt_at: now,
498
+ },
499
+ }).execute();
500
+ if ((await transaction.getAlarm()) === null) {
501
+ await transaction.setAlarm(now);
502
+ }
503
+ });
504
+ }
505
+ const execution = execute(input.id);
506
+ void execution.then(() => scheduleNextAlarm()).catch(() => undefined);
507
+ };
508
+ const alarm = async (_alarmInfo) => {
509
+ const startedAt = Date.now();
510
+ const due = listDueIds(startedAt, 100);
511
+ if (due.length === 0) {
512
+ await scheduleNextAlarm();
513
+ return;
514
+ }
515
+ const execution = runConcurrent(due, alarmConcurrency, async (id) => {
516
+ try {
517
+ await execute(id);
518
+ }
519
+ catch {
520
+ return;
521
+ }
522
+ });
523
+ let timeout;
524
+ const handoff = Symbol('alarm handoff');
525
+ const remaining = alarmHandoffMs - (Date.now() - startedAt);
526
+ const result = await Promise.race([
527
+ execution,
528
+ new Promise((resolve) => {
529
+ timeout = setTimeout(() => resolve(handoff), Math.max(remaining, 0));
530
+ }),
531
+ ]);
532
+ if (timeout !== undefined) {
533
+ clearTimeout(timeout);
534
+ }
535
+ if (result === handoff) {
536
+ await armIfMissing(Date.now());
537
+ return;
538
+ }
539
+ await scheduleNextAlarm();
540
+ };
541
+ const durability = { alarm };
542
+ for (const operation of Object.keys(handlers)) {
543
+ if (operation === 'alarm') {
544
+ throw new Error(`"${operation}" is reserved by durability`);
545
+ }
546
+ const durableOperation = (input) => run({ ...input, operation });
547
+ durableOperation.getResult = async (idempotencyKey) => getResult(operation, idempotencyKey);
548
+ durability[operation] = durableOperation;
549
+ }
550
+ return durability;
551
+ };
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Calculates a capped exponential retry delay.
3
+ *
4
+ * @param attempt One-based attempt number.
5
+ * @param initialDelayMs Delay after the first failed attempt. Defaults to 1 second.
6
+ * @param maxDelayMs Maximum returned delay. Defaults to 5 minutes.
7
+ */
8
+ export declare const exponential: (attempt: number, initialDelayMs?: number, maxDelayMs?: number) => number;
9
+ /** Applies equal jitter, returning a value between half and all of the delay. */
10
+ export declare const jitter: (delayMs: number) => number;
package/dist/utils.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Calculates a capped exponential retry delay.
3
+ *
4
+ * @param attempt One-based attempt number.
5
+ * @param initialDelayMs Delay after the first failed attempt. Defaults to 1 second.
6
+ * @param maxDelayMs Maximum returned delay. Defaults to 5 minutes.
7
+ */
8
+ export const exponential = (attempt, initialDelayMs = 1000, maxDelayMs = 300000) => Math.min(initialDelayMs * 2 ** (attempt - 1), maxDelayMs);
9
+ /** Applies equal jitter, returning a value between half and all of the delay. */
10
+ export const jitter = (delayMs) => delayMs / 2 + Math.random() * (delayMs / 2);
package/package.json CHANGED
@@ -1,13 +1,60 @@
1
1
  {
2
2
  "name": "durability",
3
- "version": "1.0.0",
4
- "description": "",
5
- "main": "index.js",
6
- "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
8
- },
9
- "keywords": [],
10
- "author": "",
3
+ "version": "2.0.0",
4
+ "description": "Alarm-backed durable operations for Cloudflare Durable Objects",
5
+ "type": "module",
11
6
  "license": "ISC",
12
- "type": "commonjs"
13
- }
7
+ "sideEffects": false,
8
+ "files": [
9
+ "dist",
10
+ "LICENSE",
11
+ "README.md"
12
+ ],
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ },
18
+ "./utils": {
19
+ "types": "./dist/utils.d.ts",
20
+ "import": "./dist/utils.js"
21
+ }
22
+ },
23
+ "publishConfig": {
24
+ "access": "public",
25
+ "registry": "https://registry.npmjs.org/"
26
+ },
27
+ "keywords": [
28
+ "cloudflare",
29
+ "durable-objects",
30
+ "idempotency",
31
+ "retries",
32
+ "workers"
33
+ ],
34
+ "dependencies": {
35
+ "workers-qb": "^1.11.2",
36
+ "zod": "^4.4.3"
37
+ },
38
+ "peerDependencies": {
39
+ "@cloudflare/workers-types": "^4.20260702.1"
40
+ },
41
+ "peerDependenciesMeta": {
42
+ "@cloudflare/workers-types": {
43
+ "optional": true
44
+ }
45
+ },
46
+ "devDependencies": {
47
+ "@cloudflare/workers-types": "^4.20260702.1",
48
+ "@types/node": "^24.12.0",
49
+ "typescript": "6.0.3",
50
+ "vitest": "^4.1.5",
51
+ "@durability/storage": "0.1.0",
52
+ "@repo/typescript-config": "0.0.0"
53
+ },
54
+ "scripts": {
55
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
56
+ "lint": "oxlint",
57
+ "test": "vitest run",
58
+ "typecheck": "tsc --noEmit"
59
+ }
60
+ }
package/index.js DELETED
@@ -1,9 +0,0 @@
1
- "use strict";
2
-
3
- function durability() {
4
- return "durability";
5
- }
6
-
7
- module.exports = {
8
- durability,
9
- };