@vite-hub/schedule 0.1.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +114 -96
  2. package/dist/console-wEhr0LWn.d.ts +330 -0
  3. package/dist/definition.d.ts +6 -2
  4. package/dist/definition.js +47 -1
  5. package/dist/due-BVMRQ93v.js +144 -0
  6. package/dist/durability.d.ts +14 -0
  7. package/dist/durability.js +23 -0
  8. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  9. package/dist/error-diagnostics-Mpeks7J0.js +166 -0
  10. package/dist/index.d.ts +59 -5
  11. package/dist/index.js +27 -2
  12. package/dist/invariant-DolT9EEx.js +22 -0
  13. package/dist/{kv-storage-Bv9ocZT-.d.ts → kv-storage-C0KZZB6v.d.ts} +2 -2
  14. package/dist/{kv-storage-DWinmLLy.js → kv-storage-iJChCS5A.js} +2 -2
  15. package/dist/object-Da1zyPCR.js +11 -0
  16. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
  17. package/dist/{operations-gk2qzhYV.js → operations-DwZWFIUX.js} +75 -22
  18. package/dist/operations.d.ts +27 -4
  19. package/dist/operations.js +127 -730
  20. package/dist/os.d.ts +167 -0
  21. package/dist/os.js +1659 -0
  22. package/dist/runtime/console.d.ts +12 -0
  23. package/dist/runtime/console.js +85 -0
  24. package/dist/runtime/kv.d.ts +1 -1
  25. package/dist/runtime/kv.js +1 -1
  26. package/dist/runtime/process.d.ts +32 -5
  27. package/dist/runtime/process.js +401 -413
  28. package/dist/runtime/state.d.ts +2 -9
  29. package/dist/runtime/state.js +2 -2
  30. package/dist/runtime/static.d.ts +28 -2
  31. package/dist/runtime/static.js +2 -2
  32. package/dist/runtime.d.ts +34 -32
  33. package/dist/runtime.js +6 -5
  34. package/dist/started-BuGmnus4.js +201 -0
  35. package/dist/started-Bx7MDbrl.js +146 -0
  36. package/dist/{execute-BJrgNgQ0.js → started-errors-p7cu_rI7.js} +69 -20
  37. package/dist/{state-DSxmHPn3.js → state-B-Fuyfb4.js} +42 -22
  38. package/dist/state-Do2wV4Tx.d.ts +49 -0
  39. package/dist/{static-6g82xguw.js → static-DQwzzvPg.js} +63 -42
  40. package/dist/store-Df0-fzCl.d.ts +53 -0
  41. package/dist/time-zone-SBldrUgt.js +59 -0
  42. package/dist/{types-CHdV9FQU.d.ts → types-Cw5LjPuc.d.ts} +62 -8
  43. package/dist/vite.d.ts +255 -2
  44. package/dist/vite.js +5876 -2
  45. package/dist/{wait-until-BmIqRo4x.js → wait-until-Dy4Bn3ZN.js} +26 -1
  46. package/package.json +19 -24
  47. package/dist/definition-CMiOg1lg.js +0 -111
  48. package/dist/error-diagnostics-A_8Kp-48.js +0 -116
  49. package/dist/error-diagnostics-in7mif5s.js +0 -45
  50. package/dist/nuxt.d.ts +0 -17
  51. package/dist/nuxt.js +0 -27
  52. package/dist/store-QAOd8bxm.d.ts +0 -11
  53. package/dist/vite-BAVyZ8hZ.d.ts +0 -474
  54. package/dist/vite-BJwZkMrn.js +0 -5193
@@ -1,464 +1,349 @@
1
- import { t as scheduleErrorDiagnostics } from "../error-diagnostics-in7mif5s.js";
2
- import { r as executeStaticSchedule } from "../execute-BJrgNgQ0.js";
3
- import { i as createScheduleError } from "../wait-until-BmIqRo4x.js";
4
- import { a as setScheduleRunStore, n as getScheduleRuntimeRegistry, o as setScheduleRuntimeRegistry, t as getScheduleRunStore } from "../state-DSxmHPn3.js";
5
- import { onShutdown } from "@vite-hub/runtime/shutdown";
6
- import { Cause, Clock, Context, Data, Duration, Effect, Exit, FiberSet, Layer, ManagedRuntime, Queue, Ref, Scheduler, Semaphore } from "effect";
7
- import { parseCronExpression } from "cron-schedule";
8
- //#region src/runtime/due.ts
9
- const weekdayIndexes = /* @__PURE__ */ new Map([
10
- ["Sun", 0],
11
- ["Mon", 1],
12
- ["Tue", 2],
13
- ["Wed", 3],
14
- ["Thu", 4],
15
- ["Fri", 5],
16
- ["Sat", 6]
17
- ]);
18
- const minuteMs$1 = 6e4;
19
- const hourMinutes = 60;
20
- const dayMinutes = 1440;
21
- const timeZoneFormatters = /* @__PURE__ */ new Map();
22
- const parsedScheduleCrons = /* @__PURE__ */ new WeakMap();
23
- function timeZoneFormatter(timeZone) {
24
- let formatter = timeZoneFormatters.get(timeZone);
25
- if (!formatter) {
26
- formatter = new Intl.DateTimeFormat("en-US", {
27
- day: "numeric",
28
- hour: "numeric",
29
- hourCycle: "h23",
30
- minute: "numeric",
31
- month: "numeric",
32
- timeZone,
33
- weekday: "short",
34
- year: "numeric"
35
- });
36
- timeZoneFormatters.set(timeZone, formatter);
37
- }
38
- return formatter;
39
- }
40
- function scheduleDateFields(scheduledAt, timeZone) {
41
- if (!timeZone || timeZone === "UTC") return {
42
- day: scheduledAt.getUTCDate(),
43
- hour: scheduledAt.getUTCHours(),
44
- minute: scheduledAt.getUTCMinutes(),
45
- month: scheduledAt.getUTCMonth(),
46
- weekday: scheduledAt.getUTCDay(),
47
- year: scheduledAt.getUTCFullYear()
48
- };
49
- const values = new Map(timeZoneFormatter(timeZone).formatToParts(scheduledAt).map((part) => [part.type, part.value]));
50
- const weekday = weekdayIndexes.get(values.get("weekday") || "");
51
- const day = Number(values.get("day"));
52
- const hour = Number(values.get("hour"));
53
- const minute = Number(values.get("minute"));
54
- const month = Number(values.get("month")) - 1;
55
- const year = Number(values.get("year"));
56
- if (weekday === void 0 || [
57
- day,
58
- hour,
59
- minute,
60
- month,
61
- year
62
- ].some((value) => !Number.isInteger(value))) throw scheduleErrorDiagnostics.SCHEDULE_R0022({ message: `Schedule time zone could not resolve calendar fields: ${timeZone}` });
63
- return {
64
- day,
65
- hour,
66
- minute,
67
- month,
68
- weekday,
69
- year
70
- };
71
- }
72
- function parseScheduleCron(schedule) {
73
- const expression = schedule.cron;
74
- const cached = parsedScheduleCrons.get(schedule);
75
- if (cached?.expression === expression) return cached.cron;
76
- if (expression.trim().split(/\s+/).length !== 5) throw scheduleErrorDiagnostics.SCHEDULE_R0023({ message: `Schedule "${schedule.id}" must use a five-field cron expression.` });
77
- const cron = parseCronExpression(expression);
78
- parsedScheduleCrons.set(schedule, {
79
- expression,
80
- cron
81
- });
82
- return cron;
83
- }
84
- function matchesCronHour(cron, fields) {
85
- if (!cron.hours.includes(fields.hour) || !cron.months.includes(fields.month)) return false;
86
- if (cron.days.length !== 31 && cron.weekdays.length !== 7) return cron.days.includes(fields.day) || cron.weekdays.includes(fields.weekday);
87
- return cron.days.includes(fields.day) && cron.weekdays.includes(fields.weekday);
88
- }
89
- function localEpochMs(fields) {
90
- const date = /* @__PURE__ */ new Date(0);
91
- date.setUTCFullYear(fields.year, fields.month, fields.day);
92
- date.setUTCHours(fields.hour, fields.minute, 0, 0);
93
- return date.getTime();
94
- }
95
- function sameLocalMinute(left, right) {
96
- return left.minute === right.minute && left.hour === right.hour && left.day === right.day && left.month === right.month && left.year === right.year;
97
- }
98
- /** Detect a repeated local minute using the actual offset before the transition (including historical 23-hour rollbacks). */
99
- function isRepeatedFixedLocalTime(cron, fields, scheduledAt, timeZone) {
100
- if (!timeZone || timeZone === "UTC" || cron.minutes.length === hourMinutes || cron.hours.length === 24) return false;
101
- const previous = /* @__PURE__ */ new Date(scheduledAt.getTime() - dayMinutes * minuteMs$1);
102
- const currentOffset = localEpochMs(fields) - scheduledAt.getTime();
103
- const previousOffset = localEpochMs(scheduleDateFields(previous, timeZone)) - previous.getTime();
104
- if (previousOffset <= currentOffset) return false;
105
- return sameLocalMinute(scheduleDateFields(new Date(scheduledAt.getTime() - (previousOffset - currentOffset)), timeZone), fields);
106
- }
107
- /** Returns `true` when `schedule` is due at the exact minute `scheduledAt`. */
108
- function isScheduleDue(schedule, scheduledAt) {
109
- if (scheduledAt.getUTCSeconds() !== 0 || scheduledAt.getUTCMilliseconds() !== 0) return false;
110
- const cron = parseScheduleCron(schedule);
111
- const fields = scheduleDateFields(scheduledAt, schedule.timeZone);
112
- return cron.minutes.includes(fields.minute) && matchesCronHour(cron, fields) && !isRepeatedFixedLocalTime(cron, fields, scheduledAt, schedule.timeZone);
113
- }
114
- //#endregion
1
+ import { n as isRecordOrFunction } from "../object-Da1zyPCR.js";
2
+ import { t as scheduleErrorDiagnostics } from "../error-diagnostics-Mpeks7J0.js";
3
+ import { i as scheduleIdempotencyKey, o as createScheduleError } from "../wait-until-Dy4Bn3ZN.js";
4
+ import { i as executeStaticSchedule, o as toRunId } from "../started-errors-p7cu_rI7.js";
5
+ import { d as setScheduleRuntimeRegistry, i as getScheduleRuntimeRegistry, l as setScheduleOccurrenceClaims, n as getScheduleOccurrenceClaims, r as getScheduleRunStore, s as registerProcessScheduleDefinitions, u as setScheduleRunStore } from "../state-B-Fuyfb4.js";
6
+ import { t as isScheduleDue } from "../due-BVMRQ93v.js";
7
+ import { i as runStartedSchedules } from "../started-BuGmnus4.js";
8
+ import { createMemoryLeaseStore } from "@vite-hub/runtime";
9
+ import { hostname } from "node:os";
10
+ import { onShutdown } from "@vite-hub/runtime/internal/shutdown";
115
11
  //#region src/internal/process-wake-runtime.ts
116
- var ProcessWakeBoundaryError = class extends Data.TaggedError("ProcessWakeBoundaryError") {};
117
- function interruptionError(signal) {
118
- if (signal?.aborted && signal.reason !== void 0) return signal.reason;
119
- const error = scheduleErrorDiagnostics.SCHEDULE_R0001({ message: "[vitehub] Process Schedule Wake Driver operation was interrupted." });
120
- error.name = "AbortError";
121
- return error;
122
- }
123
- function processWakeCauseValues(cause, signal) {
124
- return cause.reasons.map((reason) => {
125
- if (Cause.isFailReason(reason)) return reason.error instanceof ProcessWakeBoundaryError ? reason.error.cause : reason.error;
126
- if (Cause.isDieReason(reason)) return reason.defect;
127
- return interruptionError(signal);
128
- });
129
- }
130
- async function unwrapProcessWakeExit(promise, signal) {
131
- const exit = await promise;
132
- if (Exit.isSuccess(exit)) return exit.value;
133
- const causes = processWakeCauseValues(exit.cause, signal);
134
- if (causes.length === 1) throw causes[0];
135
- throw new AggregateError(causes, "[vitehub] Process Schedule Wake Driver operation failed for multiple reasons.");
136
- }
137
- function cloneState(state, patch) {
12
+ const minuteMs$1 = 6e4;
13
+ const DEFAULT_INTERVAL_MS = 6e4;
14
+ const DEFAULT_CONCURRENCY = 1;
15
+ function validateDriverOptions(options) {
16
+ const intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;
17
+ const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
18
+ const catchUpMs = options.catchUpMs ?? 36e5;
19
+ if (!Number.isFinite(catchUpMs) || catchUpMs < 0) throw scheduleErrorDiagnostics.SCHEDULE_R0024({ message: "Process Schedule Runtime catchUpMs must be a finite number of zero or more." });
20
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0 || intervalMs > DEFAULT_INTERVAL_MS) throw scheduleErrorDiagnostics.SCHEDULE_R0024({ message: "Process Schedule Runtime intervalMs must be a positive number no greater than 60000." });
21
+ if (!Number.isInteger(concurrency) || concurrency < 1) throw scheduleErrorDiagnostics.SCHEDULE_R0025({ message: "Process Schedule Runtime concurrency must be a positive integer." });
138
22
  return {
139
- active: patch.active ?? state.active,
140
- closed: patch.closed ?? state.closed,
141
- closing: patch.closing ?? state.closing,
142
- dispatched: patch.dispatched ?? state.dispatched,
143
- occurrenceMinute: patch.occurrenceMinute ?? state.occurrenceMinute,
144
- queued: patch.queued ?? state.queued,
145
- scannedThrough: patch.scannedThrough ?? state.scannedThrough,
146
- schedules: patch.schedules ?? state.schedules,
147
- started: patch.started ?? state.started
23
+ catchUpMs,
24
+ concurrency,
25
+ intervalMs
148
26
  };
149
27
  }
150
- const minuteMs = 6e4;
151
28
  function floorUTCMinute(date) {
152
- return /* @__PURE__ */ new Date(Math.floor(date.getTime() / minuteMs) * minuteMs);
29
+ return Math.floor(date.getTime() / minuteMs$1) * minuteMs$1;
153
30
  }
154
31
  function occurrenceKey(input) {
155
32
  return `${input.scheduleId}:${input.scheduledAt.getTime()}`;
156
33
  }
157
- function reportError(context, error) {
158
- return Effect.sync(() => {
34
+ function byScheduledAt(left, right) {
35
+ return left.scheduledAt.getTime() - right.scheduledAt.getTime();
36
+ }
37
+ /**
38
+ * Creates the in-process minute scanner. `reconcile()` replaces the checked Schedules and starts the scanner on the
39
+ * first call. `close()` stops the scanner and waits for active wakes. Timers do not keep the process alive.
40
+ */
41
+ function createProcessWakeDriver(options, context) {
42
+ const { catchUpMs, concurrency, intervalMs } = validateDriverOptions(options);
43
+ const now = options.now ?? (() => new Date(Date.now()));
44
+ let schedules = /* @__PURE__ */ new Map();
45
+ /** Occurrences waiting for a worker, in delivery order. */
46
+ const queued = /* @__PURE__ */ new Map();
47
+ /** Occurrences that a worker is waking now. */
48
+ const active = /* @__PURE__ */ new Set();
49
+ /** Schedules already queued for `occurrenceMinute`, so a Schedule wakes once per current minute. */
50
+ let dispatched = /* @__PURE__ */ new Set();
51
+ let occurrenceMinute;
52
+ let scannedThrough;
53
+ let started = false;
54
+ let closing = false;
55
+ let closed = false;
56
+ let timer;
57
+ let workers = 0;
58
+ let onIdle;
59
+ let closePromise;
60
+ let lock = Promise.resolve();
61
+ function exclusive(operation) {
62
+ const result = lock.then(operation);
63
+ lock = result.then(() => {}, () => {});
64
+ return result;
65
+ }
66
+ function reportError(error) {
159
67
  try {
160
68
  context.reportError(error);
161
69
  } catch {}
162
- });
163
- }
164
- function wrapBoundary(operation) {
165
- return Effect.try({
166
- try: operation,
167
- catch: (cause) => new ProcessWakeBoundaryError({ cause })
168
- });
169
- }
170
- const makeProcessWakeRuntime = Effect.fn("ScheduleProcessDriver.make")(function* (options) {
171
- const clock = yield* Clock.Clock;
172
- const operationLock = yield* Semaphore.make(1);
173
- const queue = yield* Queue.bounded(options.concurrency);
174
- const enqueueFibers = yield* FiberSet.make();
175
- const scannerFibers = yield* FiberSet.make();
176
- const workerFibers = yield* FiberSet.make();
177
- const state = yield* Ref.make({
178
- active: /* @__PURE__ */ new Set(),
179
- closed: false,
180
- closing: false,
181
- dispatched: /* @__PURE__ */ new Set(),
182
- queued: /* @__PURE__ */ new Map(),
183
- schedules: /* @__PURE__ */ new Map(),
184
- started: false
185
- });
186
- const currentDate = options.now ? wrapBoundary(() => options.now()) : Effect.map(clock.currentTimeMillis, (millis) => new Date(millis));
187
- const claimOccurrence = Effect.fn("ScheduleProcessDriver.claim")(function* (input) {
188
- const key = occurrenceKey(input);
189
- const snapshot = yield* Ref.get(state);
190
- const queuedOccurrence = snapshot.queued.get(key);
191
- if (!queuedOccurrence) return false;
192
- const schedule = snapshot.schedules.get(input.scheduleId);
193
- const due = schedule ? yield* wrapBoundary(() => isScheduleDue(schedule, input.scheduledAt)) : false;
194
- return yield* Ref.modify(state, (current) => {
195
- if (current.queued.get(key) !== queuedOccurrence || current.schedules.get(input.scheduleId) !== schedule) return [void 0, current];
196
- const queued = new Map(current.queued);
70
+ }
71
+ function take() {
72
+ for (const [key, input] of queued) {
197
73
  queued.delete(key);
198
- if (!due) {
199
- const dispatched = new Set(current.dispatched);
200
- if (current.occurrenceMinute === input.scheduledAt.getTime() && !current.active.has(key)) dispatched.delete(input.scheduleId);
201
- return [false, cloneState(current, {
202
- dispatched,
203
- queued
204
- })];
74
+ if (input.scheduledAt.getTime() < floorUTCMinute(now()) - catchUpMs) continue;
75
+ return input;
76
+ }
77
+ }
78
+ async function work() {
79
+ try {
80
+ for (let input = take(); input; input = take()) {
81
+ const key = occurrenceKey(input);
82
+ active.add(key);
83
+ try {
84
+ await context.wake(input);
85
+ } catch (error) {
86
+ reportError(error);
87
+ } finally {
88
+ active.delete(key);
89
+ }
205
90
  }
206
- const active = new Set(current.active);
207
- active.add(key);
208
- return [true, cloneState(current, {
209
- active,
210
- queued
211
- })];
212
- }).pipe(Effect.flatMap((claimed) => claimed === void 0 ? claimOccurrence(input) : Effect.succeed(claimed)));
213
- });
214
- const dispatch = Effect.fn("ScheduleProcessDriver.dispatch")(function* (input) {
215
- const key = occurrenceKey(input);
216
- const claimed = yield* claimOccurrence(input).pipe(Effect.match({
217
- onFailure: (error) => ({ error }),
218
- onSuccess: (value) => ({ value })
219
- }));
220
- if ("error" in claimed) {
221
- yield* reportError(options.context, claimed.error.cause);
222
- return;
91
+ } finally {
92
+ workers -= 1;
93
+ if (workers === 0) onIdle?.();
223
94
  }
224
- if (!claimed.value) return;
225
- yield* Effect.tryPromise({
226
- try: () => Promise.resolve(options.context.wake(input)),
227
- catch: (cause) => new ProcessWakeBoundaryError({ cause })
228
- }).pipe(Effect.catchTag("ProcessWakeBoundaryError", (error) => reportError(options.context, error.cause)), Effect.ensuring(Ref.update(state, (current) => {
229
- const active = new Set(current.active);
230
- active.delete(key);
231
- return cloneState(current, { active });
232
- })));
233
- });
234
- const worker = Effect.forever(Effect.flatMap(Queue.take(queue), dispatch)).pipe(Effect.catchCauseIf(Cause.isDone, () => Effect.void));
235
- yield* Effect.forEach(Array.from({ length: options.concurrency }), () => FiberSet.run(workerFibers, worker, { startImmediately: true }), { discard: true });
236
- /** Due occurrences of `schedules` from `first` through `last`, oldest first. */
237
- const dueOccurrences = Effect.fn("ScheduleProcessDriver.due")(function* (schedules, first, last) {
95
+ }
96
+ /** Starts workers up to `concurrency`. A free worker starts its wake before this returns. */
97
+ function startWorkers() {
98
+ while (workers < concurrency && queued.size > 0) {
99
+ workers += 1;
100
+ work();
101
+ }
102
+ }
103
+ /** Due occurrences of `entries` from `first` through `last`, oldest first. */
104
+ function dueOccurrences(entries, first, last) {
238
105
  const due = [];
239
- for (const schedule of schedules) for (let minute = Math.ceil(first / minuteMs) * minuteMs; minute <= last; minute += minuteMs) {
106
+ for (const schedule of entries) for (let minute = Math.ceil(first / minuteMs$1) * minuteMs$1; minute <= last; minute += minuteMs$1) {
240
107
  const scheduledAt = new Date(minute);
241
- const result = yield* wrapBoundary(() => isScheduleDue(schedule, scheduledAt)).pipe(Effect.match({
242
- onFailure: (error) => ({ error }),
243
- onSuccess: (isDue) => ({ isDue })
244
- }));
245
- if ("error" in result) {
246
- yield* reportError(options.context, result.error.cause);
108
+ let isDue;
109
+ try {
110
+ isDue = isScheduleDue(schedule, scheduledAt);
111
+ } catch (error) {
112
+ reportError(error);
247
113
  break;
248
114
  }
249
- if (result.isDue) due.push({
115
+ if (isDue) due.push({
250
116
  scheduleId: schedule.id,
251
117
  scheduledAt
252
118
  });
253
119
  }
254
- return due.sort((left, right) => left.scheduledAt.getTime() - right.scheduledAt.getTime());
255
- });
256
- /** Queues occurrences that are not queued or running yet. The current minute dispatches each Schedule once. */
257
- const queueOccurrences = (due, currentMinute) => Ref.modify(state, (current) => {
258
- if (current.closed || current.closing) return [[], current];
259
- if (current.occurrenceMinute !== void 0 && currentMinute < current.occurrenceMinute) return [[], current];
260
- const dispatched = current.occurrenceMinute === currentMinute ? new Set(current.dispatched) : /* @__PURE__ */ new Set();
261
- const queued = new Map(current.queued);
262
- const occurrences = [];
120
+ return due.sort(byScheduledAt);
121
+ }
122
+ /** Queues occurrences that are not queued or running yet, then starts free workers. The current minute dispatches each Schedule once. */
123
+ function enqueue(due, currentMinute, retries = []) {
124
+ if (closing) return;
125
+ if (occurrenceMinute !== void 0 && currentMinute < occurrenceMinute) return;
126
+ if (occurrenceMinute !== currentMinute) dispatched = /* @__PURE__ */ new Set();
263
127
  for (const input of due) {
264
128
  const key = occurrenceKey(input);
265
- if (queued.has(key) || current.active.has(key)) continue;
129
+ if (queued.has(key) || active.has(key)) continue;
266
130
  if (input.scheduledAt.getTime() === currentMinute) {
267
131
  if (dispatched.has(input.scheduleId)) continue;
268
132
  dispatched.add(input.scheduleId);
269
133
  }
270
134
  queued.set(key, input);
271
- occurrences.push(input);
272
135
  }
273
- return [occurrences, cloneState(current, {
274
- dispatched,
275
- occurrenceMinute: currentMinute,
276
- queued,
277
- scannedThrough: Math.max(current.scannedThrough ?? currentMinute, currentMinute)
278
- })];
279
- });
280
- const scanUnlocked = Effect.fn("ScheduleProcessDriver.scan")(function* () {
281
- const currentMinute = floorUTCMinute(yield* currentDate).getTime();
282
- const snapshot = yield* Ref.get(state);
283
- const first = snapshot.scannedThrough === void 0 ? currentMinute : Math.min(currentMinute, Math.max(snapshot.scannedThrough + minuteMs, currentMinute - options.catchUpMs));
284
- const due = yield* dueOccurrences(snapshot.schedules.values(), first, currentMinute);
285
- return yield* queueOccurrences(due, currentMinute);
286
- });
287
- const catchUpUnlocked = Effect.fn("ScheduleProcessDriver.catchUp")(function* (schedules) {
288
- const latestScheduledAt = options.context.latestScheduledAt;
289
- if (!latestScheduledAt || options.catchUpMs <= 0) return [];
290
- const currentMinute = floorUTCMinute(yield* currentDate).getTime();
136
+ for (const input of retries) {
137
+ const key = occurrenceKey(input);
138
+ const schedule = schedules.get(input.scheduleId);
139
+ if (!schedule || queued.has(key) || active.has(key) || !isScheduleDue(schedule, input.scheduledAt)) continue;
140
+ queued.set(key, input);
141
+ }
142
+ occurrenceMinute = currentMinute;
143
+ scannedThrough = Math.max(scannedThrough ?? currentMinute, currentMinute);
144
+ startWorkers();
145
+ }
146
+ function scan() {
147
+ const currentMinute = floorUTCMinute(now());
148
+ const first = scannedThrough === void 0 ? currentMinute : Math.min(currentMinute, Math.max(scannedThrough + minuteMs$1, currentMinute - catchUpMs));
149
+ enqueue(dueOccurrences(schedules.values(), first, currentMinute), currentMinute, context.retries?.() ?? []);
150
+ }
151
+ async function catchUp(entries) {
152
+ if (!context.latestScheduledAt || catchUpMs <= 0) return;
153
+ const currentMinute = floorUTCMinute(now());
291
154
  const due = [];
292
- for (const schedule of schedules) {
293
- const latest = yield* Effect.tryPromise({
294
- try: () => Promise.resolve(latestScheduledAt(schedule.id)),
295
- catch: (cause) => new ProcessWakeBoundaryError({ cause })
296
- }).pipe(Effect.catchTag("ProcessWakeBoundaryError", (error) => Effect.as(reportError(options.context, error.cause), void 0)));
155
+ for (const schedule of entries) {
156
+ let latest;
157
+ try {
158
+ latest = await context.latestScheduledAt(schedule.id);
159
+ } catch (error) {
160
+ reportError(error);
161
+ }
297
162
  if (!latest) continue;
298
- const first = Math.max(floorUTCMinute(latest).getTime() + minuteMs, currentMinute - options.catchUpMs);
299
- due.push(...yield* dueOccurrences([schedule], first, currentMinute - minuteMs));
163
+ const first = latest === "unknown" ? currentMinute - catchUpMs : Math.max(floorUTCMinute(latest) + minuteMs$1, currentMinute - catchUpMs);
164
+ due.push(...dueOccurrences([schedule], first, currentMinute - minuteMs$1));
300
165
  }
301
- return yield* queueOccurrences(due.sort((left, right) => left.scheduledAt.getTime() - right.scheduledAt.getTime()), currentMinute);
302
- });
303
- const enqueue = (occurrences) => occurrences.length === 0 ? Effect.void : FiberSet.run(enqueueFibers, Queue.offerAll(queue, occurrences), { startImmediately: true });
304
- const scanIteration = operationLock.withPermits(1)(Effect.flatMap(scanUnlocked(), enqueue)).pipe(Effect.catchTag("ProcessWakeBoundaryError", (error) => reportError(options.context, error.cause)));
305
- const scanLoop = Effect.forever(Effect.andThen(clock.sleep(Duration.millis(options.intervalMs)), FiberSet.run(scannerFibers, scanIteration, { startImmediately: true })));
306
- const reconcile = Effect.fn("ScheduleProcessDriver.reconcile")(function* (records) {
307
- yield* operationLock.withPermits(1)(Effect.gen(function* () {
308
- const snapshot = yield* Ref.get(state);
309
- if (snapshot.closed) return yield* Effect.fail(new ProcessWakeBoundaryError({ cause: scheduleErrorDiagnostics.SCHEDULE_R0002({ message: "Process Schedule Wake Driver is closed." }) }));
310
- const scheduledAt = floorUTCMinute(yield* currentDate);
311
- for (const record of records) yield* wrapBoundary(() => isScheduleDue(record, scheduledAt));
312
- const schedules = new Map(records.map((record) => [record.id, { ...record }]));
313
- const startScanner = yield* Ref.modify(state, (current) => {
314
- const dispatched = new Set(current.dispatched);
315
- const queued = new Map(current.queued);
316
- for (const [key, input] of queued) {
317
- const schedule = schedules.get(input.scheduleId);
318
- if (schedule && isScheduleDue(schedule, input.scheduledAt)) continue;
319
- queued.delete(key);
320
- if (current.occurrenceMinute === input.scheduledAt.getTime() && !current.active.has(key)) dispatched.delete(input.scheduleId);
321
- }
322
- return [!current.started, cloneState(current, {
323
- dispatched,
324
- queued,
325
- schedules
326
- })];
327
- });
328
- if (!snapshot.closing) {
329
- if (startScanner) yield* Effect.flatMap(catchUpUnlocked(records), enqueue);
330
- yield* Effect.flatMap(scanUnlocked(), enqueue);
331
- if (startScanner) {
332
- yield* FiberSet.run(scannerFibers, scanLoop, { startImmediately: true });
333
- yield* Ref.update(state, (current) => cloneState(current, { started: true }));
334
- }
335
- }
336
- }));
337
- });
338
- return {
339
- close: Effect.fn("ScheduleProcessDriver.close")(function* () {
340
- if (!(yield* operationLock.withPermits(1)(Ref.modify(state, (current) => [!current.closed && !current.closing, cloneState(current, {
341
- closing: true,
342
- queued: /* @__PURE__ */ new Map()
343
- })])))) return;
344
- yield* FiberSet.clear(scannerFibers);
345
- yield* FiberSet.awaitEmpty(enqueueFibers);
346
- yield* Queue.end(queue);
347
- yield* FiberSet.awaitEmpty(workerFibers);
348
- yield* Ref.update(state, (current) => cloneState(current, { closed: true }));
349
- })(),
350
- reconcile
351
- };
352
- });
353
- const DEFAULT_INTERVAL_MS = 6e4;
354
- const DEFAULT_CONCURRENCY = 1;
355
- const DEFAULT_CATCH_UP_MS = 36e5;
356
- function validateDriverOptions(options) {
357
- const intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;
358
- const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
359
- const catchUpMs = options.catchUpMs ?? DEFAULT_CATCH_UP_MS;
360
- if (!Number.isFinite(catchUpMs) || catchUpMs < 0) throw scheduleErrorDiagnostics.SCHEDULE_R0024({ message: "Process Schedule Runtime catchUpMs must be a finite number of zero or more." });
361
- if (!Number.isFinite(intervalMs) || intervalMs <= 0 || intervalMs > DEFAULT_INTERVAL_MS) throw scheduleErrorDiagnostics.SCHEDULE_R0024({ message: "Process Schedule Runtime intervalMs must be a positive number no greater than 60000." });
362
- if (!Number.isInteger(concurrency) || concurrency < 1) throw scheduleErrorDiagnostics.SCHEDULE_R0025({ message: "Process Schedule Runtime concurrency must be a positive integer." });
363
- return {
364
- catchUpMs,
365
- concurrency,
366
- intervalMs
367
- };
368
- }
369
- var ProcessWakeRuntimeService = class extends Context.Service()("@vite-hub/schedule/ProcessWakeRuntime") {};
370
- function createProcessClock() {
371
- const currentTimeMillisUnsafe = () => Date.now();
372
- const currentTimeNanosUnsafe = () => BigInt(currentTimeMillisUnsafe()) * 1000000n;
373
- const monotonicTimeNanosUnsafe = () => process.hrtime.bigint();
374
- return {
375
- currentTimeMillis: Effect.sync(currentTimeMillisUnsafe),
376
- currentTimeMillisUnsafe,
377
- currentTimeNanos: Effect.sync(currentTimeNanosUnsafe),
378
- currentTimeNanosUnsafe,
379
- monotonicTimeNanos: Effect.sync(monotonicTimeNanosUnsafe),
380
- monotonicTimeNanosUnsafe,
381
- sleep(duration) {
382
- return Effect.callback((resume) => {
383
- const timer = setTimeout(() => resume(Effect.void), Duration.toMillis(duration));
384
- timer.unref?.();
385
- return Effect.sync(() => clearTimeout(timer));
386
- });
166
+ enqueue(due.sort(byScheduledAt), currentMinute);
167
+ }
168
+ async function reconcile(records) {
169
+ const scheduledAt = new Date(floorUTCMinute(now()));
170
+ for (const record of records) isScheduleDue(record, scheduledAt);
171
+ const next = new Map(records.map((record) => [record.id, { ...record }]));
172
+ for (const [key, input] of queued) {
173
+ const schedule = next.get(input.scheduleId);
174
+ if (schedule && isScheduleDue(schedule, input.scheduledAt)) continue;
175
+ queued.delete(key);
176
+ if (occurrenceMinute === input.scheduledAt.getTime() && !active.has(key)) dispatched.delete(input.scheduleId);
387
177
  }
388
- };
389
- }
390
- function createProcessScheduler() {
391
- return new Scheduler.MixedScheduler("async", (run) => {
392
- let canceled = false;
393
- queueMicrotask(() => {
394
- if (!canceled) run();
178
+ schedules = next;
179
+ if (closing) return;
180
+ const startScanner = !started;
181
+ if (startScanner) await catchUp(records);
182
+ scan();
183
+ if (startScanner) {
184
+ timer = setInterval(() => {
185
+ exclusive(() => {
186
+ if (!closing) scan();
187
+ }).catch(reportError);
188
+ }, intervalMs);
189
+ timer.unref?.();
190
+ started = true;
191
+ }
192
+ }
193
+ async function close() {
194
+ await exclusive(() => {
195
+ closing = true;
196
+ queued.clear();
197
+ clearInterval(timer);
395
198
  });
396
- return () => {
397
- canceled = true;
398
- };
399
- });
400
- }
401
- /**
402
- * Creates the in-process minute scanner. `reconcile()` replaces the checked Schedules and starts the scanner on the
403
- * first call. `close()` stops the scanner and waits for active wakes. Timers do not keep the process alive.
404
- */
405
- function createProcessWakeDriver(options, context) {
406
- const { catchUpMs, concurrency, intervalMs } = validateDriverOptions(options);
407
- const ProcessWakeRuntimeLive = Layer.effect(ProcessWakeRuntimeService, makeProcessWakeRuntime({
408
- catchUpMs,
409
- concurrency,
410
- context,
411
- intervalMs,
412
- now: options.now
413
- })).pipe(Layer.provide(Layer.mergeAll(Layer.succeed(Clock.Clock, createProcessClock()), Layer.succeed(Scheduler.Scheduler, createProcessScheduler()))));
414
- const runtime = ManagedRuntime.make(ProcessWakeRuntimeLive);
415
- let closePromise;
416
- let closed = false;
417
- function run(effect) {
418
- return unwrapProcessWakeExit(runtime.runPromiseExit(effect));
199
+ if (workers > 0) await new Promise((resolve) => {
200
+ onIdle = resolve;
201
+ });
202
+ closed = true;
419
203
  }
420
204
  return {
421
205
  close() {
422
- if (closePromise) return closePromise;
423
- closePromise = run(Effect.flatMap(ProcessWakeRuntimeService, (service) => service.close)).then(() => {
424
- closed = true;
425
- return runtime.dispose();
426
- });
427
- return closePromise;
206
+ return closePromise ??= close();
428
207
  },
429
208
  reconcile(entries) {
430
209
  if (closed) return Promise.reject(scheduleErrorDiagnostics.SCHEDULE_R0026({ message: "Process Schedule Runtime is closed." }));
431
- return run(Effect.flatMap(ProcessWakeRuntimeService, (service) => service.reconcile(entries)));
210
+ return exclusive(() => reconcile(entries));
432
211
  }
433
212
  };
434
213
  }
435
214
  //#endregion
436
- //#region src/runtime/process.ts
437
- function isObject(value) {
438
- return Object(value) === value && !Array.isArray(value);
215
+ //#region src/runtime/claims.ts
216
+ /** The lease key of one occurrence within an app's Schedule prefix. */
217
+ function occurrenceLeaseKey(runId, prefix = "vitehub:schedule") {
218
+ const base = prefix.replace(/^\/+|\/+$/g, "");
219
+ return `${base ? `${base}/` : ""}schedule/${runId}`;
439
220
  }
221
+ /** The lease key that marks an occurrence as finished. */
222
+ function occurrenceDoneKey(runId, prefix) {
223
+ return `${occurrenceLeaseKey(runId, prefix)}/done`;
224
+ }
225
+ function keepAlive(lease, ttlMs, reportError) {
226
+ let stopped = false;
227
+ let renewal;
228
+ const timer = setInterval(() => {
229
+ if (renewal) return;
230
+ renewal = lease.renew().then(([error, renewed]) => {
231
+ if (stopped) return;
232
+ if (error) reportError(error);
233
+ else if (!renewed) reportError(/* @__PURE__ */ new Error(`[vitehub] Schedule occurrence claim "${lease.key}" ended before its run finished. Another process can run it too. Make the claim TTL longer than a pause of this process.`));
234
+ }, (error) => {
235
+ if (!stopped) reportError(error);
236
+ }).finally(() => {
237
+ renewal = void 0;
238
+ });
239
+ }, Math.max(1, Math.floor(ttlMs / 3)));
240
+ timer.unref?.();
241
+ return async () => {
242
+ stopped = true;
243
+ clearInterval(timer);
244
+ await renewal;
245
+ };
246
+ }
247
+ function createOccurrenceClaims(options) {
248
+ const ttl = options.ttlMs / 1e3;
249
+ const doneTtl = options.doneTtlMs / 1e3;
250
+ const owner = options.owner === void 0 ? {} : { owner: options.owner };
251
+ return { async run(runId, run) {
252
+ const [acquireError, lease] = await options.leases.acquire(occurrenceLeaseKey(runId, options.prefix), {
253
+ ttl,
254
+ ...owner
255
+ });
256
+ if (acquireError) throw acquireError;
257
+ if (!lease) return "held";
258
+ let release = true;
259
+ try {
260
+ const [doneError, done] = await options.leases.get(occurrenceDoneKey(runId, options.prefix));
261
+ if (doneError) throw doneError;
262
+ if (done) return "done";
263
+ const stop = keepAlive(lease, options.ttlMs, options.reportError);
264
+ let final = false;
265
+ try {
266
+ await run(() => {
267
+ final = true;
268
+ });
269
+ } finally {
270
+ await stop();
271
+ if (final) {
272
+ const [markError, marked] = await options.leases.acquire(occurrenceDoneKey(runId, options.prefix), {
273
+ ttl: doneTtl,
274
+ ...owner
275
+ });
276
+ if (markError) {
277
+ release = false;
278
+ options.reportError(markError);
279
+ const [renewError, renewed] = await lease.renew({ ttl: doneTtl });
280
+ if (renewError) options.reportError(renewError);
281
+ else if (!renewed) options.reportError(/* @__PURE__ */ new Error(`[vitehub] Schedule occurrence "${runId}" lost its claim before its done marker could be saved. Another process can run it too.`));
282
+ } else if (!marked) options.reportError(/* @__PURE__ */ new Error(`[vitehub] Schedule occurrence "${runId}" already had a done marker. Two processes ran it.`));
283
+ }
284
+ }
285
+ return "ran";
286
+ } finally {
287
+ if (release) {
288
+ const [releaseError] = await lease.release();
289
+ if (releaseError) options.reportError(releaseError);
290
+ }
291
+ }
292
+ } };
293
+ }
294
+ //#endregion
295
+ //#region src/runtime/process.ts
440
296
  function isStaticScheduleDefinition(value) {
441
- return isObject(value) && Object.hasOwn(value, "cron") && Object.hasOwn(value, "handler") && typeof value.handler === "function";
297
+ return isRecordOrFunction(value) && Object.hasOwn(value, "cron") && Object.hasOwn(value, "handler") && typeof value.handler === "function";
442
298
  }
443
299
  function unwrapDefinition(loaded) {
444
- if (isObject(loaded) && Object.hasOwn(loaded, "default") && isStaticScheduleDefinition(loaded.default)) return loaded.default;
300
+ if (isRecordOrFunction(loaded) && Object.hasOwn(loaded, "default") && isStaticScheduleDefinition(loaded.default)) return loaded.default;
445
301
  return isStaticScheduleDefinition(loaded) ? loaded : void 0;
446
302
  }
447
- async function loadStaticDefinitions(registry) {
303
+ function isTiming(value) {
304
+ return isRecordOrFunction(value) && String(value.cron) === value.cron && (value.timeZone === void 0 || String(value.timeZone) === value.timeZone);
305
+ }
306
+ /** Loads a Definition once, and again only after the load fails. */
307
+ function lazyDefinition(name, load) {
308
+ let loading;
309
+ return () => loading ??= load().then((loaded) => {
310
+ const definition = unwrapDefinition(loaded);
311
+ if (!definition) throw scheduleErrorDiagnostics.SCHEDULE_DEFINITION_EXPORT_INVALID({ name });
312
+ return definition;
313
+ }).catch((error) => {
314
+ loading = void 0;
315
+ throw error;
316
+ });
317
+ }
318
+ /**
319
+ * Loads the Definitions without a build timing now and keeps the others lazy. A Definition without a cron and a handler
320
+ * is skipped.
321
+ */
322
+ async function loadStaticDefinitions(registry, timings = {}) {
448
323
  const entries = await Promise.all(Object.entries(registry).map(async ([name, load]) => {
324
+ const timing = Object.hasOwn(timings, name) ? timings[name] : void 0;
325
+ if (isTiming(timing)) return {
326
+ cron: timing.cron,
327
+ definition: lazyDefinition(name, load),
328
+ name,
329
+ ...timing.timeZone ? { timeZone: timing.timeZone } : {}
330
+ };
449
331
  const definition = unwrapDefinition(await load());
450
- return definition ? {
451
- definition,
452
- name
453
- } : void 0;
332
+ if (!definition) return void 0;
333
+ return {
334
+ cron: definition.cron,
335
+ definition: async () => definition,
336
+ name,
337
+ ...definition.timeZone ? { timeZone: definition.timeZone } : {}
338
+ };
454
339
  }));
455
340
  return new Map(entries.flatMap((entry) => entry ? [[entry.name, entry]] : []));
456
341
  }
457
342
  function scheduleCronRecord(entry) {
458
343
  return {
459
- cron: entry.definition.cron,
344
+ cron: entry.cron,
460
345
  id: entry.name,
461
- ...entry.definition.timeZone ? { timeZone: entry.definition.timeZone } : {}
346
+ ...entry.timeZone ? { timeZone: entry.timeZone } : {}
462
347
  };
463
348
  }
464
349
  function createErrorReporter(onError) {
@@ -469,15 +354,35 @@ function createErrorReporter(onError) {
469
354
  } catch {}
470
355
  };
471
356
  }
357
+ const DEFAULT_LEASE_TTL_MS = 6e4;
358
+ const minuteMs = 6e4;
359
+ function resolveLeaseTtlMs(value) {
360
+ if (value === void 0) return DEFAULT_LEASE_TTL_MS;
361
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) throw scheduleErrorDiagnostics.SCHEDULE_R0024({ message: "Process Schedule Runtime leaseTtlMs must be a positive number." });
362
+ return value;
363
+ }
472
364
  /**
473
365
  * Runs Static Schedule Definitions on their cron, in their `timeZone` (UTC by default), in this long-running process. It checks every minute, runs each
474
366
  * due minute once, and records each run in `scheduleRunStore`. After a restart it runs the minutes that no process
475
- * checked, within `catchUpMs`, for Schedules that already have a run. Call `close()` during host shutdown.
367
+ * checked, within `catchUpMs`, for Schedules with a prior cron-triggered run or indeterminate legacy history.
368
+ * Processes that share `leases` run each occurrence once between them. Call `close()` during host shutdown.
476
369
  */
477
370
  async function installProcessScheduleRuntime(options) {
478
371
  const previousRegistry = getScheduleRuntimeRegistry();
479
372
  const previousScheduleRunStore = getScheduleRunStore();
373
+ const previousClaims = getScheduleOccurrenceClaims();
480
374
  const reportError = createErrorReporter(options.onError);
375
+ const leaseTtlMs = resolveLeaseTtlMs(options.leaseTtlMs);
376
+ const claims = createOccurrenceClaims({
377
+ doneTtlMs: (options.catchUpMs ?? 36e5) + leaseTtlMs + 2 * minuteMs,
378
+ leases: options.leases ?? createMemoryLeaseStore(),
379
+ owner: `${hostname()}:${process.pid}`,
380
+ prefix: options.prefix,
381
+ reportError,
382
+ ttlMs: leaseTtlMs
383
+ });
384
+ /** Occurrences that another process held when this process tried them, by run id. Each scan tries them again. */
385
+ const held = /* @__PURE__ */ new Map();
481
386
  const pendingWork = /* @__PURE__ */ new Set();
482
387
  const activeWakes = /* @__PURE__ */ new Set();
483
388
  let closing = false;
@@ -493,34 +398,109 @@ async function installProcessScheduleRuntime(options) {
493
398
  const driver = createProcessWakeDriver(options, {
494
399
  async latestScheduledAt(scheduleId) {
495
400
  const [run] = await options.scheduleRunStore.listRuns({
496
- limit: 1,
497
- scheduleId
401
+ scheduleId,
402
+ idPrefix: "srun_static_",
403
+ limit: 1
498
404
  });
499
- return run?.scheduledAt;
405
+ if (!run || run.id.startsWith("srun_static_")) return run?.scheduledAt;
406
+ const limit = 100;
407
+ const recent = await options.scheduleRunStore.listRuns({
408
+ scheduleId,
409
+ limit
410
+ });
411
+ const latest = recent.find((record) => record.id.startsWith("srun_static_"));
412
+ if (latest) return latest.scheduledAt;
413
+ return recent.length < limit ? void 0 : "unknown";
500
414
  },
501
415
  reportError,
416
+ retries() {
417
+ const since = Math.floor((options.now?.() ?? /* @__PURE__ */ new Date()).getTime() / minuteMs) * minuteMs - (options.catchUpMs ?? 36e5);
418
+ for (const [runId, input] of held) if (input.scheduledAt.getTime() < since) held.delete(runId);
419
+ return [...held.values()];
420
+ },
502
421
  wake(input) {
503
422
  if (closing) return Promise.resolve();
504
423
  const wake = (async () => {
505
424
  const entry = definitions.get(input.scheduleId);
506
425
  if (!entry || !isScheduleDue(scheduleCronRecord(entry), input.scheduledAt)) throw createScheduleError("SCHEDULE_NOT_DUE");
507
- await executeStaticSchedule({
508
- cron: entry.definition.cron,
509
- definition: entry.definition,
510
- name: entry.name,
511
- scheduledAt: input.scheduledAt,
512
- waitUntil
513
- });
426
+ const definition = await entry.definition();
427
+ if (definition.handler === runStartedSchedules) {
428
+ await runStartedSchedules({
429
+ id: `tick_${input.scheduledAt.toISOString()}`,
430
+ idempotencyKey: scheduleIdempotencyKey(entry.name, input.scheduledAt),
431
+ scheduledAt: input.scheduledAt,
432
+ scheduleId: entry.name,
433
+ target: entry.name,
434
+ waitUntil
435
+ });
436
+ return;
437
+ }
438
+ const runId = toRunId("static", entry.name, input.scheduledAt);
439
+ try {
440
+ if (await claims.run(runId, (onExecution) => executeStaticSchedule({
441
+ claimed: true,
442
+ cron: entry.cron,
443
+ definition,
444
+ name: entry.name,
445
+ onExecution,
446
+ scheduledAt: input.scheduledAt,
447
+ waitUntil
448
+ })) === "held") held.set(runId, {
449
+ scheduleId: input.scheduleId,
450
+ scheduledAt: input.scheduledAt
451
+ });
452
+ else held.delete(runId);
453
+ } catch (error) {
454
+ held.set(runId, {
455
+ scheduleId: input.scheduleId,
456
+ scheduledAt: input.scheduledAt
457
+ });
458
+ throw error;
459
+ }
514
460
  })();
515
461
  activeWakes.add(wake);
516
462
  wake.finally(() => activeWakes.delete(wake)).catch(() => {});
517
463
  return wake;
518
464
  }
519
465
  });
466
+ /**
467
+ * Catch-up starts after the newest cron-triggered run, also when that run did not finish. A run that is still pending
468
+ * or running inside the catch-up window lost its process, as when every server restarts after a crash. Try those
469
+ * occurrences again at each scan, through the claim: they run when the lease of their process ends and no process
470
+ * finished them.
471
+ */
472
+ async function recoverUnfinishedOccurrences() {
473
+ const catchUpMs = options.catchUpMs ?? 36e5;
474
+ if (catchUpMs <= 0) return;
475
+ const currentMinute = Math.floor((options.now?.() ?? /* @__PURE__ */ new Date()).getTime() / minuteMs) * minuteMs;
476
+ const since = currentMinute - catchUpMs;
477
+ for (const entry of definitions.values()) try {
478
+ let due = 0;
479
+ for (let minute = Math.ceil(since / minuteMs) * minuteMs; minute <= currentMinute; minute += minuteMs) if (isScheduleDue(scheduleCronRecord(entry), new Date(minute))) due++;
480
+ if (due === 0) continue;
481
+ const runs = await options.scheduleRunStore.listRuns({
482
+ idPrefix: "srun_static_",
483
+ limit: due,
484
+ scheduleId: entry.name
485
+ });
486
+ for (const run of runs) {
487
+ if (run.scheduledAt.getTime() < since || !run.id.startsWith("srun_static_")) continue;
488
+ if (run.status !== "pending" && run.status !== "running") continue;
489
+ held.set(run.id, {
490
+ scheduleId: entry.name,
491
+ scheduledAt: run.scheduledAt
492
+ });
493
+ }
494
+ } catch (error) {
495
+ reportError(error);
496
+ }
497
+ }
520
498
  setScheduleRuntimeRegistry(options.registry);
521
499
  setScheduleRunStore(options.scheduleRunStore);
500
+ setScheduleOccurrenceClaims(claims);
522
501
  try {
523
- definitions = await loadStaticDefinitions(options.registry);
502
+ definitions = await loadStaticDefinitions(options.registry, options.timings);
503
+ await recoverUnfinishedOccurrences();
524
504
  await driver.reconcile([...definitions.values()].map(scheduleCronRecord));
525
505
  } catch (error) {
526
506
  try {
@@ -530,8 +510,14 @@ async function installProcessScheduleRuntime(options) {
530
510
  }
531
511
  setScheduleRuntimeRegistry(previousRegistry);
532
512
  setScheduleRunStore(previousScheduleRunStore);
513
+ setScheduleOccurrenceClaims(previousClaims);
533
514
  throw error;
534
515
  }
516
+ const processDefinitions = new Map([...definitions].map(([name, entry]) => [name, {
517
+ cron: entry.cron,
518
+ ...entry.timeZone ? { timeZone: entry.timeZone } : {}
519
+ }]));
520
+ const unregisterDefinitions = registerProcessScheduleDefinitions(processDefinitions);
535
521
  let closePromise;
536
522
  return { close() {
537
523
  if (closePromise) return closePromise;
@@ -540,6 +526,8 @@ async function installProcessScheduleRuntime(options) {
540
526
  while (activeWakes.size > 0) await Promise.allSettled(activeWakes);
541
527
  while (pendingWork.size > 0) await Promise.allSettled(pendingWork);
542
528
  await driver.close();
529
+ unregisterDefinitions();
530
+ if (getScheduleOccurrenceClaims() === claims) setScheduleOccurrenceClaims(void 0);
543
531
  })();
544
532
  } };
545
533
  }