@vite-hub/schedule 0.0.3 → 0.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.
Files changed (50) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +199 -65
  3. package/dist/definition-CMiOg1lg.js +111 -0
  4. package/dist/definition.d.ts +4 -6
  5. package/dist/definition.js +2 -42
  6. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  7. package/dist/error-diagnostics-in7mif5s.js +45 -0
  8. package/dist/execute-BJrgNgQ0.js +201 -0
  9. package/dist/index.d.ts +7 -51
  10. package/dist/index.js +2 -7
  11. package/dist/inspect-DTfAo5gS.js +118 -0
  12. package/dist/kv-storage-Bv9ocZT-.d.ts +18 -0
  13. package/dist/nuxt.d.ts +4 -6
  14. package/dist/nuxt.js +3 -1
  15. package/dist/operations-gk2qzhYV.js +131 -0
  16. package/dist/operations-tNUdj3G4.d.ts +212 -0
  17. package/dist/operations.d.ts +61 -0
  18. package/dist/operations.js +921 -0
  19. package/dist/registry-module.d.ts +0 -5
  20. package/dist/runtime/kv.d.ts +4 -0
  21. package/dist/{kv-BJ1I9IlJ.js → runtime/kv.js} +1 -1
  22. package/dist/runtime/process.d.ts +26 -5
  23. package/dist/runtime/process.js +337 -75
  24. package/dist/runtime/state.d.ts +8 -12
  25. package/dist/runtime/state.js +2 -2
  26. package/dist/runtime/static.d.ts +18 -12
  27. package/dist/runtime/static.js +2 -138
  28. package/dist/runtime.d.ts +36 -4
  29. package/dist/runtime.js +5 -3
  30. package/dist/state-DSxmHPn3.js +448 -0
  31. package/dist/static-6g82xguw.js +245 -0
  32. package/dist/store-QAOd8bxm.d.ts +11 -0
  33. package/dist/types-CHdV9FQU.d.ts +113 -0
  34. package/dist/vite-BAVyZ8hZ.d.ts +474 -0
  35. package/dist/vite-BJwZkMrn.js +5193 -0
  36. package/dist/vite.d.ts +2 -38
  37. package/dist/vite.js +2 -2
  38. package/dist/wait-until-BmIqRo4x.js +87 -0
  39. package/package.json +68 -22
  40. package/dist/client-BMFCy0dX.js +0 -233
  41. package/dist/discovery-BZlat3Kc.js +0 -776
  42. package/dist/due-Bbh4yIxq.js +0 -59
  43. package/dist/execute-ClFYvmp9.js +0 -211
  44. package/dist/runtime/driver.d.ts +0 -26
  45. package/dist/runtime/driver.js +0 -334
  46. package/dist/state-By7WU_ks.js +0 -472
  47. package/dist/store-t-74rsM_.d.ts +0 -48
  48. package/dist/types-Bcje4dLV.d.ts +0 -136
  49. package/dist/vite-BX6_KiRw.js +0 -1218
  50. package/dist/wait-until-CR-JjIOb.js +0 -23
@@ -2,8 +2,3 @@ declare module "#vitehub/schedule/registry" {
2
2
  const registry: import("@vite-hub/schedule").ScheduleDefinitionRegistry
3
3
  export default registry
4
4
  }
5
-
6
- declare module "#vitehub/schedule/targets" {
7
- export const scheduleTargetNames: import("@vite-hub/schedule").ScheduleTargetName[]
8
- export type ScheduleTargetName = import("@vite-hub/schedule").ScheduleTargetName
9
- }
@@ -0,0 +1,4 @@
1
+ import { t as ScheduleKVStorage } from "../kv-storage-Bv9ocZT-.js";
2
+ //#region src/runtime/kv.d.ts
3
+ export declare const scheduleKVStorage: ScheduleKVStorage;
4
+ //#endregion
@@ -1,4 +1,4 @@
1
- import { t as createScheduleKVStorage } from "./kv-storage-DWinmLLy.js";
1
+ import { t as createScheduleKVStorage } from "../kv-storage-DWinmLLy.js";
2
2
  import * as kvPackage from "@vite-hub/kv";
3
3
  //#region src/runtime/kv.ts
4
4
  const scheduleKVStorage = createScheduleKVStorage(kvPackage.kv);
@@ -1,11 +1,32 @@
1
- import { RuntimeScheduleWakeDriverFactory } from "./driver.js";
2
-
1
+ import { a as ScheduleDefinitionRegistry, g as ScheduleRunStore } from "../types-CHdV9FQU.js";
2
+ import { onShutdown } from "@vite-hub/runtime/shutdown";
3
3
  //#region src/runtime/process.d.ts
4
- interface ProcessScheduleWakeDriverOptions {
4
+ export interface ProcessScheduleRuntimeOptions {
5
+ /**
6
+ * How far back, in milliseconds, the runtime runs due minutes that it did not check, such as minutes during a
7
+ * restart. It only catches up a Schedule that already has a run. Defaults to one hour. `0` disables it.
8
+ */
9
+ catchUpMs?: number;
10
+ /** Maximum number of Schedule runs at the same time. Defaults to `1`. */
5
11
  concurrency?: number;
12
+ /** Milliseconds between two checks, from 1 to 60000. Defaults to `60000`. */
6
13
  intervalMs?: number;
14
+ /** Clock for tests. Defaults to the system clock. */
7
15
  now?: () => Date;
16
+ onError?: (error: unknown) => void;
17
+ /** Static Schedule Definitions that this process runs on their cron. */
18
+ registry: ScheduleDefinitionRegistry;
19
+ /** Stores Schedule Runs. Catch-up after a restart reads the newest run of each Schedule from it. */
20
+ scheduleRunStore: ScheduleRunStore;
8
21
  }
9
- declare function createProcessScheduleWakeDriver(options?: ProcessScheduleWakeDriverOptions): RuntimeScheduleWakeDriverFactory;
22
+ export interface ScheduleRuntimeController {
23
+ close(): Promise<void>;
24
+ }
25
+ /**
26
+ * Runs Static Schedule Definitions on their cron, in their `timeZone` (UTC by default), in this long-running process. It checks every minute, runs each
27
+ * due minute once, and records each run in `scheduleRunStore`. After a restart it runs the minutes that no process
28
+ * checked, within `catchUpMs`, for Schedules that already have a run. Call `close()` during host shutdown.
29
+ */
30
+ export declare function installProcessScheduleRuntime(options: ProcessScheduleRuntimeOptions): Promise<ScheduleRuntimeController>;
10
31
  //#endregion
11
- export { ProcessScheduleWakeDriverOptions, createProcessScheduleWakeDriver };
32
+ export { onShutdown };
@@ -1,10 +1,122 @@
1
- import { t as isRuntimeScheduleDue } from "../due-Bbh4yIxq.js";
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";
2
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
3
115
  //#region src/internal/process-wake-runtime.ts
4
116
  var ProcessWakeBoundaryError = class extends Data.TaggedError("ProcessWakeBoundaryError") {};
5
117
  function interruptionError(signal) {
6
118
  if (signal?.aborted && signal.reason !== void 0) return signal.reason;
7
- const error = /* @__PURE__ */ new Error("[vitehub] Process Schedule Wake Driver operation was interrupted.");
119
+ const error = scheduleErrorDiagnostics.SCHEDULE_R0001({ message: "[vitehub] Process Schedule Wake Driver operation was interrupted." });
8
120
  error.name = "AbortError";
9
121
  return error;
10
122
  }
@@ -30,12 +142,14 @@ function cloneState(state, patch) {
30
142
  dispatched: patch.dispatched ?? state.dispatched,
31
143
  occurrenceMinute: patch.occurrenceMinute ?? state.occurrenceMinute,
32
144
  queued: patch.queued ?? state.queued,
145
+ scannedThrough: patch.scannedThrough ?? state.scannedThrough,
33
146
  schedules: patch.schedules ?? state.schedules,
34
147
  started: patch.started ?? state.started
35
148
  };
36
149
  }
150
+ const minuteMs = 6e4;
37
151
  function floorUTCMinute(date) {
38
- return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes()));
152
+ return /* @__PURE__ */ new Date(Math.floor(date.getTime() / minuteMs) * minuteMs);
39
153
  }
40
154
  function occurrenceKey(input) {
41
155
  return `${input.scheduleId}:${input.scheduledAt.getTime()}`;
@@ -76,7 +190,7 @@ const makeProcessWakeRuntime = Effect.fn("ScheduleProcessDriver.make")(function*
76
190
  const queuedOccurrence = snapshot.queued.get(key);
77
191
  if (!queuedOccurrence) return false;
78
192
  const schedule = snapshot.schedules.get(input.scheduleId);
79
- const due = schedule?.enabled ? yield* wrapBoundary(() => isRuntimeScheduleDue(schedule, input.scheduledAt)) : false;
193
+ const due = schedule ? yield* wrapBoundary(() => isScheduleDue(schedule, input.scheduledAt)) : false;
80
194
  return yield* Ref.modify(state, (current) => {
81
195
  if (current.queued.get(key) !== queuedOccurrence || current.schedules.get(input.scheduleId) !== schedule) return [void 0, current];
82
196
  const queued = new Map(current.queued);
@@ -119,41 +233,72 @@ const makeProcessWakeRuntime = Effect.fn("ScheduleProcessDriver.make")(function*
119
233
  });
120
234
  const worker = Effect.forever(Effect.flatMap(Queue.take(queue), dispatch)).pipe(Effect.catchCauseIf(Cause.isDone, () => Effect.void));
121
235
  yield* Effect.forEach(Array.from({ length: options.concurrency }), () => FiberSet.run(workerFibers, worker, { startImmediately: true }), { discard: true });
122
- const scanUnlocked = Effect.fn("ScheduleProcessDriver.scan")(function* () {
123
- const scheduledAt = floorUTCMinute(yield* currentDate);
124
- const snapshot = yield* Ref.get(state);
125
- const dueIds = [];
126
- for (const schedule of snapshot.schedules.values()) {
127
- if (!schedule.enabled) continue;
128
- const result = yield* wrapBoundary(() => isRuntimeScheduleDue(schedule, scheduledAt)).pipe(Effect.match({
236
+ /** Due occurrences of `schedules` from `first` through `last`, oldest first. */
237
+ const dueOccurrences = Effect.fn("ScheduleProcessDriver.due")(function* (schedules, first, last) {
238
+ const due = [];
239
+ for (const schedule of schedules) for (let minute = Math.ceil(first / minuteMs) * minuteMs; minute <= last; minute += minuteMs) {
240
+ const scheduledAt = new Date(minute);
241
+ const result = yield* wrapBoundary(() => isScheduleDue(schedule, scheduledAt)).pipe(Effect.match({
129
242
  onFailure: (error) => ({ error }),
130
- onSuccess: (due) => ({ due })
243
+ onSuccess: (isDue) => ({ isDue })
131
244
  }));
132
- if ("error" in result) yield* reportError(options.context, result.error.cause);
133
- else if (result.due) dueIds.push(schedule.id);
245
+ if ("error" in result) {
246
+ yield* reportError(options.context, result.error.cause);
247
+ break;
248
+ }
249
+ if (result.isDue) due.push({
250
+ scheduleId: schedule.id,
251
+ scheduledAt
252
+ });
134
253
  }
135
- return yield* Ref.modify(state, (current) => {
136
- if (current.closed || current.closing) return [[], current];
137
- const dispatched = current.occurrenceMinute === scheduledAt.getTime() ? new Set(current.dispatched) : /* @__PURE__ */ new Set();
138
- const queued = new Map(current.queued);
139
- const occurrences = [];
140
- for (const scheduleId of dueIds) {
141
- const input = {
142
- scheduleId,
143
- scheduledAt
144
- };
145
- const key = occurrenceKey(input);
146
- if (dispatched.has(scheduleId) || queued.has(key) || current.active.has(key)) continue;
147
- dispatched.add(scheduleId);
148
- queued.set(key, input);
149
- occurrences.push(input);
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 = [];
263
+ for (const input of due) {
264
+ const key = occurrenceKey(input);
265
+ if (queued.has(key) || current.active.has(key)) continue;
266
+ if (input.scheduledAt.getTime() === currentMinute) {
267
+ if (dispatched.has(input.scheduleId)) continue;
268
+ dispatched.add(input.scheduleId);
150
269
  }
151
- return [occurrences, cloneState(current, {
152
- dispatched,
153
- occurrenceMinute: scheduledAt.getTime(),
154
- queued
155
- })];
156
- });
270
+ queued.set(key, input);
271
+ occurrences.push(input);
272
+ }
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();
291
+ 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)));
297
+ if (!latest) continue;
298
+ const first = Math.max(floorUTCMinute(latest).getTime() + minuteMs, currentMinute - options.catchUpMs);
299
+ due.push(...yield* dueOccurrences([schedule], first, currentMinute - minuteMs));
300
+ }
301
+ return yield* queueOccurrences(due.sort((left, right) => left.scheduledAt.getTime() - right.scheduledAt.getTime()), currentMinute);
157
302
  });
158
303
  const enqueue = (occurrences) => occurrences.length === 0 ? Effect.void : FiberSet.run(enqueueFibers, Queue.offerAll(queue, occurrences), { startImmediately: true });
159
304
  const scanIteration = operationLock.withPermits(1)(Effect.flatMap(scanUnlocked(), enqueue)).pipe(Effect.catchTag("ProcessWakeBoundaryError", (error) => reportError(options.context, error.cause)));
@@ -161,19 +306,16 @@ const makeProcessWakeRuntime = Effect.fn("ScheduleProcessDriver.make")(function*
161
306
  const reconcile = Effect.fn("ScheduleProcessDriver.reconcile")(function* (records) {
162
307
  yield* operationLock.withPermits(1)(Effect.gen(function* () {
163
308
  const snapshot = yield* Ref.get(state);
164
- if (snapshot.closed) return yield* Effect.fail(new ProcessWakeBoundaryError({ cause: /* @__PURE__ */ new Error("Process Schedule Wake Driver is closed.") }));
309
+ if (snapshot.closed) return yield* Effect.fail(new ProcessWakeBoundaryError({ cause: scheduleErrorDiagnostics.SCHEDULE_R0002({ message: "Process Schedule Wake Driver is closed." }) }));
165
310
  const scheduledAt = floorUTCMinute(yield* currentDate);
166
- for (const record of records) {
167
- if (!record.enabled) continue;
168
- yield* wrapBoundary(() => isRuntimeScheduleDue(record, scheduledAt));
169
- }
311
+ for (const record of records) yield* wrapBoundary(() => isScheduleDue(record, scheduledAt));
170
312
  const schedules = new Map(records.map((record) => [record.id, { ...record }]));
171
313
  const startScanner = yield* Ref.modify(state, (current) => {
172
314
  const dispatched = new Set(current.dispatched);
173
315
  const queued = new Map(current.queued);
174
316
  for (const [key, input] of queued) {
175
317
  const schedule = schedules.get(input.scheduleId);
176
- if (schedule?.enabled && isRuntimeScheduleDue(schedule, input.scheduledAt)) continue;
318
+ if (schedule && isScheduleDue(schedule, input.scheduledAt)) continue;
177
319
  queued.delete(key);
178
320
  if (current.occurrenceMinute === input.scheduledAt.getTime() && !current.active.has(key)) dispatched.delete(input.scheduleId);
179
321
  }
@@ -184,6 +326,7 @@ const makeProcessWakeRuntime = Effect.fn("ScheduleProcessDriver.make")(function*
184
326
  })];
185
327
  });
186
328
  if (!snapshot.closing) {
329
+ if (startScanner) yield* Effect.flatMap(catchUpUnlocked(records), enqueue);
187
330
  yield* Effect.flatMap(scanUnlocked(), enqueue);
188
331
  if (startScanner) {
189
332
  yield* FiberSet.run(scannerFibers, scanLoop, { startImmediately: true });
@@ -207,16 +350,18 @@ const makeProcessWakeRuntime = Effect.fn("ScheduleProcessDriver.make")(function*
207
350
  reconcile
208
351
  };
209
352
  });
210
- //#endregion
211
- //#region src/runtime/process.ts
212
353
  const DEFAULT_INTERVAL_MS = 6e4;
213
354
  const DEFAULT_CONCURRENCY = 1;
214
- function validateOptions(options) {
355
+ const DEFAULT_CATCH_UP_MS = 36e5;
356
+ function validateDriverOptions(options) {
215
357
  const intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;
216
358
  const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
217
- if (!Number.isFinite(intervalMs) || intervalMs <= 0 || intervalMs > DEFAULT_INTERVAL_MS) throw new TypeError("Process Schedule Wake Driver intervalMs must be a positive number no greater than 60000.");
218
- if (!Number.isInteger(concurrency) || concurrency < 1) throw new TypeError("Process Schedule Wake Driver concurrency must be a positive integer.");
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." });
219
363
  return {
364
+ catchUpMs,
220
365
  concurrency,
221
366
  intervalMs
222
367
  };
@@ -225,11 +370,14 @@ var ProcessWakeRuntimeService = class extends Context.Service()("@vite-hub/sched
225
370
  function createProcessClock() {
226
371
  const currentTimeMillisUnsafe = () => Date.now();
227
372
  const currentTimeNanosUnsafe = () => BigInt(currentTimeMillisUnsafe()) * 1000000n;
373
+ const monotonicTimeNanosUnsafe = () => process.hrtime.bigint();
228
374
  return {
229
375
  currentTimeMillis: Effect.sync(currentTimeMillisUnsafe),
230
376
  currentTimeMillisUnsafe,
231
377
  currentTimeNanos: Effect.sync(currentTimeNanosUnsafe),
232
378
  currentTimeNanosUnsafe,
379
+ monotonicTimeNanos: Effect.sync(monotonicTimeNanosUnsafe),
380
+ monotonicTimeNanosUnsafe,
233
381
  sleep(duration) {
234
382
  return Effect.callback((resume) => {
235
383
  const timer = setTimeout(() => resume(Effect.void), Duration.toMillis(duration));
@@ -250,36 +398,150 @@ function createProcessScheduler() {
250
398
  };
251
399
  });
252
400
  }
253
- function createProcessScheduleWakeDriver(options = {}) {
254
- return (context) => {
255
- const { concurrency, intervalMs } = validateOptions(options);
256
- const ProcessWakeRuntimeLive = Layer.effect(ProcessWakeRuntimeService, makeProcessWakeRuntime({
257
- concurrency,
258
- context,
259
- intervalMs,
260
- now: options.now
261
- })).pipe(Layer.provide(Layer.mergeAll(Layer.succeed(Clock.Clock, createProcessClock()), Layer.succeed(Scheduler.Scheduler, createProcessScheduler()))));
262
- const runtime = ManagedRuntime.make(ProcessWakeRuntimeLive);
263
- let closePromise;
264
- let closed = false;
265
- function run(effect) {
266
- return unwrapProcessWakeExit(runtime.runPromiseExit(effect));
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));
419
+ }
420
+ return {
421
+ 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;
428
+ },
429
+ reconcile(entries) {
430
+ if (closed) return Promise.reject(scheduleErrorDiagnostics.SCHEDULE_R0026({ message: "Process Schedule Runtime is closed." }));
431
+ return run(Effect.flatMap(ProcessWakeRuntimeService, (service) => service.reconcile(entries)));
267
432
  }
268
- return {
269
- close() {
270
- if (closePromise) return closePromise;
271
- closePromise = run(Effect.flatMap(ProcessWakeRuntimeService, (service) => service.close)).then(() => {
272
- closed = true;
273
- return runtime.dispose();
274
- });
275
- return closePromise;
276
- },
277
- reconcile(records) {
278
- if (closed) return Promise.reject(/* @__PURE__ */ new Error("Process Schedule Wake Driver is closed."));
279
- return run(Effect.flatMap(ProcessWakeRuntimeService, (service) => service.reconcile(records)));
280
- }
281
- };
282
433
  };
283
434
  }
284
435
  //#endregion
285
- export { createProcessScheduleWakeDriver };
436
+ //#region src/runtime/process.ts
437
+ function isObject(value) {
438
+ return Object(value) === value && !Array.isArray(value);
439
+ }
440
+ function isStaticScheduleDefinition(value) {
441
+ return isObject(value) && Object.hasOwn(value, "cron") && Object.hasOwn(value, "handler") && typeof value.handler === "function";
442
+ }
443
+ function unwrapDefinition(loaded) {
444
+ if (isObject(loaded) && Object.hasOwn(loaded, "default") && isStaticScheduleDefinition(loaded.default)) return loaded.default;
445
+ return isStaticScheduleDefinition(loaded) ? loaded : void 0;
446
+ }
447
+ async function loadStaticDefinitions(registry) {
448
+ const entries = await Promise.all(Object.entries(registry).map(async ([name, load]) => {
449
+ const definition = unwrapDefinition(await load());
450
+ return definition ? {
451
+ definition,
452
+ name
453
+ } : void 0;
454
+ }));
455
+ return new Map(entries.flatMap((entry) => entry ? [[entry.name, entry]] : []));
456
+ }
457
+ function scheduleCronRecord(entry) {
458
+ return {
459
+ cron: entry.definition.cron,
460
+ id: entry.name,
461
+ ...entry.definition.timeZone ? { timeZone: entry.definition.timeZone } : {}
462
+ };
463
+ }
464
+ function createErrorReporter(onError) {
465
+ return (error) => {
466
+ if (!onError) return;
467
+ try {
468
+ Promise.resolve(onError(error)).catch(() => {});
469
+ } catch {}
470
+ };
471
+ }
472
+ /**
473
+ * 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
+ * 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.
476
+ */
477
+ async function installProcessScheduleRuntime(options) {
478
+ const previousRegistry = getScheduleRuntimeRegistry();
479
+ const previousScheduleRunStore = getScheduleRunStore();
480
+ const reportError = createErrorReporter(options.onError);
481
+ const pendingWork = /* @__PURE__ */ new Set();
482
+ const activeWakes = /* @__PURE__ */ new Set();
483
+ let closing = false;
484
+ let definitions = /* @__PURE__ */ new Map();
485
+ function waitUntil(value) {
486
+ const promise = Promise.resolve(value);
487
+ pendingWork.add(promise);
488
+ promise.then(() => pendingWork.delete(promise), (error) => {
489
+ pendingWork.delete(promise);
490
+ reportError(error);
491
+ });
492
+ }
493
+ const driver = createProcessWakeDriver(options, {
494
+ async latestScheduledAt(scheduleId) {
495
+ const [run] = await options.scheduleRunStore.listRuns({
496
+ limit: 1,
497
+ scheduleId
498
+ });
499
+ return run?.scheduledAt;
500
+ },
501
+ reportError,
502
+ wake(input) {
503
+ if (closing) return Promise.resolve();
504
+ const wake = (async () => {
505
+ const entry = definitions.get(input.scheduleId);
506
+ 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
+ });
514
+ })();
515
+ activeWakes.add(wake);
516
+ wake.finally(() => activeWakes.delete(wake)).catch(() => {});
517
+ return wake;
518
+ }
519
+ });
520
+ setScheduleRuntimeRegistry(options.registry);
521
+ setScheduleRunStore(options.scheduleRunStore);
522
+ try {
523
+ definitions = await loadStaticDefinitions(options.registry);
524
+ await driver.reconcile([...definitions.values()].map(scheduleCronRecord));
525
+ } catch (error) {
526
+ try {
527
+ await driver.close();
528
+ } catch (closeError) {
529
+ reportError(closeError);
530
+ }
531
+ setScheduleRuntimeRegistry(previousRegistry);
532
+ setScheduleRunStore(previousScheduleRunStore);
533
+ throw error;
534
+ }
535
+ let closePromise;
536
+ return { close() {
537
+ if (closePromise) return closePromise;
538
+ closing = true;
539
+ return closePromise = (async () => {
540
+ while (activeWakes.size > 0) await Promise.allSettled(activeWakes);
541
+ while (pendingWork.size > 0) await Promise.allSettled(pendingWork);
542
+ await driver.close();
543
+ })();
544
+ } };
545
+ }
546
+ //#endregion
547
+ export { installProcessScheduleRuntime, onShutdown };
@@ -1,13 +1,9 @@
1
- import { a as RuntimeScheduleStore, b as ScheduleRunStore, d as ScheduleDefinitionRegistry, p as ScheduleRegistryDefinition } from "../types-Bcje4dLV.js";
2
-
1
+ import { a as ScheduleDefinitionRegistry, g as ScheduleRunStore, s as ScheduleRegistryDefinition } from "../types-CHdV9FQU.js";
3
2
  //#region src/runtime/state.d.ts
4
- declare function setScheduleRuntimeRegistry(registry: ScheduleDefinitionRegistry | undefined): void;
5
- declare function getScheduleRuntimeRegistry(): ScheduleDefinitionRegistry | undefined;
6
- declare function setRuntimeScheduleStore(store: RuntimeScheduleStore | undefined): void;
7
- declare function getRuntimeScheduleStore(): RuntimeScheduleStore;
8
- declare function setScheduleRunStore(store: ScheduleRunStore | undefined): void;
9
- declare function getScheduleRunStore(): ScheduleRunStore;
10
- declare function loadScheduleDefinition(name: string): Promise<ScheduleRegistryDefinition | undefined>;
11
- declare function resetScheduleRuntime(): void;
12
- //#endregion
13
- export { getRuntimeScheduleStore, getScheduleRunStore, getScheduleRuntimeRegistry, loadScheduleDefinition, resetScheduleRuntime, setRuntimeScheduleStore, setScheduleRunStore, setScheduleRuntimeRegistry };
3
+ export declare function setScheduleRuntimeRegistry(registry: ScheduleDefinitionRegistry | undefined): void;
4
+ export declare function getScheduleRuntimeRegistry(): ScheduleDefinitionRegistry | undefined;
5
+ export declare function setScheduleRunStore(store: ScheduleRunStore | undefined): void;
6
+ export declare function getScheduleRunStore(): ScheduleRunStore;
7
+ export declare function loadScheduleDefinition(name: string): Promise<ScheduleRegistryDefinition | undefined>;
8
+ export declare function resetScheduleRuntime(): void;
9
+ //#endregion
@@ -1,2 +1,2 @@
1
- import { a as resetScheduleRuntime, c as setScheduleRuntimeRegistry, i as loadScheduleDefinition, n as getScheduleRunStore, o as setRuntimeScheduleStore, r as getScheduleRuntimeRegistry, s as setScheduleRunStore, t as getRuntimeScheduleStore } from "../state-By7WU_ks.js";
2
- export { getRuntimeScheduleStore, getScheduleRunStore, getScheduleRuntimeRegistry, loadScheduleDefinition, resetScheduleRuntime, setRuntimeScheduleStore, setScheduleRunStore, setScheduleRuntimeRegistry };
1
+ import { a as setScheduleRunStore, i as resetScheduleRuntime, n as getScheduleRuntimeRegistry, o as setScheduleRuntimeRegistry, r as loadScheduleDefinition, t as getScheduleRunStore } from "../state-DSxmHPn3.js";
2
+ export { getScheduleRunStore, getScheduleRuntimeRegistry, loadScheduleDefinition, resetScheduleRuntime, setScheduleRunStore, setScheduleRuntimeRegistry };
@@ -1,20 +1,19 @@
1
- import { c as ScheduleDefinition, d as ScheduleDefinitionRegistry, g as ScheduleRunContext } from "../types-Bcje4dLV.js";
2
-
1
+ import { a as ScheduleDefinitionRegistry, n as ScheduleDefinition, u as ScheduleRunContext } from "../types-CHdV9FQU.js";
3
2
  //#region src/runtime/static.d.ts
4
- interface ExecuteStaticScheduleOptions {
3
+ export interface ExecuteStaticScheduleOptions {
5
4
  cron: string;
6
5
  definition: ScheduleDefinition;
7
6
  name: string;
8
7
  scheduledAt?: Date;
9
8
  waitUntil?: (promise: PromiseLike<unknown>) => void;
10
9
  }
11
- interface ExecuteMatchingStaticSchedulesOptions {
10
+ export interface ExecuteMatchingStaticSchedulesOptions {
12
11
  cron: string;
13
12
  registry: ScheduleDefinitionRegistry;
14
13
  scheduledAt?: Date;
15
14
  waitUntil?: (promise: PromiseLike<unknown>) => void;
16
15
  }
17
- interface ExecuteCloudflareStaticSchedulesOptions {
16
+ export interface ExecuteCloudflareStaticSchedulesOptions {
18
17
  registry: ScheduleDefinitionRegistry;
19
18
  waitUntil?: (promise: PromiseLike<unknown>) => void;
20
19
  }
@@ -27,15 +26,22 @@ interface CloudflareScheduledEventLike {
27
26
  cron?: string;
28
27
  scheduledTime?: number | string | Date;
29
28
  }
30
- interface StaticScheduleRun extends ScheduleRunContext {
29
+ export interface StaticScheduleRun extends ScheduleRunContext {
31
30
  cron: string;
32
31
  scheduleId: string;
33
32
  }
34
- declare function createStaticScheduleRun(options: Omit<ExecuteStaticScheduleOptions, "definition" | "waitUntil"> & {
33
+ export declare function missingScheduleDefinitionError(name: string): Error;
34
+ /**
35
+ * Checks the `Authorization` header of a Vercel Cron request against `CRON_SECRET` in constant time.
36
+ */
37
+ export declare function isScheduleCronAuthorized(authorization: string | null | undefined, cronSecret: string): boolean;
38
+ export declare function normalizeCron(cron: string): string;
39
+ export declare function normalizeScheduleRuntimeError(error: unknown): Error;
40
+ export declare function createStaticScheduleRun(options: Omit<ExecuteStaticScheduleOptions, "definition" | "waitUntil"> & {
35
41
  waitUntil: NonNullable<ExecuteStaticScheduleOptions["waitUntil"]>;
36
42
  }): StaticScheduleRun;
37
- declare function executeStaticSchedule(options: ExecuteStaticScheduleOptions): Promise<unknown>;
38
- declare function executeMatchingStaticSchedules(options: ExecuteMatchingStaticSchedulesOptions): Promise<unknown[]>;
39
- declare function executeCloudflareStaticSchedules(event: CloudflareScheduledEventLike, options: ExecuteCloudflareStaticSchedulesOptions): Promise<unknown[]>;
40
- //#endregion
41
- export { ExecuteCloudflareStaticSchedulesOptions, ExecuteMatchingStaticSchedulesOptions, ExecuteStaticScheduleOptions, StaticScheduleRun, createStaticScheduleRun, executeCloudflareStaticSchedules, executeMatchingStaticSchedules, executeStaticSchedule };
43
+ export declare function executeStaticSchedule(options: ExecuteStaticScheduleOptions): Promise<unknown>;
44
+ export declare function executeMatchingStaticSchedules(options: ExecuteMatchingStaticSchedulesOptions): Promise<unknown[]>;
45
+ export declare function executeCloudflareStaticSchedules(event: CloudflareScheduledEventLike, options: ExecuteCloudflareStaticSchedulesOptions): Promise<unknown[]>;
46
+ export declare function unwrapScheduleDefinition(loaded: unknown): ScheduleDefinition | undefined;
47
+ //#endregion