@vite-hub/schedule 0.0.4 → 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 (62) hide show
  1. package/README.md +139 -58
  2. package/dist/console-wEhr0LWn.d.ts +330 -0
  3. package/dist/definition.d.ts +8 -6
  4. package/dist/definition.js +34 -28
  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 +61 -40
  11. package/dist/index.js +27 -7
  12. package/dist/inspect-DTfAo5gS.js +118 -0
  13. package/dist/invariant-DolT9EEx.js +22 -0
  14. package/dist/kv-storage-C0KZZB6v.d.ts +18 -0
  15. package/dist/{kv-storage-DWinmLLy.js → kv-storage-iJChCS5A.js} +2 -2
  16. package/dist/object-Da1zyPCR.js +11 -0
  17. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  18. package/dist/operations-DwZWFIUX.js +184 -0
  19. package/dist/operations.d.ts +84 -0
  20. package/dist/operations.js +318 -0
  21. package/dist/os.d.ts +167 -0
  22. package/dist/os.js +1659 -0
  23. package/dist/registry-module.d.ts +0 -5
  24. package/dist/runtime/console.d.ts +12 -0
  25. package/dist/runtime/console.js +85 -0
  26. package/dist/runtime/kv.d.ts +4 -0
  27. package/dist/{kv-BJ1I9IlJ.js → runtime/kv.js} +1 -1
  28. package/dist/runtime/process.d.ts +53 -5
  29. package/dist/runtime/process.js +501 -251
  30. package/dist/runtime/state.d.ts +2 -13
  31. package/dist/runtime/state.js +2 -2
  32. package/dist/runtime/static.d.ts +44 -12
  33. package/dist/runtime/static.js +2 -150
  34. package/dist/runtime.d.ts +38 -4
  35. package/dist/runtime.js +6 -3
  36. package/dist/started-BuGmnus4.js +201 -0
  37. package/dist/started-Bx7MDbrl.js +146 -0
  38. package/dist/started-errors-p7cu_rI7.js +250 -0
  39. package/dist/state-B-Fuyfb4.js +468 -0
  40. package/dist/state-Do2wV4Tx.d.ts +49 -0
  41. package/dist/static-DQwzzvPg.js +266 -0
  42. package/dist/store-Df0-fzCl.d.ts +53 -0
  43. package/dist/time-zone-SBldrUgt.js +59 -0
  44. package/dist/types-Cw5LjPuc.d.ts +167 -0
  45. package/dist/vite.d.ts +214 -11
  46. package/dist/vite.js +5876 -3
  47. package/dist/wait-until-Dy4Bn3ZN.js +112 -0
  48. package/package.json +65 -24
  49. package/dist/client-DpCD4YFE.js +0 -233
  50. package/dist/discovery-DkFAN7Wd.d.ts +0 -15
  51. package/dist/discovery-DvU3B6iD.js +0 -753
  52. package/dist/due-Bbh4yIxq.js +0 -59
  53. package/dist/execute-B-pii4wf.js +0 -211
  54. package/dist/nuxt.d.ts +0 -19
  55. package/dist/nuxt.js +0 -26
  56. package/dist/runtime/driver.d.ts +0 -26
  57. package/dist/runtime/driver.js +0 -337
  58. package/dist/state-By7WU_ks.js +0 -472
  59. package/dist/store-t-74rsM_.d.ts +0 -48
  60. package/dist/types-Bcje4dLV.d.ts +0 -136
  61. package/dist/vite-BHs17nWX.js +0 -4166
  62. package/dist/wait-until-BzIwzXw4.js +0 -23
@@ -1,285 +1,535 @@
1
- import { t as isRuntimeScheduleDue } from "../due-Bbh4yIxq.js";
2
- import { Cause, Clock, Context, Data, Duration, Effect, Exit, FiberSet, Layer, ManagedRuntime, Queue, Ref, Scheduler, Semaphore } from "effect";
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";
3
11
  //#region src/internal/process-wake-runtime.ts
4
- var ProcessWakeBoundaryError = class extends Data.TaggedError("ProcessWakeBoundaryError") {};
5
- function interruptionError(signal) {
6
- if (signal?.aborted && signal.reason !== void 0) return signal.reason;
7
- const error = /* @__PURE__ */ new Error("[vitehub] Process Schedule Wake Driver operation was interrupted.");
8
- error.name = "AbortError";
9
- return error;
10
- }
11
- function processWakeCauseValues(cause, signal) {
12
- return cause.reasons.map((reason) => {
13
- if (Cause.isFailReason(reason)) return reason.error instanceof ProcessWakeBoundaryError ? reason.error.cause : reason.error;
14
- if (Cause.isDieReason(reason)) return reason.defect;
15
- return interruptionError(signal);
16
- });
17
- }
18
- async function unwrapProcessWakeExit(promise, signal) {
19
- const exit = await promise;
20
- if (Exit.isSuccess(exit)) return exit.value;
21
- const causes = processWakeCauseValues(exit.cause, signal);
22
- if (causes.length === 1) throw causes[0];
23
- throw new AggregateError(causes, "[vitehub] Process Schedule Wake Driver operation failed for multiple reasons.");
24
- }
25
- 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." });
26
22
  return {
27
- active: patch.active ?? state.active,
28
- closed: patch.closed ?? state.closed,
29
- closing: patch.closing ?? state.closing,
30
- dispatched: patch.dispatched ?? state.dispatched,
31
- occurrenceMinute: patch.occurrenceMinute ?? state.occurrenceMinute,
32
- queued: patch.queued ?? state.queued,
33
- schedules: patch.schedules ?? state.schedules,
34
- started: patch.started ?? state.started
23
+ catchUpMs,
24
+ concurrency,
25
+ intervalMs
35
26
  };
36
27
  }
37
28
  function floorUTCMinute(date) {
38
- return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes()));
29
+ return Math.floor(date.getTime() / minuteMs$1) * minuteMs$1;
39
30
  }
40
31
  function occurrenceKey(input) {
41
32
  return `${input.scheduleId}:${input.scheduledAt.getTime()}`;
42
33
  }
43
- function reportError(context, error) {
44
- 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) {
45
67
  try {
46
68
  context.reportError(error);
47
69
  } catch {}
48
- });
49
- }
50
- function wrapBoundary(operation) {
51
- return Effect.try({
52
- try: operation,
53
- catch: (cause) => new ProcessWakeBoundaryError({ cause })
54
- });
55
- }
56
- const makeProcessWakeRuntime = Effect.fn("ScheduleProcessDriver.make")(function* (options) {
57
- const clock = yield* Clock.Clock;
58
- const operationLock = yield* Semaphore.make(1);
59
- const queue = yield* Queue.bounded(options.concurrency);
60
- const enqueueFibers = yield* FiberSet.make();
61
- const scannerFibers = yield* FiberSet.make();
62
- const workerFibers = yield* FiberSet.make();
63
- const state = yield* Ref.make({
64
- active: /* @__PURE__ */ new Set(),
65
- closed: false,
66
- closing: false,
67
- dispatched: /* @__PURE__ */ new Set(),
68
- queued: /* @__PURE__ */ new Map(),
69
- schedules: /* @__PURE__ */ new Map(),
70
- started: false
71
- });
72
- const currentDate = options.now ? wrapBoundary(() => options.now()) : Effect.map(clock.currentTimeMillis, (millis) => new Date(millis));
73
- const claimOccurrence = Effect.fn("ScheduleProcessDriver.claim")(function* (input) {
74
- const key = occurrenceKey(input);
75
- const snapshot = yield* Ref.get(state);
76
- const queuedOccurrence = snapshot.queued.get(key);
77
- if (!queuedOccurrence) return false;
78
- const schedule = snapshot.schedules.get(input.scheduleId);
79
- const due = schedule?.enabled ? yield* wrapBoundary(() => isRuntimeScheduleDue(schedule, input.scheduledAt)) : false;
80
- return yield* Ref.modify(state, (current) => {
81
- if (current.queued.get(key) !== queuedOccurrence || current.schedules.get(input.scheduleId) !== schedule) return [void 0, current];
82
- const queued = new Map(current.queued);
70
+ }
71
+ function take() {
72
+ for (const [key, input] of queued) {
83
73
  queued.delete(key);
84
- if (!due) {
85
- const dispatched = new Set(current.dispatched);
86
- if (current.occurrenceMinute === input.scheduledAt.getTime() && !current.active.has(key)) dispatched.delete(input.scheduleId);
87
- return [false, cloneState(current, {
88
- dispatched,
89
- queued
90
- })];
91
- }
92
- const active = new Set(current.active);
93
- active.add(key);
94
- return [true, cloneState(current, {
95
- active,
96
- queued
97
- })];
98
- }).pipe(Effect.flatMap((claimed) => claimed === void 0 ? claimOccurrence(input) : Effect.succeed(claimed)));
99
- });
100
- const dispatch = Effect.fn("ScheduleProcessDriver.dispatch")(function* (input) {
101
- const key = occurrenceKey(input);
102
- const claimed = yield* claimOccurrence(input).pipe(Effect.match({
103
- onFailure: (error) => ({ error }),
104
- onSuccess: (value) => ({ value })
105
- }));
106
- if ("error" in claimed) {
107
- yield* reportError(options.context, claimed.error.cause);
108
- return;
74
+ if (input.scheduledAt.getTime() < floorUTCMinute(now()) - catchUpMs) continue;
75
+ return input;
109
76
  }
110
- if (!claimed.value) return;
111
- yield* Effect.tryPromise({
112
- try: () => Promise.resolve(options.context.wake(input)),
113
- catch: (cause) => new ProcessWakeBoundaryError({ cause })
114
- }).pipe(Effect.catchTag("ProcessWakeBoundaryError", (error) => reportError(options.context, error.cause)), Effect.ensuring(Ref.update(state, (current) => {
115
- const active = new Set(current.active);
116
- active.delete(key);
117
- return cloneState(current, { active });
118
- })));
119
- });
120
- const worker = Effect.forever(Effect.flatMap(Queue.take(queue), dispatch)).pipe(Effect.catchCauseIf(Cause.isDone, () => Effect.void));
121
- 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({
129
- onFailure: (error) => ({ error }),
130
- onSuccess: (due) => ({ due })
131
- }));
132
- if ("error" in result) yield* reportError(options.context, result.error.cause);
133
- else if (result.due) dueIds.push(schedule.id);
134
- }
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
- };
77
+ }
78
+ async function work() {
79
+ try {
80
+ for (let input = take(); input; input = take()) {
145
81
  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);
82
+ active.add(key);
83
+ try {
84
+ await context.wake(input);
85
+ } catch (error) {
86
+ reportError(error);
87
+ } finally {
88
+ active.delete(key);
89
+ }
150
90
  }
151
- return [occurrences, cloneState(current, {
152
- dispatched,
153
- occurrenceMinute: scheduledAt.getTime(),
154
- queued
155
- })];
156
- });
157
- });
158
- const enqueue = (occurrences) => occurrences.length === 0 ? Effect.void : FiberSet.run(enqueueFibers, Queue.offerAll(queue, occurrences), { startImmediately: true });
159
- const scanIteration = operationLock.withPermits(1)(Effect.flatMap(scanUnlocked(), enqueue)).pipe(Effect.catchTag("ProcessWakeBoundaryError", (error) => reportError(options.context, error.cause)));
160
- const scanLoop = Effect.forever(Effect.andThen(clock.sleep(Duration.millis(options.intervalMs)), FiberSet.run(scannerFibers, scanIteration, { startImmediately: true })));
161
- const reconcile = Effect.fn("ScheduleProcessDriver.reconcile")(function* (records) {
162
- yield* operationLock.withPermits(1)(Effect.gen(function* () {
163
- 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.") }));
165
- const scheduledAt = floorUTCMinute(yield* currentDate);
166
- for (const record of records) {
167
- if (!record.enabled) continue;
168
- yield* wrapBoundary(() => isRuntimeScheduleDue(record, scheduledAt));
91
+ } finally {
92
+ workers -= 1;
93
+ if (workers === 0) onIdle?.();
94
+ }
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) {
105
+ const due = [];
106
+ for (const schedule of entries) for (let minute = Math.ceil(first / minuteMs$1) * minuteMs$1; minute <= last; minute += minuteMs$1) {
107
+ const scheduledAt = new Date(minute);
108
+ let isDue;
109
+ try {
110
+ isDue = isScheduleDue(schedule, scheduledAt);
111
+ } catch (error) {
112
+ reportError(error);
113
+ break;
169
114
  }
170
- const schedules = new Map(records.map((record) => [record.id, { ...record }]));
171
- const startScanner = yield* Ref.modify(state, (current) => {
172
- const dispatched = new Set(current.dispatched);
173
- const queued = new Map(current.queued);
174
- for (const [key, input] of queued) {
175
- const schedule = schedules.get(input.scheduleId);
176
- if (schedule?.enabled && isRuntimeScheduleDue(schedule, input.scheduledAt)) continue;
177
- queued.delete(key);
178
- if (current.occurrenceMinute === input.scheduledAt.getTime() && !current.active.has(key)) dispatched.delete(input.scheduleId);
179
- }
180
- return [!current.started, cloneState(current, {
181
- dispatched,
182
- queued,
183
- schedules
184
- })];
115
+ if (isDue) due.push({
116
+ scheduleId: schedule.id,
117
+ scheduledAt
185
118
  });
186
- if (!snapshot.closing) {
187
- yield* Effect.flatMap(scanUnlocked(), enqueue);
188
- if (startScanner) {
189
- yield* FiberSet.run(scannerFibers, scanLoop, { startImmediately: true });
190
- yield* Ref.update(state, (current) => cloneState(current, { started: true }));
191
- }
119
+ }
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();
127
+ for (const input of due) {
128
+ const key = occurrenceKey(input);
129
+ if (queued.has(key) || active.has(key)) continue;
130
+ if (input.scheduledAt.getTime() === currentMinute) {
131
+ if (dispatched.has(input.scheduleId)) continue;
132
+ dispatched.add(input.scheduleId);
192
133
  }
193
- }));
194
- });
134
+ queued.set(key, input);
135
+ }
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());
154
+ const due = [];
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
+ }
162
+ if (!latest) continue;
163
+ const first = latest === "unknown" ? currentMinute - catchUpMs : Math.max(floorUTCMinute(latest) + minuteMs$1, currentMinute - catchUpMs);
164
+ due.push(...dueOccurrences([schedule], first, currentMinute - minuteMs$1));
165
+ }
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);
177
+ }
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);
198
+ });
199
+ if (workers > 0) await new Promise((resolve) => {
200
+ onIdle = resolve;
201
+ });
202
+ closed = true;
203
+ }
195
204
  return {
196
- close: Effect.fn("ScheduleProcessDriver.close")(function* () {
197
- if (!(yield* operationLock.withPermits(1)(Ref.modify(state, (current) => [!current.closed && !current.closing, cloneState(current, {
198
- closing: true,
199
- queued: /* @__PURE__ */ new Map()
200
- })])))) return;
201
- yield* FiberSet.clear(scannerFibers);
202
- yield* FiberSet.awaitEmpty(enqueueFibers);
203
- yield* Queue.end(queue);
204
- yield* FiberSet.awaitEmpty(workerFibers);
205
- yield* Ref.update(state, (current) => cloneState(current, { closed: true }));
206
- })(),
207
- reconcile
205
+ close() {
206
+ return closePromise ??= close();
207
+ },
208
+ reconcile(entries) {
209
+ if (closed) return Promise.reject(scheduleErrorDiagnostics.SCHEDULE_R0026({ message: "Process Schedule Runtime is closed." }));
210
+ return exclusive(() => reconcile(entries));
211
+ }
212
+ };
213
+ }
214
+ //#endregion
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}`;
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;
208
245
  };
209
- });
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
+ }
210
294
  //#endregion
211
295
  //#region src/runtime/process.ts
212
- const DEFAULT_INTERVAL_MS = 6e4;
213
- const DEFAULT_CONCURRENCY = 1;
214
- function validateOptions(options) {
215
- const intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;
216
- 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.");
296
+ function isStaticScheduleDefinition(value) {
297
+ return isRecordOrFunction(value) && Object.hasOwn(value, "cron") && Object.hasOwn(value, "handler") && typeof value.handler === "function";
298
+ }
299
+ function unwrapDefinition(loaded) {
300
+ if (isRecordOrFunction(loaded) && Object.hasOwn(loaded, "default") && isStaticScheduleDefinition(loaded.default)) return loaded.default;
301
+ return isStaticScheduleDefinition(loaded) ? loaded : void 0;
302
+ }
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 = {}) {
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
+ };
331
+ const definition = unwrapDefinition(await load());
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
+ };
339
+ }));
340
+ return new Map(entries.flatMap((entry) => entry ? [[entry.name, entry]] : []));
341
+ }
342
+ function scheduleCronRecord(entry) {
219
343
  return {
220
- concurrency,
221
- intervalMs
344
+ cron: entry.cron,
345
+ id: entry.name,
346
+ ...entry.timeZone ? { timeZone: entry.timeZone } : {}
222
347
  };
223
348
  }
224
- var ProcessWakeRuntimeService = class extends Context.Service()("@vite-hub/schedule/ProcessWakeRuntime") {};
225
- function createProcessClock() {
226
- const currentTimeMillisUnsafe = () => Date.now();
227
- const currentTimeNanosUnsafe = () => BigInt(currentTimeMillisUnsafe()) * 1000000n;
228
- return {
229
- currentTimeMillis: Effect.sync(currentTimeMillisUnsafe),
230
- currentTimeMillisUnsafe,
231
- currentTimeNanos: Effect.sync(currentTimeNanosUnsafe),
232
- currentTimeNanosUnsafe,
233
- sleep(duration) {
234
- return Effect.callback((resume) => {
235
- const timer = setTimeout(() => resume(Effect.void), Duration.toMillis(duration));
236
- timer.unref?.();
237
- return Effect.sync(() => clearTimeout(timer));
238
- });
239
- }
349
+ function createErrorReporter(onError) {
350
+ return (error) => {
351
+ if (!onError) return;
352
+ try {
353
+ Promise.resolve(onError(error)).catch(() => {});
354
+ } catch {}
240
355
  };
241
356
  }
242
- function createProcessScheduler() {
243
- return new Scheduler.MixedScheduler("async", (run) => {
244
- let canceled = false;
245
- queueMicrotask(() => {
246
- if (!canceled) run();
247
- });
248
- return () => {
249
- canceled = true;
250
- };
251
- });
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;
252
363
  }
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));
364
+ /**
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
366
+ * due minute once, and records each run in `scheduleRunStore`. After a restart it runs the minutes that no process
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.
369
+ */
370
+ async function installProcessScheduleRuntime(options) {
371
+ const previousRegistry = getScheduleRuntimeRegistry();
372
+ const previousScheduleRunStore = getScheduleRunStore();
373
+ const previousClaims = getScheduleOccurrenceClaims();
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();
386
+ const pendingWork = /* @__PURE__ */ new Set();
387
+ const activeWakes = /* @__PURE__ */ new Set();
388
+ let closing = false;
389
+ let definitions = /* @__PURE__ */ new Map();
390
+ function waitUntil(value) {
391
+ const promise = Promise.resolve(value);
392
+ pendingWork.add(promise);
393
+ promise.then(() => pendingWork.delete(promise), (error) => {
394
+ pendingWork.delete(promise);
395
+ reportError(error);
396
+ });
397
+ }
398
+ const driver = createProcessWakeDriver(options, {
399
+ async latestScheduledAt(scheduleId) {
400
+ const [run] = await options.scheduleRunStore.listRuns({
401
+ scheduleId,
402
+ idPrefix: "srun_static_",
403
+ limit: 1
404
+ });
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";
414
+ },
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
+ },
421
+ wake(input) {
422
+ if (closing) return Promise.resolve();
423
+ const wake = (async () => {
424
+ const entry = definitions.get(input.scheduleId);
425
+ if (!entry || !isScheduleDue(scheduleCronRecord(entry), input.scheduledAt)) throw createScheduleError("SCHEDULE_NOT_DUE");
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
+ }
460
+ })();
461
+ activeWakes.add(wake);
462
+ wake.finally(() => activeWakes.delete(wake)).catch(() => {});
463
+ return wake;
267
464
  }
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();
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
274
492
  });
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
493
  }
281
- };
282
- };
494
+ } catch (error) {
495
+ reportError(error);
496
+ }
497
+ }
498
+ setScheduleRuntimeRegistry(options.registry);
499
+ setScheduleRunStore(options.scheduleRunStore);
500
+ setScheduleOccurrenceClaims(claims);
501
+ try {
502
+ definitions = await loadStaticDefinitions(options.registry, options.timings);
503
+ await recoverUnfinishedOccurrences();
504
+ await driver.reconcile([...definitions.values()].map(scheduleCronRecord));
505
+ } catch (error) {
506
+ try {
507
+ await driver.close();
508
+ } catch (closeError) {
509
+ reportError(closeError);
510
+ }
511
+ setScheduleRuntimeRegistry(previousRegistry);
512
+ setScheduleRunStore(previousScheduleRunStore);
513
+ setScheduleOccurrenceClaims(previousClaims);
514
+ throw error;
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);
521
+ let closePromise;
522
+ return { close() {
523
+ if (closePromise) return closePromise;
524
+ closing = true;
525
+ return closePromise = (async () => {
526
+ while (activeWakes.size > 0) await Promise.allSettled(activeWakes);
527
+ while (pendingWork.size > 0) await Promise.allSettled(pendingWork);
528
+ await driver.close();
529
+ unregisterDefinitions();
530
+ if (getScheduleOccurrenceClaims() === claims) setScheduleOccurrenceClaims(void 0);
531
+ })();
532
+ } };
283
533
  }
284
534
  //#endregion
285
- export { createProcessScheduleWakeDriver };
535
+ export { installProcessScheduleRuntime, onShutdown };