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.
@@ -0,0 +1,58 @@
1
+ import { exports as workerExports } from 'cloudflare:workers';
2
+ import { createTransformStub, } from '@durability/transforms';
3
+ import { RoutingError } from './errors.js';
4
+ import { RoutingLoad } from './load.js';
5
+ import { RoutingClient } from './routing-client.js';
6
+ /**
7
+ * Inside a DO, attach this local load observer to a fanout capability. Outside
8
+ * the DO, client() routes calls to an application-owned class using ordinary
9
+ * @durability/transforms caller transforms. No DO classes are generated.
10
+ */
11
+ export class DurabilityRouting extends RoutingLoad {
12
+ static client(config) {
13
+ const client = new RoutingClient({
14
+ invoke: (address, input) => {
15
+ let namespace = config.namespace?.();
16
+ if (!namespace) {
17
+ if (!config.exportName) {
18
+ throw new RoutingError('Use the durability Vite plugin, exportName, or an explicit namespace to resolve the routing target');
19
+ }
20
+ const exported = Reflect.get(workerExports, config.exportName);
21
+ if (exported === null ||
22
+ (typeof exported !== 'object' && typeof exported !== 'function') ||
23
+ typeof Reflect.get(exported, 'getByName') !== 'function') {
24
+ throw new RoutingError(`Export "${config.exportName}" is not a Durable Object namespace`);
25
+ }
26
+ namespace = exported;
27
+ }
28
+ const stub = namespace.getByName(address.shard, address.locationHint === undefined
29
+ ? undefined
30
+ : { locationHint: address.locationHint });
31
+ return config.invoke(stub, input);
32
+ },
33
+ ...(config.sharding === undefined ? {} : { sharding: config.sharding }),
34
+ ...(config.softBacklogLimit === undefined
35
+ ? {}
36
+ : { softBacklogLimit: config.softBacklogLimit }),
37
+ });
38
+ const session = {
39
+ push: (input, context) => client.push(input, context),
40
+ setContext: (context) => ({
41
+ invoke: (method, args) => {
42
+ if (method !== 'push') {
43
+ throw new RoutingError(`Unknown routing method "${method}"`);
44
+ }
45
+ const positional = args[1];
46
+ if (positional !== undefined &&
47
+ (positional === null ||
48
+ typeof positional !== 'object' ||
49
+ Array.isArray(positional))) {
50
+ throw new TypeError('Routing context must be an object when combined with transform context');
51
+ }
52
+ return client.push(args[0], { ...positional, ...context });
53
+ },
54
+ }),
55
+ };
56
+ return createTransformStub(session);
57
+ }
58
+ }
@@ -0,0 +1,157 @@
1
+ import { type Emit, type LifecycleEntity, type LifecycleHook } from './lifecycle.js';
2
+ import { type MigrationCapability } from './migrations.js';
3
+ import { type AttemptPolicy } from './policy.js';
4
+ import { type DurabilityStorage, type DurabilityStorageTransaction, type DurableRecord, type RecordKind } from './storage.js';
5
+ import type { DurableMigrations } from '@durability/storage';
6
+ /** The Durable Object state durability needs: storage plus optional `waitUntil`. */
7
+ export type DurabilityContext = Pick<DurableObjectState, 'storage'> & Partial<Pick<DurableObjectState, 'waitUntil'>>;
8
+ export type DurabilityStorageBackend = 'sqlite' | 'kv';
9
+ /** Options for the scheduler shared by every durability helper in one Durable Object. */
10
+ export type DurabilitySchedulerOptions = {
11
+ /** Storage backend configured for the Durable Object class. Defaults to SQLite. */
12
+ storageBackend?: DurabilityStorageBackend;
13
+ /** Maximum handlers running at once across eager operations and alarm work. Defaults to 10. */
14
+ alarmConcurrency?: number;
15
+ /** Physical-alarm delay from 1 to 15 seconds. Defaults to 15 seconds. */
16
+ alarmMinDelayMs?: number;
17
+ /** Time before a running alarm hands unfinished work to a new alarm. Defaults to 14 minutes. */
18
+ alarmHandoffMs?: number;
19
+ };
20
+ /** Configuration for a scheduler shared by several helpers. */
21
+ export type DurabilitySchedulerConfig = DurabilitySchedulerOptions & {
22
+ context: DurabilityContext;
23
+ };
24
+ /**
25
+ * How a helper attaches to a scheduler: an existing shared one, or a private
26
+ * one created from the Durable Object context with the given scheduler options.
27
+ */
28
+ export type SchedulerAttachment = {
29
+ scheduler: DurabilityScheduler;
30
+ context?: never;
31
+ } | (DurabilitySchedulerConfig & {
32
+ scheduler?: never;
33
+ });
34
+ /** One record kind attached to the scheduler: how to find and run its due work. */
35
+ export type Participant = {
36
+ kind: RecordKind;
37
+ runDue(now: number, info: AlarmInvocationInfo | undefined): Promise<void>;
38
+ };
39
+ export type ActiveExecution = {
40
+ generation: string;
41
+ createdAt: number;
42
+ settled: Promise<void>;
43
+ controller?: AbortController;
44
+ };
45
+ /** Everything that differs between running a durable operation and a named alarm attempt. */
46
+ export type ExecutionSpec = {
47
+ kind: RecordKind;
48
+ key: string;
49
+ row: DurableRecord;
50
+ label: string;
51
+ entity: LifecycleEntity;
52
+ active: Map<string, ActiveExecution>;
53
+ policy: AttemptPolicy;
54
+ emit: Emit;
55
+ exhaustedError: () => Error;
56
+ timeoutError: () => Error;
57
+ invoke: (attempt: number, signal: AbortSignal) => unknown;
58
+ /**
59
+ * Persists a successful attempt and returns its settlement timestamp, or
60
+ * undefined when a newer generation won. May throw to turn the success into
61
+ * a failure.
62
+ */
63
+ complete: (result: unknown, attempt: number) => Promise<number | undefined>;
64
+ /** Kind-specific terminal rule beyond non-retryable errors and exhausted attempts. */
65
+ isTerminal: (error: unknown) => boolean;
66
+ };
67
+ /**
68
+ * Shared machinery behind {@link DurabilityScheduler}: storage, the physical
69
+ * alarm, the concurrency pool, and the attempt lifecycle. Package-internal.
70
+ */
71
+ export declare class Engine {
72
+ readonly storage: DurabilityStorage;
73
+ private readonly backend;
74
+ private readonly context;
75
+ private readonly alarmConcurrency;
76
+ private readonly alarmMinDelayMs;
77
+ private readonly alarmHandoffMs;
78
+ private readonly participants;
79
+ private availablePermits;
80
+ private readonly permitWaiters;
81
+ private alarmRefresh;
82
+ private earlyAlarm;
83
+ private readonly transactionReconciliations;
84
+ constructor(context: DurabilityContext, options: DurabilitySchedulerOptions);
85
+ register(participant: Participant): void;
86
+ waitUntil(promise: Promise<unknown>, onError: (error: unknown) => void): void;
87
+ emitter(hook: LifecycleHook | undefined): Emit;
88
+ /** Applies a helper's SQLite migrations; KV storage has no schema. */
89
+ migrateSchema(capability: MigrationCapability, migrations: DurableMigrations): void;
90
+ /** Runs a storage transaction and publishes its timer state only after commit. */
91
+ transaction<T>(callback: (transaction: DurabilityStorageTransaction) => Promise<T>): Promise<T>;
92
+ reconcile(transaction: DurabilityStorageTransaction): Promise<void>;
93
+ private scheduleEarlyAlarm;
94
+ /** Coalesces concurrent refresh requests into one reconciliation transaction. */
95
+ scheduleNextAlarm(): Promise<void>;
96
+ /**
97
+ * Aborts matching active handlers, then deletes one kind's records created
98
+ * before the timestamp, reconciling the alarm after each committed batch.
99
+ */
100
+ purge(kind: RecordKind, before: number, active: Map<string, ActiveExecution>, abortReason: string): Promise<number>;
101
+ tryAcquirePermit(): (() => void) | undefined;
102
+ acquirePermit(): Promise<() => void>;
103
+ private createRelease;
104
+ runConcurrent<Item>(items: Item[], worker: (item: Item) => Promise<void>): Promise<void>;
105
+ /**
106
+ * Runs every participant's due work, hands off to a fresh alarm if the
107
+ * invocation approaches its wall-time limit, and re-arms the physical alarm.
108
+ */
109
+ alarm(info?: AlarmInvocationInfo): Promise<void>;
110
+ private armForHandoff;
111
+ /**
112
+ * Registers the execution in its active map synchronously, then claims and
113
+ * runs one attempt in the background. The returned promise settles when the
114
+ * attempt's outcome has been persisted, not when a timed-out handler settles.
115
+ */
116
+ startExecution(spec: ExecutionSpec, eagerPermit?: () => void): Promise<void>;
117
+ private failExhausted;
118
+ private settleFailure;
119
+ }
120
+ /**
121
+ * Owns the Durable Object's physical alarm, storage backend, and concurrency
122
+ * pool so {@link Durability} and {@link DurabilityAlarms} can share them.
123
+ *
124
+ * Construct one per Durable Object when using both helpers, pass it to each,
125
+ * and delegate the object's `alarm` method to {@link DurabilityScheduler.alarm}.
126
+ * A helper constructed directly from the Durable Object context creates a
127
+ * private scheduler instead.
128
+ *
129
+ * @example
130
+ * ```ts
131
+ * class Jobs extends DurableObject<Env> {
132
+ * private readonly scheduler = new DurabilityScheduler({ context: this.ctx });
133
+ * private readonly durability = new Durability({
134
+ * scheduler: this.scheduler,
135
+ * handlers,
136
+ * });
137
+ * private readonly alarms = new DurabilityAlarms({
138
+ * scheduler: this.scheduler,
139
+ * handlers: alarmHandlers,
140
+ * });
141
+ *
142
+ * alarm(info?: AlarmInvocationInfo) {
143
+ * return this.scheduler.alarm(info);
144
+ * }
145
+ * }
146
+ * ```
147
+ */
148
+ export declare class DurabilityScheduler {
149
+ constructor(config: DurabilitySchedulerConfig);
150
+ /** Runs due work for every attached helper and re-arms the physical alarm. */
151
+ alarm(info?: AlarmInvocationInfo): Promise<void>;
152
+ }
153
+ /**
154
+ * Resolves the engine a helper should attach to: the shared one behind a
155
+ * scheduler, or a private one built from the Durable Object context.
156
+ */
157
+ export declare const engineFor: (attachment: SchedulerAttachment) => Engine;
@@ -0,0 +1,478 @@
1
+ import { z } from 'zod';
2
+ import { DurableRetryPolicyError, isErrorInstance, isNonRetryable, reportFailure, serializeError, } from './errors.js';
3
+ import { createKvDurabilityStorage } from './kv-storage.js';
4
+ import { createEmitter, } from './lifecycle.js';
5
+ import { migrate } from './migrations.js';
6
+ import { assertPositiveInteger } from './policy.js';
7
+ import { createSqliteDurabilityStorage } from './sqlite-storage.js';
8
+ import { reconcilePhysicalAlarm, } from './storage.js';
9
+ const storageBackendSchema = z.enum(['sqlite', 'kv']);
10
+ const minAlarmDelayMs = 1000;
11
+ const maxAlarmDelayMs = 15000;
12
+ const decideRetry = (spec, attempt, error) => {
13
+ const terminal = isNonRetryable(error) ||
14
+ attempt >= spec.policy.maxAttempts ||
15
+ spec.isTerminal(error);
16
+ if (terminal) {
17
+ const timestamp = Date.now();
18
+ return { error, terminal, timestamp, nextAttemptAt: timestamp };
19
+ }
20
+ try {
21
+ const rawDelay = spec.policy.delay(attempt);
22
+ if (!Number.isFinite(rawDelay) || rawDelay < 0) {
23
+ throw new DurableRetryPolicyError(spec.label);
24
+ }
25
+ const delay = Math.round(rawDelay);
26
+ const timestamp = Date.now();
27
+ if (!Number.isSafeInteger(delay) ||
28
+ !Number.isSafeInteger(timestamp + delay)) {
29
+ throw new DurableRetryPolicyError(spec.label);
30
+ }
31
+ return {
32
+ error,
33
+ terminal: false,
34
+ timestamp,
35
+ nextAttemptAt: timestamp + delay,
36
+ };
37
+ }
38
+ catch (policyError) {
39
+ const timestamp = Date.now();
40
+ return {
41
+ error: isErrorInstance(policyError, DurableRetryPolicyError)
42
+ ? policyError
43
+ : new DurableRetryPolicyError(spec.label, policyError),
44
+ terminal: true,
45
+ timestamp,
46
+ nextAttemptAt: timestamp,
47
+ };
48
+ }
49
+ };
50
+ /**
51
+ * Shared machinery behind {@link DurabilityScheduler}: storage, the physical
52
+ * alarm, the concurrency pool, and the attempt lifecycle. Package-internal.
53
+ */
54
+ export class Engine {
55
+ constructor(context, options) {
56
+ this.participants = [];
57
+ this.permitWaiters = [];
58
+ this.transactionReconciliations = new WeakMap();
59
+ this.context = context;
60
+ this.backend = storageBackendSchema.parse(options.storageBackend ?? 'sqlite');
61
+ this.storage =
62
+ this.backend === 'kv'
63
+ ? createKvDurabilityStorage(context.storage)
64
+ : createSqliteDurabilityStorage(context.storage);
65
+ this.alarmConcurrency = options.alarmConcurrency ?? 10;
66
+ this.alarmMinDelayMs = options.alarmMinDelayMs ?? 15000;
67
+ this.alarmHandoffMs = options.alarmHandoffMs ?? 14 * 60000;
68
+ assertPositiveInteger('alarmConcurrency', this.alarmConcurrency);
69
+ assertPositiveInteger('alarmMinDelayMs', this.alarmMinDelayMs);
70
+ if (this.alarmMinDelayMs < minAlarmDelayMs ||
71
+ this.alarmMinDelayMs > maxAlarmDelayMs) {
72
+ throw new RangeError(`alarmMinDelayMs must be between ${minAlarmDelayMs} and ${maxAlarmDelayMs}`);
73
+ }
74
+ assertPositiveInteger('alarmHandoffMs', this.alarmHandoffMs);
75
+ this.availablePermits = this.alarmConcurrency;
76
+ }
77
+ register(participant) {
78
+ if (this.participants.some(({ kind }) => kind === participant.kind)) {
79
+ throw new Error(`A ${participant.kind} helper is already attached to this scheduler`);
80
+ }
81
+ this.participants.push(participant);
82
+ }
83
+ waitUntil(promise, onError) {
84
+ if (!this.context.waitUntil) {
85
+ return;
86
+ }
87
+ try {
88
+ this.context.waitUntil(promise);
89
+ }
90
+ catch (error) {
91
+ onError(error);
92
+ }
93
+ }
94
+ emitter(hook) {
95
+ return createEmitter(hook, (promise) => this.context.waitUntil?.(promise));
96
+ }
97
+ /** Applies a helper's SQLite migrations; KV storage has no schema. */
98
+ migrateSchema(capability, migrations) {
99
+ if (this.backend === 'sqlite') {
100
+ migrate(this.context.storage, capability, migrations, undefined);
101
+ }
102
+ }
103
+ /** Runs a storage transaction and publishes its timer state only after commit. */
104
+ async transaction(callback) {
105
+ let reconciliation;
106
+ const result = await this.storage.transaction(async (transaction) => {
107
+ reconciliation = { nextPendingAt: undefined, reconciled: false };
108
+ this.transactionReconciliations.set(transaction, reconciliation);
109
+ try {
110
+ return await callback(transaction);
111
+ }
112
+ finally {
113
+ this.transactionReconciliations.delete(transaction);
114
+ }
115
+ });
116
+ if (reconciliation?.reconciled) {
117
+ this.scheduleEarlyAlarm(reconciliation.nextPendingAt);
118
+ }
119
+ return result;
120
+ }
121
+ async reconcile(transaction) {
122
+ const reconciliation = this.transactionReconciliations.get(transaction);
123
+ if (!reconciliation) {
124
+ throw new Error('Scheduler reconciliation requires an Engine transaction');
125
+ }
126
+ reconciliation.nextPendingAt = await reconcilePhysicalAlarm(transaction, this.participants.map(({ kind }) => kind), this.alarmMinDelayMs);
127
+ reconciliation.reconciled = true;
128
+ }
129
+ scheduleEarlyAlarm(timestamp) {
130
+ if (this.earlyAlarm?.timestamp === timestamp) {
131
+ return;
132
+ }
133
+ if (this.earlyAlarm) {
134
+ clearTimeout(this.earlyAlarm.timer);
135
+ this.earlyAlarm = undefined;
136
+ }
137
+ if (timestamp === undefined ||
138
+ timestamp >= Date.now() + this.alarmMinDelayMs) {
139
+ return;
140
+ }
141
+ const timer = setTimeout(() => {
142
+ if (this.earlyAlarm?.timer !== timer) {
143
+ return;
144
+ }
145
+ this.earlyAlarm = undefined;
146
+ const onError = (error) => reportFailure('durability.background_execution.failed', { scheduledTime: timestamp }, error);
147
+ const execution = this.alarm().catch(onError);
148
+ this.waitUntil(execution, onError);
149
+ }, Math.max(timestamp - Date.now(), 0));
150
+ this.earlyAlarm = { timestamp, timer };
151
+ }
152
+ /** Coalesces concurrent refresh requests into one reconciliation transaction. */
153
+ scheduleNextAlarm() {
154
+ if (this.alarmRefresh) {
155
+ return this.alarmRefresh;
156
+ }
157
+ this.alarmRefresh = this.transaction((transaction) => this.reconcile(transaction)).finally(() => {
158
+ this.alarmRefresh = undefined;
159
+ });
160
+ return this.alarmRefresh;
161
+ }
162
+ /**
163
+ * Aborts matching active handlers, then deletes one kind's records created
164
+ * before the timestamp, reconciling the alarm after each committed batch.
165
+ */
166
+ async purge(kind, before, active, abortReason) {
167
+ if (!Number.isSafeInteger(before) || before < 0) {
168
+ throw new RangeError('timestamp must be a non-negative safe integer');
169
+ }
170
+ for (const running of active.values()) {
171
+ if (running.createdAt < before) {
172
+ running.controller?.abort(new Error(abortReason));
173
+ }
174
+ }
175
+ let total = 0;
176
+ let removed = 0;
177
+ do {
178
+ // eslint-disable-next-line no-await-in-loop
179
+ removed = await this.transaction(async (transaction) => {
180
+ const count = await transaction[kind].deleteCreatedBefore(before);
181
+ await this.reconcile(transaction);
182
+ return count;
183
+ });
184
+ total += removed;
185
+ } while (removed > 0);
186
+ return total;
187
+ }
188
+ tryAcquirePermit() {
189
+ if (this.availablePermits === 0) {
190
+ return undefined;
191
+ }
192
+ this.availablePermits -= 1;
193
+ return this.createRelease();
194
+ }
195
+ acquirePermit() {
196
+ const release = this.tryAcquirePermit();
197
+ if (release) {
198
+ return Promise.resolve(release);
199
+ }
200
+ return new Promise((resolve) => {
201
+ this.permitWaiters.push(resolve);
202
+ });
203
+ }
204
+ createRelease() {
205
+ let released = false;
206
+ return () => {
207
+ if (released) {
208
+ return;
209
+ }
210
+ released = true;
211
+ const waiter = this.permitWaiters.shift();
212
+ if (waiter) {
213
+ waiter(this.createRelease());
214
+ }
215
+ else {
216
+ this.availablePermits += 1;
217
+ }
218
+ };
219
+ }
220
+ async runConcurrent(items, worker) {
221
+ let nextIndex = 0;
222
+ await Promise.all(Array.from({ length: Math.min(this.alarmConcurrency, items.length) }, async () => {
223
+ while (nextIndex < items.length) {
224
+ const item = items[nextIndex++];
225
+ if (item !== undefined) {
226
+ // eslint-disable-next-line no-await-in-loop
227
+ await worker(item);
228
+ }
229
+ }
230
+ }));
231
+ }
232
+ /**
233
+ * Runs every participant's due work, hands off to a fresh alarm if the
234
+ * invocation approaches its wall-time limit, and re-arms the physical alarm.
235
+ */
236
+ async alarm(info) {
237
+ const startedAt = Date.now();
238
+ const execution = Promise.all(this.participants.map((participant) => participant.runDue(startedAt, info))).then(() => undefined);
239
+ void execution.catch(() => undefined);
240
+ const handoff = Symbol('alarm handoff');
241
+ const remaining = this.alarmHandoffMs - (Date.now() - startedAt);
242
+ let timeout;
243
+ let result;
244
+ try {
245
+ result = await Promise.race([
246
+ execution,
247
+ new Promise((resolve) => {
248
+ timeout = setTimeout(() => resolve(handoff), Math.max(remaining, 0));
249
+ }),
250
+ ]);
251
+ }
252
+ finally {
253
+ if (timeout !== undefined) {
254
+ clearTimeout(timeout);
255
+ }
256
+ }
257
+ if (result === handoff) {
258
+ await this.armForHandoff(Date.now());
259
+ return;
260
+ }
261
+ await this.scheduleNextAlarm();
262
+ }
263
+ armForHandoff(timestamp) {
264
+ return this.storage.transaction(async ({ physicalAlarm }) => {
265
+ const currentAlarm = await physicalAlarm.getAlarm();
266
+ const target = Math.max(timestamp, Date.now() + this.alarmMinDelayMs);
267
+ if (currentAlarm === null || currentAlarm > target) {
268
+ await physicalAlarm.setAlarm(target);
269
+ }
270
+ });
271
+ }
272
+ /**
273
+ * Registers the execution in its active map synchronously, then claims and
274
+ * runs one attempt in the background. The returned promise settles when the
275
+ * attempt's outcome has been persisted, not when a timed-out handler settles.
276
+ */
277
+ startExecution(spec, eagerPermit) {
278
+ const { key, row, policy } = spec;
279
+ let settleActive;
280
+ const settled = new Promise((resolve) => {
281
+ settleActive = resolve;
282
+ });
283
+ const activeExecution = {
284
+ generation: row.generation_id,
285
+ createdAt: row.created_at,
286
+ settled,
287
+ };
288
+ spec.active.set(key, activeExecution);
289
+ let releasePermit = eagerPermit;
290
+ let handlerStarted = false;
291
+ let handlerSettled = false;
292
+ let policySettled = false;
293
+ const releaseIfSettled = () => {
294
+ if (policySettled && (!handlerStarted || handlerSettled)) {
295
+ releasePermit?.();
296
+ settleActive();
297
+ }
298
+ };
299
+ const execution = (async () => {
300
+ releasePermit ?? (releasePermit = await this.acquirePermit());
301
+ const attempt = await this.storage[spec.kind].claimAttempt(key, row.generation_id, policy.maxAttempts);
302
+ if (attempt === undefined) {
303
+ await this.failExhausted(spec);
304
+ return;
305
+ }
306
+ const startedAt = Date.now();
307
+ spec.emit({
308
+ ...spec.entity,
309
+ type: 'attempt_started',
310
+ timestamp: startedAt,
311
+ attempt,
312
+ });
313
+ const controller = new AbortController();
314
+ activeExecution.controller = controller;
315
+ let timeout;
316
+ try {
317
+ handlerStarted = true;
318
+ const handlerResult = Promise.resolve().then(() => spec.invoke(attempt, controller.signal));
319
+ void handlerResult
320
+ .finally(() => {
321
+ handlerSettled = true;
322
+ releaseIfSettled();
323
+ })
324
+ .catch(() => undefined);
325
+ const timeoutResult = new Promise((_resolve, reject) => {
326
+ timeout = setTimeout(() => {
327
+ const error = spec.timeoutError();
328
+ controller.abort(error);
329
+ reject(error);
330
+ }, policy.attemptTimeoutMs);
331
+ });
332
+ const result = await Promise.race([handlerResult, timeoutResult]);
333
+ const timestamp = await spec.complete(result, attempt);
334
+ if (timestamp !== undefined) {
335
+ spec.emit({
336
+ ...spec.entity,
337
+ type: 'attempt_settled',
338
+ timestamp,
339
+ attempt,
340
+ durationMs: Math.max(0, timestamp - startedAt),
341
+ outcome: 'completed',
342
+ });
343
+ }
344
+ }
345
+ catch (caught) {
346
+ await this.settleFailure(spec, attempt, startedAt, caught);
347
+ }
348
+ finally {
349
+ if (timeout !== undefined) {
350
+ clearTimeout(timeout);
351
+ }
352
+ }
353
+ })().finally(() => {
354
+ policySettled = true;
355
+ releaseIfSettled();
356
+ });
357
+ void settled.finally(() => {
358
+ if (spec.active.get(key) === activeExecution) {
359
+ spec.active.delete(key);
360
+ }
361
+ });
362
+ return execution;
363
+ }
364
+ async failExhausted(spec) {
365
+ const { key, row, policy } = spec;
366
+ const current = await this.storage[spec.kind].get(key);
367
+ if (current?.generation_id !== row.generation_id ||
368
+ current.status !== 'pending' ||
369
+ current.attempt < policy.maxAttempts) {
370
+ return;
371
+ }
372
+ const exhausted = serializeError(spec.exhaustedError());
373
+ let updated = false;
374
+ await this.transaction(async (transaction) => {
375
+ updated = await transaction[spec.kind].exhaust(key, row.generation_id, policy.maxAttempts, {
376
+ status: 'failed',
377
+ last_error: exhausted.message,
378
+ last_error_name: exhausted.name,
379
+ });
380
+ await this.reconcile(transaction);
381
+ });
382
+ if (updated) {
383
+ spec.emit({
384
+ ...spec.entity,
385
+ type: 'terminal',
386
+ timestamp: Date.now(),
387
+ attempt: current.attempt,
388
+ reason: 'attempts_exhausted',
389
+ error: exhausted,
390
+ });
391
+ }
392
+ }
393
+ async settleFailure(spec, attempt, startedAt, caught) {
394
+ const { key, row } = spec;
395
+ const decision = decideRetry(spec, attempt, caught);
396
+ const serializedError = serializeError(decision.error);
397
+ let updated = false;
398
+ await this.transaction(async (transaction) => {
399
+ updated = await transaction[spec.kind].settle(key, row.generation_id, attempt, {
400
+ status: decision.terminal ? 'failed' : 'pending',
401
+ next_attempt_at: decision.nextAttemptAt,
402
+ last_error: serializedError.message,
403
+ last_error_name: serializedError.name,
404
+ });
405
+ await this.reconcile(transaction);
406
+ });
407
+ if (!updated) {
408
+ return;
409
+ }
410
+ const settled = {
411
+ ...spec.entity,
412
+ type: 'attempt_settled',
413
+ timestamp: decision.timestamp,
414
+ attempt,
415
+ durationMs: Math.max(0, decision.timestamp - startedAt),
416
+ error: serializedError,
417
+ };
418
+ spec.emit(decision.terminal
419
+ ? { ...settled, outcome: 'failed' }
420
+ : {
421
+ ...settled,
422
+ outcome: 'retry_scheduled',
423
+ nextAttemptAt: decision.nextAttemptAt,
424
+ });
425
+ }
426
+ }
427
+ const engines = new WeakMap();
428
+ /**
429
+ * Owns the Durable Object's physical alarm, storage backend, and concurrency
430
+ * pool so {@link Durability} and {@link DurabilityAlarms} can share them.
431
+ *
432
+ * Construct one per Durable Object when using both helpers, pass it to each,
433
+ * and delegate the object's `alarm` method to {@link DurabilityScheduler.alarm}.
434
+ * A helper constructed directly from the Durable Object context creates a
435
+ * private scheduler instead.
436
+ *
437
+ * @example
438
+ * ```ts
439
+ * class Jobs extends DurableObject<Env> {
440
+ * private readonly scheduler = new DurabilityScheduler({ context: this.ctx });
441
+ * private readonly durability = new Durability({
442
+ * scheduler: this.scheduler,
443
+ * handlers,
444
+ * });
445
+ * private readonly alarms = new DurabilityAlarms({
446
+ * scheduler: this.scheduler,
447
+ * handlers: alarmHandlers,
448
+ * });
449
+ *
450
+ * alarm(info?: AlarmInvocationInfo) {
451
+ * return this.scheduler.alarm(info);
452
+ * }
453
+ * }
454
+ * ```
455
+ */
456
+ export class DurabilityScheduler {
457
+ constructor(config) {
458
+ engines.set(this, new Engine(config.context, config));
459
+ }
460
+ /** Runs due work for every attached helper and re-arms the physical alarm. */
461
+ alarm(info) {
462
+ return engineFor({ scheduler: this }).alarm(info);
463
+ }
464
+ }
465
+ /**
466
+ * Resolves the engine a helper should attach to: the shared one behind a
467
+ * scheduler, or a private one built from the Durable Object context.
468
+ */
469
+ export const engineFor = (attachment) => {
470
+ if (attachment.scheduler === undefined) {
471
+ return new Engine(attachment.context, attachment);
472
+ }
473
+ const engine = engines.get(attachment.scheduler);
474
+ if (!engine) {
475
+ throw new Error('Unknown DurabilityScheduler instance');
476
+ }
477
+ return engine;
478
+ };
@@ -0,0 +1,2 @@
1
+ export declare const serialize: (value: unknown) => string;
2
+ export declare const deserialize: (value: string) => unknown;