durability 5.0.0 → 5.1.0

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