durability 1.0.0 → 2.1.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,235 @@
1
+ # Durability
2
+
3
+ A small, alarm-backed independent-operation queue for Cloudflare Durable Objects.
4
+
5
+ Durability is not an event-sourcing, replay-log, or workflow-orchestration engine. It registers independent operations and reconciles their earliest wake-up in one Durable Object storage transaction. Generated operation methods return `Promise<void>` after registration commits; they do not wait for the handler result. 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
+ ## Migrating to v3
8
+
9
+ `purgeBefore` is now reserved by the generated durability API, so rename any operation with that name before upgrading.
10
+
11
+ ```ts
12
+ import { DurableObject } from 'cloudflare:workers';
13
+ import { createDurability, type DurableHandler } from 'durability';
14
+
15
+ type ResizeInput = { imageId: string };
16
+
17
+ export class ImageJobs extends DurableObject<Env> {
18
+ private readonly durability = createDurability(this.ctx, {
19
+ resizeImage: (async ({ id, payload }) => {
20
+ return this.env.IMAGES.resize(payload.imageId, { idempotencyKey: id });
21
+ }) satisfies DurableHandler<ResizeInput, string>,
22
+ });
23
+
24
+ resize(imageId: string) {
25
+ return this.durability.resizeImage({
26
+ id: `resize:${imageId}`,
27
+ payload: { imageId },
28
+ });
29
+ }
30
+
31
+ alarm(alarmInfo?: AlarmInvocationInfo) {
32
+ return this.durability.alarm(alarmInfo);
33
+ }
34
+ }
35
+ ```
36
+
37
+ ## Named alarms
38
+
39
+ Named alarms share the Durable Object's physical alarm with durable operation retries. Configure handlers through `alarms`, then schedule them through the typed method on `durability.alarm`:
40
+
41
+ ```ts
42
+ import ms from 'ms';
43
+ import { createDurability } from 'durability';
44
+ import { exponential, jitter } from 'durability/utils';
45
+
46
+ class ImageJobs extends DurableObject<Env> {
47
+ private readonly durability = createDurability(
48
+ this.ctx,
49
+ {
50
+ resizeImage: async ({ payload }) =>
51
+ this.env.IMAGES.resize(payload.imageId),
52
+ },
53
+ {
54
+ alarms: {
55
+ cleanup: async ({
56
+ scheduledTime,
57
+ attempt,
58
+ idempotencyKey,
59
+ signal,
60
+ platform,
61
+ }) => {
62
+ await this.env.CLEANUP.fetch('https://cleanup.internal/run', {
63
+ method: 'POST',
64
+ headers: { 'Idempotency-Key': idempotencyKey },
65
+ signal,
66
+ });
67
+ console.log({ scheduledTime, attempt, platform });
68
+ },
69
+ },
70
+ alarmMethods: {
71
+ cleanup: {
72
+ attemptTimeoutMs: 60_000,
73
+ retries: {
74
+ maxAttempts: 5,
75
+ delay: (attempt) => jitter(exponential(attempt)),
76
+ },
77
+ retryTimeouts: true,
78
+ },
79
+ },
80
+ }
81
+ );
82
+
83
+ scheduleCleanup() {
84
+ return this.durability.alarm.cleanup(Date.now() + ms('5 seconds'));
85
+ }
86
+
87
+ alarm(alarmInfo?: AlarmInvocationInfo) {
88
+ return this.durability.alarm(alarmInfo);
89
+ }
90
+ }
91
+ ```
92
+
93
+ Scheduling the same name again replaces its pending occurrence. If that name is already running, the current handler continues and the replacement runs afterward. Different names may run concurrently, but one name never has more than one active handler in the same Durable Object instance.
94
+
95
+ Each schedule receives a new internal occurrence ID. Its generated `idempotencyKey` remains stable across retries, while `attempt` starts at one and increments for every execution of that occurrence. A successful handler removes only the occurrence it executed, so it cannot delete a replacement scheduled while it was running.
96
+
97
+ Named alarms inherit the global attempt timeout and retry policy. `alarmMethods` overrides them for one name. Failures use the same jittered exponential delay as operations by default; `NonRetryableError` and exhausted attempts make the occurrence terminal. A timeout aborts the handler's `signal` and is terminal by default because the external outcome may be unknown. Set `retryTimeouts: true` only when the handler's side effects use the generated idempotency key or reconcile their outcome before retrying. If a handler ignores the signal, the scheduler retains its per-name execution lock until the handler actually settles, preventing an overlapping retry.
98
+
99
+ Named alarm handlers are still at-least-once across eviction or restart. Pass `idempotencyKey` to external systems that support deduplication.
100
+
101
+ ## SQLite requirement
102
+
103
+ The Durable Object class must use SQLite storage:
104
+
105
+ ```jsonc
106
+ {
107
+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ImageJobs"] }],
108
+ }
109
+ ```
110
+
111
+ `createDurability` migrates to the latest schema and stores operations in `durability_calls` and named schedules in `durability_alarms`. Each package migration has `up` and `down` SQL and is tracked in the namespaced `durability_migrations` table. The v4 migration adds generation and creation timestamps; existing records receive the migration time. Rolling back to `null` removes the durability tables and `durability_migrations`, without touching application tables.
112
+
113
+ Rollbacks are explicit because rolling back the initial migration deletes durable call records:
114
+
115
+ ```ts
116
+ import { migrateDurability } from 'durability';
117
+
118
+ migrateDurability(this.ctx, 'durability_0001_create_calls');
119
+ migrateDurability(this.ctx, null); // roll back every durability migration
120
+ ```
121
+
122
+ Passing a migration name moves the schema to that exact version, applying or reverting migrations as needed. Payloads and results must be JSON-serializable.
123
+
124
+ ## Reading results
125
+
126
+ Results are read through the same typed operation using its idempotency key:
127
+
128
+ ```ts
129
+ const result = await this.durability.resizeImage.getResult(`resize:${imageId}`);
130
+
131
+ switch (result.status) {
132
+ case 'not_found':
133
+ break;
134
+ case 'pending':
135
+ console.log(result.attempt, result.nextAttemptAt, result.lastError);
136
+ break;
137
+ case 'failed':
138
+ console.error(result.error.name, result.error.message);
139
+ break;
140
+ case 'completed':
141
+ console.log(result.result);
142
+ break;
143
+ }
144
+ ```
145
+
146
+ 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.
147
+
148
+ ## Retries, timeouts, and terminal failures
149
+
150
+ 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:
151
+
152
+ ```ts
153
+ import { exponential, jitter } from 'durability/utils';
154
+
155
+ const durability = createDurability(this.ctx, handlers, {
156
+ attemptTimeoutMs: 60_000,
157
+ retries: {
158
+ maxAttempts: 5,
159
+ delay: (attempt) => jitter(exponential(attempt)),
160
+ },
161
+ methods: {
162
+ resizeImage: {
163
+ attemptTimeoutMs: 10 * 60_000,
164
+ retries: {
165
+ maxAttempts: 2,
166
+ delay: (attempt) => exponential(attempt, 500, 30_000),
167
+ },
168
+ },
169
+ },
170
+ });
171
+ ```
172
+
173
+ Each attempt receives its own `AbortSignal`:
174
+
175
+ ```ts
176
+ const handlers = {
177
+ sendEmail: async ({ payload, signal }: DurableCall<EmailPayload>) =>
178
+ fetch(payload.url, { method: 'POST', signal }),
179
+ };
180
+ ```
181
+
182
+ A timed-out operation aborts its signal and follows the normal retry policy. Named alarm timeouts remain terminal by default unless `retryTimeouts` is enabled. If a handler ignores abort, its in-memory ID lock and shared concurrency permit remain held until the real handler settles, so a same-isolate retry cannot overlap it. Across eviction or restart, delivery remains at least once.
183
+
184
+ Throw `NonRetryableError` to move a call directly to `failed` without another attempt:
185
+
186
+ ```ts
187
+ import { NonRetryableError } from 'durability';
188
+
189
+ throw new NonRetryableError('Recipient permanently rejected');
190
+ ```
191
+
192
+ Errors created by `NonRetryableError` from `cloudflare:workflows` are also recognized.
193
+
194
+ ## Delivery semantics and concurrency
195
+
196
+ 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. Handlers should be idempotent, and should pass the call ID to external services as an idempotency key when supported.
197
+
198
+ `alarmConcurrency` defaults to 10 and is one FIFO concurrency limit shared by eager operation handlers, alarm-driven operation handlers, and named-alarm handlers. Newly registered operations start eagerly only when a permit is immediately available; otherwise their persisted row is left for the reconciled alarm without creating an in-memory waiter. A timed-out handler that has not settled continues to occupy its permit.
199
+
200
+ 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.
201
+
202
+ ## Destructive retention purge
203
+
204
+ `purgeBefore(timestamp)` deletes every operation and named-alarm record whose creation time is strictly less than `timestamp`, regardless of status or scheduled time. Records created exactly at the cutoff are retained. The timestamp must be a non-negative safe integer.
205
+
206
+ ```ts
207
+ const removed = await this.durability.purgeBefore(retentionCutoff);
208
+ console.log(removed.operations, removed.namedAlarms, removed.total);
209
+ ```
210
+
211
+ The purge uses aggregate counts, deletes and reconciles the physical alarm in one storage transaction, and never touches application or migration tables. It best-effort aborts matching active handlers, but JavaScript cannot force an abort-ignoring handler to stop. Operation IDs can be reused immediately; a late old generation cannot overwrite the replacement record, but its already-started external side effects may still complete. A replacement named alarm remains serialized behind an abort-ignoring old handler with the same name until that handler settles or the isolate is evicted. Treat this API as intentionally destructive.
212
+
213
+ ## Lifecycle metrics hook
214
+
215
+ `onLifecycleEvent` receives compact events for registration or scheduling, attempt start and settlement, pre-invocation attempt exhaustion, and purge aggregates. Events include timestamps, attempts, identities, and generation IDs needed to attribute metrics.
216
+
217
+ ```ts
218
+ const durability = createDurability(this.ctx, handlers, {
219
+ onLifecycleEvent: (event) => recordDurabilityMetric(event),
220
+ });
221
+ ```
222
+
223
+ The hook is best-effort and non-blocking, is not a durable journal, and may duplicate or drop events across crashes. Hook failures are reported to `console.error` and never change queue state. Returned promises are attached to `waitUntil` when the context exposes it.
224
+
225
+ ## Long-running alarm calls
226
+
227
+ 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:
228
+
229
+ ```ts
230
+ const durability = createDurability(this.ctx, handlers, {
231
+ alarmHandoffMs: 14 * 60_000,
232
+ });
233
+ ```
234
+
235
+ 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,435 @@
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 {};