@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.
- package/README.md +114 -96
- package/dist/console-wEhr0LWn.d.ts +330 -0
- package/dist/definition.d.ts +6 -2
- package/dist/definition.js +47 -1
- package/dist/due-BVMRQ93v.js +144 -0
- package/dist/durability.d.ts +14 -0
- package/dist/durability.js +23 -0
- package/dist/error-diagnostics-DSkCJC_L.js +266 -0
- package/dist/error-diagnostics-Mpeks7J0.js +166 -0
- package/dist/index.d.ts +59 -5
- package/dist/index.js +27 -2
- package/dist/invariant-DolT9EEx.js +22 -0
- package/dist/{kv-storage-Bv9ocZT-.d.ts → kv-storage-C0KZZB6v.d.ts} +2 -2
- package/dist/{kv-storage-DWinmLLy.js → kv-storage-iJChCS5A.js} +2 -2
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
- package/dist/{operations-gk2qzhYV.js → operations-DwZWFIUX.js} +75 -22
- package/dist/operations.d.ts +27 -4
- package/dist/operations.js +127 -730
- package/dist/os.d.ts +167 -0
- package/dist/os.js +1659 -0
- package/dist/runtime/console.d.ts +12 -0
- package/dist/runtime/console.js +85 -0
- package/dist/runtime/kv.d.ts +1 -1
- package/dist/runtime/kv.js +1 -1
- package/dist/runtime/process.d.ts +32 -5
- package/dist/runtime/process.js +401 -413
- package/dist/runtime/state.d.ts +2 -9
- package/dist/runtime/state.js +2 -2
- package/dist/runtime/static.d.ts +28 -2
- package/dist/runtime/static.js +2 -2
- package/dist/runtime.d.ts +34 -32
- package/dist/runtime.js +6 -5
- package/dist/started-BuGmnus4.js +201 -0
- package/dist/started-Bx7MDbrl.js +146 -0
- package/dist/{execute-BJrgNgQ0.js → started-errors-p7cu_rI7.js} +69 -20
- package/dist/{state-DSxmHPn3.js → state-B-Fuyfb4.js} +42 -22
- package/dist/state-Do2wV4Tx.d.ts +49 -0
- package/dist/{static-6g82xguw.js → static-DQwzzvPg.js} +63 -42
- package/dist/store-Df0-fzCl.d.ts +53 -0
- package/dist/time-zone-SBldrUgt.js +59 -0
- package/dist/{types-CHdV9FQU.d.ts → types-Cw5LjPuc.d.ts} +62 -8
- package/dist/vite.d.ts +255 -2
- package/dist/vite.js +5876 -2
- package/dist/{wait-until-BmIqRo4x.js → wait-until-Dy4Bn3ZN.js} +26 -1
- package/package.json +19 -24
- package/dist/definition-CMiOg1lg.js +0 -111
- package/dist/error-diagnostics-A_8Kp-48.js +0 -116
- package/dist/error-diagnostics-in7mif5s.js +0 -45
- package/dist/nuxt.d.ts +0 -17
- package/dist/nuxt.js +0 -27
- package/dist/store-QAOd8bxm.d.ts +0 -11
- package/dist/vite-BAVyZ8hZ.d.ts +0 -474
- package/dist/vite-BJwZkMrn.js +0 -5193
package/dist/runtime/process.js
CHANGED
|
@@ -1,464 +1,349 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { i as createScheduleError } from "../wait-until-
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
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
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
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
|
-
|
|
140
|
-
|
|
141
|
-
|
|
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
|
|
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
|
|
158
|
-
return
|
|
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
|
-
|
|
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 (
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
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
|
-
|
|
207
|
-
|
|
208
|
-
|
|
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
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
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
|
|
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
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
})
|
|
245
|
-
|
|
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 (
|
|
115
|
+
if (isDue) due.push({
|
|
250
116
|
scheduleId: schedule.id,
|
|
251
117
|
scheduledAt
|
|
252
118
|
});
|
|
253
119
|
}
|
|
254
|
-
return due.sort(
|
|
255
|
-
}
|
|
256
|
-
/** Queues occurrences that are not queued or running yet. The current minute dispatches each Schedule once. */
|
|
257
|
-
|
|
258
|
-
if (
|
|
259
|
-
if (
|
|
260
|
-
|
|
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) ||
|
|
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
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
queued,
|
|
277
|
-
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
const
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
if (!latestScheduledAt ||
|
|
290
|
-
const currentMinute = floorUTCMinute(
|
|
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
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
}
|
|
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)
|
|
299
|
-
due.push(...
|
|
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
|
-
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
const
|
|
309
|
-
if (
|
|
310
|
-
|
|
311
|
-
|
|
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
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
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
|
-
|
|
397
|
-
|
|
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
|
-
|
|
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
|
|
210
|
+
return exclusive(() => reconcile(entries));
|
|
432
211
|
}
|
|
433
212
|
};
|
|
434
213
|
}
|
|
435
214
|
//#endregion
|
|
436
|
-
//#region src/runtime/
|
|
437
|
-
|
|
438
|
-
|
|
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
|
|
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 (
|
|
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
|
-
|
|
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
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
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.
|
|
344
|
+
cron: entry.cron,
|
|
460
345
|
id: entry.name,
|
|
461
|
-
...entry.
|
|
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
|
|
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
|
-
|
|
497
|
-
|
|
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
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
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
|
}
|