durability 5.0.0 → 5.2.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.
Files changed (89) hide show
  1. package/README.md +238 -7
  2. package/dist/{durability-alarms.d.ts → alarms/index.d.ts} +23 -6
  3. package/dist/{durability-alarms.js → alarms/index.js} +96 -52
  4. package/dist/alarms/migrations.d.ts +9 -0
  5. package/dist/alarms/migrations.js +133 -0
  6. package/dist/errors.d.ts +15 -0
  7. package/dist/errors.js +24 -0
  8. package/dist/experimental.d.ts +11 -8
  9. package/dist/experimental.js +8 -5
  10. package/dist/{fanout.d.ts → fanout/index.d.ts} +13 -6
  11. package/dist/{fanout.js → fanout/index.js} +55 -49
  12. package/dist/fanout/migrations.d.ts +9 -0
  13. package/dist/fanout/migrations.js +181 -0
  14. package/dist/{stored-message.d.ts → fanout/stored-message.d.ts} +1 -1
  15. package/dist/index.d.ts +14 -9
  16. package/dist/index.js +13 -8
  17. package/dist/{log.d.ts → log/index.d.ts} +15 -3
  18. package/dist/{log.js → log/index.js} +152 -124
  19. package/dist/log/migrations.d.ts +18 -0
  20. package/dist/log/migrations.js +297 -0
  21. package/dist/{memoize.d.ts → memoize/index.d.ts} +1 -1
  22. package/dist/{memoize.js → memoize/index.js} +14 -11
  23. package/dist/memoize/migrations.d.ts +10 -0
  24. package/dist/memoize/migrations.js +21 -0
  25. package/dist/migrations.d.ts +1 -103
  26. package/dist/migrations.js +1 -570
  27. package/dist/{durability.d.ts → operations/index.d.ts} +13 -5
  28. package/dist/{durability.js → operations/index.js} +63 -46
  29. package/dist/operations/migrations.d.ts +10 -0
  30. package/dist/operations/migrations.js +150 -0
  31. package/dist/{outbox.d.ts → outbox/index.d.ts} +4 -4
  32. package/dist/{outbox.js → outbox/index.js} +18 -63
  33. package/dist/outbox/migrations.d.ts +9 -0
  34. package/dist/outbox/migrations.js +43 -0
  35. package/dist/{routing-client.js → routing/client.js} +1 -1
  36. package/dist/{routing.d.ts → routing/index.d.ts} +3 -3
  37. package/dist/{routing.js → routing/index.js} +3 -3
  38. package/dist/{load.d.ts → routing/load.d.ts} +1 -1
  39. package/dist/schedule/index.d.ts +165 -0
  40. package/dist/schedule/index.js +667 -0
  41. package/dist/schedule/migrations.d.ts +9 -0
  42. package/dist/schedule/migrations.js +118 -0
  43. package/dist/{scheduler.d.ts → scheduler/index.d.ts} +122 -22
  44. package/dist/scheduler/index.js +925 -0
  45. package/dist/{semaphore-client.d.ts → semaphore/client.d.ts} +1 -1
  46. package/dist/{semaphore-client.js → semaphore/client.js} +2 -2
  47. package/dist/{semaphore.d.ts → semaphore/index.d.ts} +10 -10
  48. package/dist/{semaphore.js → semaphore/index.js} +7 -7
  49. package/dist/{semaphore-leases.d.ts → semaphore/leases.d.ts} +17 -6
  50. package/dist/{semaphore-leases.js → semaphore/leases.js} +28 -12
  51. package/dist/semaphore/migrations.d.ts +18 -0
  52. package/dist/semaphore/migrations.js +444 -0
  53. package/dist/{semaphore-protocol.d.ts → semaphore/protocol.d.ts} +16 -8
  54. package/dist/{semaphore-protocol.js → semaphore/protocol.js} +37 -14
  55. package/dist/{semaphore-queue-store.d.ts → semaphore/queue-store.d.ts} +12 -6
  56. package/dist/{semaphore-queue-store.js → semaphore/queue-store.js} +87 -75
  57. package/dist/{semaphore-queue.d.ts → semaphore/queue.d.ts} +15 -5
  58. package/dist/{semaphore-queue.js → semaphore/queue.js} +105 -46
  59. package/dist/{semaphore-server.d.ts → semaphore/server.d.ts} +12 -4
  60. package/dist/{semaphore-server.js → semaphore/server.js} +51 -24
  61. package/dist/{semaphore-store.d.ts → semaphore/store.d.ts} +8 -3
  62. package/dist/{semaphore-store.js → semaphore/store.js} +35 -33
  63. package/dist/{client.d.ts → socket/client.d.ts} +3 -3
  64. package/dist/{client.js → socket/client.js} +4 -4
  65. package/dist/{socket.d.ts → socket/index.d.ts} +15 -4
  66. package/dist/{socket.js → socket/index.js} +66 -20
  67. package/dist/socket/migrations.d.ts +9 -0
  68. package/dist/socket/migrations.js +57 -0
  69. package/dist/{socket-protocol.d.ts → socket/protocol.d.ts} +1 -1
  70. package/dist/storage.d.ts +9 -2
  71. package/dist/storage.js +24 -11
  72. package/dist/{topology-client.d.ts → topology/client.d.ts} +2 -2
  73. package/dist/{topology-client.js → topology/client.js} +3 -3
  74. package/dist/{topology.d.ts → topology/index.d.ts} +17 -7
  75. package/dist/{topology.js → topology/index.js} +92 -58
  76. package/dist/topology/migrations.d.ts +10 -0
  77. package/dist/topology/migrations.js +138 -0
  78. package/dist/{tracker.d.ts → tracker/index.d.ts} +3 -3
  79. package/dist/{tracker.js → tracker/index.js} +2 -2
  80. package/package.json +11 -11
  81. package/dist/scheduler.js +0 -577
  82. /package/dist/{stored-message.js → fanout/stored-message.js} +0 -0
  83. /package/dist/{routing-client.d.ts → routing/client.d.ts} +0 -0
  84. /package/dist/{load.js → routing/load.js} +0 -0
  85. /package/dist/{socket-protocol.js → socket/protocol.js} +0 -0
  86. /package/dist/{topology-snapshot.d.ts → topology/snapshot.d.ts} +0 -0
  87. /package/dist/{topology-snapshot.js → topology/snapshot.js} +0 -0
  88. /package/dist/{tracked-source.d.ts → tracker/source.d.ts} +0 -0
  89. /package/dist/{tracked-source.js → tracker/source.js} +0 -0
package/dist/scheduler.js DELETED
@@ -1,577 +0,0 @@
1
- import { z } from 'zod';
2
- import { trace, traceMethods, traceStorage } from './dev.js';
3
- import { DurableRetryPolicyError, isErrorInstance, isNonRetryable, reportFailure, serializeError, } from './errors.js';
4
- import { createEmitter, } from './lifecycle.js';
5
- import { isSchemaCurrent, migrateCapability, } from './migrations.js';
6
- import { assertPositiveInteger } from './policy.js';
7
- import { deleteMemos, deleteStaleMemos } from './memoize.js';
8
- import { claimAttempt, exhaustAttempts, updateAttempt, } from './storage.js';
9
- const minAlarmDelayMs = 1000;
10
- const maxAlarmDelayMs = 15000;
11
- const nextAttemptRowSchema = z.object({
12
- next_attempt_at: z.number().int().nonnegative(),
13
- });
14
- const countRowSchema = z.object({ count: z.number().int().nonnegative() });
15
- const decideRetry = (spec, attempt, error) => {
16
- const terminal = isNonRetryable(error) ||
17
- attempt >= spec.policy.maxAttempts ||
18
- spec.isTerminal(error);
19
- if (terminal) {
20
- const timestamp = Date.now();
21
- return { error, terminal, timestamp, nextAttemptAt: timestamp };
22
- }
23
- try {
24
- const rawDelay = spec.policy.delay(attempt);
25
- if (!Number.isFinite(rawDelay) || rawDelay < 0) {
26
- throw new DurableRetryPolicyError(spec.label);
27
- }
28
- const delay = Math.round(rawDelay);
29
- const timestamp = Date.now();
30
- if (!Number.isSafeInteger(delay) ||
31
- !Number.isSafeInteger(timestamp + delay)) {
32
- throw new DurableRetryPolicyError(spec.label);
33
- }
34
- return {
35
- error,
36
- terminal: false,
37
- timestamp,
38
- nextAttemptAt: timestamp + delay,
39
- };
40
- }
41
- catch (policyError) {
42
- const timestamp = Date.now();
43
- return {
44
- error: isErrorInstance(policyError, DurableRetryPolicyError)
45
- ? policyError
46
- : new DurableRetryPolicyError(spec.label, policyError),
47
- terminal: true,
48
- timestamp,
49
- nextAttemptAt: timestamp,
50
- };
51
- }
52
- };
53
- /**
54
- * Shared machinery behind {@link DurabilityScheduler}: transactions, the physical
55
- * alarm, the concurrency pool, and the attempt lifecycle. Package-internal.
56
- */
57
- export class Engine {
58
- constructor(context, options) {
59
- this.participants = [];
60
- this.migrated = new Set();
61
- this.permitWaiters = [];
62
- this.watchers = new Map();
63
- this.context = context;
64
- this.storage = traceStorage(context.storage);
65
- this.sql = this.storage.sql;
66
- this.alarmConcurrency = options.alarmConcurrency ?? 10;
67
- this.alarmMinDelayMs = options.alarmMinDelayMs ?? 15000;
68
- this.alarmHandoffMs = options.alarmHandoffMs ?? 14 * 60000;
69
- assertPositiveInteger('alarmConcurrency', this.alarmConcurrency);
70
- assertPositiveInteger('alarmMinDelayMs', this.alarmMinDelayMs);
71
- if (this.alarmMinDelayMs < minAlarmDelayMs ||
72
- this.alarmMinDelayMs > maxAlarmDelayMs) {
73
- throw new RangeError(`alarmMinDelayMs must be between ${minAlarmDelayMs} and ${maxAlarmDelayMs}`);
74
- }
75
- assertPositiveInteger('alarmHandoffMs', this.alarmHandoffMs);
76
- this.availablePermits = this.alarmConcurrency;
77
- }
78
- register(participant) {
79
- const { name } = participant.table;
80
- if (this.participants.some(({ table }) => table.name === name)) {
81
- throw new Error(`A ${name} helper is already attached to this scheduler`);
82
- }
83
- this.participants.push(participant);
84
- }
85
- waitUntil(promise, onError) {
86
- if (!this.context.waitUntil) {
87
- return;
88
- }
89
- try {
90
- this.context.waitUntil(promise);
91
- }
92
- catch (error) {
93
- onError(error);
94
- }
95
- }
96
- /**
97
- * The owning Durable Object's ID. The public context type omits it, but the
98
- * `DurableObjectState` applications pass at runtime carries it.
99
- */
100
- objectId() {
101
- const id = Reflect.get(this.context, 'id');
102
- return id === undefined || id === null ? undefined : String(id);
103
- }
104
- emitter(hook) {
105
- return createEmitter(hook, (promise) => this.context.waitUntil?.(promise));
106
- }
107
- /** Applies a helper's SQLite migrations. */
108
- migrateSchema(capability, migrations) {
109
- // Helpers of one kind on one scheduler share their tables; checking the
110
- // schema again for each would only add statements to every construction.
111
- if (this.migrated.has(capability)) {
112
- return;
113
- }
114
- if (!isSchemaCurrent(this.sql, capability, migrations)) {
115
- migrateCapability(this.storage, capability, migrations, undefined);
116
- }
117
- this.migrated.add(capability);
118
- }
119
- /** Runs synchronous writes atomically without touching the physical alarm. */
120
- transactionSync(write) {
121
- return this.storage.transactionSync(() => write(this.sql));
122
- }
123
- /**
124
- * Runs the writes and reconciles the physical alarm in one storage
125
- * transaction, then publishes the in-memory timer only after commit.
126
- */
127
- async transaction(write) {
128
- let nextPendingAt;
129
- const result = await this.storage.transaction(async (transaction) => {
130
- const value = write(this.sql);
131
- nextPendingAt = await this.reconcile(transaction);
132
- return value;
133
- });
134
- this.scheduleEarlyAlarm(nextPendingAt);
135
- return result;
136
- }
137
- /** Returns the earliest pending time and maintains its bounded physical fallback. */
138
- async reconcile(physicalAlarm) {
139
- const scheduled = this.participants.flatMap((participant) => {
140
- if (participant.nextPendingAt) {
141
- const at = participant.nextPendingAt(this.sql);
142
- return at === undefined ? [] : [at];
143
- }
144
- return nextAttemptRowSchema
145
- .array()
146
- .parse(this.sql
147
- .exec(`SELECT next_attempt_at FROM ${participant.table.name}
148
- WHERE status = 'pending'
149
- ORDER BY next_attempt_at ASC
150
- LIMIT 1`)
151
- .toArray())
152
- .map((row) => row.next_attempt_at);
153
- });
154
- const nextAlarmAt = scheduled.length === 0 ? undefined : Math.min(...scheduled);
155
- const currentAlarm = await physicalAlarm.getAlarm();
156
- if (nextAlarmAt === undefined) {
157
- if (currentAlarm !== null) {
158
- await physicalAlarm.deleteAlarm();
159
- }
160
- return undefined;
161
- }
162
- const target = Math.max(nextAlarmAt, Date.now() + this.alarmMinDelayMs);
163
- // Preserve a fallback inside this range so frequent reconciliation cannot push it later.
164
- if (currentAlarm === null ||
165
- currentAlarm < nextAlarmAt ||
166
- currentAlarm > target) {
167
- await physicalAlarm.setAlarm(target);
168
- }
169
- return nextAlarmAt;
170
- }
171
- scheduleEarlyAlarm(timestamp) {
172
- if (this.earlyAlarm?.timestamp === timestamp) {
173
- return;
174
- }
175
- if (this.earlyAlarm) {
176
- clearTimeout(this.earlyAlarm.timer);
177
- this.earlyAlarm = undefined;
178
- }
179
- if (timestamp === undefined ||
180
- timestamp >= Date.now() + this.alarmMinDelayMs) {
181
- return;
182
- }
183
- const timer = setTimeout(() => {
184
- if (this.earlyAlarm?.timer !== timer) {
185
- return;
186
- }
187
- this.earlyAlarm = undefined;
188
- trace('scheduler.early_alarm', { scheduledTime: timestamp });
189
- const onError = (error) => reportFailure('durability.background_execution.failed', { scheduledTime: timestamp }, error);
190
- const execution = this.alarm().catch(onError);
191
- this.waitUntil(execution, onError);
192
- }, Math.max(timestamp - Date.now(), 0));
193
- this.earlyAlarm = { timestamp, timer };
194
- }
195
- /** Coalesces concurrent refresh requests into one reconciliation transaction. */
196
- scheduleNextAlarm() {
197
- if (this.alarmRefresh) {
198
- return this.alarmRefresh;
199
- }
200
- this.alarmRefresh = this.transaction(() => undefined).finally(() => {
201
- this.alarmRefresh = undefined;
202
- });
203
- return this.alarmRefresh;
204
- }
205
- /**
206
- * Aborts matching active handlers, then deletes one kind's records created
207
- * before the timestamp and reconciles the alarm in the same transaction.
208
- */
209
- async purge(table, before, active, abortReason) {
210
- if (!Number.isSafeInteger(before) || before < 0) {
211
- throw new RangeError('timestamp must be a non-negative safe integer');
212
- }
213
- for (const running of active.values()) {
214
- if (running.createdAt < before) {
215
- running.controller?.abort(new Error(abortReason));
216
- }
217
- }
218
- const removed = await this.transaction((sql) => {
219
- const { count } = countRowSchema.parse(sql
220
- .exec(`SELECT COUNT(*) AS count FROM ${table.name} WHERE created_at < ?`, before)
221
- .toArray()[0]);
222
- sql.exec(`DELETE FROM ${table.name} WHERE created_at < ?`, before);
223
- deleteStaleMemos(sql, table);
224
- return count;
225
- });
226
- if (removed > 0) {
227
- for (const key of this.watchers.get(table.name)?.keys() ?? []) {
228
- this.notify(table, key);
229
- }
230
- }
231
- return removed;
232
- }
233
- /** In-memory only: listeners never survive eviction. */
234
- watch(table, key, listener) {
235
- const byKey = this.watchers.get(table.name) ??
236
- new Map();
237
- this.watchers.set(table.name, byKey);
238
- const listeners = byKey.get(key) ?? new Set();
239
- byKey.set(key, listeners);
240
- listeners.add(listener);
241
- return () => {
242
- listeners.delete(listener);
243
- if (listeners.size === 0 && byKey.get(key) === listeners) {
244
- byKey.delete(key);
245
- }
246
- };
247
- }
248
- /** Call only after the change has committed. */
249
- notify(table, key, completed) {
250
- for (const listener of this.watchers.get(table.name)?.get(key) ?? []) {
251
- listener(completed);
252
- }
253
- }
254
- tryAcquirePermit() {
255
- if (this.availablePermits === 0) {
256
- return undefined;
257
- }
258
- this.availablePermits -= 1;
259
- return this.createRelease();
260
- }
261
- acquirePermit() {
262
- const release = this.tryAcquirePermit();
263
- if (release) {
264
- return Promise.resolve(release);
265
- }
266
- return new Promise((resolve) => {
267
- this.permitWaiters.push(resolve);
268
- });
269
- }
270
- createRelease() {
271
- let released = false;
272
- return () => {
273
- if (released) {
274
- return;
275
- }
276
- released = true;
277
- const waiter = this.permitWaiters.shift();
278
- if (waiter) {
279
- waiter(this.createRelease());
280
- }
281
- else {
282
- this.availablePermits += 1;
283
- }
284
- };
285
- }
286
- async runConcurrent(items, worker) {
287
- let nextIndex = 0;
288
- await Promise.all(Array.from({ length: Math.min(this.alarmConcurrency, items.length) }, async () => {
289
- while (nextIndex < items.length) {
290
- const item = items[nextIndex++];
291
- if (item !== undefined) {
292
- // eslint-disable-next-line no-await-in-loop
293
- await worker(item);
294
- }
295
- }
296
- }));
297
- }
298
- /**
299
- * Runs due work and re-arms the physical alarm. A failure that would
300
- * otherwise propagate to the platform is turned into a retry of our own,
301
- * because the platform drops an alarm after a few failed deliveries.
302
- */
303
- async alarm(info) {
304
- try {
305
- await this.runAlarm(info);
306
- }
307
- catch (error) {
308
- // Throwing lets the platform retry, but it gives up after a few failures
309
- // and drops the alarm, stranding pending work. Keeping our own alarm
310
- // armed turns the failure into a retry we control instead.
311
- if (!(await this.armFallbackAlarm())) {
312
- throw error;
313
- }
314
- reportFailure('durability.alarm.failed', { retryInMs: this.alarmMinDelayMs }, error);
315
- }
316
- }
317
- /**
318
- * Runs every participant's due work, hands off to a fresh alarm if the
319
- * invocation approaches its wall-time limit, and re-arms the physical alarm.
320
- */
321
- async runAlarm(info) {
322
- const startedAt = Date.now();
323
- const execution = Promise.all(this.participants.map((participant) => participant.runDue(startedAt, info))).then(() => undefined);
324
- void execution.catch(() => undefined);
325
- const handoff = Symbol('alarm handoff');
326
- const remaining = this.alarmHandoffMs - (Date.now() - startedAt);
327
- let timeout;
328
- let result;
329
- try {
330
- result = await Promise.race([
331
- execution,
332
- new Promise((resolve) => {
333
- timeout = setTimeout(() => resolve(handoff), Math.max(remaining, 0));
334
- }),
335
- ]);
336
- }
337
- finally {
338
- if (timeout !== undefined) {
339
- clearTimeout(timeout);
340
- }
341
- }
342
- if (result === handoff) {
343
- await this.armForHandoff(Date.now());
344
- return;
345
- }
346
- await this.scheduleNextAlarm();
347
- }
348
- /** Arms the physical alarm directly, outside any transaction; the next run reconciles properly. */
349
- async armFallbackAlarm() {
350
- try {
351
- await this.storage.setAlarm(Date.now() + this.alarmMinDelayMs);
352
- return true;
353
- }
354
- catch {
355
- return false;
356
- }
357
- }
358
- armForHandoff(timestamp) {
359
- return this.storage.transaction(async (physicalAlarm) => {
360
- const currentAlarm = await physicalAlarm.getAlarm();
361
- const target = Math.max(timestamp, Date.now() + this.alarmMinDelayMs);
362
- if (currentAlarm === null || currentAlarm > target) {
363
- await physicalAlarm.setAlarm(target);
364
- }
365
- });
366
- }
367
- /**
368
- * Registers the execution in its active map synchronously, then claims and
369
- * runs one attempt in the background. The returned promise settles when the
370
- * attempt's outcome has been persisted, not when a timed-out handler settles.
371
- */
372
- startExecution(spec, eagerPermit) {
373
- const { key, row, policy } = spec;
374
- let settleActive;
375
- const settled = new Promise((resolve) => {
376
- settleActive = resolve;
377
- });
378
- const activeExecution = {
379
- generation: row.generation_id,
380
- createdAt: row.created_at,
381
- settled,
382
- };
383
- spec.active.set(key, activeExecution);
384
- let releasePermit = eagerPermit;
385
- let handlerStarted = false;
386
- let handlerSettled = false;
387
- let policySettled = false;
388
- const releaseIfSettled = () => {
389
- if (policySettled && (!handlerStarted || handlerSettled)) {
390
- releasePermit?.();
391
- settleActive();
392
- }
393
- };
394
- const execution = (async () => {
395
- releasePermit ?? (releasePermit = await this.acquirePermit());
396
- const attempt = claimAttempt(this.sql, spec.table, key, row.generation_id, policy.maxAttempts);
397
- if (attempt === undefined) {
398
- await this.failExhausted(spec);
399
- return;
400
- }
401
- const startedAt = Date.now();
402
- spec.emit({
403
- ...spec.entity,
404
- type: 'attempt_started',
405
- timestamp: startedAt,
406
- attempt,
407
- });
408
- const controller = new AbortController();
409
- activeExecution.controller = controller;
410
- let timeout;
411
- try {
412
- handlerStarted = true;
413
- const handlerResult = Promise.resolve().then(() => spec.invoke(attempt, controller.signal));
414
- void handlerResult
415
- .finally(() => {
416
- handlerSettled = true;
417
- releaseIfSettled();
418
- })
419
- .catch(() => undefined);
420
- const timeoutResult = new Promise((_resolve, reject) => {
421
- timeout = setTimeout(() => {
422
- const error = spec.timeoutError();
423
- controller.abort(error);
424
- reject(error);
425
- }, policy.attemptTimeoutMs);
426
- });
427
- const result = await Promise.race([handlerResult, timeoutResult]);
428
- // One transaction: a failed memo cleanup must undo the completion, not orphan the memos.
429
- const timestamp = this.transactionSync((sql) => {
430
- const completedAt = spec.complete(result, attempt);
431
- if (completedAt !== undefined) {
432
- deleteMemos(sql, spec.table, key);
433
- }
434
- return completedAt;
435
- });
436
- if (timestamp !== undefined) {
437
- this.notify(spec.table, key, row);
438
- spec.emit({
439
- ...spec.entity,
440
- type: 'attempt_settled',
441
- timestamp,
442
- attempt,
443
- durationMs: Math.max(0, timestamp - startedAt),
444
- outcome: 'completed',
445
- ...(spec.includeResult ? { result } : {}),
446
- });
447
- }
448
- }
449
- catch (caught) {
450
- await this.settleFailure(spec, attempt, startedAt, caught);
451
- }
452
- finally {
453
- if (timeout !== undefined) {
454
- clearTimeout(timeout);
455
- }
456
- }
457
- })().finally(() => {
458
- policySettled = true;
459
- releaseIfSettled();
460
- });
461
- void settled.finally(() => {
462
- if (spec.active.get(key) === activeExecution) {
463
- spec.active.delete(key);
464
- }
465
- });
466
- return execution;
467
- }
468
- async failExhausted(spec) {
469
- const { key, row, policy } = spec;
470
- const exhausted = serializeError(spec.exhaustedError());
471
- const attempt = await this.transaction((sql) => {
472
- const exhaustedAttempt = exhaustAttempts(sql, spec.table, key, row.generation_id, policy.maxAttempts, exhausted);
473
- if (exhaustedAttempt !== undefined) {
474
- deleteMemos(sql, spec.table, key);
475
- }
476
- return exhaustedAttempt;
477
- });
478
- if (attempt === undefined) {
479
- return;
480
- }
481
- this.notify(spec.table, key);
482
- spec.emit({
483
- ...spec.entity,
484
- type: 'terminal',
485
- timestamp: Date.now(),
486
- attempt,
487
- reason: 'attempts_exhausted',
488
- error: exhausted,
489
- });
490
- }
491
- async settleFailure(spec, attempt, startedAt, caught) {
492
- const { key, row } = spec;
493
- const decision = decideRetry(spec, attempt, caught);
494
- const serializedError = serializeError(decision.error);
495
- const updated = await this.transaction((sql) => {
496
- const owned = updateAttempt(sql, spec.table, { key, generation: row.generation_id, attempt }, 'status = ?, next_attempt_at = ?, last_error = ?, last_error_name = ?', decision.terminal ? 'failed' : 'pending', decision.nextAttemptAt, serializedError.message, serializedError.name);
497
- if (owned && decision.terminal) {
498
- deleteMemos(sql, spec.table, key);
499
- }
500
- return owned;
501
- });
502
- if (!updated) {
503
- return;
504
- }
505
- if (decision.terminal) {
506
- this.notify(spec.table, key);
507
- }
508
- const settled = {
509
- ...spec.entity,
510
- type: 'attempt_settled',
511
- timestamp: decision.timestamp,
512
- attempt,
513
- durationMs: Math.max(0, decision.timestamp - startedAt),
514
- error: serializedError,
515
- };
516
- spec.emit(decision.terminal
517
- ? { ...settled, outcome: 'failed' }
518
- : {
519
- ...settled,
520
- outcome: 'retry_scheduled',
521
- nextAttemptAt: decision.nextAttemptAt,
522
- });
523
- }
524
- }
525
- const engines = new WeakMap();
526
- /**
527
- * Owns the Durable Object's physical alarm, storage, and concurrency
528
- * pool so {@link Durability} and {@link DurabilityAlarms} can share them.
529
- *
530
- * Construct one per Durable Object when using both helpers, pass it to each,
531
- * and delegate the object's `alarm` method to {@link DurabilityScheduler.alarm}.
532
- * A helper constructed directly from the Durable Object context creates a
533
- * private scheduler instead.
534
- *
535
- * @example
536
- * ```ts
537
- * class Jobs extends DurableObject<Env> {
538
- * private readonly scheduler = new DurabilityScheduler({ context: this.ctx });
539
- * private readonly durability = new Durability({
540
- * scheduler: this.scheduler,
541
- * handlers,
542
- * });
543
- * private readonly alarms = new DurabilityAlarms({
544
- * scheduler: this.scheduler,
545
- * handlers: alarmHandlers,
546
- * });
547
- *
548
- * alarm(info?: AlarmInvocationInfo) {
549
- * return this.scheduler.alarm(info);
550
- * }
551
- * }
552
- * ```
553
- */
554
- export class DurabilityScheduler {
555
- constructor(config) {
556
- engines.set(this, new Engine(config.context, config));
557
- }
558
- /** Runs due work for every attached helper and re-arms the physical alarm. */
559
- alarm(info) {
560
- return engineFor({ scheduler: this }).alarm(info);
561
- }
562
- }
563
- traceMethods(DurabilityScheduler.prototype, 'DurabilityScheduler');
564
- /**
565
- * Resolves the engine a helper should attach to: the shared one behind a
566
- * scheduler, or a private one built from the Durable Object context.
567
- */
568
- export const engineFor = (attachment) => {
569
- if (attachment.scheduler === undefined) {
570
- return new Engine(attachment.context, attachment);
571
- }
572
- const engine = engines.get(attachment.scheduler);
573
- if (!engine) {
574
- throw new Error('Unknown DurabilityScheduler instance');
575
- }
576
- return engine;
577
- };
File without changes
File without changes
File without changes