@vite-hub/schedule 0.0.3 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +199 -65
- package/dist/definition-CMiOg1lg.js +111 -0
- package/dist/definition.d.ts +4 -6
- package/dist/definition.js +2 -42
- package/dist/error-diagnostics-A_8Kp-48.js +116 -0
- package/dist/error-diagnostics-in7mif5s.js +45 -0
- package/dist/execute-BJrgNgQ0.js +201 -0
- package/dist/index.d.ts +7 -51
- package/dist/index.js +2 -7
- package/dist/inspect-DTfAo5gS.js +118 -0
- package/dist/kv-storage-Bv9ocZT-.d.ts +18 -0
- package/dist/nuxt.d.ts +4 -6
- package/dist/nuxt.js +3 -1
- package/dist/operations-gk2qzhYV.js +131 -0
- package/dist/operations-tNUdj3G4.d.ts +212 -0
- package/dist/operations.d.ts +61 -0
- package/dist/operations.js +921 -0
- package/dist/registry-module.d.ts +0 -5
- package/dist/runtime/kv.d.ts +4 -0
- package/dist/{kv-BJ1I9IlJ.js → runtime/kv.js} +1 -1
- package/dist/runtime/process.d.ts +26 -5
- package/dist/runtime/process.js +337 -75
- package/dist/runtime/state.d.ts +8 -12
- package/dist/runtime/state.js +2 -2
- package/dist/runtime/static.d.ts +18 -12
- package/dist/runtime/static.js +2 -138
- package/dist/runtime.d.ts +36 -4
- package/dist/runtime.js +5 -3
- package/dist/state-DSxmHPn3.js +448 -0
- package/dist/static-6g82xguw.js +245 -0
- package/dist/store-QAOd8bxm.d.ts +11 -0
- package/dist/types-CHdV9FQU.d.ts +113 -0
- package/dist/vite-BAVyZ8hZ.d.ts +474 -0
- package/dist/vite-BJwZkMrn.js +5193 -0
- package/dist/vite.d.ts +2 -38
- package/dist/vite.js +2 -2
- package/dist/wait-until-BmIqRo4x.js +87 -0
- package/package.json +68 -22
- package/dist/client-BMFCy0dX.js +0 -233
- package/dist/discovery-BZlat3Kc.js +0 -776
- package/dist/due-Bbh4yIxq.js +0 -59
- package/dist/execute-ClFYvmp9.js +0 -211
- package/dist/runtime/driver.d.ts +0 -26
- package/dist/runtime/driver.js +0 -334
- package/dist/state-By7WU_ks.js +0 -472
- package/dist/store-t-74rsM_.d.ts +0 -48
- package/dist/types-Bcje4dLV.d.ts +0 -136
- package/dist/vite-BX6_KiRw.js +0 -1218
- package/dist/wait-until-CR-JjIOb.js +0 -23
package/dist/runtime/static.js
CHANGED
|
@@ -1,138 +1,2 @@
|
|
|
1
|
-
import { t as
|
|
2
|
-
|
|
3
|
-
function createStaticScheduleRun(options) {
|
|
4
|
-
const scheduledAt = options.scheduledAt ?? /* @__PURE__ */ new Date();
|
|
5
|
-
return {
|
|
6
|
-
cron: options.cron,
|
|
7
|
-
id: `run_${options.name}_${scheduledAt.toISOString()}`,
|
|
8
|
-
scheduleId: options.name,
|
|
9
|
-
scheduledAt,
|
|
10
|
-
waitUntil: options.waitUntil
|
|
11
|
-
};
|
|
12
|
-
}
|
|
13
|
-
async function executeStaticSchedule(options) {
|
|
14
|
-
const localWaitUntil = createLocalWaitUntil();
|
|
15
|
-
try {
|
|
16
|
-
const result = await options.definition.handler(createStaticScheduleRun({
|
|
17
|
-
...options,
|
|
18
|
-
waitUntil: options.waitUntil ?? localWaitUntil.waitUntil
|
|
19
|
-
}));
|
|
20
|
-
if (!options.waitUntil) await localWaitUntil.flush();
|
|
21
|
-
return result;
|
|
22
|
-
} catch (error) {
|
|
23
|
-
if (!options.waitUntil) try {
|
|
24
|
-
await localWaitUntil.flush();
|
|
25
|
-
} catch {}
|
|
26
|
-
throw error;
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
async function executeMatchingStaticSchedules(options) {
|
|
30
|
-
const scheduledAt = options.scheduledAt ?? /* @__PURE__ */ new Date();
|
|
31
|
-
const runs = [];
|
|
32
|
-
for (const [name, load] of Object.entries(options.registry)) {
|
|
33
|
-
const definition = unwrapScheduleDefinition(await load());
|
|
34
|
-
if (!definition || definition.cron !== options.cron) continue;
|
|
35
|
-
runs.push(executeStaticSchedule({
|
|
36
|
-
cron: options.cron,
|
|
37
|
-
definition,
|
|
38
|
-
name,
|
|
39
|
-
scheduledAt,
|
|
40
|
-
waitUntil: options.waitUntil
|
|
41
|
-
}));
|
|
42
|
-
}
|
|
43
|
-
return await Promise.all(runs);
|
|
44
|
-
}
|
|
45
|
-
async function executeCloudflareStaticSchedules(event, options) {
|
|
46
|
-
const scheduled = readCloudflareScheduledEvent(event);
|
|
47
|
-
return await runWithCloudflareServerEnv(event, async (waitUntil) => {
|
|
48
|
-
return await executeMatchingStaticSchedules({
|
|
49
|
-
cron: scheduled.cron,
|
|
50
|
-
registry: options.registry,
|
|
51
|
-
scheduledAt: scheduled.scheduledAt,
|
|
52
|
-
waitUntil
|
|
53
|
-
});
|
|
54
|
-
}, options.waitUntil ?? readCloudflareWaitUntil(event));
|
|
55
|
-
}
|
|
56
|
-
function readCloudflareScheduledEvent(event) {
|
|
57
|
-
const cron = event.controller?.cron ?? event.cron;
|
|
58
|
-
if (!cron) throw new TypeError("[vitehub:schedule] Cloudflare scheduled event is missing a cron string.");
|
|
59
|
-
const scheduledTime = event.controller?.scheduledTime ?? event.scheduledTime;
|
|
60
|
-
const scheduledAt = scheduledTime instanceof Date ? scheduledTime : typeof scheduledTime === "number" || typeof scheduledTime === "string" ? new Date(scheduledTime) : /* @__PURE__ */ new Date();
|
|
61
|
-
if (Number.isNaN(scheduledAt.getTime())) throw new TypeError("[vitehub:schedule] Cloudflare scheduled event has an invalid scheduledTime.");
|
|
62
|
-
return {
|
|
63
|
-
cron,
|
|
64
|
-
scheduledAt
|
|
65
|
-
};
|
|
66
|
-
}
|
|
67
|
-
async function runWithCloudflareServerEnv(event, callback, hostWaitUntil) {
|
|
68
|
-
const globals = globalThis;
|
|
69
|
-
const hadGlobalEnv = Object.prototype.hasOwnProperty.call(globals, "__env__");
|
|
70
|
-
const previousGlobalEnv = globals.__env__;
|
|
71
|
-
const env = readCloudflareEventEnv(event);
|
|
72
|
-
if (env) globals.__env__ = env;
|
|
73
|
-
const pending = /* @__PURE__ */ new Set();
|
|
74
|
-
const waitUntil = hostWaitUntil ? (value) => {
|
|
75
|
-
const promise = Promise.resolve(value);
|
|
76
|
-
pending.add(promise);
|
|
77
|
-
promise.then(() => pending.delete(promise), () => pending.delete(promise));
|
|
78
|
-
hostWaitUntil(promise);
|
|
79
|
-
} : void 0;
|
|
80
|
-
try {
|
|
81
|
-
return await callback(waitUntil);
|
|
82
|
-
} finally {
|
|
83
|
-
if (pending.size === 0) restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv);
|
|
84
|
-
else hostWaitUntil(flushPendingWork(pending).finally(() => {
|
|
85
|
-
restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv);
|
|
86
|
-
}));
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
async function flushPendingWork(pending) {
|
|
90
|
-
while (pending.size > 0) await Promise.allSettled([...pending]);
|
|
91
|
-
}
|
|
92
|
-
function restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv) {
|
|
93
|
-
if (hadGlobalEnv) globals.__env__ = previousGlobalEnv;
|
|
94
|
-
else delete globals.__env__;
|
|
95
|
-
}
|
|
96
|
-
function isRecord(value) {
|
|
97
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
98
|
-
}
|
|
99
|
-
function readCloudflareWaitUntil(event) {
|
|
100
|
-
const context = isRecord(event.context) ? event.context : void 0;
|
|
101
|
-
const cloudflareContext = isRecord(context?.cloudflare) ? context.cloudflare : void 0;
|
|
102
|
-
const platformContext = isRecord(context?._platform) ? context._platform : void 0;
|
|
103
|
-
const platformCloudflareContext = isRecord(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
|
|
104
|
-
const request = isRecord(event.req) ? event.req : void 0;
|
|
105
|
-
const runtime = isRecord(request?.runtime) ? request.runtime : void 0;
|
|
106
|
-
const runtimeCloudflare = isRecord(runtime?.cloudflare) ? runtime.cloudflare : void 0;
|
|
107
|
-
const owners = [
|
|
108
|
-
event,
|
|
109
|
-
context,
|
|
110
|
-
cloudflareContext,
|
|
111
|
-
isRecord(cloudflareContext?.context) ? cloudflareContext.context : void 0,
|
|
112
|
-
platformCloudflareContext,
|
|
113
|
-
isRecord(platformCloudflareContext?.context) ? platformCloudflareContext.context : void 0,
|
|
114
|
-
request,
|
|
115
|
-
runtimeCloudflare,
|
|
116
|
-
isRecord(runtimeCloudflare?.context) ? runtimeCloudflare.context : void 0
|
|
117
|
-
];
|
|
118
|
-
for (const owner of owners) if (typeof owner?.waitUntil === "function") return owner.waitUntil.bind(owner);
|
|
119
|
-
}
|
|
120
|
-
function readCloudflareEventEnv(event) {
|
|
121
|
-
if (isRecord(event.env)) return event.env;
|
|
122
|
-
const context = isRecord(event.context) ? event.context : void 0;
|
|
123
|
-
const cloudflareContext = isRecord(context?.cloudflare) ? context.cloudflare : void 0;
|
|
124
|
-
if (isRecord(cloudflareContext?.env)) return cloudflareContext.env;
|
|
125
|
-
const platformContext = isRecord(context?._platform) ? context._platform : void 0;
|
|
126
|
-
const platformCloudflareContext = isRecord(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
|
|
127
|
-
if (isRecord(platformCloudflareContext?.env)) return platformCloudflareContext.env;
|
|
128
|
-
const request = isRecord(event.req) ? event.req : void 0;
|
|
129
|
-
const runtime = isRecord(request?.runtime) ? request.runtime : void 0;
|
|
130
|
-
const runtimeCloudflare = isRecord(runtime?.cloudflare) ? runtime.cloudflare : void 0;
|
|
131
|
-
return isRecord(runtimeCloudflare?.env) ? runtimeCloudflare.env : void 0;
|
|
132
|
-
}
|
|
133
|
-
function unwrapScheduleDefinition(loaded) {
|
|
134
|
-
const definition = typeof loaded === "object" && loaded !== null && "default" in loaded ? loaded.default : loaded;
|
|
135
|
-
return definition && "cron" in definition ? definition : void 0;
|
|
136
|
-
}
|
|
137
|
-
//#endregion
|
|
138
|
-
export { createStaticScheduleRun, executeCloudflareStaticSchedules, executeMatchingStaticSchedules, executeStaticSchedule };
|
|
1
|
+
import { a as isScheduleCronAuthorized, c as normalizeScheduleRuntimeError, i as executeStaticSchedule, l as unwrapScheduleDefinition, n as executeCloudflareStaticSchedules, o as missingScheduleDefinitionError, r as executeMatchingStaticSchedules, s as normalizeCron, t as createStaticScheduleRun } from "../static-6g82xguw.js";
|
|
2
|
+
export { createStaticScheduleRun, executeCloudflareStaticSchedules, executeMatchingStaticSchedules, executeStaticSchedule, isScheduleCronAuthorized, missingScheduleDefinitionError, normalizeCron, normalizeScheduleRuntimeError, unwrapScheduleDefinition };
|
package/dist/runtime.d.ts
CHANGED
|
@@ -1,5 +1,37 @@
|
|
|
1
1
|
/// <reference path="./registry-module.d.ts" />
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
|
|
2
|
+
import { a as ScheduleDefinitionRegistry, c as ScheduleRunAttemptRecord, f as ScheduleRunListOptions, g as ScheduleRunStore, i as ScheduleDefinitionOptions, n as ScheduleDefinition, o as ScheduleHandler, p as ScheduleRunRecord, s as ScheduleRegistryDefinition, u as ScheduleRunContext } from "./types-CHdV9FQU.js";
|
|
3
|
+
import { n as createScheduleKVStorage, t as ScheduleKVStorage } from "./kv-storage-Bv9ocZT-.js";
|
|
4
|
+
import { n as createKVScheduleRunStore, r as createMemoryScheduleRunStore, t as KVScheduleStoreOptions } from "./store-QAOd8bxm.js";
|
|
5
|
+
import { normalizeCron, unwrapScheduleDefinition } from "./runtime/static.js";
|
|
6
|
+
import { getScheduleRunStore, getScheduleRuntimeRegistry, loadScheduleDefinition, resetScheduleRuntime, setScheduleRunStore, setScheduleRuntimeRegistry } from "./runtime/state.js";
|
|
7
|
+
//#region src/runtime/execute.d.ts
|
|
8
|
+
interface ExecuteScheduleOptions {
|
|
9
|
+
/** Return the persisted failed run when the handler throws. Guards still throw. */
|
|
10
|
+
captureHandlerFailure?: boolean;
|
|
11
|
+
definition: ScheduleDefinition;
|
|
12
|
+
runStore?: ScheduleRunStore;
|
|
13
|
+
runIdSuffix?: string;
|
|
14
|
+
scheduleId: string;
|
|
15
|
+
source?: "direct" | "manual" | "static";
|
|
16
|
+
scheduledAt?: Date;
|
|
17
|
+
target: string;
|
|
18
|
+
waitUntil?: (promise: PromiseLike<unknown>) => void;
|
|
19
|
+
}
|
|
20
|
+
interface ExecuteStaticScheduleOptions {
|
|
21
|
+
cron: string;
|
|
22
|
+
definition: ScheduleDefinition;
|
|
23
|
+
name: string;
|
|
24
|
+
scheduledAt?: Date;
|
|
25
|
+
waitUntil?: (promise: PromiseLike<unknown>) => void;
|
|
26
|
+
}
|
|
27
|
+
interface RunScheduleOptions {
|
|
28
|
+
/** Loads the definition from this registry instead of the one installed with `setScheduleRuntimeRegistry()`. */
|
|
29
|
+
registry?: ScheduleDefinitionRegistry;
|
|
30
|
+
}
|
|
31
|
+
export declare function createScheduleRun(options: Omit<ExecuteScheduleOptions, "definition" | "waitUntil">): Promise<ScheduleRunRecord>;
|
|
32
|
+
export declare function executeSchedule(options: ExecuteScheduleOptions): Promise<ScheduleRunRecord>;
|
|
33
|
+
export declare function executeStaticSchedule(options: ExecuteStaticScheduleOptions): Promise<ScheduleRunRecord>;
|
|
34
|
+
/** Runs a manually dispatchable static Schedule Definition immediately. */
|
|
35
|
+
export declare function runSchedule(name: string, options?: RunScheduleOptions): Promise<ScheduleRunRecord>;
|
|
36
|
+
//#endregion
|
|
37
|
+
export { type KVScheduleStoreOptions, type RunScheduleOptions, type ScheduleDefinition, type ScheduleDefinitionOptions, type ScheduleDefinitionRegistry, type ScheduleHandler, type ScheduleKVStorage, type ScheduleRegistryDefinition, type ScheduleRunAttemptRecord, type ScheduleRunContext, type ScheduleRunListOptions, type ScheduleRunRecord, type ScheduleRunStore, createKVScheduleRunStore, createMemoryScheduleRunStore, createScheduleKVStorage, getScheduleRunStore, getScheduleRuntimeRegistry, loadScheduleDefinition, normalizeCron, resetScheduleRuntime, setScheduleRunStore, setScheduleRuntimeRegistry, unwrapScheduleDefinition };
|
package/dist/runtime.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as
|
|
3
|
-
|
|
1
|
+
import { i as runSchedule, n as executeSchedule, r as executeStaticSchedule, t as createScheduleRun } from "./execute-BJrgNgQ0.js";
|
|
2
|
+
import { a as setScheduleRunStore, c as createMemoryScheduleRunStore, i as resetScheduleRuntime, n as getScheduleRuntimeRegistry, o as setScheduleRuntimeRegistry, r as loadScheduleDefinition, s as createKVScheduleRunStore, t as getScheduleRunStore } from "./state-DSxmHPn3.js";
|
|
3
|
+
import { l as unwrapScheduleDefinition, s as normalizeCron } from "./static-6g82xguw.js";
|
|
4
|
+
import { t as createScheduleKVStorage } from "./kv-storage-DWinmLLy.js";
|
|
5
|
+
export { createKVScheduleRunStore, createMemoryScheduleRunStore, createScheduleKVStorage, createScheduleRun, executeSchedule, executeStaticSchedule, getScheduleRunStore, getScheduleRuntimeRegistry, loadScheduleDefinition, normalizeCron, resetScheduleRuntime, runSchedule, setScheduleRunStore, setScheduleRuntimeRegistry, unwrapScheduleDefinition };
|
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
import { t as scheduleErrorDiagnostics } from "./error-diagnostics-in7mif5s.js";
|
|
2
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
|
+
//#region src/runtime/store.ts
|
|
4
|
+
const maxLegacyHistoryRecords = 1e3;
|
|
5
|
+
/** Raised when the metadata index cannot provide a complete history safely. */
|
|
6
|
+
var ScheduleHistoryIncompleteError = class extends Error {
|
|
7
|
+
recordCount;
|
|
8
|
+
maxRecords;
|
|
9
|
+
code = "SCHEDULE_HISTORY_INCOMPLETE";
|
|
10
|
+
constructor(recordCount, maxRecords) {
|
|
11
|
+
super(`Schedule run history is incomplete because ${recordCount} records have no usable metadata index (maximum fallback is ${maxRecords}). Rebuild the schedule run index before listing history.`);
|
|
12
|
+
this.recordCount = recordCount;
|
|
13
|
+
this.maxRecords = maxRecords;
|
|
14
|
+
this.name = "ScheduleHistoryIncompleteError";
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
function trimPrefix(prefix) {
|
|
18
|
+
return prefix.replace(/^\/+|\/+$/g, "");
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Decoded trailing segments of a listed key. Some KV stores, such as unstorage, list keys with `:` instead of `/`.
|
|
22
|
+
* Encoded parts contain neither, so both separators are safe to split on.
|
|
23
|
+
*/
|
|
24
|
+
function keySegments(key, count) {
|
|
25
|
+
return key.split(/[/:]/).slice(-count).map(decodeURIComponent);
|
|
26
|
+
}
|
|
27
|
+
function joinKey(prefix, ...parts) {
|
|
28
|
+
const base = trimPrefix(prefix);
|
|
29
|
+
const suffix = parts.map(encodeURIComponent).join("/");
|
|
30
|
+
return base ? `${base}/${suffix}` : suffix;
|
|
31
|
+
}
|
|
32
|
+
function scheduleRunKey(prefix, id) {
|
|
33
|
+
return joinKey(prefix, "schedule-runs", id);
|
|
34
|
+
}
|
|
35
|
+
function scheduleRunAttemptKey(prefix, id) {
|
|
36
|
+
return joinKey(prefix, "schedule-run-attempts", id);
|
|
37
|
+
}
|
|
38
|
+
function scheduleRunBase(prefix) {
|
|
39
|
+
return `${joinKey(prefix, "schedule-runs")}/`;
|
|
40
|
+
}
|
|
41
|
+
function scheduleRunAttemptBase(prefix) {
|
|
42
|
+
return `${joinKey(prefix, "schedule-run-attempts")}/`;
|
|
43
|
+
}
|
|
44
|
+
const keyLocks = /* @__PURE__ */ new Map();
|
|
45
|
+
async function withKVKeyLock(key, operation) {
|
|
46
|
+
const previous = keyLocks.get(key) ?? Promise.resolve();
|
|
47
|
+
let release;
|
|
48
|
+
const current = new Promise((resolve) => {
|
|
49
|
+
release = resolve;
|
|
50
|
+
});
|
|
51
|
+
const queued = previous.then(() => current, () => current);
|
|
52
|
+
keyLocks.set(key, queued);
|
|
53
|
+
await previous;
|
|
54
|
+
try {
|
|
55
|
+
return await operation();
|
|
56
|
+
} finally {
|
|
57
|
+
release();
|
|
58
|
+
if (keyLocks.get(key) === queued) keyLocks.delete(key);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function cloneScheduleRun(record) {
|
|
62
|
+
return {
|
|
63
|
+
...record,
|
|
64
|
+
completedAt: record.completedAt ? new Date(record.completedAt) : void 0,
|
|
65
|
+
createdAt: new Date(record.createdAt),
|
|
66
|
+
error: record.error ? { ...record.error } : void 0,
|
|
67
|
+
response: record.response ? structuredClone(record.response) : void 0,
|
|
68
|
+
scheduledAt: new Date(record.scheduledAt),
|
|
69
|
+
startedAt: record.startedAt ? new Date(record.startedAt) : void 0,
|
|
70
|
+
updatedAt: new Date(record.updatedAt)
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function cloneScheduleRunAttempt(record) {
|
|
74
|
+
return {
|
|
75
|
+
...record,
|
|
76
|
+
completedAt: record.completedAt ? new Date(record.completedAt) : void 0,
|
|
77
|
+
createdAt: new Date(record.createdAt),
|
|
78
|
+
error: record.error ? { ...record.error } : void 0,
|
|
79
|
+
startedAt: new Date(record.startedAt),
|
|
80
|
+
updatedAt: new Date(record.updatedAt)
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function serializeScheduleRun(record) {
|
|
84
|
+
return {
|
|
85
|
+
...record,
|
|
86
|
+
completedAt: record.completedAt?.toISOString(),
|
|
87
|
+
createdAt: record.createdAt.toISOString(),
|
|
88
|
+
error: record.error ? { ...record.error } : void 0,
|
|
89
|
+
response: record.response ? structuredClone(record.response) : void 0,
|
|
90
|
+
scheduledAt: record.scheduledAt.toISOString(),
|
|
91
|
+
startedAt: record.startedAt?.toISOString(),
|
|
92
|
+
updatedAt: record.updatedAt.toISOString()
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
function serializeScheduleRunAttempt(record) {
|
|
96
|
+
return {
|
|
97
|
+
...record,
|
|
98
|
+
completedAt: record.completedAt?.toISOString(),
|
|
99
|
+
createdAt: record.createdAt.toISOString(),
|
|
100
|
+
error: record.error ? { ...record.error } : void 0,
|
|
101
|
+
startedAt: record.startedAt.toISOString(),
|
|
102
|
+
updatedAt: record.updatedAt.toISOString()
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function createMemoryScheduleRunStore() {
|
|
106
|
+
const runs = /* @__PURE__ */ new Map();
|
|
107
|
+
const attempts = /* @__PURE__ */ new Map();
|
|
108
|
+
return {
|
|
109
|
+
createAttempt(attempt) {
|
|
110
|
+
if (attempts.has(attempt.id)) throw scheduleErrorDiagnostics.SCHEDULE_R0030({ message: `Schedule Run Attempt already exists: ${attempt.id}` });
|
|
111
|
+
attempts.set(attempt.id, cloneScheduleRunAttempt(attempt));
|
|
112
|
+
return cloneScheduleRunAttempt(attempt);
|
|
113
|
+
},
|
|
114
|
+
createRun(run) {
|
|
115
|
+
if (runs.has(run.id)) throw scheduleErrorDiagnostics.SCHEDULE_R0031({ message: `Schedule Run already exists: ${run.id}` });
|
|
116
|
+
runs.set(run.id, cloneScheduleRun(run));
|
|
117
|
+
return cloneScheduleRun(run);
|
|
118
|
+
},
|
|
119
|
+
getAttempt(id) {
|
|
120
|
+
const attempt = attempts.get(id);
|
|
121
|
+
return attempt ? cloneScheduleRunAttempt(attempt) : void 0;
|
|
122
|
+
},
|
|
123
|
+
getRun(id) {
|
|
124
|
+
const run = runs.get(id);
|
|
125
|
+
return run ? cloneScheduleRun(run) : void 0;
|
|
126
|
+
},
|
|
127
|
+
listAttempts(runId) {
|
|
128
|
+
return [...attempts.values()].filter((attempt) => attempt.runId === runId).map(cloneScheduleRunAttempt);
|
|
129
|
+
},
|
|
130
|
+
listRuns(options) {
|
|
131
|
+
return selectRuns([...runs.values()], options).map(cloneScheduleRun);
|
|
132
|
+
},
|
|
133
|
+
updateAttempt(id, patch) {
|
|
134
|
+
const existing = attempts.get(id);
|
|
135
|
+
if (!existing) return;
|
|
136
|
+
const next = cloneScheduleRunAttempt({
|
|
137
|
+
...existing,
|
|
138
|
+
...patch,
|
|
139
|
+
updatedAt: patch.updatedAt
|
|
140
|
+
});
|
|
141
|
+
attempts.set(id, next);
|
|
142
|
+
return cloneScheduleRunAttempt(next);
|
|
143
|
+
},
|
|
144
|
+
updateRun(id, patch) {
|
|
145
|
+
const existing = runs.get(id);
|
|
146
|
+
if (!existing) return;
|
|
147
|
+
const next = cloneScheduleRun({
|
|
148
|
+
...existing,
|
|
149
|
+
...patch,
|
|
150
|
+
updatedAt: patch.updatedAt
|
|
151
|
+
});
|
|
152
|
+
runs.set(id, next);
|
|
153
|
+
return cloneScheduleRun(next);
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
function selectRuns(runs, options = {}) {
|
|
158
|
+
const selected = runs.filter((run) => options.scheduleId === void 0 || run.scheduleId === options.scheduleId);
|
|
159
|
+
selected.sort((left, right) => right.scheduledAt.getTime() - left.scheduledAt.getTime());
|
|
160
|
+
return options.limit === void 0 ? selected : selected.slice(0, options.limit);
|
|
161
|
+
}
|
|
162
|
+
/** Index keys carry metadata from the stored record, independent of caller-selected run IDs. */
|
|
163
|
+
function runIndexMetadata(key) {
|
|
164
|
+
try {
|
|
165
|
+
const parts = keySegments(key, 3);
|
|
166
|
+
const scheduledAt = Date.parse(parts[2]);
|
|
167
|
+
if (!Number.isFinite(scheduledAt)) return;
|
|
168
|
+
return {
|
|
169
|
+
id: parts[0],
|
|
170
|
+
scheduleId: parts[1],
|
|
171
|
+
scheduledAt
|
|
172
|
+
};
|
|
173
|
+
} catch {
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
function createKVScheduleRunStore(options) {
|
|
178
|
+
const prefix = options.prefix ?? "vitehub:schedule";
|
|
179
|
+
const store = options.kvStore;
|
|
180
|
+
async function indexRun(run) {
|
|
181
|
+
try {
|
|
182
|
+
await store.set(joinKey(prefix, "schedule-run-index", run.id, run.scheduleId, run.scheduledAt.toISOString()), true);
|
|
183
|
+
} catch {}
|
|
184
|
+
}
|
|
185
|
+
async function indexAttempt(attempt) {
|
|
186
|
+
try {
|
|
187
|
+
await store.set(joinKey(prefix, "schedule-run-attempt-index", attempt.runId, attempt.id), true);
|
|
188
|
+
} catch {}
|
|
189
|
+
}
|
|
190
|
+
async function readSnapshot() {
|
|
191
|
+
const keys = await store.keys(scheduleRunBase(prefix));
|
|
192
|
+
const indexKeys = await store.keys(`${joinKey(prefix, "schedule-run-index")}/`);
|
|
193
|
+
const metadataById = new Map(indexKeys.flatMap((key) => {
|
|
194
|
+
const metadata = runIndexMetadata(key);
|
|
195
|
+
return metadata ? [[metadata.id, metadata]] : [];
|
|
196
|
+
}));
|
|
197
|
+
const known = [];
|
|
198
|
+
const bySchedule = /* @__PURE__ */ new Map();
|
|
199
|
+
const unknown = [];
|
|
200
|
+
const recordsByKey = /* @__PURE__ */ new Map();
|
|
201
|
+
function groupRun(key, metadata) {
|
|
202
|
+
const entry = {
|
|
203
|
+
key,
|
|
204
|
+
scheduledAt: metadata.scheduledAt
|
|
205
|
+
};
|
|
206
|
+
known.push(entry);
|
|
207
|
+
const group = bySchedule.get(metadata.scheduleId) ?? [];
|
|
208
|
+
bySchedule.set(metadata.scheduleId, group);
|
|
209
|
+
group.push(entry);
|
|
210
|
+
}
|
|
211
|
+
for (const key of keys) {
|
|
212
|
+
let id;
|
|
213
|
+
try {
|
|
214
|
+
id = keySegments(key, 1)[0];
|
|
215
|
+
} catch {
|
|
216
|
+
unknown.push(key);
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
const metadata = metadataById.get(id);
|
|
220
|
+
if (!metadata) {
|
|
221
|
+
unknown.push(key);
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
groupRun(key, metadata);
|
|
225
|
+
}
|
|
226
|
+
if (unknown.length > maxLegacyHistoryRecords) return {
|
|
227
|
+
keys,
|
|
228
|
+
known,
|
|
229
|
+
bySchedule,
|
|
230
|
+
recordsByKey,
|
|
231
|
+
unknown
|
|
232
|
+
};
|
|
233
|
+
const legacyKeys = unknown;
|
|
234
|
+
for (let offset = 0; offset < legacyKeys.length; offset += 16) {
|
|
235
|
+
const batch = await Promise.all(legacyKeys.slice(offset, offset + 16).map(async (key) => {
|
|
236
|
+
const stored = await store.get(key);
|
|
237
|
+
const run = stored ? cloneScheduleRun(stored) : void 0;
|
|
238
|
+
recordsByKey.set(key, run);
|
|
239
|
+
if (run) await indexRun(run);
|
|
240
|
+
return {
|
|
241
|
+
key,
|
|
242
|
+
run
|
|
243
|
+
};
|
|
244
|
+
}));
|
|
245
|
+
for (const { key, run } of batch) if (run) groupRun(key, {
|
|
246
|
+
id: run.id,
|
|
247
|
+
scheduleId: run.scheduleId,
|
|
248
|
+
scheduledAt: run.scheduledAt.getTime()
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
for (const entries of [known, ...bySchedule.values()]) entries.sort((left, right) => right.scheduledAt - left.scheduledAt);
|
|
252
|
+
return {
|
|
253
|
+
keys,
|
|
254
|
+
known,
|
|
255
|
+
bySchedule,
|
|
256
|
+
recordsByKey,
|
|
257
|
+
unknown
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
async function listRuns(options, snapshot) {
|
|
261
|
+
if (snapshot.unknown.length > maxLegacyHistoryRecords) throw new ScheduleHistoryIncompleteError(snapshot.unknown.length, maxLegacyHistoryRecords);
|
|
262
|
+
const { keys, recordsByKey } = snapshot;
|
|
263
|
+
const known = options.scheduleId === void 0 ? snapshot.known : snapshot.bySchedule.get(options.scheduleId) ?? [];
|
|
264
|
+
const records = [];
|
|
265
|
+
const selectedKeys = options.scheduleId === void 0 && options.limit === void 0 ? keys : known.slice(0, options.limit ?? known.length).map((entry) => entry.key);
|
|
266
|
+
for (let index = 0; index < selectedKeys.length; index += 16) {
|
|
267
|
+
const batch = await Promise.all(selectedKeys.slice(index, index + 16).map(async (key) => {
|
|
268
|
+
if (recordsByKey.has(key)) return recordsByKey.get(key);
|
|
269
|
+
const stored = await store.get(key);
|
|
270
|
+
const run = stored ? cloneScheduleRun(stored) : void 0;
|
|
271
|
+
recordsByKey.set(key, run);
|
|
272
|
+
return run;
|
|
273
|
+
}));
|
|
274
|
+
records.push(...batch.flatMap((run) => run ? [run] : []));
|
|
275
|
+
}
|
|
276
|
+
return selectRuns(records, options).map(cloneScheduleRun);
|
|
277
|
+
}
|
|
278
|
+
return {
|
|
279
|
+
async createAttempt(attempt) {
|
|
280
|
+
const key = scheduleRunAttemptKey(prefix, attempt.id);
|
|
281
|
+
return await withKVKeyLock(key, async () => {
|
|
282
|
+
if (await store.has(key)) throw scheduleErrorDiagnostics.SCHEDULE_R0032({ message: `Schedule Run Attempt already exists: ${attempt.id}` });
|
|
283
|
+
await store.set(key, serializeScheduleRunAttempt(attempt));
|
|
284
|
+
await indexAttempt(attempt);
|
|
285
|
+
return cloneScheduleRunAttempt(attempt);
|
|
286
|
+
});
|
|
287
|
+
},
|
|
288
|
+
async createRun(run) {
|
|
289
|
+
const key = scheduleRunKey(prefix, run.id);
|
|
290
|
+
return await withKVKeyLock(key, async () => {
|
|
291
|
+
if (await store.has(key)) throw scheduleErrorDiagnostics.SCHEDULE_R0033({ message: `Schedule Run already exists: ${run.id}` });
|
|
292
|
+
await store.set(key, serializeScheduleRun(run));
|
|
293
|
+
await indexRun(run);
|
|
294
|
+
return cloneScheduleRun(run);
|
|
295
|
+
});
|
|
296
|
+
},
|
|
297
|
+
async getAttempt(id) {
|
|
298
|
+
const attempt = await store.get(scheduleRunAttemptKey(prefix, id));
|
|
299
|
+
return attempt ? cloneScheduleRunAttempt(attempt) : void 0;
|
|
300
|
+
},
|
|
301
|
+
async getRun(id) {
|
|
302
|
+
const run = await store.get(scheduleRunKey(prefix, id));
|
|
303
|
+
return run ? cloneScheduleRun(run) : void 0;
|
|
304
|
+
},
|
|
305
|
+
async listAttempts(runId) {
|
|
306
|
+
const [keys, indexKeys] = await Promise.all([store.keys(scheduleRunAttemptBase(prefix)), store.keys(`${joinKey(prefix, "schedule-run-attempt-index")}/`)]);
|
|
307
|
+
const runByAttemptId = /* @__PURE__ */ new Map();
|
|
308
|
+
for (const key of indexKeys) try {
|
|
309
|
+
const parts = keySegments(key, 2);
|
|
310
|
+
runByAttemptId.set(parts[1], parts[0]);
|
|
311
|
+
} catch {}
|
|
312
|
+
const selectedKeys = keys.filter((key) => {
|
|
313
|
+
try {
|
|
314
|
+
const id = keySegments(key, 1)[0];
|
|
315
|
+
const indexedRunId = runByAttemptId.get(id);
|
|
316
|
+
return indexedRunId === void 0 || indexedRunId === runId;
|
|
317
|
+
} catch {
|
|
318
|
+
return true;
|
|
319
|
+
}
|
|
320
|
+
});
|
|
321
|
+
const attempts = [];
|
|
322
|
+
for (let offset = 0; offset < selectedKeys.length; offset += 16) {
|
|
323
|
+
const batch = await Promise.all(selectedKeys.slice(offset, offset + 16).map(async (key) => {
|
|
324
|
+
const stored = await store.get(key);
|
|
325
|
+
if (!stored) return;
|
|
326
|
+
const attempt = cloneScheduleRunAttempt(stored);
|
|
327
|
+
if (!runByAttemptId.has(attempt.id)) await indexAttempt(attempt);
|
|
328
|
+
return attempt.runId === runId ? attempt : void 0;
|
|
329
|
+
}));
|
|
330
|
+
attempts.push(...batch.flatMap((attempt) => attempt ? [attempt] : []));
|
|
331
|
+
}
|
|
332
|
+
return attempts;
|
|
333
|
+
},
|
|
334
|
+
async listRuns(options = {}) {
|
|
335
|
+
return listRuns(options, await readSnapshot());
|
|
336
|
+
},
|
|
337
|
+
async listRunsBatch(options) {
|
|
338
|
+
if (!options.length) return [];
|
|
339
|
+
const snapshot = await readSnapshot();
|
|
340
|
+
const results = [];
|
|
341
|
+
for (const query of options) results.push(await listRuns(query, snapshot));
|
|
342
|
+
return results;
|
|
343
|
+
},
|
|
344
|
+
async updateAttempt(id, patch) {
|
|
345
|
+
const key = scheduleRunAttemptKey(prefix, id);
|
|
346
|
+
return await withKVKeyLock(key, async () => {
|
|
347
|
+
const existing = await store.get(key);
|
|
348
|
+
if (!existing) return;
|
|
349
|
+
const next = cloneScheduleRunAttempt({
|
|
350
|
+
...cloneScheduleRunAttempt(existing),
|
|
351
|
+
...patch,
|
|
352
|
+
updatedAt: patch.updatedAt
|
|
353
|
+
});
|
|
354
|
+
await store.set(key, serializeScheduleRunAttempt(next));
|
|
355
|
+
return cloneScheduleRunAttempt(next);
|
|
356
|
+
});
|
|
357
|
+
},
|
|
358
|
+
async updateRun(id, patch) {
|
|
359
|
+
const key = scheduleRunKey(prefix, id);
|
|
360
|
+
return await withKVKeyLock(key, async () => {
|
|
361
|
+
const existing = await store.get(key);
|
|
362
|
+
if (!existing) return;
|
|
363
|
+
const next = cloneScheduleRun({
|
|
364
|
+
...cloneScheduleRun(existing),
|
|
365
|
+
...patch,
|
|
366
|
+
updatedAt: patch.updatedAt
|
|
367
|
+
});
|
|
368
|
+
await store.set(key, serializeScheduleRun(next));
|
|
369
|
+
return cloneScheduleRun(next);
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
//#endregion
|
|
375
|
+
//#region src/runtime/state.ts
|
|
376
|
+
let runtimeRegistry;
|
|
377
|
+
let runtimeRegistryVersion = 0;
|
|
378
|
+
let runStore;
|
|
379
|
+
const loadedRegistryEntries = /* @__PURE__ */ new Map();
|
|
380
|
+
const loadingRegistryEntries = /* @__PURE__ */ new Map();
|
|
381
|
+
const loadingRegistryStorage = new AsyncLocalStorage();
|
|
382
|
+
function isObjectRecord(value) {
|
|
383
|
+
return Object(value) === value && !Array.isArray(value);
|
|
384
|
+
}
|
|
385
|
+
function isScheduleDefinition(value) {
|
|
386
|
+
return isObjectRecord(value) && Object.hasOwn(value, "handler") && typeof Reflect.get(value, "handler") === "function";
|
|
387
|
+
}
|
|
388
|
+
function setScheduleRuntimeRegistry(registry) {
|
|
389
|
+
runtimeRegistry = registry;
|
|
390
|
+
runtimeRegistryVersion++;
|
|
391
|
+
loadedRegistryEntries.clear();
|
|
392
|
+
loadingRegistryEntries.clear();
|
|
393
|
+
}
|
|
394
|
+
function getScheduleRuntimeRegistry() {
|
|
395
|
+
return runtimeRegistry;
|
|
396
|
+
}
|
|
397
|
+
function setScheduleRunStore(store) {
|
|
398
|
+
runStore = store;
|
|
399
|
+
}
|
|
400
|
+
function getScheduleRunStore() {
|
|
401
|
+
return runStore ??= createMemoryScheduleRunStore();
|
|
402
|
+
}
|
|
403
|
+
async function loadScheduleDefinition(name) {
|
|
404
|
+
const entry = runtimeRegistry && Object.hasOwn(runtimeRegistry, name) ? runtimeRegistry[name] : void 0;
|
|
405
|
+
if (typeof entry !== "function") return;
|
|
406
|
+
if (loadedRegistryEntries.has(name)) return loadedRegistryEntries.get(name);
|
|
407
|
+
const activeLoads = loadingRegistryStorage.getStore();
|
|
408
|
+
const inFlightEntry = loadingRegistryEntries.get(name);
|
|
409
|
+
if (inFlightEntry) {
|
|
410
|
+
if (activeLoads?.has(name)) return void 0;
|
|
411
|
+
const loaded = await inFlightEntry.promise;
|
|
412
|
+
return inFlightEntry.version === runtimeRegistryVersion ? loaded : void 0;
|
|
413
|
+
}
|
|
414
|
+
const loadingVersion = runtimeRegistryVersion;
|
|
415
|
+
const nextActiveLoads = new Set(activeLoads);
|
|
416
|
+
nextActiveLoads.add(name);
|
|
417
|
+
const loadingEntry = Promise.resolve().then(() => loadingRegistryStorage.run(nextActiveLoads, async () => {
|
|
418
|
+
const loaded = await entry();
|
|
419
|
+
if (isScheduleDefinition(loaded)) return loaded;
|
|
420
|
+
if (isObjectRecord(loaded) && Object.hasOwn(loaded, "default")) {
|
|
421
|
+
const definition = Reflect.get(loaded, "default");
|
|
422
|
+
if (isScheduleDefinition(definition)) return definition;
|
|
423
|
+
}
|
|
424
|
+
}));
|
|
425
|
+
loadingRegistryEntries.set(name, {
|
|
426
|
+
promise: loadingEntry,
|
|
427
|
+
version: loadingVersion
|
|
428
|
+
});
|
|
429
|
+
try {
|
|
430
|
+
const loaded = await loadingEntry;
|
|
431
|
+
if (loadingVersion === runtimeRegistryVersion) {
|
|
432
|
+
loadedRegistryEntries.set(name, loaded);
|
|
433
|
+
return loaded;
|
|
434
|
+
}
|
|
435
|
+
return;
|
|
436
|
+
} finally {
|
|
437
|
+
if (loadingRegistryEntries.get(name)?.promise === loadingEntry) loadingRegistryEntries.delete(name);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
function resetScheduleRuntime() {
|
|
441
|
+
runtimeRegistry = void 0;
|
|
442
|
+
runtimeRegistryVersion++;
|
|
443
|
+
runStore = void 0;
|
|
444
|
+
loadedRegistryEntries.clear();
|
|
445
|
+
loadingRegistryEntries.clear();
|
|
446
|
+
}
|
|
447
|
+
//#endregion
|
|
448
|
+
export { setScheduleRunStore as a, createMemoryScheduleRunStore as c, resetScheduleRuntime as i, getScheduleRuntimeRegistry as n, setScheduleRuntimeRegistry as o, loadScheduleDefinition as r, createKVScheduleRunStore as s, getScheduleRunStore as t };
|