@vite-hub/schedule 0.1.0 → 0.4.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 +118 -100
- package/dist/console-wEhr0LWn.d.ts +330 -0
- package/dist/definition.d.ts +6 -2
- package/dist/definition.js +47 -1
- package/dist/due-sOJvF_6Z.js +144 -0
- package/dist/durability.d.ts +14 -0
- package/dist/durability.js +23 -0
- package/dist/error-diagnostics-BBtYYl8j.js +170 -0
- package/dist/error-diagnostics-CQ4BUqRe.js +270 -0
- package/dist/index.d.ts +73 -5
- package/dist/index.js +56 -2
- package/dist/invariant-DolT9EEx.js +22 -0
- package/dist/{kv-storage-DWinmLLy.js → kv-storage-2kZtP2CC.js} +4 -4
- package/dist/{kv-storage-Bv9ocZT-.d.ts → kv-storage-Bm9aYLfZ.d.ts} +7 -3
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/{operations-tNUdj3G4.d.ts → operation-definition-nmRu_O3V.d.ts} +42 -15
- package/dist/operations-DqwmJ8MN.js +207 -0
- package/dist/operations.d.ts +36 -4
- package/dist/operations.js +130 -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-B0pc3JY0.js +146 -0
- package/dist/started-Bk2Icknk.js +201 -0
- package/dist/{execute-BJrgNgQ0.js → started-errors-DEmYH-vp.js} +94 -38
- package/dist/{inspect-DTfAo5gS.js → started-name-ruCM1EtQ.js} +5 -1
- package/dist/state-CPd10SXq.d.ts +58 -0
- package/dist/{state-DSxmHPn3.js → state-D4SZH6zk.js} +50 -22
- package/dist/{static-6g82xguw.js → static-7JCga3Iu.js} +80 -44
- package/dist/store-DeMojnXM.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 +6128 -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/operations-gk2qzhYV.js +0 -131
- package/dist/store-QAOd8bxm.d.ts +0 -11
- package/dist/vite-BAVyZ8hZ.d.ts +0 -474
- package/dist/vite-BJwZkMrn.js +0 -5193
|
@@ -1,6 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { r as
|
|
3
|
-
import {
|
|
1
|
+
import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
|
|
2
|
+
import { a as validateScheduledAt, i as scheduleIdempotencyKey, o as createScheduleError, r as parseScheduledAt, t as runWithScheduleWaitUntil } from "./wait-until-Dy4Bn3ZN.js";
|
|
3
|
+
import { i as getScheduleRunStore } from "./state-D4SZH6zk.js";
|
|
4
|
+
import { defineErrors, serializeResponse, toResponse } from "@vite-hub/runtime";
|
|
5
|
+
import { emitRunFailed, toRunFailedError } from "@vite-hub/runtime/internal/run-failed";
|
|
6
|
+
import { runInRunScopes } from "@vite-hub/runtime/internal/run-scope";
|
|
4
7
|
//#region ../internal/src/runtime/random.ts
|
|
5
8
|
function randomId(prefix) {
|
|
6
9
|
const body = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
|
|
@@ -86,6 +89,7 @@ function toHandlerContext(run, attempt, waitUntil) {
|
|
|
86
89
|
return {
|
|
87
90
|
attemptId: attempt.id,
|
|
88
91
|
id: run.id,
|
|
92
|
+
idempotencyKey: scheduleIdempotencyKey(run.scheduleId, run.scheduledAt),
|
|
89
93
|
runId: run.id,
|
|
90
94
|
scheduleId: run.scheduleId,
|
|
91
95
|
scheduledAt: run.scheduledAt,
|
|
@@ -123,6 +127,22 @@ async function failRun(run, attempt, error, store = getScheduleRunStore()) {
|
|
|
123
127
|
updatedAt: now
|
|
124
128
|
}));
|
|
125
129
|
}
|
|
130
|
+
const stoppedAttemptError = {
|
|
131
|
+
message: "The process that ran this attempt stopped before the attempt finished.",
|
|
132
|
+
name: "ScheduleAttemptStopped"
|
|
133
|
+
};
|
|
134
|
+
async function failStoppedAttempts(run, store) {
|
|
135
|
+
const now = /* @__PURE__ */ new Date();
|
|
136
|
+
for (const attempt of await store.listAttempts(run.id)) {
|
|
137
|
+
if (attempt.status !== "running") continue;
|
|
138
|
+
await store.updateAttempt(attempt.id, {
|
|
139
|
+
completedAt: now,
|
|
140
|
+
error: stoppedAttemptError,
|
|
141
|
+
status: "failed",
|
|
142
|
+
updatedAt: now
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
}
|
|
126
146
|
async function createScheduleRun(options) {
|
|
127
147
|
const scheduledAt = validateScheduledAt(options.scheduledAt ?? /* @__PURE__ */ new Date());
|
|
128
148
|
return (await createOrGetRun({
|
|
@@ -136,21 +156,39 @@ async function executeSchedule(options) {
|
|
|
136
156
|
...options,
|
|
137
157
|
scheduledAt
|
|
138
158
|
});
|
|
139
|
-
if (!created) return run;
|
|
140
159
|
const runStore = options.runStore ?? getScheduleRunStore();
|
|
160
|
+
if (!created) {
|
|
161
|
+
if (!options.claimed || run.status === "succeeded" || run.status === "failed") {
|
|
162
|
+
options.onExecution?.();
|
|
163
|
+
return run;
|
|
164
|
+
}
|
|
165
|
+
await failStoppedAttempts(run, runStore);
|
|
166
|
+
}
|
|
141
167
|
const attempt = await startAttempt(run, runStore);
|
|
168
|
+
options.onExecution?.();
|
|
169
|
+
let response;
|
|
142
170
|
try {
|
|
143
|
-
const value = await runWithScheduleWaitUntil((waitUntil) => options.definition.handler(toHandlerContext(run, attempt, waitUntil)), options.waitUntil);
|
|
144
|
-
|
|
171
|
+
const value = await runInRunScopes(() => runWithScheduleWaitUntil((waitUntil) => options.definition.handler(toHandlerContext(run, attempt, waitUntil)), options.waitUntil));
|
|
172
|
+
response = await serializeResponse(toResponse(value));
|
|
145
173
|
} catch (error) {
|
|
146
174
|
const failed = await failRun(run, attempt, error, runStore);
|
|
175
|
+
await emitRunFailed({
|
|
176
|
+
event: "schedule.failed",
|
|
177
|
+
schedule: failed.scheduleId,
|
|
178
|
+
runId: failed.id,
|
|
179
|
+
error: toRunFailedError(error),
|
|
180
|
+
failedAt: (failed.completedAt ?? /* @__PURE__ */ new Date()).toISOString()
|
|
181
|
+
});
|
|
147
182
|
if (options.captureHandlerFailure) return failed;
|
|
148
183
|
throw error;
|
|
149
184
|
}
|
|
185
|
+
return await completeRun(run, attempt, response, runStore);
|
|
150
186
|
}
|
|
151
187
|
async function executeStaticSchedule(options) {
|
|
152
188
|
return await executeSchedule({
|
|
189
|
+
...options.claimed ? { claimed: true } : {},
|
|
153
190
|
definition: options.definition,
|
|
191
|
+
onExecution: options.onExecution,
|
|
154
192
|
scheduleId: options.name,
|
|
155
193
|
source: "static",
|
|
156
194
|
scheduledAt: options.scheduledAt,
|
|
@@ -158,44 +196,62 @@ async function executeStaticSchedule(options) {
|
|
|
158
196
|
waitUntil: options.waitUntil
|
|
159
197
|
});
|
|
160
198
|
}
|
|
161
|
-
function isObjectRecord(value) {
|
|
162
|
-
return Object(value) === value && !Array.isArray(value);
|
|
163
|
-
}
|
|
164
199
|
function isStaticScheduleDefinition(value) {
|
|
165
|
-
return
|
|
200
|
+
return isRecordOrFunction(value) && Object.hasOwn(value, "handler") && typeof value.handler === "function" && Object.hasOwn(value, "cron");
|
|
166
201
|
}
|
|
167
202
|
async function loadStaticScheduleDefinition(name, registry) {
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
loaded = typeof entry === "function" ? await entry() : void 0;
|
|
172
|
-
} else loaded = await loadScheduleDefinition(name);
|
|
173
|
-
const record = isObjectRecord(loaded) ? loaded : void 0;
|
|
203
|
+
const entry = Object.hasOwn(registry, name) ? registry[name] : void 0;
|
|
204
|
+
const loaded = typeof entry === "function" ? await entry() : void 0;
|
|
205
|
+
const record = isRecordOrFunction(loaded) ? loaded : void 0;
|
|
174
206
|
return record && isStaticScheduleDefinition(record) ? record : record && Object.hasOwn(record, "default") && isStaticScheduleDefinition(record.default) ? record.default : void 0;
|
|
175
207
|
}
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
const definition = typeof name === "string" && name ? await loadStaticScheduleDefinition(name, options.registry) : void 0;
|
|
208
|
+
async function resolveManualSchedule(registry, name) {
|
|
209
|
+
const definition = typeof name === "string" && name ? await loadStaticScheduleDefinition(name, registry) : void 0;
|
|
179
210
|
if (!definition) throw createScheduleError("SCHEDULE_DEFINITION_NOT_FOUND");
|
|
180
211
|
if (definition.options?.manual !== true) throw createScheduleError("SCHEDULE_MANUAL_RUN_DISABLED");
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
throw error;
|
|
198
|
-
}
|
|
212
|
+
return definition;
|
|
213
|
+
}
|
|
214
|
+
function executeManualSchedule(definition, name, scheduledAt) {
|
|
215
|
+
return executeSchedule({
|
|
216
|
+
captureHandlerFailure: true,
|
|
217
|
+
definition,
|
|
218
|
+
runIdSuffix: randomId("manual"),
|
|
219
|
+
scheduleId: name,
|
|
220
|
+
scheduledAt,
|
|
221
|
+
source: "manual",
|
|
222
|
+
target: name
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
/** Runs a manually dispatchable static Schedule Definition of `registry` immediately. */
|
|
226
|
+
async function runScheduleFrom(registry, name, options = {}) {
|
|
227
|
+
return await executeManualSchedule(await resolveManualSchedule(registry, name), name, parseScheduledAt(options.scheduledAt));
|
|
199
228
|
}
|
|
200
229
|
//#endregion
|
|
201
|
-
|
|
230
|
+
//#region src/started-errors.ts
|
|
231
|
+
const startedScheduleErrors = /*#__PURE__*/ defineErrors({
|
|
232
|
+
docs: "https://vitehub.dev/docs/schedule/diagnostics",
|
|
233
|
+
codes: {
|
|
234
|
+
SCHEDULE_NOT_STARTABLE: {
|
|
235
|
+
why: ({ name }) => `No Schedule Definition without \`cron\` is named "${name}", so \`startSchedule()\` cannot start it.`,
|
|
236
|
+
fix: "Add `server/schedules/<name>.ts` with `export default defineSchedule({ handler })` and no `cron`. A Definition with its own `cron` runs only on that cron."
|
|
237
|
+
},
|
|
238
|
+
SCHEDULE_INVALID_OPTIONS: {
|
|
239
|
+
why: ({ problem }) => `\`startSchedule()\` options are invalid: ${problem}`,
|
|
240
|
+
fix: "Pass `{ at }` for one run, or `{ cron, timeZone }` for a repeating Schedule, and a JSON `payload`."
|
|
241
|
+
},
|
|
242
|
+
SCHEDULE_NOT_FOUND: {
|
|
243
|
+
why: ({ id }) => `No started Schedule has the id "${id}". It ran its last time, was cancelled, or never existed.`,
|
|
244
|
+
fix: "List the started Schedules with `listSchedules()` or `vitehub schedule list`."
|
|
245
|
+
},
|
|
246
|
+
SCHEDULE_STORE_MISSING: {
|
|
247
|
+
why: "This server has no store for started Schedules.",
|
|
248
|
+
fix: "Add a Schedule Definition without `cron` in `server/schedules/`, enable `kv`, and build with Nitro. On Node, also set `schedule: { runtime: { driver: \"process\" } }`."
|
|
249
|
+
},
|
|
250
|
+
SCHEDULE_STORE_FAILED: {
|
|
251
|
+
why: "The store of started Schedules failed. `error.cause` has the store error.",
|
|
252
|
+
fix: "Check that KV is enabled and reachable from this server, then try again."
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
//#endregion
|
|
257
|
+
export { executeStaticSchedule as a, runScheduleFrom as c, executeSchedule as i, toRunId as l, createScheduleRun as n, loadStaticScheduleDefinition as o, executeManualSchedule as r, resolveManualSchedule as s, startedScheduleErrors as t, randomId as u };
|
|
@@ -115,4 +115,8 @@ function redactInspectionText(value) {
|
|
|
115
115
|
return value.replace(embeddedUrlCredentialPattern, `$1${redactedInspectionValue}@`).replace(embeddedAuthorizationPattern, `$1${redactedInspectionValue}`).replace(embeddedCookiePattern, `$1${redactedInspectionValue}`).replace(embeddedBearerPattern, `Bearer ${redactedInspectionValue}`).replace(embeddedSecretAssignmentPattern, `$1${redactedInspectionValue}`);
|
|
116
116
|
}
|
|
117
117
|
//#endregion
|
|
118
|
-
|
|
118
|
+
//#region src/runtime/started-name.ts
|
|
119
|
+
/** Name of the Schedule that runs due started Schedules each minute. Discovery adds it when a Definition has no `cron`. */
|
|
120
|
+
const startedSchedulesTickName = "vitehub/started-schedules";
|
|
121
|
+
//#endregion
|
|
122
|
+
export { isAbsolute as a, dirname as i, redactInspectionText as n, relative as o, relativeDefinitionFile as r, resolve as s, startedSchedulesTickName as t };
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { a as ScheduleDefinitionRegistry, b as StartedScheduleStore, g as ScheduleRunStore, n as ScheduleDefinition, s as ScheduleRegistryDefinition } from "./types-Cw5LjPuc.js";
|
|
2
|
+
import { LeaseStore } from "@vite-hub/runtime";
|
|
3
|
+
//#region src/runtime/claims.d.ts
|
|
4
|
+
/** `held` when another process holds the occurrence now, `done` when a process finished it, `ran` when this call ran it. */
|
|
5
|
+
type OccurrenceClaimResult = "done" | "held" | "ran";
|
|
6
|
+
/** Runs each Schedule occurrence in one process of all the processes that share `leases`. */
|
|
7
|
+
interface OccurrenceClaims {
|
|
8
|
+
/**
|
|
9
|
+
* Runs `run` when this process gets the claim on `runId` and no process finished it. While `run` works, the claim is
|
|
10
|
+
* renewed. Call `markFinal` before invoking the handler or when an existing run is final. Then a done marker stays
|
|
11
|
+
* for `doneTtlMs`, also when the handler throws. Errors before `markFinal` leave the occurrence retryable.
|
|
12
|
+
*/
|
|
13
|
+
run(runId: string, run: (markFinal: () => void) => Promise<unknown>): Promise<OccurrenceClaimResult>;
|
|
14
|
+
}
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region src/runtime/state.d.ts
|
|
17
|
+
/** The cron and time zone of a Schedule that the Process Runtime runs. */
|
|
18
|
+
type ProcessScheduleTimingRecord = Pick<ScheduleDefinition, "cron" | "timeZone">;
|
|
19
|
+
interface HostScheduleInventory {
|
|
20
|
+
timings: Readonly<Record<string, {
|
|
21
|
+
cron: string;
|
|
22
|
+
timeZone?: string;
|
|
23
|
+
}>>;
|
|
24
|
+
registry?: ScheduleDefinitionRegistry;
|
|
25
|
+
}
|
|
26
|
+
/** What `startSchedule()` and the started-Schedule tick use. The generated Nitro plugin installs it. */
|
|
27
|
+
interface StartedScheduleRuntime {
|
|
28
|
+
/** How far back the first tick after a start runs cron minutes that no tick checked. */
|
|
29
|
+
catchUpMs: number;
|
|
30
|
+
/** Last minute, in epoch milliseconds, that a tick of this process checked. */
|
|
31
|
+
checkedThrough?: number;
|
|
32
|
+
/** Occurrences that another process held at a tick, by run id. The next tick tries them again. */
|
|
33
|
+
held?: Map<string, {
|
|
34
|
+
scheduledAt: Date;
|
|
35
|
+
scheduleId: string;
|
|
36
|
+
}>;
|
|
37
|
+
/** Schedule Definitions without `cron`, by name. */
|
|
38
|
+
registry: ScheduleDefinitionRegistry;
|
|
39
|
+
store: StartedScheduleStore;
|
|
40
|
+
}
|
|
41
|
+
declare function setScheduleRuntimeRegistry(registry: ScheduleDefinitionRegistry | undefined): void;
|
|
42
|
+
declare function getScheduleRuntimeRegistry(): ScheduleDefinitionRegistry | undefined;
|
|
43
|
+
/** Publish only ready runtimes, retaining earlier snapshots until their controllers close. */
|
|
44
|
+
declare function registerProcessScheduleDefinitions(definitions: ReadonlyMap<string, ProcessScheduleTimingRecord>): () => void;
|
|
45
|
+
declare function getProcessScheduleDefinitions(): ReadonlyMap<string, ProcessScheduleTimingRecord> | undefined;
|
|
46
|
+
declare function setHostScheduleInventory(inventory: HostScheduleInventory): void;
|
|
47
|
+
declare function getHostScheduleInventory(): HostScheduleInventory | undefined;
|
|
48
|
+
declare function setScheduleRunStore(store: ScheduleRunStore | undefined): void;
|
|
49
|
+
declare function getScheduleRunStore(): ScheduleRunStore;
|
|
50
|
+
/** Installs the claims that make each occurrence run in one process only. The Process Runtime installs them. */
|
|
51
|
+
declare function setScheduleOccurrenceClaims(claims: OccurrenceClaims | undefined): void;
|
|
52
|
+
declare function getScheduleOccurrenceClaims(): OccurrenceClaims | undefined;
|
|
53
|
+
declare function setStartedScheduleRuntime(runtime: StartedScheduleRuntime | undefined): void;
|
|
54
|
+
declare function getStartedScheduleRuntime(): StartedScheduleRuntime | undefined;
|
|
55
|
+
declare function loadScheduleDefinition(name: string): Promise<ScheduleRegistryDefinition | undefined>;
|
|
56
|
+
declare function resetScheduleRuntime(): void;
|
|
57
|
+
//#endregion
|
|
58
|
+
export { getScheduleRunStore as a, loadScheduleDefinition as c, setHostScheduleInventory as d, setScheduleOccurrenceClaims as f, setStartedScheduleRuntime as h, getScheduleOccurrenceClaims as i, registerProcessScheduleDefinitions as l, setScheduleRuntimeRegistry as m, getHostScheduleInventory as n, getScheduleRuntimeRegistry as o, setScheduleRunStore as p, getProcessScheduleDefinitions as r, getStartedScheduleRuntime as s, StartedScheduleRuntime as t, resetScheduleRuntime as u };
|
|
@@ -1,19 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
|
|
2
|
+
import { t as scheduleErrorDiagnostics } from "./error-diagnostics-BBtYYl8j.js";
|
|
2
3
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
4
|
//#region src/runtime/store.ts
|
|
4
5
|
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
6
|
function trimPrefix(prefix) {
|
|
18
7
|
return prefix.replace(/^\/+|\/+$/g, "");
|
|
19
8
|
}
|
|
@@ -155,7 +144,7 @@ function createMemoryScheduleRunStore() {
|
|
|
155
144
|
};
|
|
156
145
|
}
|
|
157
146
|
function selectRuns(runs, options = {}) {
|
|
158
|
-
const selected = runs.filter((run) => options.scheduleId === void 0 || run.scheduleId === options.scheduleId);
|
|
147
|
+
const selected = runs.filter((run) => (options.scheduleId === void 0 || run.scheduleId === options.scheduleId) && (options.idPrefix === void 0 || run.id.startsWith(options.idPrefix)));
|
|
159
148
|
selected.sort((left, right) => right.scheduledAt.getTime() - left.scheduledAt.getTime());
|
|
160
149
|
return options.limit === void 0 ? selected : selected.slice(0, options.limit);
|
|
161
150
|
}
|
|
@@ -200,6 +189,7 @@ function createKVScheduleRunStore(options) {
|
|
|
200
189
|
const recordsByKey = /* @__PURE__ */ new Map();
|
|
201
190
|
function groupRun(key, metadata) {
|
|
202
191
|
const entry = {
|
|
192
|
+
id: metadata.id,
|
|
203
193
|
key,
|
|
204
194
|
scheduledAt: metadata.scheduledAt
|
|
205
195
|
};
|
|
@@ -258,11 +248,15 @@ function createKVScheduleRunStore(options) {
|
|
|
258
248
|
};
|
|
259
249
|
}
|
|
260
250
|
async function listRuns(options, snapshot) {
|
|
261
|
-
if (snapshot.unknown.length > maxLegacyHistoryRecords) throw
|
|
251
|
+
if (snapshot.unknown.length > maxLegacyHistoryRecords) throw scheduleErrorDiagnostics.SCHEDULE_HISTORY_INCOMPLETE({
|
|
252
|
+
maxRecords: maxLegacyHistoryRecords,
|
|
253
|
+
recordCount: snapshot.unknown.length
|
|
254
|
+
});
|
|
262
255
|
const { keys, recordsByKey } = snapshot;
|
|
263
256
|
const known = options.scheduleId === void 0 ? snapshot.known : snapshot.bySchedule.get(options.scheduleId) ?? [];
|
|
257
|
+
const matching = options.idPrefix === void 0 ? known : known.filter((entry) => entry.id.startsWith(options.idPrefix));
|
|
264
258
|
const records = [];
|
|
265
|
-
const selectedKeys = options.scheduleId === void 0 && options.limit === void 0 ? keys :
|
|
259
|
+
const selectedKeys = options.scheduleId === void 0 && options.idPrefix === void 0 && options.limit === void 0 ? keys : matching.slice(0, options.limit ?? matching.length).map((entry) => entry.key);
|
|
266
260
|
for (let index = 0; index < selectedKeys.length; index += 16) {
|
|
267
261
|
const batch = await Promise.all(selectedKeys.slice(index, index + 16).map(async (key) => {
|
|
268
262
|
if (recordsByKey.has(key)) return recordsByKey.get(key);
|
|
@@ -374,16 +368,17 @@ function createKVScheduleRunStore(options) {
|
|
|
374
368
|
//#endregion
|
|
375
369
|
//#region src/runtime/state.ts
|
|
376
370
|
let runtimeRegistry;
|
|
371
|
+
let hostInventory;
|
|
372
|
+
const processDefinitions = /* @__PURE__ */ new Set();
|
|
377
373
|
let runtimeRegistryVersion = 0;
|
|
378
374
|
let runStore;
|
|
375
|
+
let startedRuntime;
|
|
376
|
+
let occurrenceClaims;
|
|
379
377
|
const loadedRegistryEntries = /* @__PURE__ */ new Map();
|
|
380
378
|
const loadingRegistryEntries = /* @__PURE__ */ new Map();
|
|
381
379
|
const loadingRegistryStorage = new AsyncLocalStorage();
|
|
382
|
-
function isObjectRecord(value) {
|
|
383
|
-
return Object(value) === value && !Array.isArray(value);
|
|
384
|
-
}
|
|
385
380
|
function isScheduleDefinition(value) {
|
|
386
|
-
return
|
|
381
|
+
return isRecordOrFunction(value) && Object.hasOwn(value, "handler") && typeof Reflect.get(value, "handler") === "function";
|
|
387
382
|
}
|
|
388
383
|
function setScheduleRuntimeRegistry(registry) {
|
|
389
384
|
runtimeRegistry = registry;
|
|
@@ -394,12 +389,41 @@ function setScheduleRuntimeRegistry(registry) {
|
|
|
394
389
|
function getScheduleRuntimeRegistry() {
|
|
395
390
|
return runtimeRegistry;
|
|
396
391
|
}
|
|
392
|
+
/** Publish only ready runtimes, retaining earlier snapshots until their controllers close. */
|
|
393
|
+
function registerProcessScheduleDefinitions(definitions) {
|
|
394
|
+
processDefinitions.add(definitions);
|
|
395
|
+
return () => {
|
|
396
|
+
processDefinitions.delete(definitions);
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
function getProcessScheduleDefinitions() {
|
|
400
|
+
return [...processDefinitions].at(-1);
|
|
401
|
+
}
|
|
402
|
+
function setHostScheduleInventory(inventory) {
|
|
403
|
+
hostInventory = inventory;
|
|
404
|
+
}
|
|
405
|
+
function getHostScheduleInventory() {
|
|
406
|
+
return hostInventory;
|
|
407
|
+
}
|
|
397
408
|
function setScheduleRunStore(store) {
|
|
398
409
|
runStore = store;
|
|
399
410
|
}
|
|
400
411
|
function getScheduleRunStore() {
|
|
401
412
|
return runStore ??= createMemoryScheduleRunStore();
|
|
402
413
|
}
|
|
414
|
+
/** Installs the claims that make each occurrence run in one process only. The Process Runtime installs them. */
|
|
415
|
+
function setScheduleOccurrenceClaims(claims) {
|
|
416
|
+
occurrenceClaims = claims;
|
|
417
|
+
}
|
|
418
|
+
function getScheduleOccurrenceClaims() {
|
|
419
|
+
return occurrenceClaims;
|
|
420
|
+
}
|
|
421
|
+
function setStartedScheduleRuntime(runtime) {
|
|
422
|
+
startedRuntime = runtime;
|
|
423
|
+
}
|
|
424
|
+
function getStartedScheduleRuntime() {
|
|
425
|
+
return startedRuntime;
|
|
426
|
+
}
|
|
403
427
|
async function loadScheduleDefinition(name) {
|
|
404
428
|
const entry = runtimeRegistry && Object.hasOwn(runtimeRegistry, name) ? runtimeRegistry[name] : void 0;
|
|
405
429
|
if (typeof entry !== "function") return;
|
|
@@ -417,7 +441,7 @@ async function loadScheduleDefinition(name) {
|
|
|
417
441
|
const loadingEntry = Promise.resolve().then(() => loadingRegistryStorage.run(nextActiveLoads, async () => {
|
|
418
442
|
const loaded = await entry();
|
|
419
443
|
if (isScheduleDefinition(loaded)) return loaded;
|
|
420
|
-
if (
|
|
444
|
+
if (isRecordOrFunction(loaded) && Object.hasOwn(loaded, "default")) {
|
|
421
445
|
const definition = Reflect.get(loaded, "default");
|
|
422
446
|
if (isScheduleDefinition(definition)) return definition;
|
|
423
447
|
}
|
|
@@ -439,10 +463,14 @@ async function loadScheduleDefinition(name) {
|
|
|
439
463
|
}
|
|
440
464
|
function resetScheduleRuntime() {
|
|
441
465
|
runtimeRegistry = void 0;
|
|
466
|
+
hostInventory = void 0;
|
|
467
|
+
processDefinitions.clear();
|
|
442
468
|
runtimeRegistryVersion++;
|
|
443
469
|
runStore = void 0;
|
|
470
|
+
startedRuntime = void 0;
|
|
471
|
+
occurrenceClaims = void 0;
|
|
444
472
|
loadedRegistryEntries.clear();
|
|
445
473
|
loadingRegistryEntries.clear();
|
|
446
474
|
}
|
|
447
475
|
//#endregion
|
|
448
|
-
export {
|
|
476
|
+
export { joinKey as _, getScheduleRuntimeRegistry as a, registerProcessScheduleDefinitions as c, setScheduleOccurrenceClaims as d, setScheduleRunStore as f, createMemoryScheduleRunStore as g, createKVScheduleRunStore as h, getScheduleRunStore as i, resetScheduleRuntime as l, setStartedScheduleRuntime as m, getProcessScheduleDefinitions as n, getStartedScheduleRuntime as o, setScheduleRuntimeRegistry as p, getScheduleOccurrenceClaims as r, loadScheduleDefinition as s, getHostScheduleInventory as t, setHostScheduleInventory as u, keySegments as v };
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
|
|
2
|
+
import { t as scheduleErrorDiagnostics } from "./error-diagnostics-BBtYYl8j.js";
|
|
3
|
+
import { a as validateScheduledAt, i as scheduleIdempotencyKey, n as isScheduleDate, o as createScheduleError, s as invalidScheduleValueDetails, t as runWithScheduleWaitUntil } from "./wait-until-Dy4Bn3ZN.js";
|
|
4
|
+
import { n as latestCronMinute, t as isScheduleDue } from "./due-sOJvF_6Z.js";
|
|
3
5
|
import { normalizeRuntimeDiagnosticError } from "@vite-hub/runtime";
|
|
4
|
-
import {
|
|
6
|
+
import { emitRunFailed, toRunFailedError } from "@vite-hub/runtime/internal/run-failed";
|
|
7
|
+
import { runInRunScopes } from "@vite-hub/runtime/internal/run-scope";
|
|
5
8
|
//#region ../internal/src/secret.ts
|
|
6
9
|
const secretEncoder = new TextEncoder();
|
|
7
10
|
/**
|
|
@@ -23,6 +26,7 @@ function isViteHubSecretEqual(actual, expected) {
|
|
|
23
26
|
function isViteHubBearerSecretEqual(authorization, expected) {
|
|
24
27
|
return isViteHubSecretEqual(/^Bearer\s+(.+)$/i.exec(authorization ?? "")?.[1], expected);
|
|
25
28
|
}
|
|
29
|
+
Object.freeze({ prefix: "sha256=" });
|
|
26
30
|
//#endregion
|
|
27
31
|
//#region src/runtime/static.ts
|
|
28
32
|
const intrinsicErrorIsError = Error.isError;
|
|
@@ -88,30 +92,69 @@ function isScheduleRuntimeError(error) {
|
|
|
88
92
|
return false;
|
|
89
93
|
}
|
|
90
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* Estimates a wake minute from callback time when the host supplies no scheduled timestamp. This is the newest UTC
|
|
97
|
+
* cron match within one day, or the current minute when none matches. It cannot identify a delayed or retried wake
|
|
98
|
+
* after another cron match; callers must not treat it as the provider's occurrence identity.
|
|
99
|
+
*/
|
|
100
|
+
function scheduledWakeTime(cron, now = /* @__PURE__ */ new Date()) {
|
|
101
|
+
return latestCronMinute(normalizeCron(cron), now);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Returns `true` when a host wake at `scheduledAt` is an occurrence of the Definition's cron in its `timeZone`. The host
|
|
105
|
+
* runs a wider UTC cron for a time-zoned Schedule, so the runtime skips the wakes that are not local occurrences.
|
|
106
|
+
*/
|
|
107
|
+
function isTimeZoneWakeDue(definition, name, scheduledAt) {
|
|
108
|
+
const minute = /* @__PURE__ */ new Date(Math.floor(scheduledAt.getTime() / 6e4) * 6e4);
|
|
109
|
+
return isScheduleDue({
|
|
110
|
+
cron: definition.cron,
|
|
111
|
+
id: name,
|
|
112
|
+
...definition.timeZone ? { timeZone: definition.timeZone } : {}
|
|
113
|
+
}, minute);
|
|
114
|
+
}
|
|
91
115
|
function createStaticScheduleRun(options) {
|
|
92
116
|
const scheduledAt = validateScheduledAt(options.scheduledAt);
|
|
93
117
|
return {
|
|
94
118
|
cron: options.cron,
|
|
95
119
|
id: `run_${options.name}_${scheduledAt.toISOString()}`,
|
|
120
|
+
idempotencyKey: scheduleIdempotencyKey(options.name, scheduledAt),
|
|
96
121
|
scheduleId: options.name,
|
|
97
122
|
scheduledAt,
|
|
98
123
|
waitUntil: options.waitUntil
|
|
99
124
|
};
|
|
100
125
|
}
|
|
101
126
|
async function executeStaticSchedule(options) {
|
|
102
|
-
return await runWithScheduleWaitUntil((waitUntil) =>
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
127
|
+
return await runInRunScopes(() => runWithScheduleWaitUntil(async (waitUntil) => {
|
|
128
|
+
const run = createStaticScheduleRun({
|
|
129
|
+
...options,
|
|
130
|
+
waitUntil
|
|
131
|
+
});
|
|
132
|
+
try {
|
|
133
|
+
return await options.definition.handler(run);
|
|
134
|
+
} catch (error) {
|
|
135
|
+
await emitRunFailed({
|
|
136
|
+
event: "schedule.failed",
|
|
137
|
+
schedule: run.scheduleId,
|
|
138
|
+
runId: run.id,
|
|
139
|
+
error: toRunFailedError(error),
|
|
140
|
+
failedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
141
|
+
});
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
}, options.waitUntil));
|
|
106
145
|
}
|
|
107
146
|
async function executeMatchingStaticSchedules(options) {
|
|
108
|
-
if (
|
|
147
|
+
if (typeof options.cron !== "string" || !options.cron.trim()) throw createScheduleError("SCHEDULE_INVALID_CRON", { details: invalidScheduleValueDetails("cron", options.cron) });
|
|
109
148
|
const cron = normalizeCron(options.cron);
|
|
110
149
|
const scheduledAt = validateScheduledAt(options.scheduledAt);
|
|
111
150
|
const runs = [];
|
|
112
151
|
for (const [name, load] of Object.entries(options.registry)) {
|
|
113
152
|
const definition = unwrapScheduleDefinition(await load());
|
|
114
|
-
if (!definition
|
|
153
|
+
if (!definition) continue;
|
|
154
|
+
const override = options.cronOverrides && Object.hasOwn(options.cronOverrides, name) ? options.cronOverrides[name] : void 0;
|
|
155
|
+
const timeZoneCron = override === void 0 && options.timeZoneCrons && Object.hasOwn(options.timeZoneCrons, name) ? options.timeZoneCrons[name] : void 0;
|
|
156
|
+
if (normalizeCron(override ?? timeZoneCron ?? definition.cron) !== cron) continue;
|
|
157
|
+
if (timeZoneCron !== void 0 && !isTimeZoneWakeDue(definition, name, scheduledAt)) continue;
|
|
115
158
|
runs.push({
|
|
116
159
|
name,
|
|
117
160
|
run: executeStaticSchedule({
|
|
@@ -139,15 +182,17 @@ async function executeCloudflareStaticSchedules(event, options) {
|
|
|
139
182
|
return await runWithCloudflareServerEnv(event, async (waitUntil) => {
|
|
140
183
|
return await executeMatchingStaticSchedules({
|
|
141
184
|
cron: scheduled.cron,
|
|
185
|
+
cronOverrides: options.cronOverrides,
|
|
142
186
|
registry: options.registry,
|
|
143
187
|
scheduledAt: scheduled.scheduledAt,
|
|
188
|
+
timeZoneCrons: options.timeZoneCrons,
|
|
144
189
|
waitUntil
|
|
145
190
|
});
|
|
146
191
|
}, options.waitUntil ?? readCloudflareWaitUntil(event));
|
|
147
192
|
}
|
|
148
193
|
function readCloudflareScheduledEvent(event) {
|
|
149
194
|
const cron = event.controller?.cron ?? event.cron;
|
|
150
|
-
if (
|
|
195
|
+
if (typeof cron !== "string" || !cron.trim()) throw scheduleErrorDiagnostics.SCHEDULE_R0027({ message: "[vitehub:schedule] Cloudflare scheduled event is missing a cron string." });
|
|
151
196
|
const scheduledTime = event.controller?.scheduledTime ?? event.scheduledTime;
|
|
152
197
|
const scheduledAt = isScheduleDate(scheduledTime) ? new Date(Date.prototype.getTime.call(scheduledTime)) : scheduledTime === void 0 ? /* @__PURE__ */ new Date() : new Date(scheduledTime);
|
|
153
198
|
if (Number.isNaN(scheduledAt.getTime())) throw scheduleErrorDiagnostics.SCHEDULE_R0028({ message: "[vitehub:schedule] Cloudflare scheduled event has an invalid scheduledTime." });
|
|
@@ -185,36 +230,27 @@ function restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv) {
|
|
|
185
230
|
if (hadGlobalEnv) globals.__env__ = previousGlobalEnv;
|
|
186
231
|
else delete globals.__env__;
|
|
187
232
|
}
|
|
188
|
-
function isRecord(value) {
|
|
189
|
-
return Object(value) === value && !Array.isArray(value);
|
|
190
|
-
}
|
|
191
233
|
function isCallable(value) {
|
|
192
|
-
|
|
193
|
-
try {
|
|
194
|
-
Function.prototype.toString.call(value);
|
|
195
|
-
return true;
|
|
196
|
-
} catch {
|
|
197
|
-
return false;
|
|
198
|
-
}
|
|
234
|
+
return typeof value === "function" || typeof value === "undefined" && value !== void 0;
|
|
199
235
|
}
|
|
200
236
|
function readCloudflareWaitUntil(event) {
|
|
201
|
-
const context =
|
|
202
|
-
const cloudflareContext =
|
|
203
|
-
const platformContext =
|
|
204
|
-
const platformCloudflareContext =
|
|
205
|
-
const request =
|
|
206
|
-
const runtime =
|
|
207
|
-
const runtimeCloudflare =
|
|
237
|
+
const context = isRecordOrFunction(event.context) ? event.context : void 0;
|
|
238
|
+
const cloudflareContext = isRecordOrFunction(context?.cloudflare) ? context.cloudflare : void 0;
|
|
239
|
+
const platformContext = isRecordOrFunction(context?._platform) ? context._platform : void 0;
|
|
240
|
+
const platformCloudflareContext = isRecordOrFunction(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
|
|
241
|
+
const request = isRecordOrFunction(event.req) ? event.req : void 0;
|
|
242
|
+
const runtime = isRecordOrFunction(request?.runtime) ? request.runtime : void 0;
|
|
243
|
+
const runtimeCloudflare = isRecordOrFunction(runtime?.cloudflare) ? runtime.cloudflare : void 0;
|
|
208
244
|
const owners = [
|
|
209
245
|
event,
|
|
210
246
|
context,
|
|
211
247
|
cloudflareContext,
|
|
212
|
-
|
|
248
|
+
isRecordOrFunction(cloudflareContext?.context) ? cloudflareContext.context : void 0,
|
|
213
249
|
platformCloudflareContext,
|
|
214
|
-
|
|
250
|
+
isRecordOrFunction(platformCloudflareContext?.context) ? platformCloudflareContext.context : void 0,
|
|
215
251
|
request,
|
|
216
252
|
runtimeCloudflare,
|
|
217
|
-
|
|
253
|
+
isRecordOrFunction(runtimeCloudflare?.context) ? runtimeCloudflare.context : void 0
|
|
218
254
|
];
|
|
219
255
|
for (const owner of owners) {
|
|
220
256
|
const waitUntil = owner?.waitUntil;
|
|
@@ -222,24 +258,24 @@ function readCloudflareWaitUntil(event) {
|
|
|
222
258
|
}
|
|
223
259
|
}
|
|
224
260
|
function readCloudflareEventEnv(event) {
|
|
225
|
-
if (
|
|
226
|
-
const context =
|
|
227
|
-
const cloudflareContext =
|
|
228
|
-
if (
|
|
229
|
-
const platformContext =
|
|
230
|
-
const platformCloudflareContext =
|
|
231
|
-
if (
|
|
232
|
-
const request =
|
|
233
|
-
const runtime =
|
|
234
|
-
const runtimeCloudflare =
|
|
235
|
-
return
|
|
261
|
+
if (isRecordOrFunction(event.env)) return event.env;
|
|
262
|
+
const context = isRecordOrFunction(event.context) ? event.context : void 0;
|
|
263
|
+
const cloudflareContext = isRecordOrFunction(context?.cloudflare) ? context.cloudflare : void 0;
|
|
264
|
+
if (isRecordOrFunction(cloudflareContext?.env)) return cloudflareContext.env;
|
|
265
|
+
const platformContext = isRecordOrFunction(context?._platform) ? context._platform : void 0;
|
|
266
|
+
const platformCloudflareContext = isRecordOrFunction(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
|
|
267
|
+
if (isRecordOrFunction(platformCloudflareContext?.env)) return platformCloudflareContext.env;
|
|
268
|
+
const request = isRecordOrFunction(event.req) ? event.req : void 0;
|
|
269
|
+
const runtime = isRecordOrFunction(request?.runtime) ? request.runtime : void 0;
|
|
270
|
+
const runtimeCloudflare = isRecordOrFunction(runtime?.cloudflare) ? runtime.cloudflare : void 0;
|
|
271
|
+
return isRecordOrFunction(runtimeCloudflare?.env) ? runtimeCloudflare.env : void 0;
|
|
236
272
|
}
|
|
237
273
|
function isStaticScheduleDefinition(value) {
|
|
238
|
-
return
|
|
274
|
+
return isRecordOrFunction(value) && Object.hasOwn(value, "cron") && typeof value.cron === "string" && Object.hasOwn(value, "handler") && typeof value.handler === "function";
|
|
239
275
|
}
|
|
240
276
|
function unwrapScheduleDefinition(loaded) {
|
|
241
|
-
const candidate =
|
|
277
|
+
const candidate = isRecordOrFunction(loaded) && Object.hasOwn(loaded, "default") ? loaded.default : loaded;
|
|
242
278
|
return isStaticScheduleDefinition(candidate) ? candidate : void 0;
|
|
243
279
|
}
|
|
244
280
|
//#endregion
|
|
245
|
-
export { isScheduleCronAuthorized as a,
|
|
281
|
+
export { isScheduleCronAuthorized as a, normalizeCron as c, unwrapScheduleDefinition as d, executeStaticSchedule as i, normalizeScheduleRuntimeError as l, executeCloudflareStaticSchedules as n, isTimeZoneWakeDue as o, executeMatchingStaticSchedules as r, missingScheduleDefinitionError as s, createStaticScheduleRun as t, scheduledWakeTime as u };
|