@vite-hub/schedule 0.0.1 → 0.0.2

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.
@@ -0,0 +1,334 @@
1
+ import { a as executeStaticSchedule, r as executeRuntimeScheduleWake } from "../execute-BnR8oEKq.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-BcEhBV8v.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 isScheduleRegistryDefinition(value) {
8
+ return !!value && typeof value === "object" && "handler" in value;
9
+ }
10
+ function unwrapDefinition(loaded) {
11
+ if ("default" in loaded && isScheduleRegistryDefinition(loaded.default)) return loaded.default;
12
+ if (isScheduleRegistryDefinition(loaded)) return loaded;
13
+ }
14
+ async function loadStaticDefinitions(registry) {
15
+ if (!registry) return [];
16
+ return (await Promise.all(Object.entries(registry).map(async ([name, load]) => {
17
+ const definition = unwrapDefinition(await load());
18
+ return definition && "cron" in definition ? {
19
+ definition,
20
+ name
21
+ } : void 0;
22
+ }))).filter((definition) => definition !== void 0);
23
+ }
24
+ function createStaticSchedules(definitions, runtimeSchedules) {
25
+ const occupiedIds = new Set(runtimeSchedules.map((schedule) => schedule.id));
26
+ const byId = /* @__PURE__ */ new Map();
27
+ const timestamp = /* @__PURE__ */ new Date(0);
28
+ return {
29
+ byId,
30
+ records: definitions.map((entry) => {
31
+ const baseId = `${staticScheduleIdPrefix}${encodeURIComponent(entry.name)}`;
32
+ let id = baseId;
33
+ let suffix = 2;
34
+ while (occupiedIds.has(id)) id = `${baseId}:${suffix++}`;
35
+ occupiedIds.add(id);
36
+ const record = {
37
+ createdAt: timestamp,
38
+ cron: entry.definition.cron,
39
+ enabled: true,
40
+ id,
41
+ target: entry.name,
42
+ updatedAt: timestamp
43
+ };
44
+ byId.set(id, {
45
+ ...entry,
46
+ record
47
+ });
48
+ return record;
49
+ })
50
+ };
51
+ }
52
+ function createSerializer() {
53
+ let tail = Promise.resolve();
54
+ const operationStorage = new AsyncLocalStorage();
55
+ const serialize = function serialize(operation) {
56
+ const activeOperation = operationStorage.getStore();
57
+ if (activeOperation?.active) return (async () => {
58
+ activeOperation.depth++;
59
+ try {
60
+ return await operation();
61
+ } finally {
62
+ activeOperation.depth--;
63
+ }
64
+ })();
65
+ const operationContext = {
66
+ active: true,
67
+ deferred: [],
68
+ depth: 0,
69
+ wakeReleases: /* @__PURE__ */ new Set()
70
+ };
71
+ const result = tail.then(() => operationStorage.run(operationContext, async () => {
72
+ try {
73
+ const value = await operation();
74
+ while (operationContext.deferred.length > 0) await operationContext.deferred.shift()();
75
+ return value;
76
+ } finally {
77
+ operationContext.active = false;
78
+ }
79
+ }));
80
+ tail = result.then(() => {}, () => {});
81
+ return result;
82
+ };
83
+ serialize.defer = (operation) => {
84
+ const activeOperation = operationStorage.getStore();
85
+ if (!activeOperation?.active) throw new Error("Cannot defer work outside an active serialized operation.");
86
+ activeOperation.deferred.push(operation);
87
+ for (const release of activeOperation.wakeReleases) release();
88
+ };
89
+ serialize.isReentrant = () => {
90
+ const activeOperation = operationStorage.getStore();
91
+ return Boolean(activeOperation?.active && activeOperation.depth > 0);
92
+ };
93
+ serialize.runWake = async (operation) => {
94
+ const activeOperation = operationStorage.getStore();
95
+ if (!activeOperation?.active) {
96
+ await operation();
97
+ return;
98
+ }
99
+ let release;
100
+ let released = false;
101
+ const releasePromise = new Promise((resolve) => {
102
+ release = () => {
103
+ released = true;
104
+ resolve();
105
+ };
106
+ });
107
+ activeOperation.wakeReleases.add(release);
108
+ let execution;
109
+ try {
110
+ execution = Promise.resolve(operation());
111
+ } catch (error) {
112
+ execution = Promise.reject(error);
113
+ }
114
+ try {
115
+ await Promise.race([execution, releasePromise]);
116
+ if (released) activeOperation.deferred.push(async () => {
117
+ await execution;
118
+ });
119
+ } finally {
120
+ activeOperation.wakeReleases.delete(release);
121
+ }
122
+ };
123
+ return serialize;
124
+ }
125
+ function createErrorReporter(onError) {
126
+ return (error) => {
127
+ if (!onError) return;
128
+ try {
129
+ Promise.resolve(onError(error)).catch(() => {});
130
+ } catch {}
131
+ };
132
+ }
133
+ async function reconcileAfterMutation(driver, store, rollback, reportError) {
134
+ try {
135
+ await driver.reconcile(await store.list());
136
+ } catch (error) {
137
+ try {
138
+ await rollback();
139
+ } catch (rollbackError) {
140
+ throw new AggregateError([error, rollbackError], "Runtime Schedule reconciliation failed and the stored record could not be rolled back.");
141
+ }
142
+ try {
143
+ await driver.reconcile(await store.list());
144
+ } catch (rollbackReconcileError) {
145
+ reportError(rollbackReconcileError);
146
+ }
147
+ throw error;
148
+ }
149
+ }
150
+ function deferReentrantReconciliation(driver, store, rollback, reportError, serialize) {
151
+ if (!serialize.isReentrant()) return;
152
+ let rejectReconciliation;
153
+ let resolveReconciliation;
154
+ const reconciliation = new Promise((resolve, reject) => {
155
+ rejectReconciliation = reject;
156
+ resolveReconciliation = resolve;
157
+ });
158
+ serialize.defer(async () => {
159
+ try {
160
+ await reconcileAfterMutation(driver, store, rollback, reportError);
161
+ resolveReconciliation();
162
+ } catch (error) {
163
+ rejectReconciliation(error);
164
+ }
165
+ });
166
+ return reconciliation;
167
+ }
168
+ function createReconciledStore(store, getDriver, reportError, serialize) {
169
+ return {
170
+ create(record) {
171
+ return serialize(async () => {
172
+ const driver = getDriver();
173
+ const created = await store.create(record);
174
+ const rollback = async () => {
175
+ if (!await store.delete(created.id)) throw new Error(`Runtime Schedule create rollback failed: ${created.id}`);
176
+ };
177
+ const deferred = deferReentrantReconciliation(driver, store, rollback, reportError, serialize);
178
+ if (deferred) await deferred;
179
+ else await reconcileAfterMutation(driver, store, rollback, reportError);
180
+ return created;
181
+ });
182
+ },
183
+ delete(id) {
184
+ return serialize(async () => {
185
+ const driver = getDriver();
186
+ const previous = await store.get(id);
187
+ if (!await store.delete(id)) return false;
188
+ const rollback = async () => {
189
+ if (!previous) throw new Error(`Runtime Schedule delete rollback failed: ${id}`);
190
+ await store.create(previous);
191
+ };
192
+ const deferred = deferReentrantReconciliation(driver, store, rollback, reportError, serialize);
193
+ if (deferred) await deferred;
194
+ else await reconcileAfterMutation(driver, store, rollback, reportError);
195
+ return true;
196
+ });
197
+ },
198
+ get(id) {
199
+ return store.get(id);
200
+ },
201
+ list() {
202
+ return store.list();
203
+ },
204
+ update(id, patch) {
205
+ return serialize(async () => {
206
+ const driver = getDriver();
207
+ const previous = await store.get(id);
208
+ const updated = await store.update(id, patch);
209
+ if (!updated) return void 0;
210
+ const rollback = async () => {
211
+ if (!previous) {
212
+ if (!await store.delete(id)) throw new Error(`Runtime Schedule update rollback failed: ${id}`);
213
+ return;
214
+ }
215
+ if (!await store.delete(id)) throw new Error(`Runtime Schedule update rollback failed: ${id}`);
216
+ await store.create(previous);
217
+ };
218
+ const deferred = deferReentrantReconciliation(driver, store, rollback, reportError, serialize);
219
+ if (deferred) await deferred;
220
+ else await reconcileAfterMutation(driver, store, rollback, reportError);
221
+ return updated;
222
+ });
223
+ }
224
+ };
225
+ }
226
+ async function installScheduleRuntime(options) {
227
+ const previousRegistry = getScheduleRuntimeRegistry();
228
+ const previousRuntimeScheduleStore = getRuntimeScheduleStore();
229
+ const previousScheduleRunStore = getScheduleRunStore();
230
+ const reportError = createErrorReporter(options.onError);
231
+ const pendingWork = /* @__PURE__ */ new Set();
232
+ function waitUntil(value) {
233
+ const promise = Promise.resolve(value);
234
+ pendingWork.add(promise);
235
+ promise.then(() => pendingWork.delete(promise), (error) => {
236
+ pendingWork.delete(promise);
237
+ reportError(error);
238
+ });
239
+ }
240
+ async function flushWaitUntil() {
241
+ while (pendingWork.size > 0) await Promise.allSettled([...pendingWork]);
242
+ }
243
+ const serialize = createSerializer();
244
+ const activeWakes = /* @__PURE__ */ new Set();
245
+ let driver;
246
+ let reconciledDriver;
247
+ let staticSchedules = {
248
+ byId: /* @__PURE__ */ new Map(),
249
+ records: []
250
+ };
251
+ let aborted = false;
252
+ let closing = false;
253
+ setScheduleRuntimeRegistry(options.registry);
254
+ setScheduleRunStore(options.scheduleRunStore);
255
+ const initializing = serialize(async () => {
256
+ try {
257
+ const runtimeSchedules = await options.runtimeScheduleStore.list();
258
+ staticSchedules = createStaticSchedules(await loadStaticDefinitions(options.staticRegistry), runtimeSchedules);
259
+ driver = await options.createDriver({
260
+ reportError,
261
+ wake(input) {
262
+ if (closing) return Promise.resolve();
263
+ const wake = serialize.runWake(async () => {
264
+ const staticSchedule = staticSchedules.byId.get(input.scheduleId);
265
+ if (staticSchedule) {
266
+ if (!isRuntimeScheduleDue(staticSchedule.record, input.scheduledAt)) throw createScheduleError("SCHEDULE_NOT_DUE");
267
+ await executeStaticSchedule({
268
+ cron: staticSchedule.definition.cron,
269
+ definition: staticSchedule.definition,
270
+ name: staticSchedule.name,
271
+ scheduledAt: input.scheduledAt,
272
+ waitUntil
273
+ });
274
+ return;
275
+ }
276
+ await executeRuntimeScheduleWake(input, {
277
+ runtimeScheduleStore: options.runtimeScheduleStore,
278
+ scheduleRunStore: options.scheduleRunStore,
279
+ waitUntil
280
+ });
281
+ });
282
+ activeWakes.add(wake);
283
+ wake.finally(() => activeWakes.delete(wake)).catch(() => {});
284
+ return wake;
285
+ }
286
+ });
287
+ const installedDriver = driver;
288
+ reconciledDriver = {
289
+ close: () => installedDriver.close?.(),
290
+ async reconcile(records) {
291
+ const conflictingId = records.find((record) => staticSchedules.byId.has(record.id))?.id;
292
+ if (conflictingId) throw new Error(`Runtime Schedule id conflicts with a Static Schedule driver identity: ${JSON.stringify(conflictingId)}`);
293
+ await installedDriver.reconcile([...staticSchedules.records, ...records]);
294
+ }
295
+ };
296
+ await reconciledDriver.reconcile(runtimeSchedules);
297
+ } catch (error) {
298
+ aborted = true;
299
+ throw error;
300
+ }
301
+ });
302
+ setRuntimeScheduleStore(createReconciledStore(options.runtimeScheduleStore, () => {
303
+ if (!reconciledDriver || aborted) throw new Error("Runtime Schedule wake driver installation did not complete.");
304
+ return reconciledDriver;
305
+ }, reportError, serialize));
306
+ try {
307
+ await initializing;
308
+ } catch (error) {
309
+ try {
310
+ await driver?.close?.();
311
+ } catch (closeError) {
312
+ reportError(closeError);
313
+ }
314
+ setScheduleRuntimeRegistry(previousRegistry);
315
+ setRuntimeScheduleStore(previousRuntimeScheduleStore);
316
+ setScheduleRunStore(previousScheduleRunStore);
317
+ throw error;
318
+ }
319
+ if (!reconciledDriver) throw new Error("Runtime Schedule wake driver installation did not produce a driver.");
320
+ const installedDriver = reconciledDriver;
321
+ let closePromise;
322
+ return { close() {
323
+ if (closePromise) return closePromise;
324
+ closing = true;
325
+ return closePromise = (async () => {
326
+ while (activeWakes.size > 0) await Promise.allSettled([...activeWakes]);
327
+ await serialize(async () => {});
328
+ await flushWaitUntil();
329
+ await installedDriver.close?.();
330
+ })();
331
+ } };
332
+ }
333
+ //#endregion
334
+ export { installScheduleRuntime };
@@ -0,0 +1,11 @@
1
+ import { RuntimeScheduleWakeDriverFactory } from "./driver.js";
2
+
3
+ //#region src/runtime/process.d.ts
4
+ interface ProcessScheduleWakeDriverOptions {
5
+ concurrency?: number;
6
+ intervalMs?: number;
7
+ now?: () => Date;
8
+ }
9
+ declare function createProcessScheduleWakeDriver(options?: ProcessScheduleWakeDriverOptions): RuntimeScheduleWakeDriverFactory;
10
+ //#endregion
11
+ export { ProcessScheduleWakeDriverOptions, createProcessScheduleWakeDriver };
@@ -0,0 +1,285 @@
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";
3
+ //#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) {
26
+ 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
35
+ };
36
+ }
37
+ function floorUTCMinute(date) {
38
+ return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes()));
39
+ }
40
+ function occurrenceKey(input) {
41
+ return `${input.scheduleId}:${input.scheduledAt.getTime()}`;
42
+ }
43
+ function reportError(context, error) {
44
+ return Effect.sync(() => {
45
+ try {
46
+ context.reportError(error);
47
+ } 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);
83
+ 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;
109
+ }
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
+ };
145
+ const key = occurrenceKey(input);
146
+ if (dispatched.has(scheduleId) || queued.has(key) || current.active.has(key)) continue;
147
+ dispatched.add(scheduleId);
148
+ queued.set(key, input);
149
+ occurrences.push(input);
150
+ }
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));
169
+ }
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
+ })];
185
+ });
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
+ }
192
+ }
193
+ }));
194
+ });
195
+ 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
208
+ };
209
+ });
210
+ //#endregion
211
+ //#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.");
219
+ return {
220
+ concurrency,
221
+ intervalMs
222
+ };
223
+ }
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
+ }
240
+ };
241
+ }
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
+ });
252
+ }
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));
267
+ }
268
+ return {
269
+ close() {
270
+ if (closePromise) return closePromise;
271
+ closePromise = run(Effect.flatMap(ProcessWakeRuntimeService, (service) => service.close)).then(() => {
272
+ closed = true;
273
+ return runtime.dispose();
274
+ });
275
+ return closePromise;
276
+ },
277
+ reconcile(records) {
278
+ if (closed) return Promise.reject(/* @__PURE__ */ new Error("Process Schedule Wake Driver is closed."));
279
+ return run(Effect.flatMap(ProcessWakeRuntimeService, (service) => service.reconcile(records)));
280
+ }
281
+ };
282
+ };
283
+ }
284
+ //#endregion
285
+ export { createProcessScheduleWakeDriver };
@@ -1,4 +1,4 @@
1
- import { a as RuntimeScheduleStore, s as ScheduleDefinition, u as ScheduleDefinitionRegistry, v as ScheduleRunStore } from "../types-DOjXDq0s.js";
1
+ import { a as RuntimeScheduleStore, b as ScheduleRunStore, d as ScheduleDefinitionRegistry, p as ScheduleRegistryDefinition } from "../types-Bcje4dLV.js";
2
2
 
3
3
  //#region src/runtime/state.d.ts
4
4
  declare function setScheduleRuntimeRegistry(registry: ScheduleDefinitionRegistry | undefined): void;
@@ -7,7 +7,7 @@ declare function setRuntimeScheduleStore(store: RuntimeScheduleStore | undefined
7
7
  declare function getRuntimeScheduleStore(): RuntimeScheduleStore;
8
8
  declare function setScheduleRunStore(store: ScheduleRunStore | undefined): void;
9
9
  declare function getScheduleRunStore(): ScheduleRunStore;
10
- declare function loadScheduleDefinition(name: string): Promise<ScheduleDefinition | undefined>;
10
+ declare function loadScheduleDefinition(name: string): Promise<ScheduleRegistryDefinition | undefined>;
11
11
  declare function resetScheduleRuntime(): void;
12
12
  //#endregion
13
13
  export { getRuntimeScheduleStore, getScheduleRunStore, getScheduleRuntimeRegistry, loadScheduleDefinition, resetScheduleRuntime, setRuntimeScheduleStore, setScheduleRunStore, setScheduleRuntimeRegistry };
@@ -1,2 +1,2 @@
1
- import { a as resetScheduleRuntime, c as setScheduleRuntimeRegistry, i as loadScheduleDefinition, n as getScheduleRunStore, o as setRuntimeScheduleStore, r as getScheduleRuntimeRegistry, s as setScheduleRunStore, t as getRuntimeScheduleStore } from "../state-DoONzfij.js";
1
+ import { a as resetScheduleRuntime, c as setScheduleRuntimeRegistry, i as loadScheduleDefinition, n as getScheduleRunStore, o as setRuntimeScheduleStore, r as getScheduleRuntimeRegistry, s as setScheduleRunStore, t as getRuntimeScheduleStore } from "../state-BcEhBV8v.js";
2
2
  export { getRuntimeScheduleStore, getScheduleRunStore, getScheduleRuntimeRegistry, loadScheduleDefinition, resetScheduleRuntime, setRuntimeScheduleStore, setScheduleRunStore, setScheduleRuntimeRegistry };