@vite-hub/schedule 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +24 -19
  2. package/dist/{console-wEhr0LWn.d.ts → console-DueeEBcM.d.ts} +2 -0
  3. package/dist/cron-C1l3TquN.js +70 -0
  4. package/dist/definition.js +1 -2
  5. package/dist/{due-BVMRQ93v.js → due-n120-_nz.js} +22 -7
  6. package/dist/durability.d.ts +2 -2
  7. package/dist/durability.js +5 -5
  8. package/dist/{error-diagnostics-DSkCJC_L.js → error-diagnostics-C0KyI408.js} +10 -2
  9. package/dist/{error-diagnostics-Mpeks7J0.js → error-diagnostics-DTmP6baC.js} +5 -5
  10. package/dist/index.d.ts +19 -5
  11. package/dist/index.js +34 -6
  12. package/dist/{kv-storage-iJChCS5A.js → kv-storage-2kZtP2CC.js} +2 -2
  13. package/dist/{kv-storage-C0KZZB6v.d.ts → kv-storage-Bm9aYLfZ.d.ts} +5 -1
  14. package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-CI2PJGqu.d.ts} +13 -2
  15. package/dist/{operations-DwZWFIUX.js → operations-DlrK9mlH.js} +29 -9
  16. package/dist/operations.d.ts +10 -1
  17. package/dist/operations.js +13 -10
  18. package/dist/os.d.ts +0 -1
  19. package/dist/os.js +12 -84
  20. package/dist/out-BbXG-yVX.js +21755 -0
  21. package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
  22. package/dist/runtime/console.d.ts +1 -1
  23. package/dist/runtime/console.js +2 -2
  24. package/dist/runtime/kv.d.ts +1 -1
  25. package/dist/runtime/kv.js +1 -1
  26. package/dist/runtime/process.js +24 -45
  27. package/dist/runtime/state.d.ts +2 -2
  28. package/dist/runtime/state.js +2 -2
  29. package/dist/runtime/static.d.ts +2 -73
  30. package/dist/runtime/static.js +3 -2
  31. package/dist/runtime.d.ts +4 -4
  32. package/dist/runtime.js +5 -5
  33. package/dist/{started-Bx7MDbrl.js → started-BWWr7Ufw.js} +3 -4
  34. package/dist/{started-BuGmnus4.js → started-BXdWMdji.js} +24 -6
  35. package/dist/{started-errors-p7cu_rI7.js → started-errors-BMg04lL3.js} +73 -26
  36. package/dist/started-name-DudQ0fsR.js +5 -0
  37. package/dist/{state-B-Fuyfb4.js → state-BjWnxyhv.js} +79 -118
  38. package/dist/{state-Do2wV4Tx.d.ts → state-CJKAhskJ.d.ts} +12 -2
  39. package/dist/static-BgoOCoe5.js +610 -0
  40. package/dist/static-CcBWx1kU.d.ts +96 -0
  41. package/dist/{store-Df0-fzCl.d.ts → store-CZHZfttA.d.ts} +3 -7
  42. package/dist/vite.d.ts +5 -3
  43. package/dist/vite.js +2963 -590
  44. package/package.json +6 -6
  45. package/dist/invariant-DolT9EEx.js +0 -22
  46. package/dist/static-DQwzzvPg.js +0 -266
  47. package/dist/wait-until-Dy4Bn3ZN.js +0 -112
@@ -1,8 +1,7 @@
1
1
  import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
2
- import { t as scheduleErrorDiagnostics } from "./error-diagnostics-Mpeks7J0.js";
2
+ import { t as scheduleErrorDiagnostics } from "./error-diagnostics-DTmP6baC.js";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
4
  //#region src/runtime/store.ts
5
- const maxLegacyHistoryRecords = 1e3;
6
5
  function trimPrefix(prefix) {
7
6
  return prefix.replace(/^\/+|\/+$/g, "");
8
7
  }
@@ -27,9 +26,6 @@ function scheduleRunAttemptKey(prefix, id) {
27
26
  function scheduleRunBase(prefix) {
28
27
  return `${joinKey(prefix, "schedule-runs")}/`;
29
28
  }
30
- function scheduleRunAttemptBase(prefix) {
31
- return `${joinKey(prefix, "schedule-run-attempts")}/`;
32
- }
33
29
  const keyLocks = /* @__PURE__ */ new Map();
34
30
  async function withKVKeyLock(key, operation) {
35
31
  const previous = keyLocks.get(key) ?? Promise.resolve();
@@ -148,115 +144,91 @@ function selectRuns(runs, options = {}) {
148
144
  selected.sort((left, right) => right.scheduledAt.getTime() - left.scheduledAt.getTime());
149
145
  return options.limit === void 0 ? selected : selected.slice(0, options.limit);
150
146
  }
151
- /** Index keys carry metadata from the stored record, independent of caller-selected run IDs. */
152
- function runIndexMetadata(key) {
147
+ function listedKeyId(key) {
153
148
  try {
154
- const parts = keySegments(key, 3);
155
- const scheduledAt = Date.parse(parts[2]);
156
- if (!Number.isFinite(scheduledAt)) return;
157
- return {
158
- id: parts[0],
159
- scheduleId: parts[1],
160
- scheduledAt
161
- };
149
+ return keySegments(key, 1)[0];
162
150
  } catch {
163
151
  return;
164
152
  }
165
153
  }
154
+ async function mapInBatches(items, map) {
155
+ const result = [];
156
+ for (let offset = 0; offset < items.length; offset += 16) result.push(...await Promise.all(items.slice(offset, offset + 16).map(map)));
157
+ return result;
158
+ }
166
159
  function createKVScheduleRunStore(options) {
167
160
  const prefix = options.prefix ?? "vitehub:schedule";
168
161
  const store = options.kvStore;
169
- async function indexRun(run) {
170
- try {
171
- await store.set(joinKey(prefix, "schedule-run-index", run.id, run.scheduleId, run.scheduledAt.toISOString()), true);
172
- } catch {}
162
+ const runIndex = joinKey(prefix, "run-index");
163
+ const attemptIndex = joinKey(prefix, "attempt-index");
164
+ const upgradeKey = joinKey(prefix, "indexes-v2");
165
+ let indexesReady = false;
166
+ function writeRunIndex(key, run) {
167
+ return store.set(key, {
168
+ scheduleId: run.scheduleId,
169
+ scheduledAt: new Date(run.scheduledAt).getTime()
170
+ });
173
171
  }
174
- async function indexAttempt(attempt) {
175
- try {
176
- await store.set(joinKey(prefix, "schedule-run-attempt-index", attempt.runId, attempt.id), true);
177
- } catch {}
172
+ async function ensureIndexes() {
173
+ if (indexesReady) return;
174
+ await withKVKeyLock(upgradeKey, async () => {
175
+ if (indexesReady) return;
176
+ if (!await store.has(upgradeKey)) {
177
+ await mapInBatches(await store.keys(scheduleRunBase(prefix)), async (key) => {
178
+ const id = listedKeyId(key);
179
+ if (id === void 0) return;
180
+ const indexKey = joinKey(runIndex, id);
181
+ if (await store.has(indexKey)) return;
182
+ const run = await store.get(key);
183
+ if (run) await writeRunIndex(indexKey, run);
184
+ });
185
+ await mapInBatches(await store.keys(`${joinKey(prefix, "schedule-run-attempts")}/`), async (key) => {
186
+ const id = listedKeyId(key);
187
+ if (id === void 0) return;
188
+ const indexKey = joinKey(attemptIndex, id);
189
+ if (await store.has(indexKey)) return;
190
+ const attempt = await store.get(key);
191
+ if (attempt) await store.set(indexKey, { runId: attempt.runId });
192
+ });
193
+ await store.set(upgradeKey, true);
194
+ }
195
+ indexesReady = true;
196
+ });
178
197
  }
179
198
  async function readSnapshot() {
180
- const keys = await store.keys(scheduleRunBase(prefix));
181
- const indexKeys = await store.keys(`${joinKey(prefix, "schedule-run-index")}/`);
182
- const metadataById = new Map(indexKeys.flatMap((key) => {
183
- const metadata = runIndexMetadata(key);
184
- return metadata ? [[metadata.id, metadata]] : [];
185
- }));
186
- const known = [];
187
- const bySchedule = /* @__PURE__ */ new Map();
188
- const unknown = [];
189
- const recordsByKey = /* @__PURE__ */ new Map();
190
- function groupRun(key, metadata) {
191
- const entry = {
192
- id: metadata.id,
199
+ await ensureIndexes();
200
+ const indexed = await mapInBatches(await store.keys(scheduleRunBase(prefix)), async (key) => {
201
+ const id = listedKeyId(key);
202
+ if (id === void 0) return;
203
+ const metadata = await store.get(joinKey(runIndex, id));
204
+ if (metadata) return {
205
+ id,
193
206
  key,
194
- scheduledAt: metadata.scheduledAt
207
+ ...metadata
195
208
  };
209
+ });
210
+ const known = [];
211
+ const bySchedule = /* @__PURE__ */ new Map();
212
+ for (const entry of indexed) {
213
+ if (!entry) continue;
196
214
  known.push(entry);
197
- const group = bySchedule.get(metadata.scheduleId) ?? [];
198
- bySchedule.set(metadata.scheduleId, group);
215
+ const group = bySchedule.get(entry.scheduleId) ?? [];
216
+ bySchedule.set(entry.scheduleId, group);
199
217
  group.push(entry);
200
218
  }
201
- for (const key of keys) {
202
- let id;
203
- try {
204
- id = keySegments(key, 1)[0];
205
- } catch {
206
- unknown.push(key);
207
- continue;
208
- }
209
- const metadata = metadataById.get(id);
210
- if (!metadata) {
211
- unknown.push(key);
212
- continue;
213
- }
214
- groupRun(key, metadata);
215
- }
216
- if (unknown.length > maxLegacyHistoryRecords) return {
217
- keys,
218
- known,
219
- bySchedule,
220
- recordsByKey,
221
- unknown
222
- };
223
- const legacyKeys = unknown;
224
- for (let offset = 0; offset < legacyKeys.length; offset += 16) {
225
- const batch = await Promise.all(legacyKeys.slice(offset, offset + 16).map(async (key) => {
226
- const stored = await store.get(key);
227
- const run = stored ? cloneScheduleRun(stored) : void 0;
228
- recordsByKey.set(key, run);
229
- if (run) await indexRun(run);
230
- return {
231
- key,
232
- run
233
- };
234
- }));
235
- for (const { key, run } of batch) if (run) groupRun(key, {
236
- id: run.id,
237
- scheduleId: run.scheduleId,
238
- scheduledAt: run.scheduledAt.getTime()
239
- });
240
- }
241
219
  for (const entries of [known, ...bySchedule.values()]) entries.sort((left, right) => right.scheduledAt - left.scheduledAt);
242
220
  return {
243
- keys,
244
221
  known,
245
222
  bySchedule,
246
- recordsByKey,
247
- unknown
223
+ recordsByKey: /* @__PURE__ */ new Map()
248
224
  };
249
225
  }
250
226
  async function listRuns(options, snapshot) {
251
- if (snapshot.unknown.length > maxLegacyHistoryRecords) throw scheduleErrorDiagnostics.SCHEDULE_HISTORY_INCOMPLETE({
252
- maxRecords: maxLegacyHistoryRecords,
253
- recordCount: snapshot.unknown.length
254
- });
255
- const { keys, recordsByKey } = snapshot;
227
+ const { recordsByKey } = snapshot;
256
228
  const known = options.scheduleId === void 0 ? snapshot.known : snapshot.bySchedule.get(options.scheduleId) ?? [];
257
229
  const matching = options.idPrefix === void 0 ? known : known.filter((entry) => entry.id.startsWith(options.idPrefix));
258
230
  const records = [];
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);
231
+ const selectedKeys = matching.slice(0, options.limit ?? matching.length).map((entry) => entry.key);
260
232
  for (let index = 0; index < selectedKeys.length; index += 16) {
261
233
  const batch = await Promise.all(selectedKeys.slice(index, index + 16).map(async (key) => {
262
234
  if (recordsByKey.has(key)) return recordsByKey.get(key);
@@ -274,8 +246,8 @@ function createKVScheduleRunStore(options) {
274
246
  const key = scheduleRunAttemptKey(prefix, attempt.id);
275
247
  return await withKVKeyLock(key, async () => {
276
248
  if (await store.has(key)) throw scheduleErrorDiagnostics.SCHEDULE_R0032({ message: `Schedule Run Attempt already exists: ${attempt.id}` });
249
+ await store.set(joinKey(attemptIndex, attempt.id), { runId: attempt.runId });
277
250
  await store.set(key, serializeScheduleRunAttempt(attempt));
278
- await indexAttempt(attempt);
279
251
  return cloneScheduleRunAttempt(attempt);
280
252
  });
281
253
  },
@@ -283,8 +255,8 @@ function createKVScheduleRunStore(options) {
283
255
  const key = scheduleRunKey(prefix, run.id);
284
256
  return await withKVKeyLock(key, async () => {
285
257
  if (await store.has(key)) throw scheduleErrorDiagnostics.SCHEDULE_R0033({ message: `Schedule Run already exists: ${run.id}` });
258
+ await writeRunIndex(joinKey(runIndex, run.id), run);
286
259
  await store.set(key, serializeScheduleRun(run));
287
- await indexRun(run);
288
260
  return cloneScheduleRun(run);
289
261
  });
290
262
  },
@@ -297,33 +269,14 @@ function createKVScheduleRunStore(options) {
297
269
  return run ? cloneScheduleRun(run) : void 0;
298
270
  },
299
271
  async listAttempts(runId) {
300
- const [keys, indexKeys] = await Promise.all([store.keys(scheduleRunAttemptBase(prefix)), store.keys(`${joinKey(prefix, "schedule-run-attempt-index")}/`)]);
301
- const runByAttemptId = /* @__PURE__ */ new Map();
302
- for (const key of indexKeys) try {
303
- const parts = keySegments(key, 2);
304
- runByAttemptId.set(parts[1], parts[0]);
305
- } catch {}
306
- const selectedKeys = keys.filter((key) => {
307
- try {
308
- const id = keySegments(key, 1)[0];
309
- const indexedRunId = runByAttemptId.get(id);
310
- return indexedRunId === void 0 || indexedRunId === runId;
311
- } catch {
312
- return true;
313
- }
314
- });
315
- const attempts = [];
316
- for (let offset = 0; offset < selectedKeys.length; offset += 16) {
317
- const batch = await Promise.all(selectedKeys.slice(offset, offset + 16).map(async (key) => {
318
- const stored = await store.get(key);
319
- if (!stored) return;
320
- const attempt = cloneScheduleRunAttempt(stored);
321
- if (!runByAttemptId.has(attempt.id)) await indexAttempt(attempt);
322
- return attempt.runId === runId ? attempt : void 0;
323
- }));
324
- attempts.push(...batch.flatMap((attempt) => attempt ? [attempt] : []));
325
- }
326
- return attempts;
272
+ await ensureIndexes();
273
+ return (await mapInBatches(await store.keys(`${attemptIndex}/`), async (key) => {
274
+ if ((await store.get(key))?.runId !== runId) return;
275
+ const id = listedKeyId(key);
276
+ if (id === void 0) return;
277
+ const attempt = await store.get(scheduleRunAttemptKey(prefix, id));
278
+ if (attempt?.runId === runId) return cloneScheduleRunAttempt(attempt);
279
+ })).flatMap((attempt) => attempt ? [attempt] : []);
327
280
  },
328
281
  async listRuns(options = {}) {
329
282
  return listRuns(options, await readSnapshot());
@@ -368,6 +321,7 @@ function createKVScheduleRunStore(options) {
368
321
  //#endregion
369
322
  //#region src/runtime/state.ts
370
323
  let runtimeRegistry;
324
+ let hostInventory;
371
325
  const processDefinitions = /* @__PURE__ */ new Set();
372
326
  let runtimeRegistryVersion = 0;
373
327
  let runStore;
@@ -398,6 +352,12 @@ function registerProcessScheduleDefinitions(definitions) {
398
352
  function getProcessScheduleDefinitions() {
399
353
  return [...processDefinitions].at(-1);
400
354
  }
355
+ function setHostScheduleInventory(inventory) {
356
+ hostInventory = inventory;
357
+ }
358
+ function getHostScheduleInventory() {
359
+ return hostInventory;
360
+ }
401
361
  function setScheduleRunStore(store) {
402
362
  runStore = store;
403
363
  }
@@ -456,6 +416,7 @@ async function loadScheduleDefinition(name) {
456
416
  }
457
417
  function resetScheduleRuntime() {
458
418
  runtimeRegistry = void 0;
419
+ hostInventory = void 0;
459
420
  processDefinitions.clear();
460
421
  runtimeRegistryVersion++;
461
422
  runStore = void 0;
@@ -465,4 +426,4 @@ function resetScheduleRuntime() {
465
426
  loadingRegistryEntries.clear();
466
427
  }
467
428
  //#endregion
468
- export { getStartedScheduleRuntime as a, resetScheduleRuntime as c, setScheduleRuntimeRegistry as d, setStartedScheduleRuntime as f, keySegments as g, joinKey as h, getScheduleRuntimeRegistry as i, setScheduleOccurrenceClaims as l, createMemoryScheduleRunStore as m, getScheduleOccurrenceClaims as n, loadScheduleDefinition as o, createKVScheduleRunStore as p, getScheduleRunStore as r, registerProcessScheduleDefinitions as s, getProcessScheduleDefinitions as t, setScheduleRunStore as u };
429
+ 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 };
@@ -14,8 +14,14 @@ interface OccurrenceClaims {
14
14
  }
15
15
  //#endregion
16
16
  //#region src/runtime/state.d.ts
17
- /** The cron and time zone of a Schedule that the Process Runtime runs. */
18
17
  type ProcessScheduleTimingRecord = Pick<ScheduleDefinition, "cron" | "timeZone">;
18
+ interface HostScheduleInventory {
19
+ timings: Readonly<Record<string, {
20
+ cron: string;
21
+ timeZone?: string;
22
+ }>>;
23
+ registry?: ScheduleDefinitionRegistry;
24
+ }
19
25
  /** What `startSchedule()` and the started-Schedule tick use. The generated Nitro plugin installs it. */
20
26
  interface StartedScheduleRuntime {
21
27
  /** How far back the first tick after a start runs cron minutes that no tick checked. */
@@ -27,6 +33,8 @@ interface StartedScheduleRuntime {
27
33
  scheduledAt: Date;
28
34
  scheduleId: string;
29
35
  }>;
36
+ /** The cause that each failing started Schedule last logged, by id. A held occurrence fails again each tick. */
37
+ failing?: Map<string, string>;
30
38
  /** Schedule Definitions without `cron`, by name. */
31
39
  registry: ScheduleDefinitionRegistry;
32
40
  store: StartedScheduleStore;
@@ -36,6 +44,8 @@ declare function getScheduleRuntimeRegistry(): ScheduleDefinitionRegistry | unde
36
44
  /** Publish only ready runtimes, retaining earlier snapshots until their controllers close. */
37
45
  declare function registerProcessScheduleDefinitions(definitions: ReadonlyMap<string, ProcessScheduleTimingRecord>): () => void;
38
46
  declare function getProcessScheduleDefinitions(): ReadonlyMap<string, ProcessScheduleTimingRecord> | undefined;
47
+ declare function setHostScheduleInventory(inventory: HostScheduleInventory): void;
48
+ declare function getHostScheduleInventory(): HostScheduleInventory | undefined;
39
49
  declare function setScheduleRunStore(store: ScheduleRunStore | undefined): void;
40
50
  declare function getScheduleRunStore(): ScheduleRunStore;
41
51
  /** Installs the claims that make each occurrence run in one process only. The Process Runtime installs them. */
@@ -46,4 +56,4 @@ declare function getStartedScheduleRuntime(): StartedScheduleRuntime | undefined
46
56
  declare function loadScheduleDefinition(name: string): Promise<ScheduleRegistryDefinition | undefined>;
47
57
  declare function resetScheduleRuntime(): void;
48
58
  //#endregion
49
- export { getScheduleRuntimeRegistry as a, registerProcessScheduleDefinitions as c, setScheduleRunStore as d, setScheduleRuntimeRegistry as f, getScheduleRunStore as i, resetScheduleRuntime as l, getProcessScheduleDefinitions as n, getStartedScheduleRuntime as o, setStartedScheduleRuntime as p, getScheduleOccurrenceClaims as r, loadScheduleDefinition as s, StartedScheduleRuntime as t, setScheduleOccurrenceClaims as u };
59
+ 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 };