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
@@ -0,0 +1,667 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _DurabilitySchedule_instances, _DurabilitySchedule_engine, _DurabilitySchedule_channel, _DurabilitySchedule_nextOccurrence, _DurabilitySchedule_run, _DurabilitySchedule_onOutcome, _DurabilitySchedule_maxConcurrentRuns, _DurabilitySchedule_runTimeoutMs, _DurabilitySchedule_outcomeTimeoutMs, _DurabilitySchedule_maxOutcomeAttempts, _DurabilitySchedule_delay, _DurabilitySchedule_keyPrefix, _DurabilitySchedule_keySuffix, _DurabilitySchedule_emit, _DurabilitySchedule_active, _DurabilitySchedule_delivering, _DurabilitySchedule_loop, _DurabilitySchedule_woken, _DurabilitySchedule_wakeSleeper, _DurabilitySchedule_nextPendingAt, _DurabilitySchedule_nextAfter, _DurabilitySchedule_idempotencyKey, _DurabilitySchedule_describe, _DurabilitySchedule_entity, _DurabilitySchedule_hold, _DurabilitySchedule_drive, _DurabilitySchedule_pass, _DurabilitySchedule_wake, _DurabilitySchedule_sleep, _DurabilitySchedule_nextWakeAt, _DurabilitySchedule_interruptOrphans, _DurabilitySchedule_tick, _DurabilitySchedule_startQueued, _DurabilitySchedule_reserveSlots, _DurabilitySchedule_start, _DurabilitySchedule_record, _DurabilitySchedule_deliverDue, _DurabilitySchedule_deliver, _DurabilitySchedule_deliverOnce, _DurabilitySchedule_failDelivery, _DurabilitySchedule_retryDelay;
13
+ import { z } from 'zod';
14
+ import { traceLifecycle, traceMethods } from '../dev.js';
15
+ import { reportFailure, ScheduledOutcomeTimeoutError, ScheduledRunInterruptedError, ScheduledRunTimeoutError, serializeError, } from '../errors.js';
16
+ import { durabilityScheduleMigrations } from './migrations.js';
17
+ import { migrateCapability, } from '../migrations.js';
18
+ import { assertPositiveInteger, } from '../policy.js';
19
+ import { assertChannel, defaultChannel, engineFor, } from '../scheduler/index.js';
20
+ import { exponential, jitter } from '../utils.js';
21
+ const runsTable = {
22
+ name: 'durability_schedule_runs',
23
+ key: 'scheduled_time',
24
+ };
25
+ // setTimeout overflows past 2^31 - 1 ms.
26
+ const maxDelayMs = 2 ** 31 - 1;
27
+ const fallbackRetryMs = 60000;
28
+ const scheduleRowSchema = z.object({
29
+ version: z.number().int().nonnegative(),
30
+ expression: z.string().nullable(),
31
+ next_at: z.number().int().nonnegative().nullable(),
32
+ jitter_ms: z.number().int().nonnegative(),
33
+ });
34
+ const runStateSchema = z.enum(['queued', 'running', 'complete', 'errored']);
35
+ const runRowSchema = z.object({
36
+ scheduled_time: z.number().int().nonnegative(),
37
+ due_at: z.number().int().nonnegative(),
38
+ state: runStateSchema,
39
+ next_at: z.number().int().nonnegative(),
40
+ attempt: z.number().int().nonnegative(),
41
+ error: z.string().nullable(),
42
+ });
43
+ const timeRowSchema = z.object({
44
+ scheduled_time: z.number().int().nonnegative(),
45
+ });
46
+ const dueRowSchema = z.object({
47
+ scheduled_time: z.number().int().nonnegative(),
48
+ due_at: z.number().int().nonnegative(),
49
+ });
50
+ const timedRowSchema = z.object({
51
+ scheduled_time: z.number().int().nonnegative(),
52
+ next_at: z.number().int().nonnegative(),
53
+ });
54
+ const serializedErrorSchema = z.object({
55
+ name: z.string(),
56
+ message: z.string(),
57
+ });
58
+ const readSchedule = (sql, channel) => scheduleRowSchema.optional().parse(sql
59
+ .exec(`SELECT
60
+ version,
61
+ expression,
62
+ next_at,
63
+ jitter_ms
64
+ FROM durability_schedule
65
+ WHERE channel = ? AND id = 1`, channel)
66
+ .toArray()[0]);
67
+ const writeSchedule = (sql, channel, schedule) => {
68
+ sql.exec(`INSERT INTO durability_schedule (
69
+ channel,
70
+ id,
71
+ version,
72
+ expression,
73
+ next_at,
74
+ jitter_ms
75
+ )
76
+ VALUES (?, 1, ?, ?, ?, ?)
77
+ ON CONFLICT (channel, id) DO UPDATE SET
78
+ version = excluded.version,
79
+ expression = excluded.expression,
80
+ next_at = excluded.next_at,
81
+ jitter_ms = excluded.jitter_ms`, channel, schedule.version, schedule.expression, schedule.next_at, schedule.jitter_ms);
82
+ };
83
+ const firesAt = (schedule) => schedule === undefined || schedule.next_at === null
84
+ ? undefined
85
+ : schedule.next_at + schedule.jitter_ms;
86
+ const scheduledTimes = (cursor) => timeRowSchema
87
+ .array()
88
+ .parse(cursor.toArray())
89
+ .map((row) => row.scheduled_time);
90
+ const outcomeOf = (row) => row.state === 'errored'
91
+ ? {
92
+ status: 'errored',
93
+ error: serializedErrorSchema.parse(JSON.parse(row.error ?? '{}')),
94
+ }
95
+ : { status: 'complete' };
96
+ const assertNonNegative = (name, value) => {
97
+ if (!Number.isSafeInteger(value) || value < 0) {
98
+ throw new RangeError(`${name} must be a non-negative safe integer`);
99
+ }
100
+ };
101
+ // Bounds the firing time so adding the offset to a nominal time stays safe.
102
+ const assertJitter = (name, value) => {
103
+ assertNonNegative(name, value);
104
+ if (value > maxDelayMs) {
105
+ throw new RangeError(`${name} must be at most ${maxDelayMs}`);
106
+ }
107
+ };
108
+ const pickJitter = (jitterMs = 0) => {
109
+ if (typeof jitterMs === 'number') {
110
+ assertJitter('Schedule jitterMs', jitterMs);
111
+ return jitterMs;
112
+ }
113
+ if (typeof jitterMs !== 'object' || jitterMs === null) {
114
+ throw new TypeError('Schedule jitterMs must be a number or { maxMs }');
115
+ }
116
+ assertJitter('Schedule jitterMs.maxMs', jitterMs.maxMs);
117
+ return Math.floor(Math.random() * (jitterMs.maxMs + 1));
118
+ };
119
+ const assertDelay = (name, value) => {
120
+ assertPositiveInteger(name, value);
121
+ if (value > maxDelayMs) {
122
+ throw new RangeError(`${name} must be at most ${maxDelayMs}`);
123
+ }
124
+ };
125
+ const deadline = async (work, timeoutMs, onTimeout) => {
126
+ let timer;
127
+ try {
128
+ await Promise.race([
129
+ work,
130
+ new Promise((_resolve, reject) => {
131
+ timer = setTimeout(() => reject(onTimeout()), timeoutMs);
132
+ }),
133
+ ]);
134
+ }
135
+ finally {
136
+ if (timer !== undefined) {
137
+ clearTimeout(timer);
138
+ }
139
+ }
140
+ };
141
+ /**
142
+ * Experimental. One recurring schedule per channel of a Durable Object whose
143
+ * ticks start individually tracked, overlapping runs and report each run's
144
+ * outcome once, keeping a run's row only until its outcome is delivered.
145
+ *
146
+ * A tick inserts its run in the transaction that advances the stored next
147
+ * tick, so a tick fires at most once without retaining finished runs. Missed
148
+ * ticks collapse into one run for the earliest missed time.
149
+ */
150
+ export class DurabilitySchedule {
151
+ constructor(config) {
152
+ _DurabilitySchedule_instances.add(this);
153
+ _DurabilitySchedule_engine.set(this, void 0);
154
+ _DurabilitySchedule_channel.set(this, void 0);
155
+ _DurabilitySchedule_nextOccurrence.set(this, void 0);
156
+ _DurabilitySchedule_run.set(this, void 0);
157
+ _DurabilitySchedule_onOutcome.set(this, void 0);
158
+ _DurabilitySchedule_maxConcurrentRuns.set(this, void 0);
159
+ _DurabilitySchedule_runTimeoutMs.set(this, void 0);
160
+ _DurabilitySchedule_outcomeTimeoutMs.set(this, void 0);
161
+ _DurabilitySchedule_maxOutcomeAttempts.set(this, void 0);
162
+ _DurabilitySchedule_delay.set(this, void 0);
163
+ _DurabilitySchedule_keyPrefix.set(this, void 0);
164
+ _DurabilitySchedule_keySuffix.set(this, void 0);
165
+ _DurabilitySchedule_emit.set(this, void 0);
166
+ /** Runs holding a slot: marked running and not yet settled in this instance. */
167
+ _DurabilitySchedule_active.set(this, new Set());
168
+ _DurabilitySchedule_delivering.set(this, new Set());
169
+ /** The loop that keeps an alarm invocation open while work is in flight. */
170
+ _DurabilitySchedule_loop.set(this, void 0);
171
+ _DurabilitySchedule_woken.set(this, false);
172
+ _DurabilitySchedule_wakeSleeper.set(this, void 0);
173
+ __classPrivateFieldSet(this, _DurabilitySchedule_channel, assertChannel('DurabilitySchedule', config.channel ?? defaultChannel), "f");
174
+ for (const name of ['nextOccurrence', 'run', 'onOutcome']) {
175
+ if (typeof config[name] !== 'function') {
176
+ throw new TypeError(`Schedule requires a ${name} function`);
177
+ }
178
+ }
179
+ __classPrivateFieldSet(this, _DurabilitySchedule_nextOccurrence, config.nextOccurrence, "f");
180
+ __classPrivateFieldSet(this, _DurabilitySchedule_run, config.run, "f");
181
+ __classPrivateFieldSet(this, _DurabilitySchedule_onOutcome, config.onOutcome, "f");
182
+ __classPrivateFieldSet(this, _DurabilitySchedule_maxConcurrentRuns, config.maxConcurrentRuns ?? 10, "f");
183
+ assertPositiveInteger('maxConcurrentRuns', __classPrivateFieldGet(this, _DurabilitySchedule_maxConcurrentRuns, "f"));
184
+ __classPrivateFieldSet(this, _DurabilitySchedule_runTimeoutMs, config.runTimeoutMs ?? 15 * 60000, "f");
185
+ assertDelay('runTimeoutMs', __classPrivateFieldGet(this, _DurabilitySchedule_runTimeoutMs, "f"));
186
+ __classPrivateFieldSet(this, _DurabilitySchedule_outcomeTimeoutMs, config.outcomeTimeoutMs ?? 60000, "f");
187
+ assertDelay('outcomeTimeoutMs', __classPrivateFieldGet(this, _DurabilitySchedule_outcomeTimeoutMs, "f"));
188
+ __classPrivateFieldSet(this, _DurabilitySchedule_maxOutcomeAttempts, config.outcomeRetries?.maxAttempts ?? 10, "f");
189
+ assertPositiveInteger('outcomeRetries.maxAttempts', __classPrivateFieldGet(this, _DurabilitySchedule_maxOutcomeAttempts, "f"));
190
+ __classPrivateFieldSet(this, _DurabilitySchedule_delay, config.outcomeRetries?.delay ??
191
+ ((attempt) => jitter(exponential(attempt))), "f");
192
+ __classPrivateFieldSet(this, _DurabilitySchedule_engine, engineFor(config), "f");
193
+ const objectId = __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").objectId();
194
+ __classPrivateFieldSet(this, _DurabilitySchedule_keyPrefix, objectId === undefined ? '' : `${objectId}:`, "f");
195
+ // Default keys end in a digit and named keys in a quote, so the two never
196
+ // meet, and the default channel keeps the keys it had before channels.
197
+ __classPrivateFieldSet(this, _DurabilitySchedule_keySuffix, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f") === defaultChannel
198
+ ? ''
199
+ : `:${JSON.stringify(__classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"))}`, "f");
200
+ __classPrivateFieldSet(this, _DurabilitySchedule_emit, traceLifecycle(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").emitter(config.onLifecycleEvent)), "f");
201
+ __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").migrateSchema('schedule', durabilityScheduleMigrations);
202
+ __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").registerChannel({
203
+ table: runsTable,
204
+ channelTables: ['durability_schedule'],
205
+ channel: __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"),
206
+ helper: 'DurabilitySchedule',
207
+ runDue: () => __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_hold).call(this),
208
+ nextPendingAt: (sql) => __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_nextPendingAt).call(this, sql),
209
+ holding: () => __classPrivateFieldGet(this, _DurabilitySchedule_loop, "f") !== undefined,
210
+ });
211
+ }
212
+ static migrate(context, target) {
213
+ return migrateCapability(context.storage, 'schedule', durabilityScheduleMigrations, target);
214
+ }
215
+ alarm(info) {
216
+ return __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").alarm(info);
217
+ }
218
+ /** The stored schedule, or `undefined` when none is set or it was cancelled. */
219
+ get() {
220
+ const stored = readSchedule(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"));
221
+ if (stored === undefined || stored.expression === null) {
222
+ return undefined;
223
+ }
224
+ return {
225
+ expression: stored.expression,
226
+ version: stored.version,
227
+ jitterMs: stored.jitter_ms,
228
+ nextAt: stored.next_at ?? undefined,
229
+ };
230
+ }
231
+ /**
232
+ * Stores the schedule and its next tick when `version` is higher than the
233
+ * stored one, and resolves `true` when it did. A lower version is ignored; the
234
+ * same version changes nothing, keeping its stored jitter, but re-arms the
235
+ * alarm if it was lost.
236
+ */
237
+ async set(definition) {
238
+ const { expression, version } = definition;
239
+ if (typeof expression !== 'string' || expression.length === 0) {
240
+ throw new TypeError('Schedule expression must be a non-empty string');
241
+ }
242
+ assertNonNegative('Schedule version', version);
243
+ const jitterMs = pickJitter(definition.jitterMs);
244
+ // Even a no-op transaction reconciles the physical alarm.
245
+ const applied = await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
246
+ const stored = readSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"));
247
+ if (stored !== undefined && stored.version >= version) {
248
+ return false;
249
+ }
250
+ const nextAt = __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_nextAfter).call(this, expression, Date.now());
251
+ writeSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), {
252
+ version,
253
+ expression,
254
+ next_at: nextAt ?? null,
255
+ jitter_ms: jitterMs,
256
+ });
257
+ return true;
258
+ });
259
+ __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_wake).call(this);
260
+ return applied;
261
+ }
262
+ /**
263
+ * Stops future ticks and resolves `true` when a schedule was live. Runs
264
+ * already due or running still finish and report. With `version`, the
265
+ * cancellation is ignored when the stored version is higher, and is
266
+ * otherwise recorded so a later `set` of that version or lower is ignored.
267
+ */
268
+ async cancel(version) {
269
+ if (version !== undefined) {
270
+ assertNonNegative('Schedule version', version);
271
+ }
272
+ return __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
273
+ const stored = readSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"));
274
+ const live = stored !== undefined && stored.expression !== null;
275
+ if (version === undefined && !live) {
276
+ return false;
277
+ }
278
+ if (version !== undefined &&
279
+ stored !== undefined &&
280
+ stored.version > version) {
281
+ return false;
282
+ }
283
+ writeSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), {
284
+ version: version ?? stored?.version ?? 0,
285
+ expression: null,
286
+ next_at: null,
287
+ jitter_ms: 0,
288
+ });
289
+ return live;
290
+ });
291
+ }
292
+ }
293
+ _DurabilitySchedule_engine = new WeakMap(), _DurabilitySchedule_channel = new WeakMap(), _DurabilitySchedule_nextOccurrence = new WeakMap(), _DurabilitySchedule_run = new WeakMap(), _DurabilitySchedule_onOutcome = new WeakMap(), _DurabilitySchedule_maxConcurrentRuns = new WeakMap(), _DurabilitySchedule_runTimeoutMs = new WeakMap(), _DurabilitySchedule_outcomeTimeoutMs = new WeakMap(), _DurabilitySchedule_maxOutcomeAttempts = new WeakMap(), _DurabilitySchedule_delay = new WeakMap(), _DurabilitySchedule_keyPrefix = new WeakMap(), _DurabilitySchedule_keySuffix = new WeakMap(), _DurabilitySchedule_emit = new WeakMap(), _DurabilitySchedule_active = new WeakMap(), _DurabilitySchedule_delivering = new WeakMap(), _DurabilitySchedule_loop = new WeakMap(), _DurabilitySchedule_woken = new WeakMap(), _DurabilitySchedule_wakeSleeper = new WeakMap(), _DurabilitySchedule_instances = new WeakSet(), _DurabilitySchedule_nextPendingAt = function _DurabilitySchedule_nextPendingAt(sql) {
294
+ const rows = timedRowSchema.array().parse(sql
295
+ .exec(`SELECT scheduled_time, next_at FROM durability_schedule_runs
296
+ WHERE channel = ?`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"))
297
+ .toArray());
298
+ const held = [];
299
+ const pending = [];
300
+ for (const row of rows) {
301
+ if (__classPrivateFieldGet(this, _DurabilitySchedule_active, "f").has(row.scheduled_time) ||
302
+ __classPrivateFieldGet(this, _DurabilitySchedule_delivering, "f").has(row.scheduled_time)) {
303
+ held.push(row.next_at);
304
+ }
305
+ else {
306
+ pending.push(row.next_at);
307
+ }
308
+ }
309
+ const tick = firesAt(readSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f")));
310
+ if (tick !== undefined) {
311
+ pending.push(tick);
312
+ }
313
+ if (pending.length > 0) {
314
+ return Math.min(...pending);
315
+ }
316
+ return held.length === 0 ? undefined : Math.min(...held);
317
+ }, _DurabilitySchedule_nextAfter = function _DurabilitySchedule_nextAfter(expression, after) {
318
+ const next = __classPrivateFieldGet(this, _DurabilitySchedule_nextOccurrence, "f").call(this, expression, after);
319
+ if (next === undefined) {
320
+ return undefined;
321
+ }
322
+ if (!Number.isSafeInteger(next) || next <= after) {
323
+ throw new RangeError(`nextOccurrence must return undefined or a safe integer after ${after}, got ${String(next)}`);
324
+ }
325
+ return next;
326
+ }, _DurabilitySchedule_idempotencyKey = function _DurabilitySchedule_idempotencyKey(scheduledTime) {
327
+ return `${__classPrivateFieldGet(this, _DurabilitySchedule_keyPrefix, "f")}${scheduledTime}${__classPrivateFieldGet(this, _DurabilitySchedule_keySuffix, "f")}`;
328
+ }, _DurabilitySchedule_describe = function _DurabilitySchedule_describe(row) {
329
+ return {
330
+ scheduledTime: row.scheduled_time,
331
+ dueAt: row.due_at,
332
+ idempotencyKey: __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_idempotencyKey).call(this, row.scheduled_time),
333
+ };
334
+ }, _DurabilitySchedule_entity = function _DurabilitySchedule_entity(scheduledTime) {
335
+ return {
336
+ entityKind: 'scheduled_run',
337
+ id: __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_idempotencyKey).call(this, scheduledTime),
338
+ scheduledTime,
339
+ timestamp: Date.now(),
340
+ };
341
+ }, _DurabilitySchedule_hold = function _DurabilitySchedule_hold() {
342
+ __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_wake).call(this);
343
+ if (__classPrivateFieldGet(this, _DurabilitySchedule_loop, "f")) {
344
+ return __classPrivateFieldGet(this, _DurabilitySchedule_loop, "f");
345
+ }
346
+ const loop = __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_drive).call(this).finally(() => {
347
+ if (__classPrivateFieldGet(this, _DurabilitySchedule_loop, "f") === loop) {
348
+ __classPrivateFieldSet(this, _DurabilitySchedule_loop, undefined, "f");
349
+ }
350
+ // A loop that outlived its alarm invocation republishes the in-memory
351
+ // timer it suppressed while holding.
352
+ void __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f")
353
+ .scheduleNextAlarm()
354
+ .catch((error) => reportFailure('durability.schedule.refresh_failed', {}, error));
355
+ });
356
+ __classPrivateFieldSet(this, _DurabilitySchedule_loop, loop, "f");
357
+ return loop;
358
+ }, _DurabilitySchedule_drive = async function _DurabilitySchedule_drive() {
359
+ for (;;) {
360
+ __classPrivateFieldSet(this, _DurabilitySchedule_woken, false, "f");
361
+ // eslint-disable-next-line no-await-in-loop
362
+ await __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_pass).call(this);
363
+ if (__classPrivateFieldGet(this, _DurabilitySchedule_active, "f").size === 0 && __classPrivateFieldGet(this, _DurabilitySchedule_delivering, "f").size === 0) {
364
+ return;
365
+ }
366
+ // eslint-disable-next-line no-await-in-loop
367
+ await __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_sleep).call(this, __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_nextWakeAt).call(this));
368
+ }
369
+ }, _DurabilitySchedule_pass = async function _DurabilitySchedule_pass() {
370
+ await __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_interruptOrphans).call(this);
371
+ __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_deliverDue).call(this);
372
+ try {
373
+ await __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_tick).call(this);
374
+ }
375
+ finally {
376
+ await __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_startQueued).call(this);
377
+ }
378
+ }, _DurabilitySchedule_wake = function _DurabilitySchedule_wake() {
379
+ __classPrivateFieldSet(this, _DurabilitySchedule_woken, true, "f");
380
+ __classPrivateFieldGet(this, _DurabilitySchedule_wakeSleeper, "f")?.call(this);
381
+ }, _DurabilitySchedule_sleep = async function _DurabilitySchedule_sleep(until) {
382
+ if (__classPrivateFieldGet(this, _DurabilitySchedule_woken, "f")) {
383
+ return;
384
+ }
385
+ let timer;
386
+ try {
387
+ await new Promise((resolve) => {
388
+ __classPrivateFieldSet(this, _DurabilitySchedule_wakeSleeper, resolve, "f");
389
+ if (until !== undefined) {
390
+ const delay = Math.min(Math.max(until - Date.now(), 0), maxDelayMs);
391
+ timer = setTimeout(resolve, delay);
392
+ }
393
+ });
394
+ }
395
+ finally {
396
+ if (timer !== undefined) {
397
+ clearTimeout(timer);
398
+ }
399
+ __classPrivateFieldSet(this, _DurabilitySchedule_wakeSleeper, undefined, "f");
400
+ }
401
+ }, _DurabilitySchedule_nextWakeAt = function _DurabilitySchedule_nextWakeAt() {
402
+ const sql = __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql;
403
+ const times = runRowSchema
404
+ .array()
405
+ .parse(sql
406
+ .exec(`SELECT * FROM durability_schedule_runs
407
+ WHERE channel = ? AND state IN ('complete', 'errored')`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"))
408
+ .toArray())
409
+ .filter((row) => !__classPrivateFieldGet(this, _DurabilitySchedule_delivering, "f").has(row.scheduled_time))
410
+ .map((row) => row.next_at);
411
+ const tick = firesAt(readSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f")));
412
+ if (tick !== undefined) {
413
+ times.push(tick);
414
+ }
415
+ return times.length === 0 ? undefined : Math.min(...times);
416
+ }, _DurabilitySchedule_interruptOrphans =
417
+ /**
418
+ * A row marked running that no slot in this instance holds outlived the
419
+ * instance that started it, so it is reported as errored instead of re-run.
420
+ */
421
+ async function _DurabilitySchedule_interruptOrphans() {
422
+ const orphans = (sql) => scheduledTimes(sql.exec(`SELECT scheduled_time FROM durability_schedule_runs
423
+ WHERE channel = ? AND state = 'running'`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"))).filter((time) => !__classPrivateFieldGet(this, _DurabilitySchedule_active, "f").has(time));
424
+ if (orphans(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql).length === 0) {
425
+ return;
426
+ }
427
+ const error = serializeError(new ScheduledRunInterruptedError());
428
+ const interrupted = await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
429
+ const times = orphans(sql);
430
+ const now = Date.now();
431
+ for (const time of times) {
432
+ sql.exec(`UPDATE durability_schedule_runs
433
+ SET state = 'errored', error = ?, next_at = ?, attempt = 0
434
+ WHERE channel = ? AND scheduled_time = ?`, JSON.stringify(error), now, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), time);
435
+ }
436
+ return times;
437
+ });
438
+ for (const time of interrupted) {
439
+ __classPrivateFieldGet(this, _DurabilitySchedule_emit, "f").call(this, {
440
+ ...__classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_entity).call(this, time),
441
+ type: 'settled',
442
+ outcome: 'errored',
443
+ error,
444
+ });
445
+ }
446
+ }, _DurabilitySchedule_tick = async function _DurabilitySchedule_tick() {
447
+ const dueAt = firesAt(readSchedule(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f")));
448
+ if (dueAt === undefined || dueAt > Date.now()) {
449
+ return;
450
+ }
451
+ const due = await __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_reserveSlots).call(this, (sql, free) => {
452
+ const schedule = readSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"));
453
+ const now = Date.now();
454
+ if (schedule === undefined ||
455
+ schedule.expression === null ||
456
+ schedule.next_at === null ||
457
+ schedule.next_at + schedule.jitter_ms > now) {
458
+ return { reserve: [], result: undefined };
459
+ }
460
+ const scheduledTime = schedule.next_at;
461
+ // Searching from nominal times keeps the offset from drifting; ticks
462
+ // whose firing time already passed collapse into this run.
463
+ const nextAt = __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_nextAfter).call(this, schedule.expression, Math.max(scheduledTime, now - schedule.jitter_ms));
464
+ sql.exec('UPDATE durability_schedule SET next_at = ? WHERE channel = ? AND id = 1', nextAt ?? null, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"));
465
+ const queued = free <= 0;
466
+ const [row] = dueRowSchema.array().parse(sql
467
+ .exec(`INSERT INTO durability_schedule_runs
468
+ (channel, scheduled_time, due_at, state, next_at)
469
+ VALUES (?, ?, ?, ?, ?)
470
+ ON CONFLICT DO NOTHING
471
+ RETURNING scheduled_time, due_at`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), scheduledTime, scheduledTime + schedule.jitter_ms, queued ? 'queued' : 'running', queued ? scheduledTime : now)
472
+ .toArray());
473
+ if (row === undefined) {
474
+ return { reserve: [], result: undefined };
475
+ }
476
+ return {
477
+ reserve: queued ? [] : [scheduledTime],
478
+ result: { run: __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_describe).call(this, row), queued },
479
+ };
480
+ });
481
+ if (due === undefined) {
482
+ return;
483
+ }
484
+ __classPrivateFieldGet(this, _DurabilitySchedule_emit, "f").call(this, {
485
+ ...__classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_entity).call(this, due.run.scheduledTime),
486
+ type: 'due',
487
+ queued: due.queued,
488
+ });
489
+ if (!due.queued) {
490
+ __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_start).call(this, due.run);
491
+ }
492
+ }, _DurabilitySchedule_startQueued = async function _DurabilitySchedule_startQueued() {
493
+ if (__classPrivateFieldGet(this, _DurabilitySchedule_active, "f").size >= __classPrivateFieldGet(this, _DurabilitySchedule_maxConcurrentRuns, "f")) {
494
+ return;
495
+ }
496
+ const queued = __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql
497
+ .exec(`SELECT 1 FROM durability_schedule_runs
498
+ WHERE channel = ? AND state = 'queued'
499
+ LIMIT 1`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"))
500
+ .toArray();
501
+ if (queued.length === 0) {
502
+ return;
503
+ }
504
+ const started = await __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_reserveSlots).call(this, (sql, free) => {
505
+ const rows = free <= 0
506
+ ? []
507
+ : dueRowSchema.array().parse(sql
508
+ .exec(`UPDATE durability_schedule_runs
509
+ SET state = 'running', next_at = ?
510
+ WHERE channel = ? AND scheduled_time IN (
511
+ SELECT scheduled_time FROM durability_schedule_runs
512
+ WHERE channel = ? AND state = 'queued'
513
+ ORDER BY scheduled_time
514
+ LIMIT ?
515
+ )
516
+ RETURNING scheduled_time, due_at`, Date.now(), __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), free)
517
+ .toArray());
518
+ return {
519
+ reserve: rows.map((row) => row.scheduled_time),
520
+ result: rows,
521
+ };
522
+ });
523
+ started.sort((a, b) => a.scheduled_time - b.scheduled_time);
524
+ for (const row of started) {
525
+ __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_start).call(this, __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_describe).call(this, row));
526
+ }
527
+ }, _DurabilitySchedule_reserveSlots =
528
+ /**
529
+ * Runs `mark`, which marks runs running and returns them in `reserve`, in a
530
+ * transaction that reserves their slots before it commits, so concurrent
531
+ * transactions cannot overfill the slots; a rollback releases them.
532
+ */
533
+ async function _DurabilitySchedule_reserveSlots(mark) {
534
+ let reserved = [];
535
+ try {
536
+ return await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
537
+ const { reserve, result } = mark(sql, __classPrivateFieldGet(this, _DurabilitySchedule_maxConcurrentRuns, "f") - __classPrivateFieldGet(this, _DurabilitySchedule_active, "f").size);
538
+ reserved = reserve;
539
+ for (const time of reserve) {
540
+ __classPrivateFieldGet(this, _DurabilitySchedule_active, "f").add(time);
541
+ }
542
+ return result;
543
+ });
544
+ }
545
+ catch (error) {
546
+ for (const time of reserved) {
547
+ __classPrivateFieldGet(this, _DurabilitySchedule_active, "f").delete(time);
548
+ }
549
+ throw error;
550
+ }
551
+ }, _DurabilitySchedule_start = function _DurabilitySchedule_start(run) {
552
+ const { scheduledTime } = run;
553
+ const startedAt = Date.now();
554
+ __classPrivateFieldGet(this, _DurabilitySchedule_emit, "f").call(this, { ...__classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_entity).call(this, scheduledTime), type: 'started' });
555
+ const controller = new AbortController();
556
+ const handler = Promise.resolve().then(() => __classPrivateFieldGet(this, _DurabilitySchedule_run, "f").call(this, { ...run, signal: controller.signal }));
557
+ const recorded = deadline(handler, __classPrivateFieldGet(this, _DurabilitySchedule_runTimeoutMs, "f"), () => {
558
+ const error = new ScheduledRunTimeoutError(__classPrivateFieldGet(this, _DurabilitySchedule_runTimeoutMs, "f"));
559
+ controller.abort(error);
560
+ return error;
561
+ })
562
+ .then(() => ({ status: 'complete' }), (error) => ({
563
+ status: 'errored',
564
+ error: serializeError(error),
565
+ }))
566
+ .then((outcome) => __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_record).call(this, run, outcome, startedAt))
567
+ .catch((error) => reportFailure('durability.schedule.record_failed', { scheduledTime }, error));
568
+ // The slot is held until the handler itself settles, even after a
569
+ // timeout, so maxConcurrentRuns bounds the work actually in flight.
570
+ void Promise.allSettled([handler, recorded])
571
+ .then(() => {
572
+ __classPrivateFieldGet(this, _DurabilitySchedule_active, "f").delete(scheduledTime);
573
+ __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_wake).call(this);
574
+ return __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_startQueued).call(this);
575
+ })
576
+ .catch((error) => reportFailure('durability.schedule.dispatch_failed', { scheduledTime }, error));
577
+ }, _DurabilitySchedule_record = async function _DurabilitySchedule_record(run, outcome, startedAt) {
578
+ const error = outcome.status === 'errored' ? outcome.error : undefined;
579
+ const recorded = await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => scheduledTimes(sql.exec(`UPDATE durability_schedule_runs
580
+ SET state = ?, error = ?, next_at = ?, attempt = 0
581
+ WHERE channel = ? AND scheduled_time = ? AND state = 'running'
582
+ RETURNING scheduled_time`, outcome.status, error === undefined ? null : JSON.stringify(error), Date.now(), __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), run.scheduledTime)).length > 0);
583
+ if (!recorded) {
584
+ return;
585
+ }
586
+ const entity = __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_entity).call(this, run.scheduledTime);
587
+ __classPrivateFieldGet(this, _DurabilitySchedule_emit, "f").call(this, {
588
+ ...entity,
589
+ type: 'settled',
590
+ outcome: outcome.status,
591
+ durationMs: Math.max(0, entity.timestamp - startedAt),
592
+ ...(error === undefined ? {} : { error }),
593
+ });
594
+ __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_deliver).call(this, run, outcome, 1);
595
+ }, _DurabilitySchedule_deliverDue = function _DurabilitySchedule_deliverDue() {
596
+ const due = runRowSchema.array().parse(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql
597
+ .exec(`SELECT * FROM durability_schedule_runs
598
+ WHERE channel = ? AND state IN ('complete', 'errored') AND next_at <= ?`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), Date.now())
599
+ .toArray());
600
+ for (const row of due) {
601
+ __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_deliver).call(this, __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_describe).call(this, row), outcomeOf(row), row.attempt + 1);
602
+ }
603
+ }, _DurabilitySchedule_deliver = function _DurabilitySchedule_deliver(run, outcome, attempt) {
604
+ const { scheduledTime } = run;
605
+ if (__classPrivateFieldGet(this, _DurabilitySchedule_delivering, "f").has(scheduledTime)) {
606
+ return;
607
+ }
608
+ __classPrivateFieldGet(this, _DurabilitySchedule_delivering, "f").add(scheduledTime);
609
+ void __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_deliverOnce).call(this, run, outcome, attempt)
610
+ .catch((error) => reportFailure('durability.schedule.delivery_failed', { scheduledTime }, error))
611
+ .finally(() => {
612
+ __classPrivateFieldGet(this, _DurabilitySchedule_delivering, "f").delete(scheduledTime);
613
+ __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_wake).call(this);
614
+ });
615
+ }, _DurabilitySchedule_deliverOnce = async function _DurabilitySchedule_deliverOnce(run, outcome, attempt) {
616
+ try {
617
+ await deadline(Promise.resolve().then(() => __classPrivateFieldGet(this, _DurabilitySchedule_onOutcome, "f").call(this, { ...run, attempt }, outcome)), __classPrivateFieldGet(this, _DurabilitySchedule_outcomeTimeoutMs, "f"), () => new ScheduledOutcomeTimeoutError(__classPrivateFieldGet(this, _DurabilitySchedule_outcomeTimeoutMs, "f")));
618
+ }
619
+ catch (failure) {
620
+ await __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_failDelivery).call(this, run, attempt, failure);
621
+ return;
622
+ }
623
+ await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
624
+ sql.exec(`DELETE FROM durability_schedule_runs
625
+ WHERE channel = ? AND scheduled_time = ?`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), run.scheduledTime);
626
+ });
627
+ }, _DurabilitySchedule_failDelivery = async function _DurabilitySchedule_failDelivery(run, attempt, failure) {
628
+ const error = serializeError(failure);
629
+ if (attempt >= __classPrivateFieldGet(this, _DurabilitySchedule_maxOutcomeAttempts, "f")) {
630
+ await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
631
+ sql.exec(`DELETE FROM durability_schedule_runs
632
+ WHERE channel = ? AND scheduled_time = ?`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), run.scheduledTime);
633
+ });
634
+ reportFailure('durability.schedule.outcome_dead_lettered', { scheduledTime: run.scheduledTime, attempt }, failure);
635
+ __classPrivateFieldGet(this, _DurabilitySchedule_emit, "f").call(this, {
636
+ ...__classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_entity).call(this, run.scheduledTime),
637
+ type: 'dead_lettered',
638
+ attempt,
639
+ error,
640
+ });
641
+ return;
642
+ }
643
+ const nextAttemptAt = Date.now() + __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_retryDelay).call(this, attempt);
644
+ await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
645
+ sql.exec(`UPDATE durability_schedule_runs SET attempt = ?, next_at = ?
646
+ WHERE channel = ? AND scheduled_time = ?`, attempt, nextAttemptAt, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), run.scheduledTime);
647
+ });
648
+ __classPrivateFieldGet(this, _DurabilitySchedule_emit, "f").call(this, {
649
+ ...__classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_entity).call(this, run.scheduledTime),
650
+ type: 'outcome_retry',
651
+ attempt,
652
+ error,
653
+ nextAttemptAt,
654
+ });
655
+ }, _DurabilitySchedule_retryDelay = function _DurabilitySchedule_retryDelay(attempt) {
656
+ try {
657
+ const delay = Math.round(__classPrivateFieldGet(this, _DurabilitySchedule_delay, "f").call(this, attempt));
658
+ if (Number.isSafeInteger(delay) && delay >= 0 && delay <= maxDelayMs) {
659
+ return delay;
660
+ }
661
+ }
662
+ catch (error) {
663
+ reportFailure('durability.schedule.retry_policy_failed', {}, error);
664
+ }
665
+ return fallbackRetryMs;
666
+ };
667
+ traceMethods(DurabilitySchedule.prototype, 'DurabilitySchedule');