@vite-hub/schedule 0.6.1 → 0.7.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/README.md +27 -6
- package/dist/cron-D0mqg3ql.js +22 -0
- package/dist/definition.d.ts +1 -1
- package/dist/definition.js +3 -4
- package/dist/{due-D-0trD1g.js → due-DXgXKgzg.js} +1 -1
- package/dist/{error-diagnostics-kKXseq8d.js → error-diagnostics-CsiNo_oI.js} +3 -3
- package/dist/{error-diagnostics-B1AaIGWP.js → error-diagnostics-KvK9MX6w.js} +14 -2
- package/dist/{started-errors-IG9DlT2A.js → execute-DoQC2i_V.js} +7 -34
- package/dist/index.d.ts +12 -8
- package/dist/index.js +1 -51
- package/dist/{kv-storage-hI2IOjb5.d.ts → kv-storage-CKSSQ6Fk.d.ts} +7 -3
- package/dist/{kv-storage-Dsr3TL9c.js → kv-storage-CszEkof6.js} +2 -2
- package/dist/{operation-definition-CqZkx1Rm.d.ts → operations-Blwi3jQF.d.ts} +1 -0
- package/dist/{operations-BTUQeba1.js → operations-CEZCefAG.js} +25 -13
- package/dist/operations.d.ts +2 -2
- package/dist/operations.js +7 -5
- package/dist/os.js +2 -2
- package/dist/runtime/console.js +24 -11
- package/dist/runtime/kv.d.ts +1 -1
- package/dist/runtime/kv.js +1 -1
- package/dist/runtime/process.d.ts +1 -1
- package/dist/runtime/process.js +14 -16
- package/dist/runtime/state.d.ts +1 -1
- package/dist/runtime/state.js +1 -1
- package/dist/runtime/static.d.ts +1 -1
- package/dist/runtime/static.js +2 -2
- package/dist/runtime.d.ts +6 -6
- package/dist/runtime.js +5 -5
- package/dist/{started-B1Se_Iwo.js → started-ClJ5XOWH.js} +48 -9
- package/dist/started-errors-DVw5cYHR.js +28 -0
- package/dist/{started-Bzvr4t5f.js → started-yb49f37g.js} +6 -4
- package/dist/state-CcVY3UzB.js +570 -0
- package/dist/{state-BDEDVlyr.d.ts → state-LuEgYpwR.d.ts} +1 -1
- package/dist/{static-Bg7Jj92L.js → static--wi-oIIb.js} +7 -5
- package/dist/{static-DeRvJqcQ.d.ts → static-BFV4x94g.d.ts} +1 -1
- package/dist/{store-CEv3cScg.d.ts → store-TOayO0NL.d.ts} +6 -3
- package/dist/{types-DTVPVY5O.d.ts → types-Wllh0U8N.d.ts} +35 -4
- package/dist/vite.d.ts +4 -2
- package/dist/vite.js +377 -118
- package/package.json +10 -4
- package/dist/started-name-w6n9uDdt.js +0 -4
- package/dist/state-BZLy46UJ.js +0 -427
- package/dist/{cron-BT3ef48f.js → cron-imqlBgO-.js} +1 -1
|
@@ -0,0 +1,570 @@
|
|
|
1
|
+
import { t as scheduleErrorDiagnostics } from "./error-diagnostics-KvK9MX6w.js";
|
|
2
|
+
import { n as isRecordOrFunction } from "./object-CAK6UYR5.js";
|
|
3
|
+
import { parseDuration } from "@vite-hub/runtime";
|
|
4
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
5
|
+
// src/runtime/store.ts
|
|
6
|
+
const DEFAULT_SCHEDULE_RETENTION = "30 days";
|
|
7
|
+
function trimPrefix(prefix) {
|
|
8
|
+
return prefix.replace(/^\/+|\/+$/g, "");
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Decoded trailing segments of a listed key. Some KV stores, such as unstorage, list keys with `:` instead of `/`.
|
|
12
|
+
* Encoded parts contain neither, so both separators are safe to split on.
|
|
13
|
+
*/
|
|
14
|
+
function keySegments(key, count) {
|
|
15
|
+
return key.split(/[/:]/).slice(-count).map(decodeURIComponent);
|
|
16
|
+
}
|
|
17
|
+
function joinKey(prefix, ...parts) {
|
|
18
|
+
const base = trimPrefix(prefix);
|
|
19
|
+
const suffix = parts.map(encodeURIComponent).join("/");
|
|
20
|
+
return base ? `${base}/${suffix}` : suffix;
|
|
21
|
+
}
|
|
22
|
+
function scheduleRunKey(prefix, id) {
|
|
23
|
+
return joinKey(prefix, "schedule-runs", id);
|
|
24
|
+
}
|
|
25
|
+
function scheduleRunAttemptKey(prefix, id) {
|
|
26
|
+
return joinKey(prefix, "schedule-run-attempts", id);
|
|
27
|
+
}
|
|
28
|
+
function scheduleRunBase(prefix) {
|
|
29
|
+
return `${joinKey(prefix, "schedule-runs")}/`;
|
|
30
|
+
}
|
|
31
|
+
const latestPossibleTime = 8640000000000000n;
|
|
32
|
+
function newestFirst(scheduledAt) {
|
|
33
|
+
return (latestPossibleTime - BigInt(scheduledAt)).toString().padStart(17, "0");
|
|
34
|
+
}
|
|
35
|
+
function shortHash(value) {
|
|
36
|
+
let left = 2166136261;
|
|
37
|
+
let right = 84696351;
|
|
38
|
+
for (let index = 0; index < value.length; index++) {
|
|
39
|
+
const code = value.charCodeAt(index);
|
|
40
|
+
left = Math.imul(left ^ code, 16777619);
|
|
41
|
+
right = Math.imul(right ^ code, 16777619);
|
|
42
|
+
}
|
|
43
|
+
return `${(left >>> 0).toString(36).padStart(7, "0")}${(right >>> 0).toString(36).padStart(7, "0")}`;
|
|
44
|
+
}
|
|
45
|
+
function runSource(id) {
|
|
46
|
+
return /^srun_([^_]+)_/.exec(id)?.[1] ?? "-";
|
|
47
|
+
}
|
|
48
|
+
function ttlUntil(expiresAt) {
|
|
49
|
+
return expiresAt === void 0 ? void 0 : { ttl: Math.max(1, Math.ceil((expiresAt - Date.now()) / 1e3)) };
|
|
50
|
+
}
|
|
51
|
+
const keyLocks = /* @__PURE__ */ new Map();
|
|
52
|
+
async function withKVKeyLock(key, operation) {
|
|
53
|
+
const previous = keyLocks.get(key) ?? Promise.resolve();
|
|
54
|
+
let release;
|
|
55
|
+
const current = new Promise((resolve) => {
|
|
56
|
+
release = resolve;
|
|
57
|
+
});
|
|
58
|
+
const queued = previous.then(() => current, () => current);
|
|
59
|
+
keyLocks.set(key, queued);
|
|
60
|
+
await previous;
|
|
61
|
+
try {
|
|
62
|
+
return await operation();
|
|
63
|
+
} finally {
|
|
64
|
+
release();
|
|
65
|
+
if (keyLocks.get(key) === queued) keyLocks.delete(key);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function cloneScheduleRun(stored) {
|
|
69
|
+
const { expiresAt: _expiresAt, oneShot: _oneShot, ...record } = stored;
|
|
70
|
+
return {
|
|
71
|
+
...record,
|
|
72
|
+
completedAt: record.completedAt ? new Date(record.completedAt) : void 0,
|
|
73
|
+
createdAt: new Date(record.createdAt),
|
|
74
|
+
error: record.error ? { ...record.error } : void 0,
|
|
75
|
+
response: record.response ? structuredClone(record.response) : void 0,
|
|
76
|
+
scheduledAt: new Date(record.scheduledAt),
|
|
77
|
+
startedAt: record.startedAt ? new Date(record.startedAt) : void 0,
|
|
78
|
+
updatedAt: new Date(record.updatedAt)
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function cloneScheduleRunAttempt(stored) {
|
|
82
|
+
const { expiresAt: _expiresAt, ...record } = stored;
|
|
83
|
+
return {
|
|
84
|
+
...record,
|
|
85
|
+
completedAt: record.completedAt ? new Date(record.completedAt) : void 0,
|
|
86
|
+
createdAt: new Date(record.createdAt),
|
|
87
|
+
error: record.error ? { ...record.error } : void 0,
|
|
88
|
+
startedAt: new Date(record.startedAt),
|
|
89
|
+
updatedAt: new Date(record.updatedAt)
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
function serializeScheduleRun(record) {
|
|
93
|
+
return {
|
|
94
|
+
...record,
|
|
95
|
+
completedAt: record.completedAt?.toISOString(),
|
|
96
|
+
createdAt: record.createdAt.toISOString(),
|
|
97
|
+
error: record.error ? { ...record.error } : void 0,
|
|
98
|
+
response: record.response ? structuredClone(record.response) : void 0,
|
|
99
|
+
scheduledAt: record.scheduledAt.toISOString(),
|
|
100
|
+
startedAt: record.startedAt?.toISOString(),
|
|
101
|
+
updatedAt: record.updatedAt.toISOString()
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function serializeScheduleRunAttempt(record) {
|
|
105
|
+
return {
|
|
106
|
+
...record,
|
|
107
|
+
completedAt: record.completedAt?.toISOString(),
|
|
108
|
+
createdAt: record.createdAt.toISOString(),
|
|
109
|
+
error: record.error ? { ...record.error } : void 0,
|
|
110
|
+
startedAt: record.startedAt.toISOString(),
|
|
111
|
+
updatedAt: record.updatedAt.toISOString()
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function createMemoryScheduleRunStore() {
|
|
115
|
+
const runs = /* @__PURE__ */ new Map();
|
|
116
|
+
const attempts = /* @__PURE__ */ new Map();
|
|
117
|
+
return {
|
|
118
|
+
createAttempt(attempt) {
|
|
119
|
+
if (attempts.has(attempt.id)) throw scheduleErrorDiagnostics.SCHEDULE_R0030({ message: `Schedule Run Attempt already exists: ${attempt.id}` });
|
|
120
|
+
attempts.set(attempt.id, cloneScheduleRunAttempt(attempt));
|
|
121
|
+
return cloneScheduleRunAttempt(attempt);
|
|
122
|
+
},
|
|
123
|
+
createRun(run) {
|
|
124
|
+
if (runs.has(run.id)) throw scheduleErrorDiagnostics.SCHEDULE_R0031({ message: `Schedule Run already exists: ${run.id}` });
|
|
125
|
+
runs.set(run.id, cloneScheduleRun(run));
|
|
126
|
+
return cloneScheduleRun(run);
|
|
127
|
+
},
|
|
128
|
+
getAttempt(id) {
|
|
129
|
+
const attempt = attempts.get(id);
|
|
130
|
+
return attempt ? cloneScheduleRunAttempt(attempt) : void 0;
|
|
131
|
+
},
|
|
132
|
+
getRun(id) {
|
|
133
|
+
const run = runs.get(id);
|
|
134
|
+
return run ? cloneScheduleRun(run) : void 0;
|
|
135
|
+
},
|
|
136
|
+
listAttempts(runId) {
|
|
137
|
+
return [...attempts.values()].filter((attempt) => attempt.runId === runId).map(cloneScheduleRunAttempt);
|
|
138
|
+
},
|
|
139
|
+
listRuns(options) {
|
|
140
|
+
return selectRuns([...runs.values()], options).map(cloneScheduleRun);
|
|
141
|
+
},
|
|
142
|
+
updateAttempt(id, patch) {
|
|
143
|
+
const existing = attempts.get(id);
|
|
144
|
+
if (!existing) return;
|
|
145
|
+
const next = cloneScheduleRunAttempt({
|
|
146
|
+
...existing,
|
|
147
|
+
...patch,
|
|
148
|
+
updatedAt: patch.updatedAt
|
|
149
|
+
});
|
|
150
|
+
attempts.set(id, next);
|
|
151
|
+
return cloneScheduleRunAttempt(next);
|
|
152
|
+
},
|
|
153
|
+
updateRun(id, patch) {
|
|
154
|
+
const existing = runs.get(id);
|
|
155
|
+
if (!existing) return;
|
|
156
|
+
const next = cloneScheduleRun({
|
|
157
|
+
...existing,
|
|
158
|
+
...patch,
|
|
159
|
+
updatedAt: patch.updatedAt
|
|
160
|
+
});
|
|
161
|
+
runs.set(id, next);
|
|
162
|
+
return cloneScheduleRun(next);
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
function selectRuns(runs, options = {}) {
|
|
167
|
+
const selected = runs.filter((run) => (options.scheduleId === void 0 || run.scheduleId === options.scheduleId) && (options.idPrefix === void 0 || run.id.startsWith(options.idPrefix)));
|
|
168
|
+
selected.sort((left, right) => right.scheduledAt.getTime() - left.scheduledAt.getTime());
|
|
169
|
+
return options.limit === void 0 ? selected : selected.slice(0, options.limit);
|
|
170
|
+
}
|
|
171
|
+
function listedSegments(key, count) {
|
|
172
|
+
const segments = key.split(/[/:]/).slice(-count);
|
|
173
|
+
return segments.length === count ? segments : void 0;
|
|
174
|
+
}
|
|
175
|
+
function isFinished(run) {
|
|
176
|
+
return run.status === "succeeded" || run.status === "failed";
|
|
177
|
+
}
|
|
178
|
+
async function mapInBatches(items, map) {
|
|
179
|
+
const result = [];
|
|
180
|
+
for (let offset = 0; offset < items.length; offset += 16) result.push(...await Promise.all(items.slice(offset, offset + 16).map(map)));
|
|
181
|
+
return result;
|
|
182
|
+
}
|
|
183
|
+
function createKVScheduleRunStore(options) {
|
|
184
|
+
const prefix = options.prefix ?? "vitehub:schedule";
|
|
185
|
+
const store = options.kvStore;
|
|
186
|
+
const retentionMs = parseDuration(options.retention ?? "30 days", "retention");
|
|
187
|
+
const historyIndex = joinKey(prefix, "run-history-index");
|
|
188
|
+
const attemptIndex = joinKey(prefix, "run-attempt-index");
|
|
189
|
+
const newestRuns = joinKey(prefix, "newest-run");
|
|
190
|
+
const upgradeKey = joinKey(prefix, "indexes-v3");
|
|
191
|
+
let indexesReady = false;
|
|
192
|
+
const runKey = (id) => scheduleRunKey(prefix, id);
|
|
193
|
+
const attemptKey = (id) => scheduleRunAttemptKey(prefix, id);
|
|
194
|
+
const historyKey = (run) => joinKey(historyIndex, shortHash(run.scheduleId), newestFirst(new Date(run.scheduledAt).getTime()), shortHash(run.id));
|
|
195
|
+
const writeHistory = (run, expiresAt) => store.set(historyKey(run), { id: run.id }, ttlUntil(expiresAt));
|
|
196
|
+
const runAttemptsKey = (runId) => joinKey(attemptIndex, shortHash(runId));
|
|
197
|
+
const newestRunKey = (scheduleId, source) => joinKey(newestRuns, shortHash(scheduleId), source);
|
|
198
|
+
const newestKeyFor = (run) => newestRunKey(run.scheduleId, runSource(run.id));
|
|
199
|
+
async function listAttemptIds(runId) {
|
|
200
|
+
return await store.get(runAttemptsKey(runId)) ?? [];
|
|
201
|
+
}
|
|
202
|
+
async function expireAttempt(runId, id, expiresAt) {
|
|
203
|
+
await withKVKeyLock(attemptKey(id), async () => {
|
|
204
|
+
const attempt = await store.get(attemptKey(id));
|
|
205
|
+
if (attempt?.runId !== runId) return;
|
|
206
|
+
await store.set(attemptKey(id), {
|
|
207
|
+
...attempt,
|
|
208
|
+
expiresAt
|
|
209
|
+
}, ttlUntil(expiresAt));
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
async function writeExpiringRun(run, expiresAt) {
|
|
213
|
+
const ids = await listAttemptIds(run.id);
|
|
214
|
+
for (const id of ids) await expireAttempt(run.id, id, expiresAt);
|
|
215
|
+
if (ids.length) await store.set(runAttemptsKey(run.id), ids, ttlUntil(expiresAt));
|
|
216
|
+
await writeHistory(run, expiresAt);
|
|
217
|
+
await store.set(runKey(run.id), {
|
|
218
|
+
...run,
|
|
219
|
+
expiresAt
|
|
220
|
+
}, ttlUntil(expiresAt));
|
|
221
|
+
}
|
|
222
|
+
async function retireRun(id) {
|
|
223
|
+
await withKVKeyLock(runKey(id), async () => {
|
|
224
|
+
const stored = await store.get(runKey(id));
|
|
225
|
+
if (!stored || !isFinished(stored) || stored.expiresAt !== void 0) return;
|
|
226
|
+
await writeExpiringRun(stored, Date.now() + retentionMs);
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
async function upgradeIndexes() {
|
|
230
|
+
const runs = (await mapInBatches(await store.keys(scheduleRunBase(prefix)), async (key) => store.get(key))).filter((run) => typeof run?.id === "string" && typeof run.scheduleId === "string");
|
|
231
|
+
const newest = /* @__PURE__ */ new Map();
|
|
232
|
+
for (const run of runs) {
|
|
233
|
+
if (runSource(run.id) === "started" && run.scheduleId.startsWith("sched_")) {
|
|
234
|
+
const schedule = await store.get(joinKey(prefix, "started-schedules", run.scheduleId));
|
|
235
|
+
if (!schedule || schedule.at !== void 0) run.oneShot = true;
|
|
236
|
+
}
|
|
237
|
+
if (run.oneShot) continue;
|
|
238
|
+
const key = newestKeyFor(run);
|
|
239
|
+
const scheduledAt = new Date(run.scheduledAt).getTime();
|
|
240
|
+
if (run.expiresAt === void 0 && scheduledAt >= (newest.get(key)?.scheduledAt ?? -Infinity)) newest.set(key, {
|
|
241
|
+
id: run.id,
|
|
242
|
+
scheduledAt
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
const attempts = (await mapInBatches(await store.keys(`${joinKey(prefix, "schedule-run-attempts")}/`), (key) => Promise.resolve(store.get(key)))).filter((attempt) => typeof attempt?.id === "string" && typeof attempt.runId === "string");
|
|
246
|
+
const attemptIdsByRun = /* @__PURE__ */ new Map();
|
|
247
|
+
const runIds = new Set(runs.map((run) => run.id));
|
|
248
|
+
for (const attempt of attempts) {
|
|
249
|
+
const ids = attemptIdsByRun.get(attempt.runId) ?? [];
|
|
250
|
+
ids.push(attempt.id);
|
|
251
|
+
attemptIdsByRun.set(attempt.runId, ids);
|
|
252
|
+
}
|
|
253
|
+
await mapInBatches([...attemptIdsByRun], async ([runId, ids]) => {
|
|
254
|
+
await store.set(runAttemptsKey(runId), ids, runIds.has(runId) ? void 0 : ttlUntil(Date.now() + retentionMs));
|
|
255
|
+
});
|
|
256
|
+
await mapInBatches(attempts.filter((attempt) => !runIds.has(attempt.runId)), (attempt) => expireAttempt(attempt.runId, attempt.id, Date.now() + retentionMs));
|
|
257
|
+
await mapInBatches([...newest], async ([key, candidate]) => store.set(key, candidate));
|
|
258
|
+
await mapInBatches(runs, async (run) => {
|
|
259
|
+
if (isFinished(run) && (run.oneShot || newest.get(newestKeyFor(run))?.id !== run.id)) await writeExpiringRun(run, run.expiresAt ?? Date.now() + retentionMs);
|
|
260
|
+
else {
|
|
261
|
+
await writeHistory(run, void 0);
|
|
262
|
+
if (run.oneShot) await store.set(runKey(run.id), run);
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
await mapInBatches([
|
|
266
|
+
...await store.keys(`${joinKey(prefix, "run-index")}/`),
|
|
267
|
+
...await store.keys(`${joinKey(prefix, "attempt-index")}/`),
|
|
268
|
+
joinKey(prefix, "indexes-v2")
|
|
269
|
+
], async (key) => store.delete(key));
|
|
270
|
+
await store.set(upgradeKey, true);
|
|
271
|
+
}
|
|
272
|
+
async function ensureIndexes() {
|
|
273
|
+
if (indexesReady) return;
|
|
274
|
+
await withKVKeyLock(upgradeKey, async () => {
|
|
275
|
+
if (indexesReady) return;
|
|
276
|
+
if (!await store.has(upgradeKey)) await upgradeIndexes();
|
|
277
|
+
indexesReady = true;
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
async function readHistory(scheduleId) {
|
|
281
|
+
const base = scheduleId === void 0 ? `${historyIndex}/` : `${joinKey(historyIndex, shortHash(scheduleId))}/`;
|
|
282
|
+
const entries = [];
|
|
283
|
+
for (const key of await store.keys(base)) {
|
|
284
|
+
const [scheduleSegment, order, runSegment] = listedSegments(key, 3) ?? [];
|
|
285
|
+
if (scheduleSegment !== void 0 && order !== void 0 && runSegment !== void 0) entries.push({
|
|
286
|
+
indexKey: key,
|
|
287
|
+
orderKey: `${order}/${runSegment}`,
|
|
288
|
+
scheduleSegment
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
return entries.sort((left, right) => left.orderKey < right.orderKey ? -1 : left.orderKey > right.orderKey ? 1 : 0);
|
|
292
|
+
}
|
|
293
|
+
function cached(cache, key, read) {
|
|
294
|
+
let value = cache.get(key);
|
|
295
|
+
if (!value) {
|
|
296
|
+
value = read();
|
|
297
|
+
cache.set(key, value);
|
|
298
|
+
}
|
|
299
|
+
return value;
|
|
300
|
+
}
|
|
301
|
+
async function readEntry(entry, options, cache) {
|
|
302
|
+
const id = await cached(cache.ids, entry.indexKey, async () => (await store.get(entry.indexKey))?.id);
|
|
303
|
+
if (id === void 0 || options.idPrefix !== void 0 && !id.startsWith(options.idPrefix)) return;
|
|
304
|
+
const run = await cached(cache.runs, id, async () => {
|
|
305
|
+
const stored = await store.get(runKey(id));
|
|
306
|
+
return stored ? cloneScheduleRun(stored) : void 0;
|
|
307
|
+
});
|
|
308
|
+
if (run && (options.scheduleId === void 0 || run.scheduleId === options.scheduleId)) return run;
|
|
309
|
+
}
|
|
310
|
+
async function listRuns(options, history, cache) {
|
|
311
|
+
const scheduleSegment = options.scheduleId === void 0 ? void 0 : shortHash(options.scheduleId);
|
|
312
|
+
const matching = scheduleSegment === void 0 ? history : history.filter((entry) => entry.scheduleSegment === scheduleSegment);
|
|
313
|
+
const runs = [];
|
|
314
|
+
let offset = 0;
|
|
315
|
+
while (offset < matching.length && (options.limit === void 0 || runs.length < options.limit)) {
|
|
316
|
+
const size = Math.min(16, options.limit === void 0 ? 16 : options.limit - runs.length);
|
|
317
|
+
const batch = await Promise.all(matching.slice(offset, offset + size).map((entry) => readEntry(entry, options, cache)));
|
|
318
|
+
offset += size;
|
|
319
|
+
runs.push(...batch.filter((run) => run !== void 0));
|
|
320
|
+
}
|
|
321
|
+
runs.sort((left, right) => left.id < right.id ? -1 : left.id > right.id ? 1 : 0);
|
|
322
|
+
return selectRuns(runs, options).map(cloneScheduleRun);
|
|
323
|
+
}
|
|
324
|
+
return {
|
|
325
|
+
async createAttempt(attempt) {
|
|
326
|
+
await ensureIndexes();
|
|
327
|
+
const key = attemptKey(attempt.id);
|
|
328
|
+
return await withKVKeyLock(runKey(attempt.runId), () => withKVKeyLock(key, async () => {
|
|
329
|
+
if (await store.has(key)) throw scheduleErrorDiagnostics.SCHEDULE_R0032({ message: `Schedule Run Attempt already exists: ${attempt.id}` });
|
|
330
|
+
const run = await store.get(runKey(attempt.runId));
|
|
331
|
+
const expiresAt = run ? run.expiresAt : Date.now() + retentionMs;
|
|
332
|
+
const indexKey = runAttemptsKey(attempt.runId);
|
|
333
|
+
const ids = await listAttemptIds(attempt.runId);
|
|
334
|
+
try {
|
|
335
|
+
await store.set(key, {
|
|
336
|
+
...serializeScheduleRunAttempt(attempt),
|
|
337
|
+
...expiresAt === void 0 ? {} : { expiresAt }
|
|
338
|
+
}, ttlUntil(expiresAt));
|
|
339
|
+
await store.set(indexKey, [.../* @__PURE__ */ new Set([...ids, attempt.id])], ttlUntil(expiresAt));
|
|
340
|
+
} catch (error) {
|
|
341
|
+
await Promise.allSettled([ids.length ? store.set(indexKey, ids, ttlUntil(expiresAt)) : store.delete(indexKey), store.delete(key)]);
|
|
342
|
+
throw error;
|
|
343
|
+
}
|
|
344
|
+
return cloneScheduleRunAttempt(attempt);
|
|
345
|
+
}));
|
|
346
|
+
},
|
|
347
|
+
async createRun(run, runOptions) {
|
|
348
|
+
const oneShot = runOptions?.oneShot;
|
|
349
|
+
await ensureIndexes();
|
|
350
|
+
const key = runKey(run.id);
|
|
351
|
+
const newestKey = newestKeyFor(run);
|
|
352
|
+
return await withKVKeyLock(newestKey, () => withKVKeyLock(key, async () => {
|
|
353
|
+
if (await store.has(key)) throw scheduleErrorDiagnostics.SCHEDULE_R0033({ message: `Schedule Run already exists: ${run.id}` });
|
|
354
|
+
const previous = oneShot ? void 0 : await store.get(newestKey);
|
|
355
|
+
const isNewest = !oneShot && (!previous || previous.id === run.id || run.scheduledAt.getTime() >= previous.scheduledAt);
|
|
356
|
+
const expiresAt = !isNewest && isFinished(run) ? Date.now() + retentionMs : void 0;
|
|
357
|
+
const indexKey = historyKey(run);
|
|
358
|
+
try {
|
|
359
|
+
await writeHistory(run, expiresAt);
|
|
360
|
+
await store.set(key, {
|
|
361
|
+
...serializeScheduleRun(run),
|
|
362
|
+
...oneShot ? { oneShot } : {},
|
|
363
|
+
...expiresAt === void 0 ? {} : { expiresAt }
|
|
364
|
+
}, ttlUntil(expiresAt));
|
|
365
|
+
if (isNewest) await store.set(newestKey, {
|
|
366
|
+
id: run.id,
|
|
367
|
+
scheduledAt: run.scheduledAt.getTime()
|
|
368
|
+
});
|
|
369
|
+
} catch (error) {
|
|
370
|
+
await Promise.allSettled([store.delete(indexKey), store.delete(key)]);
|
|
371
|
+
throw error;
|
|
372
|
+
}
|
|
373
|
+
if (isNewest && previous && previous.id !== run.id) await retireRun(previous.id);
|
|
374
|
+
return cloneScheduleRun(run);
|
|
375
|
+
}));
|
|
376
|
+
},
|
|
377
|
+
async getAttempt(id) {
|
|
378
|
+
const attempt = await store.get(attemptKey(id));
|
|
379
|
+
return attempt ? cloneScheduleRunAttempt(attempt) : void 0;
|
|
380
|
+
},
|
|
381
|
+
async getRun(id) {
|
|
382
|
+
const run = await store.get(runKey(id));
|
|
383
|
+
return run ? cloneScheduleRun(run) : void 0;
|
|
384
|
+
},
|
|
385
|
+
async listAttempts(runId) {
|
|
386
|
+
await ensureIndexes();
|
|
387
|
+
return (await mapInBatches(await listAttemptIds(runId), async (id) => {
|
|
388
|
+
const attempt = await store.get(attemptKey(id));
|
|
389
|
+
if (attempt?.runId === runId) return cloneScheduleRunAttempt(attempt);
|
|
390
|
+
})).filter((attempt) => attempt !== void 0);
|
|
391
|
+
},
|
|
392
|
+
async listRuns(options = {}) {
|
|
393
|
+
await ensureIndexes();
|
|
394
|
+
if (options.scheduleId !== void 0 && options.idPrefix === "srun_static_" && options.limit === 1) {
|
|
395
|
+
const newest = await store.get(newestRunKey(options.scheduleId, "static"));
|
|
396
|
+
const run = newest && await store.get(runKey(newest.id));
|
|
397
|
+
return run && run.scheduleId === options.scheduleId ? [cloneScheduleRun(run)] : [];
|
|
398
|
+
}
|
|
399
|
+
return listRuns(options, await readHistory(options.scheduleId), {
|
|
400
|
+
ids: /* @__PURE__ */ new Map(),
|
|
401
|
+
runs: /* @__PURE__ */ new Map()
|
|
402
|
+
});
|
|
403
|
+
},
|
|
404
|
+
async listRunsBatch(options) {
|
|
405
|
+
if (!options.length) return [];
|
|
406
|
+
await ensureIndexes();
|
|
407
|
+
const history = await readHistory();
|
|
408
|
+
const cache = {
|
|
409
|
+
ids: /* @__PURE__ */ new Map(),
|
|
410
|
+
runs: /* @__PURE__ */ new Map()
|
|
411
|
+
};
|
|
412
|
+
const results = [];
|
|
413
|
+
for (const query of options) results.push(await listRuns(query, history, cache));
|
|
414
|
+
return results;
|
|
415
|
+
},
|
|
416
|
+
async updateAttempt(id, patch) {
|
|
417
|
+
const key = attemptKey(id);
|
|
418
|
+
return await withKVKeyLock(key, async () => {
|
|
419
|
+
const existing = await store.get(key);
|
|
420
|
+
if (!existing) return;
|
|
421
|
+
const next = cloneScheduleRunAttempt({
|
|
422
|
+
...cloneScheduleRunAttempt(existing),
|
|
423
|
+
...patch,
|
|
424
|
+
updatedAt: patch.updatedAt
|
|
425
|
+
});
|
|
426
|
+
const { expiresAt } = existing;
|
|
427
|
+
await store.set(key, {
|
|
428
|
+
...serializeScheduleRunAttempt(next),
|
|
429
|
+
...expiresAt === void 0 ? {} : { expiresAt }
|
|
430
|
+
}, ttlUntil(expiresAt));
|
|
431
|
+
return cloneScheduleRunAttempt(next);
|
|
432
|
+
});
|
|
433
|
+
},
|
|
434
|
+
async updateRun(id, patch) {
|
|
435
|
+
await ensureIndexes();
|
|
436
|
+
const key = runKey(id);
|
|
437
|
+
return await withKVKeyLock(key, async () => {
|
|
438
|
+
const existing = await store.get(key);
|
|
439
|
+
if (!existing) return;
|
|
440
|
+
const next = cloneScheduleRun({
|
|
441
|
+
...cloneScheduleRun(existing),
|
|
442
|
+
...patch,
|
|
443
|
+
updatedAt: patch.updatedAt
|
|
444
|
+
});
|
|
445
|
+
const { expiresAt, oneShot } = existing;
|
|
446
|
+
const stored = {
|
|
447
|
+
...serializeScheduleRun(next),
|
|
448
|
+
...oneShot ? { oneShot } : {},
|
|
449
|
+
...expiresAt === void 0 ? {} : { expiresAt }
|
|
450
|
+
};
|
|
451
|
+
if (expiresAt === void 0 && isFinished(next) && !isFinished(existing)) {
|
|
452
|
+
const newest = oneShot ? void 0 : await store.get(newestKeyFor(existing));
|
|
453
|
+
if (oneShot || newest && newest.id !== id) {
|
|
454
|
+
await writeExpiringRun(stored, Date.now() + retentionMs);
|
|
455
|
+
return cloneScheduleRun(next);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
await store.set(key, stored, ttlUntil(expiresAt));
|
|
459
|
+
return cloneScheduleRun(next);
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
// src/runtime/state.ts
|
|
465
|
+
let runtimeRegistry;
|
|
466
|
+
let hostInventory;
|
|
467
|
+
const processDefinitions = /* @__PURE__ */ new Set();
|
|
468
|
+
let runtimeRegistryVersion = 0;
|
|
469
|
+
let runStore;
|
|
470
|
+
let startedRuntime;
|
|
471
|
+
let occurrenceClaims;
|
|
472
|
+
const loadedRegistryEntries = /* @__PURE__ */ new Map();
|
|
473
|
+
const loadingRegistryEntries = /* @__PURE__ */ new Map();
|
|
474
|
+
const loadingRegistryStorage = new AsyncLocalStorage();
|
|
475
|
+
function isScheduleDefinition(value) {
|
|
476
|
+
return isRecordOrFunction(value) && Object.hasOwn(value, "handler") && typeof Reflect.get(value, "handler") === "function";
|
|
477
|
+
}
|
|
478
|
+
function setScheduleRuntimeRegistry(registry) {
|
|
479
|
+
runtimeRegistry = registry;
|
|
480
|
+
runtimeRegistryVersion++;
|
|
481
|
+
loadedRegistryEntries.clear();
|
|
482
|
+
loadingRegistryEntries.clear();
|
|
483
|
+
}
|
|
484
|
+
function getScheduleRuntimeRegistry() {
|
|
485
|
+
return runtimeRegistry;
|
|
486
|
+
}
|
|
487
|
+
/** Publish only ready runtimes, retaining earlier snapshots until their controllers close. */
|
|
488
|
+
function registerProcessScheduleDefinitions(definitions) {
|
|
489
|
+
processDefinitions.add(definitions);
|
|
490
|
+
return () => {
|
|
491
|
+
processDefinitions.delete(definitions);
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
function getProcessScheduleDefinitions() {
|
|
495
|
+
return [...processDefinitions].at(-1);
|
|
496
|
+
}
|
|
497
|
+
function setHostScheduleInventory(inventory) {
|
|
498
|
+
hostInventory = inventory;
|
|
499
|
+
}
|
|
500
|
+
function getHostScheduleInventory() {
|
|
501
|
+
return hostInventory;
|
|
502
|
+
}
|
|
503
|
+
function setScheduleRunStore(store) {
|
|
504
|
+
runStore = store;
|
|
505
|
+
}
|
|
506
|
+
function getScheduleRunStore() {
|
|
507
|
+
return runStore ??= createMemoryScheduleRunStore();
|
|
508
|
+
}
|
|
509
|
+
/** Installs the claims that make each occurrence run in one process only. The Process Runtime installs them. */
|
|
510
|
+
function setScheduleOccurrenceClaims(claims) {
|
|
511
|
+
occurrenceClaims = claims;
|
|
512
|
+
}
|
|
513
|
+
function getScheduleOccurrenceClaims() {
|
|
514
|
+
return occurrenceClaims;
|
|
515
|
+
}
|
|
516
|
+
function setStartedScheduleRuntime(runtime) {
|
|
517
|
+
startedRuntime = runtime;
|
|
518
|
+
}
|
|
519
|
+
function getStartedScheduleRuntime() {
|
|
520
|
+
return startedRuntime;
|
|
521
|
+
}
|
|
522
|
+
async function loadScheduleDefinition(name) {
|
|
523
|
+
const entry = runtimeRegistry && Object.hasOwn(runtimeRegistry, name) ? runtimeRegistry[name] : void 0;
|
|
524
|
+
if (typeof entry !== "function") return;
|
|
525
|
+
if (loadedRegistryEntries.has(name)) return loadedRegistryEntries.get(name);
|
|
526
|
+
const activeLoads = loadingRegistryStorage.getStore();
|
|
527
|
+
const inFlightEntry = loadingRegistryEntries.get(name);
|
|
528
|
+
if (inFlightEntry) {
|
|
529
|
+
if (activeLoads?.has(name)) return void 0;
|
|
530
|
+
const loaded = await inFlightEntry.promise;
|
|
531
|
+
return inFlightEntry.version === runtimeRegistryVersion ? loaded : void 0;
|
|
532
|
+
}
|
|
533
|
+
const loadingVersion = runtimeRegistryVersion;
|
|
534
|
+
const nextActiveLoads = new Set(activeLoads);
|
|
535
|
+
nextActiveLoads.add(name);
|
|
536
|
+
const loadingEntry = Promise.resolve().then(() => loadingRegistryStorage.run(nextActiveLoads, async () => {
|
|
537
|
+
const loaded = await entry();
|
|
538
|
+
if (isScheduleDefinition(loaded)) return loaded;
|
|
539
|
+
if (isRecordOrFunction(loaded) && Object.hasOwn(loaded, "default")) {
|
|
540
|
+
const definition = Reflect.get(loaded, "default");
|
|
541
|
+
if (isScheduleDefinition(definition)) return definition;
|
|
542
|
+
}
|
|
543
|
+
}));
|
|
544
|
+
loadingRegistryEntries.set(name, {
|
|
545
|
+
promise: loadingEntry,
|
|
546
|
+
version: loadingVersion
|
|
547
|
+
});
|
|
548
|
+
try {
|
|
549
|
+
const loaded = await loadingEntry;
|
|
550
|
+
if (loadingVersion === runtimeRegistryVersion) {
|
|
551
|
+
loadedRegistryEntries.set(name, loaded);
|
|
552
|
+
return loaded;
|
|
553
|
+
}
|
|
554
|
+
return;
|
|
555
|
+
} finally {
|
|
556
|
+
if (loadingRegistryEntries.get(name)?.promise === loadingEntry) loadingRegistryEntries.delete(name);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
function resetScheduleRuntime() {
|
|
560
|
+
runtimeRegistry = void 0;
|
|
561
|
+
hostInventory = void 0;
|
|
562
|
+
processDefinitions.clear();
|
|
563
|
+
runtimeRegistryVersion++;
|
|
564
|
+
runStore = void 0;
|
|
565
|
+
startedRuntime = void 0;
|
|
566
|
+
occurrenceClaims = void 0;
|
|
567
|
+
loadedRegistryEntries.clear();
|
|
568
|
+
loadingRegistryEntries.clear();
|
|
569
|
+
}
|
|
570
|
+
export { createMemoryScheduleRunStore as _, getScheduleRuntimeRegistry as a, registerProcessScheduleDefinitions as c, setScheduleOccurrenceClaims as d, setScheduleRunStore as f, createKVScheduleRunStore as g, DEFAULT_SCHEDULE_RETENTION 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, joinKey as v, keySegments as y };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { E as StartedScheduleStore, b as ScheduleRunStore, o as ScheduleDefinitionRegistry, r as ScheduleDefinition, u as ScheduleRegistryDefinition } from "./types-Wllh0U8N.js";
|
|
2
2
|
import { LeaseStore } from "@vite-hub/runtime";
|
|
3
3
|
/** `held` when another process holds the occurrence now, `done` when a process finished it, `ran` when this call ran it. */
|
|
4
4
|
type OccurrenceClaimResult = "done" | "held" | "ran";
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { t as scheduleErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { t as scheduleErrorDiagnostics } from "./error-diagnostics-KvK9MX6w.js";
|
|
2
2
|
import { n as isRecordOrFunction } from "./object-CAK6UYR5.js";
|
|
3
|
-
import { n as isScheduleDue, r as latestCronMinute, t as cronWithWeekdayNames } from "./due-
|
|
4
|
-
import "./started-name-w6n9uDdt.js";
|
|
3
|
+
import { n as isScheduleDue, r as latestCronMinute, t as cronWithWeekdayNames } from "./due-DXgXKgzg.js";
|
|
5
4
|
import { ViteHubError, normalizeRuntimeDiagnosticError } from "@vite-hub/runtime";
|
|
6
5
|
import { emitRunFailed, toRunFailedError } from "@vite-hub/runtime/internal/run-failed";
|
|
7
6
|
import { runInRunScopes } from "@vite-hub/runtime/internal/run-scope";
|
|
@@ -10,7 +9,7 @@ const scheduleErrorMessages = {
|
|
|
10
9
|
SCHEDULE_DEFINITION_NOT_FOUND: "Static Schedule Definition was not found.",
|
|
11
10
|
SCHEDULE_INVALID_CRON: "Schedule cron is invalid.",
|
|
12
11
|
SCHEDULE_INVALID_SCHEDULED_AT: "Schedule scheduledAt value is invalid.",
|
|
13
|
-
SCHEDULE_MANUAL_RUN_DISABLED: "Schedule Definition
|
|
12
|
+
SCHEDULE_MANUAL_RUN_DISABLED: "Schedule Definition sets manual: false, so it runs only on its cron.",
|
|
14
13
|
SCHEDULE_NOT_DUE: "Schedule is not due.",
|
|
15
14
|
SCHEDULE_RUN_NOT_FOUND: "Schedule Run was not found."
|
|
16
15
|
};
|
|
@@ -287,6 +286,9 @@ function isViteHubBearerSecretEqual(authorization, expected) {
|
|
|
287
286
|
return isViteHubSecretEqual(/^Bearer\s+(.+)$/i.exec(authorization ?? "")?.[1], expected);
|
|
288
287
|
}
|
|
289
288
|
Object.freeze({ prefix: "sha256=" });
|
|
289
|
+
// src/runtime/started-name.ts
|
|
290
|
+
/** Name of the Schedule that runs due started Schedules each minute. Discovery adds it when a Definition has no `cron`. */
|
|
291
|
+
const startedSchedulesTickName = "vitehub/started-schedules";
|
|
290
292
|
// src/runtime/static.ts
|
|
291
293
|
const intrinsicErrorIsError = Error.isError;
|
|
292
294
|
const intrinsicNativeErrorIsError = (() => {
|
|
@@ -600,4 +602,4 @@ function unwrapScheduleDefinition(loaded) {
|
|
|
600
602
|
const candidate = isRecordOrFunction(loaded) && Object.hasOwn(loaded, "default") ? loaded.default : loaded;
|
|
601
603
|
return isStaticScheduleDefinition(candidate) ? candidate : void 0;
|
|
602
604
|
}
|
|
603
|
-
export { createScheduleError as S,
|
|
605
|
+
export { createScheduleError as C, validateScheduledAt as S, emitLogEvent as _, isScheduleCronAuthorized as a, parseScheduledAt as b, markLoggedScheduleError as c, normalizeScheduleRuntimeError as d, scheduledWakeTime as f, logScheduleRun as g, runWithScheduleWaitUntil as h, executeStaticSchedule as i, missingScheduleDefinitionError as l, startedSchedulesTickName as m, executeCloudflareStaticSchedules as n, isTimeZoneWakeDue as o, unwrapScheduleDefinition as p, executeMatchingStaticSchedules as r, logScheduleRuntimeError as s, createStaticScheduleRun as t, normalizeCron as u, errorCode as v, scheduleIdempotencyKey as x, logFailure as y };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { m as ScheduleRunContext, o as ScheduleDefinitionRegistry, r as ScheduleDefinition } from "./types-Wllh0U8N.js";
|
|
2
2
|
/**
|
|
3
3
|
* Returns `cron` with its weekday field written as names, such as `0 4 * * MON,FRI`. Cloudflare and Deno number
|
|
4
4
|
* weekdays 1-7 from Sunday, so standard 0-6 numbers fire one day early or fail to deploy. Names have one meaning on
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { _ as ScheduleRunRecord, b as ScheduleRunStore, o as ScheduleDefinitionRegistry, r as ScheduleDefinition } from "./types-Wllh0U8N.js";
|
|
2
|
+
import { n as ScheduleKVStorage } from "./kv-storage-CKSSQ6Fk.js";
|
|
3
|
+
import { Duration } from "@vite-hub/runtime";
|
|
3
4
|
interface ExecuteScheduleOptions {
|
|
4
5
|
captureHandlerFailure?: boolean;
|
|
5
6
|
claimed?: boolean;
|
|
6
7
|
definition: ScheduleDefinition;
|
|
8
|
+
oneShot?: boolean;
|
|
7
9
|
onExecution?: () => void;
|
|
8
10
|
onRunLogged?: () => void;
|
|
9
11
|
runStore?: ScheduleRunStore;
|
|
@@ -34,11 +36,12 @@ interface RunScheduleOptions {
|
|
|
34
36
|
declare function createScheduleRun(options: Omit<ExecuteScheduleOptions, "definition" | "waitUntil">): Promise<ScheduleRunRecord>;
|
|
35
37
|
declare function executeSchedule(options: ExecuteScheduleOptions): Promise<ScheduleRunRecord>;
|
|
36
38
|
declare function executeStaticSchedule(options: ExecuteStaticScheduleOptions): Promise<ScheduleRunRecord>;
|
|
37
|
-
/** Runs a
|
|
39
|
+
/** Runs a Static Schedule Definition of `registry` immediately, unless it sets `manual: false`. */
|
|
38
40
|
declare function runScheduleFrom(registry: ScheduleDefinitionRegistry, name: string, options?: RunScheduleOptions): Promise<ScheduleRunRecord>;
|
|
39
41
|
interface KVScheduleStoreOptions {
|
|
40
42
|
kvStore: ScheduleKVStorage;
|
|
41
43
|
prefix?: string;
|
|
44
|
+
retention?: Duration;
|
|
42
45
|
}
|
|
43
46
|
declare function createMemoryScheduleRunStore(): ScheduleRunStore;
|
|
44
47
|
declare function createKVScheduleRunStore(options: KVScheduleStoreOptions): ScheduleRunStore;
|