@vite-hub/schedule 0.0.4 → 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 (49) hide show
  1. package/README.md +68 -5
  2. package/dist/definition-CMiOg1lg.js +111 -0
  3. package/dist/definition.d.ts +4 -6
  4. package/dist/definition.js +2 -42
  5. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  6. package/dist/error-diagnostics-in7mif5s.js +45 -0
  7. package/dist/execute-BJrgNgQ0.js +201 -0
  8. package/dist/index.d.ts +7 -40
  9. package/dist/index.js +2 -7
  10. package/dist/inspect-DTfAo5gS.js +118 -0
  11. package/dist/kv-storage-Bv9ocZT-.d.ts +18 -0
  12. package/dist/nuxt.d.ts +4 -6
  13. package/dist/nuxt.js +2 -1
  14. package/dist/operations-gk2qzhYV.js +131 -0
  15. package/dist/operations-tNUdj3G4.d.ts +212 -0
  16. package/dist/operations.d.ts +61 -0
  17. package/dist/operations.js +921 -0
  18. package/dist/registry-module.d.ts +0 -5
  19. package/dist/runtime/kv.d.ts +4 -0
  20. package/dist/{kv-BJ1I9IlJ.js → runtime/kv.js} +1 -1
  21. package/dist/runtime/process.d.ts +26 -5
  22. package/dist/runtime/process.js +337 -75
  23. package/dist/runtime/state.d.ts +8 -12
  24. package/dist/runtime/state.js +2 -2
  25. package/dist/runtime/static.d.ts +18 -12
  26. package/dist/runtime/static.js +2 -150
  27. package/dist/runtime.d.ts +36 -4
  28. package/dist/runtime.js +5 -3
  29. package/dist/state-DSxmHPn3.js +448 -0
  30. package/dist/static-6g82xguw.js +245 -0
  31. package/dist/store-QAOd8bxm.d.ts +11 -0
  32. package/dist/types-CHdV9FQU.d.ts +113 -0
  33. package/dist/vite-BAVyZ8hZ.d.ts +474 -0
  34. package/dist/{vite-BHs17nWX.js → vite-BJwZkMrn.js} +1366 -339
  35. package/dist/vite.d.ts +2 -52
  36. package/dist/vite.js +2 -3
  37. package/dist/wait-until-BmIqRo4x.js +87 -0
  38. package/package.json +67 -21
  39. package/dist/client-DpCD4YFE.js +0 -233
  40. package/dist/discovery-DkFAN7Wd.d.ts +0 -15
  41. package/dist/discovery-DvU3B6iD.js +0 -753
  42. package/dist/due-Bbh4yIxq.js +0 -59
  43. package/dist/execute-B-pii4wf.js +0 -211
  44. package/dist/runtime/driver.d.ts +0 -26
  45. package/dist/runtime/driver.js +0 -337
  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/wait-until-BzIwzXw4.js +0 -23
@@ -1,59 +0,0 @@
1
- import { parseCronExpression } from "cron-schedule";
2
- //#region src/runtime/due.ts
3
- const weekdayIndexes = new Map([
4
- ["Sun", 0],
5
- ["Mon", 1],
6
- ["Tue", 2],
7
- ["Wed", 3],
8
- ["Thu", 4],
9
- ["Fri", 5],
10
- ["Sat", 6]
11
- ]);
12
- function scheduleDateFields(scheduledAt, timeZone) {
13
- if (!timeZone) return {
14
- day: scheduledAt.getUTCDate(),
15
- hour: scheduledAt.getUTCHours(),
16
- minute: scheduledAt.getUTCMinutes(),
17
- month: scheduledAt.getUTCMonth(),
18
- weekday: scheduledAt.getUTCDay()
19
- };
20
- const parts = new Intl.DateTimeFormat("en-US", {
21
- day: "numeric",
22
- hour: "numeric",
23
- hourCycle: "h23",
24
- minute: "numeric",
25
- month: "numeric",
26
- timeZone,
27
- weekday: "short"
28
- }).formatToParts(scheduledAt);
29
- const values = new Map(parts.map((part) => [part.type, part.value]));
30
- const weekday = weekdayIndexes.get(values.get("weekday") || "");
31
- const day = Number(values.get("day"));
32
- const hour = Number(values.get("hour"));
33
- const minute = Number(values.get("minute"));
34
- const month = Number(values.get("month")) - 1;
35
- if (weekday === void 0 || [
36
- day,
37
- hour,
38
- minute,
39
- month
40
- ].some((value) => !Number.isInteger(value))) throw new TypeError(`Runtime Schedule time zone could not resolve calendar fields: ${timeZone}`);
41
- return {
42
- day,
43
- hour,
44
- minute,
45
- month,
46
- weekday
47
- };
48
- }
49
- function isRuntimeScheduleDue(schedule, scheduledAt) {
50
- if (scheduledAt.getUTCSeconds() !== 0 || scheduledAt.getUTCMilliseconds() !== 0) return false;
51
- if (schedule.cron.trim().split(/\s+/).length !== 5) throw new TypeError(`Runtime Schedule "${schedule.id}" must use a five-field cron expression.`);
52
- const cron = parseCronExpression(schedule.cron);
53
- const { day, hour, minute, month, weekday } = scheduleDateFields(scheduledAt, schedule.timeZone);
54
- if (!cron.minutes.includes(minute) || !cron.hours.includes(hour) || !cron.months.includes(month)) return false;
55
- if (cron.days.length !== 31 && cron.weekdays.length !== 7) return cron.days.includes(day) || cron.weekdays.includes(weekday);
56
- return cron.days.includes(day) && cron.weekdays.includes(weekday);
57
- }
58
- //#endregion
59
- export { isRuntimeScheduleDue as t };
@@ -1,211 +0,0 @@
1
- import { h as invalidScheduleValueDetails, i as loadScheduleDefinition, m as createScheduleError, n as getScheduleRunStore, p as assertRuntimeScheduleId, t as getRuntimeScheduleStore } from "./state-By7WU_ks.js";
2
- import { t as isRuntimeScheduleDue } from "./due-Bbh4yIxq.js";
3
- import { t as createLocalWaitUntil } from "./wait-until-BzIwzXw4.js";
4
- //#region ../internal/src/runtime/random.ts
5
- function randomId(prefix) {
6
- const body = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
7
- return prefix ? `${prefix}_${body}` : body;
8
- }
9
- //#endregion
10
- //#region src/runtime/execute.ts
11
- function assertRuntimeExecuteOptionsObject(options) {
12
- if (typeof options !== "object" || options === null || Array.isArray(options)) throw createScheduleError("SCHEDULE_INVALID_INPUT", { details: invalidScheduleValueDetails("options", options) });
13
- }
14
- function normalizeRunSource(source) {
15
- return source ?? "direct";
16
- }
17
- function toRunId(source, scheduleId, scheduledAt) {
18
- return `srun_${normalizeRunSource(source)}_${encodeURIComponent(scheduleId)}_${scheduledAt.toISOString()}`;
19
- }
20
- function validateScheduledAt(scheduledAt) {
21
- if (!(scheduledAt instanceof Date) || Number.isNaN(scheduledAt.getTime())) throw createScheduleError("SCHEDULE_INVALID_SCHEDULED_AT", { details: invalidScheduleValueDetails("scheduledAt", scheduledAt) });
22
- return scheduledAt;
23
- }
24
- function toRunError(error) {
25
- if (error instanceof Error) return {
26
- message: error.message,
27
- name: error.name,
28
- stack: error.stack
29
- };
30
- return { message: String(error) };
31
- }
32
- function requireUpdatedRun(run) {
33
- if (!run) throw createScheduleError("SCHEDULE_RUN_NOT_FOUND");
34
- return run;
35
- }
36
- async function createOrGetRun(options) {
37
- const store = options.runStore ?? getScheduleRunStore();
38
- const id = toRunId(options.source, options.scheduleId, options.scheduledAt);
39
- const existing = await store.getRun(id);
40
- if (existing) return {
41
- created: false,
42
- run: existing
43
- };
44
- const now = /* @__PURE__ */ new Date();
45
- const runInput = {
46
- attemptCount: 0,
47
- createdAt: now,
48
- id,
49
- scheduleId: options.scheduleId,
50
- scheduledAt: options.scheduledAt,
51
- status: "pending",
52
- target: options.target,
53
- updatedAt: now
54
- };
55
- try {
56
- return {
57
- created: true,
58
- run: await store.createRun(runInput)
59
- };
60
- } catch (error) {
61
- const run = await store.getRun(id);
62
- if (run) return {
63
- created: false,
64
- run
65
- };
66
- throw error;
67
- }
68
- }
69
- async function startAttempt(run, store = getScheduleRunStore()) {
70
- const now = /* @__PURE__ */ new Date();
71
- const attempt = await store.createAttempt({
72
- createdAt: now,
73
- id: randomId("satt"),
74
- runId: run.id,
75
- startedAt: now,
76
- status: "running",
77
- updatedAt: now
78
- });
79
- await store.updateRun(run.id, {
80
- attemptCount: run.attemptCount + 1,
81
- startedAt: run.startedAt ?? now,
82
- status: "running",
83
- updatedAt: now
84
- });
85
- return attempt;
86
- }
87
- function toHandlerContext(run, attempt, input, waitUntil) {
88
- return {
89
- attemptId: attempt.id,
90
- id: run.id,
91
- ...input !== void 0 ? { input } : {},
92
- runId: run.id,
93
- scheduleId: run.scheduleId,
94
- scheduledAt: run.scheduledAt,
95
- target: run.target,
96
- waitUntil
97
- };
98
- }
99
- async function completeRun(run, attempt, store = getScheduleRunStore()) {
100
- const now = /* @__PURE__ */ new Date();
101
- await store.updateAttempt(attempt.id, {
102
- completedAt: now,
103
- status: "succeeded",
104
- updatedAt: now
105
- });
106
- return requireUpdatedRun(await store.updateRun(run.id, {
107
- completedAt: now,
108
- status: "succeeded",
109
- updatedAt: now
110
- }));
111
- }
112
- async function failRun(run, attempt, error, store = getScheduleRunStore()) {
113
- const now = /* @__PURE__ */ new Date();
114
- const serializedError = toRunError(error);
115
- await store.updateAttempt(attempt.id, {
116
- completedAt: now,
117
- error: serializedError,
118
- status: "failed",
119
- updatedAt: now
120
- });
121
- return requireUpdatedRun(await store.updateRun(run.id, {
122
- completedAt: now,
123
- error: serializedError,
124
- status: "failed",
125
- updatedAt: now
126
- }));
127
- }
128
- async function createScheduleRun(options) {
129
- const scheduledAt = validateScheduledAt(options.scheduledAt ?? /* @__PURE__ */ new Date());
130
- return (await createOrGetRun({
131
- ...options,
132
- scheduledAt
133
- })).run;
134
- }
135
- async function executeSchedule(options) {
136
- const scheduledAt = validateScheduledAt(options.scheduledAt ?? /* @__PURE__ */ new Date());
137
- const { created, run } = await createOrGetRun({
138
- ...options,
139
- scheduledAt
140
- });
141
- if (!created) return run;
142
- const runStore = options.runStore ?? getScheduleRunStore();
143
- const attempt = await startAttempt(run, runStore);
144
- const localWaitUntil = createLocalWaitUntil();
145
- const waitUntil = options.waitUntil ?? localWaitUntil.waitUntil;
146
- try {
147
- await options.definition.handler(toHandlerContext(run, attempt, options.input, waitUntil));
148
- if (!options.waitUntil) await localWaitUntil.flush();
149
- return await completeRun(run, attempt, runStore);
150
- } catch (error) {
151
- if (!options.waitUntil) try {
152
- await localWaitUntil.flush();
153
- } catch {}
154
- await failRun(run, attempt, error, runStore);
155
- throw error;
156
- }
157
- }
158
- async function executeStaticSchedule(options) {
159
- return await executeSchedule({
160
- definition: options.definition,
161
- scheduleId: options.name,
162
- source: "static",
163
- scheduledAt: options.scheduledAt,
164
- target: options.name,
165
- waitUntil: options.waitUntil
166
- });
167
- }
168
- async function loadRequiredRuntimeSchedule(id, store = getRuntimeScheduleStore()) {
169
- const schedule = await store.get(id);
170
- if (!schedule) throw createScheduleError("SCHEDULE_NOT_FOUND");
171
- return schedule;
172
- }
173
- async function executeRuntimeSchedule(options) {
174
- const runtimeOptions = typeof options === "string" ? { id: options } : options;
175
- assertRuntimeExecuteOptionsObject(runtimeOptions);
176
- assertRuntimeScheduleId(runtimeOptions.id);
177
- const id = runtimeOptions.id;
178
- const scheduledAt = validateScheduledAt(runtimeOptions.scheduledAt ?? /* @__PURE__ */ new Date());
179
- const runtimeScheduleStore = runtimeOptions.runtimeScheduleStore;
180
- const scheduleRunStore = runtimeOptions.scheduleRunStore;
181
- const existingRun = await (scheduleRunStore ?? getScheduleRunStore()).getRun(toRunId("runtime", id, scheduledAt));
182
- if (existingRun) return existingRun;
183
- const schedule = await loadRequiredRuntimeSchedule(id, runtimeScheduleStore);
184
- if (!schedule.enabled) throw createScheduleError("SCHEDULE_DISABLED");
185
- if (runtimeOptions.requireDue && !isRuntimeScheduleDue(schedule, scheduledAt)) throw createScheduleError("SCHEDULE_NOT_DUE");
186
- const definition = await loadScheduleDefinition(schedule.target);
187
- if (!definition) throw createScheduleError("SCHEDULE_TARGET_NOT_FOUND");
188
- if (definition.options?.allowRuntimeSchedules !== true) throw createScheduleError("SCHEDULE_TARGET_NOT_ELIGIBLE");
189
- return await executeSchedule({
190
- definition,
191
- input: schedule.input,
192
- runStore: scheduleRunStore,
193
- scheduleId: schedule.id,
194
- source: "runtime",
195
- scheduledAt,
196
- target: schedule.target,
197
- waitUntil: runtimeOptions.waitUntil
198
- });
199
- }
200
- async function executeRuntimeScheduleWake(input, options) {
201
- await executeRuntimeSchedule({
202
- id: input.scheduleId,
203
- requireDue: true,
204
- runtimeScheduleStore: options.runtimeScheduleStore,
205
- scheduledAt: input.scheduledAt,
206
- scheduleRunStore: options.scheduleRunStore,
207
- waitUntil: options.waitUntil
208
- });
209
- }
210
- //#endregion
211
- export { executeStaticSchedule as a, executeSchedule as i, executeRuntimeSchedule as n, randomId as o, executeRuntimeScheduleWake as r, createScheduleRun as t };
@@ -1,26 +0,0 @@
1
- import { a as RuntimeScheduleStore, b as ScheduleRunStore, d as ScheduleDefinitionRegistry, i as RuntimeScheduleRecord, s as RuntimeScheduleWake } from "../types-Bcje4dLV.js";
2
-
3
- //#region src/runtime/driver.d.ts
4
- interface RuntimeScheduleWakeDriverContext {
5
- reportError(error: unknown): void;
6
- wake(input: RuntimeScheduleWake): Promise<void>;
7
- }
8
- interface RuntimeScheduleWakeDriver {
9
- close?(): Promise<void> | void;
10
- reconcile(schedules: readonly RuntimeScheduleRecord[]): Promise<void>;
11
- }
12
- type RuntimeScheduleWakeDriverFactory = (context: RuntimeScheduleWakeDriverContext) => Promise<RuntimeScheduleWakeDriver> | RuntimeScheduleWakeDriver;
13
- interface InstallScheduleRuntimeOptions {
14
- createDriver: RuntimeScheduleWakeDriverFactory;
15
- onError?: (error: unknown) => void;
16
- registry: ScheduleDefinitionRegistry;
17
- runtimeScheduleStore: RuntimeScheduleStore;
18
- scheduleRunStore: ScheduleRunStore;
19
- staticRegistry?: ScheduleDefinitionRegistry;
20
- }
21
- interface ScheduleRuntimeController {
22
- close(): Promise<void>;
23
- }
24
- declare function installScheduleRuntime(options: InstallScheduleRuntimeOptions): Promise<ScheduleRuntimeController>;
25
- //#endregion
26
- export { InstallScheduleRuntimeOptions, type RuntimeScheduleWake, RuntimeScheduleWakeDriver, RuntimeScheduleWakeDriverContext, RuntimeScheduleWakeDriverFactory, ScheduleRuntimeController, installScheduleRuntime };
@@ -1,337 +0,0 @@
1
- import { a as executeStaticSchedule, r as executeRuntimeScheduleWake } from "../execute-B-pii4wf.js";
2
- import { c as setScheduleRuntimeRegistry, m as createScheduleError, n as getScheduleRunStore, o as setRuntimeScheduleStore, r as getScheduleRuntimeRegistry, s as setScheduleRunStore, t as getRuntimeScheduleStore } from "../state-By7WU_ks.js";
3
- import { t as isRuntimeScheduleDue } from "../due-Bbh4yIxq.js";
4
- import { AsyncLocalStorage } from "node:async_hooks";
5
- //#region src/runtime/driver.ts
6
- const staticScheduleIdPrefix = "\0vitehub:static:";
7
- function isObject(value) {
8
- return Object(value) === value;
9
- }
10
- function isScheduleRegistryDefinition(value) {
11
- return isObject(value) && "handler" in value;
12
- }
13
- function unwrapDefinition(loaded) {
14
- if ("default" in loaded && isScheduleRegistryDefinition(loaded.default)) return loaded.default;
15
- if (isScheduleRegistryDefinition(loaded)) return loaded;
16
- }
17
- async function loadStaticDefinitions(registry) {
18
- if (!registry) return [];
19
- return (await Promise.all(Object.entries(registry).map(async ([name, load]) => {
20
- const definition = unwrapDefinition(await load());
21
- return definition && "cron" in definition ? {
22
- definition,
23
- name
24
- } : void 0;
25
- }))).filter((definition) => definition !== void 0);
26
- }
27
- function createStaticSchedules(definitions, runtimeSchedules) {
28
- const occupiedIds = new Set(runtimeSchedules.map((schedule) => schedule.id));
29
- const byId = /* @__PURE__ */ new Map();
30
- const timestamp = /* @__PURE__ */ new Date(0);
31
- return {
32
- byId,
33
- records: definitions.map((entry) => {
34
- const baseId = `${staticScheduleIdPrefix}${encodeURIComponent(entry.name)}`;
35
- let id = baseId;
36
- let suffix = 2;
37
- while (occupiedIds.has(id)) id = `${baseId}:${suffix++}`;
38
- occupiedIds.add(id);
39
- const record = {
40
- createdAt: timestamp,
41
- cron: entry.definition.cron,
42
- enabled: true,
43
- id,
44
- target: entry.name,
45
- updatedAt: timestamp
46
- };
47
- byId.set(id, {
48
- ...entry,
49
- record
50
- });
51
- return record;
52
- })
53
- };
54
- }
55
- function createSerializer() {
56
- let tail = Promise.resolve();
57
- const operationStorage = new AsyncLocalStorage();
58
- const serialize = function serialize(operation) {
59
- const activeOperation = operationStorage.getStore();
60
- if (activeOperation?.active) return (async () => {
61
- activeOperation.depth++;
62
- try {
63
- return await operation();
64
- } finally {
65
- activeOperation.depth--;
66
- }
67
- })();
68
- const operationContext = {
69
- active: true,
70
- deferred: [],
71
- depth: 0,
72
- wakeReleases: /* @__PURE__ */ new Set()
73
- };
74
- const result = tail.then(() => operationStorage.run(operationContext, async () => {
75
- try {
76
- const value = await operation();
77
- while (operationContext.deferred.length > 0) await operationContext.deferred.shift()();
78
- return value;
79
- } finally {
80
- operationContext.active = false;
81
- }
82
- }));
83
- tail = result.then(() => {}, () => {});
84
- return result;
85
- };
86
- serialize.defer = (operation) => {
87
- const activeOperation = operationStorage.getStore();
88
- if (!activeOperation?.active) throw new Error("Cannot defer work outside an active serialized operation.");
89
- activeOperation.deferred.push(operation);
90
- for (const release of activeOperation.wakeReleases) release();
91
- };
92
- serialize.isReentrant = () => {
93
- const activeOperation = operationStorage.getStore();
94
- return Boolean(activeOperation?.active && activeOperation.depth > 0);
95
- };
96
- serialize.runWake = async (operation) => {
97
- const activeOperation = operationStorage.getStore();
98
- if (!activeOperation?.active) {
99
- await operation();
100
- return;
101
- }
102
- let release;
103
- let released = false;
104
- const releasePromise = new Promise((resolve) => {
105
- release = () => {
106
- released = true;
107
- resolve();
108
- };
109
- });
110
- activeOperation.wakeReleases.add(release);
111
- let execution;
112
- try {
113
- execution = Promise.resolve(operation());
114
- } catch (error) {
115
- execution = Promise.reject(error);
116
- }
117
- try {
118
- await Promise.race([execution, releasePromise]);
119
- if (released) activeOperation.deferred.push(async () => {
120
- await execution;
121
- });
122
- } finally {
123
- activeOperation.wakeReleases.delete(release);
124
- }
125
- };
126
- return serialize;
127
- }
128
- function createErrorReporter(onError) {
129
- return (error) => {
130
- if (!onError) return;
131
- try {
132
- Promise.resolve(onError(error)).catch(() => {});
133
- } catch {}
134
- };
135
- }
136
- async function reconcileAfterMutation(driver, store, rollback, reportError) {
137
- try {
138
- await driver.reconcile(await store.list());
139
- } catch (error) {
140
- try {
141
- await rollback();
142
- } catch (rollbackError) {
143
- throw new AggregateError([error, rollbackError], "Runtime Schedule reconciliation failed and the stored record could not be rolled back.");
144
- }
145
- try {
146
- await driver.reconcile(await store.list());
147
- } catch (rollbackReconcileError) {
148
- reportError(rollbackReconcileError);
149
- }
150
- throw error;
151
- }
152
- }
153
- function deferReentrantReconciliation(driver, store, rollback, reportError, serialize) {
154
- if (!serialize.isReentrant()) return;
155
- let rejectReconciliation;
156
- let resolveReconciliation;
157
- const reconciliation = new Promise((resolve, reject) => {
158
- rejectReconciliation = reject;
159
- resolveReconciliation = resolve;
160
- });
161
- serialize.defer(async () => {
162
- try {
163
- await reconcileAfterMutation(driver, store, rollback, reportError);
164
- resolveReconciliation();
165
- } catch (error) {
166
- rejectReconciliation(error);
167
- }
168
- });
169
- return reconciliation;
170
- }
171
- function createReconciledStore(store, getDriver, reportError, serialize) {
172
- return {
173
- create(record) {
174
- return serialize(async () => {
175
- const driver = getDriver();
176
- const created = await store.create(record);
177
- const rollback = async () => {
178
- if (!await store.delete(created.id)) throw new Error(`Runtime Schedule create rollback failed: ${created.id}`);
179
- };
180
- const deferred = deferReentrantReconciliation(driver, store, rollback, reportError, serialize);
181
- if (deferred) await deferred;
182
- else await reconcileAfterMutation(driver, store, rollback, reportError);
183
- return created;
184
- });
185
- },
186
- delete(id) {
187
- return serialize(async () => {
188
- const driver = getDriver();
189
- const previous = await store.get(id);
190
- if (!await store.delete(id)) return false;
191
- const rollback = async () => {
192
- if (!previous) throw new Error(`Runtime Schedule delete rollback failed: ${id}`);
193
- await store.create(previous);
194
- };
195
- const deferred = deferReentrantReconciliation(driver, store, rollback, reportError, serialize);
196
- if (deferred) await deferred;
197
- else await reconcileAfterMutation(driver, store, rollback, reportError);
198
- return true;
199
- });
200
- },
201
- get(id) {
202
- return store.get(id);
203
- },
204
- list() {
205
- return store.list();
206
- },
207
- update(id, patch) {
208
- return serialize(async () => {
209
- const driver = getDriver();
210
- const previous = await store.get(id);
211
- const updated = await store.update(id, patch);
212
- if (!updated) return void 0;
213
- const rollback = async () => {
214
- if (!previous) {
215
- if (!await store.delete(id)) throw new Error(`Runtime Schedule update rollback failed: ${id}`);
216
- return;
217
- }
218
- if (!await store.delete(id)) throw new Error(`Runtime Schedule update rollback failed: ${id}`);
219
- await store.create(previous);
220
- };
221
- const deferred = deferReentrantReconciliation(driver, store, rollback, reportError, serialize);
222
- if (deferred) await deferred;
223
- else await reconcileAfterMutation(driver, store, rollback, reportError);
224
- return updated;
225
- });
226
- }
227
- };
228
- }
229
- async function installScheduleRuntime(options) {
230
- const previousRegistry = getScheduleRuntimeRegistry();
231
- const previousRuntimeScheduleStore = getRuntimeScheduleStore();
232
- const previousScheduleRunStore = getScheduleRunStore();
233
- const reportError = createErrorReporter(options.onError);
234
- const pendingWork = /* @__PURE__ */ new Set();
235
- function waitUntil(value) {
236
- const promise = Promise.resolve(value);
237
- pendingWork.add(promise);
238
- promise.then(() => pendingWork.delete(promise), (error) => {
239
- pendingWork.delete(promise);
240
- reportError(error);
241
- });
242
- }
243
- async function flushWaitUntil() {
244
- while (pendingWork.size > 0) await Promise.allSettled(pendingWork);
245
- }
246
- const serialize = createSerializer();
247
- const activeWakes = /* @__PURE__ */ new Set();
248
- let driver;
249
- let reconciledDriver;
250
- let staticSchedules = {
251
- byId: /* @__PURE__ */ new Map(),
252
- records: []
253
- };
254
- let aborted = false;
255
- let closing = false;
256
- setScheduleRuntimeRegistry(options.registry);
257
- setScheduleRunStore(options.scheduleRunStore);
258
- const initializing = serialize(async () => {
259
- try {
260
- const runtimeSchedules = await options.runtimeScheduleStore.list();
261
- staticSchedules = createStaticSchedules(await loadStaticDefinitions(options.staticRegistry), runtimeSchedules);
262
- driver = await options.createDriver({
263
- reportError,
264
- wake(input) {
265
- if (closing) return Promise.resolve();
266
- const wake = serialize.runWake(async () => {
267
- const staticSchedule = staticSchedules.byId.get(input.scheduleId);
268
- if (staticSchedule) {
269
- if (!isRuntimeScheduleDue(staticSchedule.record, input.scheduledAt)) throw createScheduleError("SCHEDULE_NOT_DUE");
270
- await executeStaticSchedule({
271
- cron: staticSchedule.definition.cron,
272
- definition: staticSchedule.definition,
273
- name: staticSchedule.name,
274
- scheduledAt: input.scheduledAt,
275
- waitUntil
276
- });
277
- return;
278
- }
279
- await executeRuntimeScheduleWake(input, {
280
- runtimeScheduleStore: options.runtimeScheduleStore,
281
- scheduleRunStore: options.scheduleRunStore,
282
- waitUntil
283
- });
284
- });
285
- activeWakes.add(wake);
286
- wake.finally(() => activeWakes.delete(wake)).catch(() => {});
287
- return wake;
288
- }
289
- });
290
- const installedDriver = driver;
291
- reconciledDriver = {
292
- close: () => installedDriver.close?.(),
293
- async reconcile(records) {
294
- const conflictingId = records.find((record) => staticSchedules.byId.has(record.id))?.id;
295
- if (conflictingId) throw new Error(`Runtime Schedule id conflicts with a Static Schedule driver identity: ${JSON.stringify(conflictingId)}`);
296
- await installedDriver.reconcile([...staticSchedules.records, ...records]);
297
- }
298
- };
299
- await reconciledDriver.reconcile(runtimeSchedules);
300
- } catch (error) {
301
- aborted = true;
302
- throw error;
303
- }
304
- });
305
- setRuntimeScheduleStore(createReconciledStore(options.runtimeScheduleStore, () => {
306
- if (!reconciledDriver || aborted) throw new Error("Runtime Schedule wake driver installation did not complete.");
307
- return reconciledDriver;
308
- }, reportError, serialize));
309
- try {
310
- await initializing;
311
- } catch (error) {
312
- try {
313
- await driver?.close?.();
314
- } catch (closeError) {
315
- reportError(closeError);
316
- }
317
- setScheduleRuntimeRegistry(previousRegistry);
318
- setRuntimeScheduleStore(previousRuntimeScheduleStore);
319
- setScheduleRunStore(previousScheduleRunStore);
320
- throw error;
321
- }
322
- if (!reconciledDriver) throw new Error("Runtime Schedule wake driver installation did not produce a driver.");
323
- const installedDriver = reconciledDriver;
324
- let closePromise;
325
- return { close() {
326
- if (closePromise) return closePromise;
327
- closing = true;
328
- return closePromise = (async () => {
329
- while (activeWakes.size > 0) await Promise.allSettled(activeWakes);
330
- await serialize(async () => {});
331
- await flushWaitUntil();
332
- await installedDriver.close?.();
333
- })();
334
- } };
335
- }
336
- //#endregion
337
- export { installScheduleRuntime };