@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
@@ -0,0 +1,26 @@
1
+ import { createRequire } from "node:module";
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
+ key = keys[i];
13
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
21
+ value: mod,
22
+ enumerable: true
23
+ }) : target, mod));
24
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
25
+ //#endregion
26
+ export { __require as n, __toESM as r, __commonJSMin as t };
@@ -1,4 +1,4 @@
1
- import { t as ViteHubConsoleRecord } from "../console-wEhr0LWn.js";
1
+ import { t as ViteHubConsoleRecord } from "../console-DueeEBcM.js";
2
2
  //#region src/runtime/console.d.ts
3
3
  /** The Cron column of the Console: the cron, with the time zone when it is not UTC. */
4
4
  export declare function scheduleConsoleTiming(cron: string, timeZone: string): string;
@@ -1,4 +1,4 @@
1
- import { a as getStartedScheduleRuntime, t as getProcessScheduleDefinitions } from "../state-B-Fuyfb4.js";
1
+ import { n as getProcessScheduleDefinitions, o as getStartedScheduleRuntime } from "../state-BjWnxyhv.js";
2
2
  //#region src/runtime/console.ts
3
3
  /** The Cron column of the Console: the cron, with the time zone when it is not UTC. */
4
4
  function scheduleConsoleTiming(cron, timeZone) {
@@ -46,7 +46,7 @@ function startedScheduleRecord(schedule) {
46
46
  },
47
47
  {
48
48
  label: "Runs",
49
- value: `Use \`vitehub schedule runs ${schedule.id}\` to list its runs, and \`vitehub schedule cancel ${schedule.id}\` to stop it.`
49
+ value: `Use \`vitehub schedule runs list ${schedule.id}\` to list its runs, and \`vitehub schedule cancel ${schedule.id}\` to stop it.`
50
50
  }
51
51
  ],
52
52
  id: `started:${schedule.id}`
@@ -1,4 +1,4 @@
1
- import { t as ScheduleKVStorage } from "../kv-storage-C0KZZB6v.js";
1
+ import { t as ScheduleKVStorage } from "../kv-storage-Bm9aYLfZ.js";
2
2
  //#region src/runtime/kv.d.ts
3
3
  export declare const scheduleKVStorage: ScheduleKVStorage;
4
4
  //#endregion
@@ -1,4 +1,4 @@
1
- import { t as createScheduleKVStorage } from "../kv-storage-iJChCS5A.js";
1
+ import { t as createScheduleKVStorage } from "../kv-storage-2kZtP2CC.js";
2
2
  import * as kvPackage from "@vite-hub/kv";
3
3
  //#region src/runtime/kv.ts
4
4
  const scheduleKVStorage = createScheduleKVStorage(kvPackage.kv);
@@ -1,12 +1,11 @@
1
1
  import { n as isRecordOrFunction } from "../object-Da1zyPCR.js";
2
- import { t as scheduleErrorDiagnostics } from "../error-diagnostics-Mpeks7J0.js";
3
- import { i as scheduleIdempotencyKey, o as createScheduleError } from "../wait-until-Dy4Bn3ZN.js";
4
- import { i as executeStaticSchedule, o as toRunId } from "../started-errors-p7cu_rI7.js";
5
- import { d as setScheduleRuntimeRegistry, i as getScheduleRuntimeRegistry, l as setScheduleOccurrenceClaims, n as getScheduleOccurrenceClaims, r as getScheduleRunStore, s as registerProcessScheduleDefinitions, u as setScheduleRunStore } from "../state-B-Fuyfb4.js";
6
- import { t as isScheduleDue } from "../due-BVMRQ93v.js";
7
- import { i as runStartedSchedules } from "../started-BuGmnus4.js";
8
- import { createMemoryLeaseStore } from "@vite-hub/runtime";
9
- import { hostname } from "node:os";
2
+ import { t as scheduleErrorDiagnostics } from "../error-diagnostics-DTmP6baC.js";
3
+ import { S as createScheduleError, b as scheduleIdempotencyKey, c as markLoggedScheduleError } from "../static-BgoOCoe5.js";
4
+ import { a as executeStaticSchedule, l as toRunId } from "../started-errors-BMg04lL3.js";
5
+ import { n as isScheduleDue } from "../due-n120-_nz.js";
6
+ import { a as getScheduleRuntimeRegistry, c as registerProcessScheduleDefinitions, d as setScheduleOccurrenceClaims, f as setScheduleRunStore, i as getScheduleRunStore, p as setScheduleRuntimeRegistry, r as getScheduleOccurrenceClaims } from "../state-BjWnxyhv.js";
7
+ import { i as runStartedSchedules } from "../started-BXdWMdji.js";
8
+ import { createMemoryLeaseStore, getInstanceId } from "@vite-hub/runtime";
10
9
  import { onShutdown } from "@vite-hub/runtime/internal/shutdown";
11
10
  //#region src/internal/process-wake-runtime.ts
12
11
  const minuteMs$1 = 6e4;
@@ -42,11 +41,8 @@ function createProcessWakeDriver(options, context) {
42
41
  const { catchUpMs, concurrency, intervalMs } = validateDriverOptions(options);
43
42
  const now = options.now ?? (() => new Date(Date.now()));
44
43
  let schedules = /* @__PURE__ */ new Map();
45
- /** Occurrences waiting for a worker, in delivery order. */
46
44
  const queued = /* @__PURE__ */ new Map();
47
- /** Occurrences that a worker is waking now. */
48
45
  const active = /* @__PURE__ */ new Set();
49
- /** Schedules already queued for `occurrenceMinute`, so a Schedule wakes once per current minute. */
50
46
  let dispatched = /* @__PURE__ */ new Set();
51
47
  let occurrenceMinute;
52
48
  let scannedThrough;
@@ -71,7 +67,7 @@ function createProcessWakeDriver(options, context) {
71
67
  function take() {
72
68
  for (const [key, input] of queued) {
73
69
  queued.delete(key);
74
- if (input.scheduledAt.getTime() < floorUTCMinute(now()) - catchUpMs) continue;
70
+ if (floorUTCMinute(now()) > (input.startBy ?? input.scheduledAt.getTime() + catchUpMs)) continue;
75
71
  return input;
76
72
  }
77
73
  }
@@ -93,14 +89,12 @@ function createProcessWakeDriver(options, context) {
93
89
  if (workers === 0) onIdle?.();
94
90
  }
95
91
  }
96
- /** Starts workers up to `concurrency`. A free worker starts its wake before this returns. */
97
92
  function startWorkers() {
98
93
  while (workers < concurrency && queued.size > 0) {
99
94
  workers += 1;
100
95
  work();
101
96
  }
102
97
  }
103
- /** Due occurrences of `entries` from `first` through `last`, oldest first. */
104
98
  function dueOccurrences(entries, first, last) {
105
99
  const due = [];
106
100
  for (const schedule of entries) for (let minute = Math.ceil(first / minuteMs$1) * minuteMs$1; minute <= last; minute += minuteMs$1) {
@@ -119,7 +113,6 @@ function createProcessWakeDriver(options, context) {
119
113
  }
120
114
  return due.sort(byScheduledAt);
121
115
  }
122
- /** Queues occurrences that are not queued or running yet, then starts free workers. The current minute dispatches each Schedule once. */
123
116
  function enqueue(due, currentMinute, retries = []) {
124
117
  if (closing) return;
125
118
  if (occurrenceMinute !== void 0 && currentMinute < occurrenceMinute) return;
@@ -160,7 +153,7 @@ function createProcessWakeDriver(options, context) {
160
153
  reportError(error);
161
154
  }
162
155
  if (!latest) continue;
163
- const first = latest === "unknown" ? currentMinute - catchUpMs : Math.max(floorUTCMinute(latest) + minuteMs$1, currentMinute - catchUpMs);
156
+ const first = Math.max(floorUTCMinute(latest) + minuteMs$1, currentMinute - catchUpMs);
164
157
  due.push(...dueOccurrences([schedule], first, currentMinute - minuteMs$1));
165
158
  }
166
159
  enqueue(due.sort(byScheduledAt), currentMinute);
@@ -303,7 +296,6 @@ function unwrapDefinition(loaded) {
303
296
  function isTiming(value) {
304
297
  return isRecordOrFunction(value) && String(value.cron) === value.cron && (value.timeZone === void 0 || String(value.timeZone) === value.timeZone);
305
298
  }
306
- /** Loads a Definition once, and again only after the load fails. */
307
299
  function lazyDefinition(name, load) {
308
300
  let loading;
309
301
  return () => loading ??= load().then((loaded) => {
@@ -315,10 +307,6 @@ function lazyDefinition(name, load) {
315
307
  throw error;
316
308
  });
317
309
  }
318
- /**
319
- * Loads the Definitions without a build timing now and keeps the others lazy. A Definition without a cron and a handler
320
- * is skipped.
321
- */
322
310
  async function loadStaticDefinitions(registry, timings = {}) {
323
311
  const entries = await Promise.all(Object.entries(registry).map(async ([name, load]) => {
324
312
  const timing = Object.hasOwn(timings, name) ? timings[name] : void 0;
@@ -373,15 +361,15 @@ async function installProcessScheduleRuntime(options) {
373
361
  const previousClaims = getScheduleOccurrenceClaims();
374
362
  const reportError = createErrorReporter(options.onError);
375
363
  const leaseTtlMs = resolveLeaseTtlMs(options.leaseTtlMs);
364
+ const catchUpMs = options.catchUpMs ?? 36e5;
376
365
  const claims = createOccurrenceClaims({
377
- doneTtlMs: (options.catchUpMs ?? 36e5) + leaseTtlMs + 2 * minuteMs,
366
+ doneTtlMs: catchUpMs + leaseTtlMs + 2 * minuteMs,
378
367
  leases: options.leases ?? createMemoryLeaseStore(),
379
- owner: `${hostname()}:${process.pid}`,
368
+ owner: getInstanceId(),
380
369
  prefix: options.prefix,
381
370
  reportError,
382
371
  ttlMs: leaseTtlMs
383
372
  });
384
- /** Occurrences that another process held when this process tried them, by run id. Each scan tries them again. */
385
373
  const held = /* @__PURE__ */ new Map();
386
374
  const pendingWork = /* @__PURE__ */ new Set();
387
375
  const activeWakes = /* @__PURE__ */ new Set();
@@ -402,20 +390,12 @@ async function installProcessScheduleRuntime(options) {
402
390
  idPrefix: "srun_static_",
403
391
  limit: 1
404
392
  });
405
- if (!run || run.id.startsWith("srun_static_")) return run?.scheduledAt;
406
- const limit = 100;
407
- const recent = await options.scheduleRunStore.listRuns({
408
- scheduleId,
409
- limit
410
- });
411
- const latest = recent.find((record) => record.id.startsWith("srun_static_"));
412
- if (latest) return latest.scheduledAt;
413
- return recent.length < limit ? void 0 : "unknown";
393
+ return run?.scheduledAt;
414
394
  },
415
395
  reportError,
416
396
  retries() {
417
- const since = Math.floor((options.now?.() ?? /* @__PURE__ */ new Date()).getTime() / minuteMs) * minuteMs - (options.catchUpMs ?? 36e5);
418
- for (const [runId, input] of held) if (input.scheduledAt.getTime() < since) held.delete(runId);
397
+ const currentMinute = Math.floor((options.now?.() ?? /* @__PURE__ */ new Date()).getTime() / minuteMs) * minuteMs;
398
+ for (const [runId, input] of held) if (currentMinute > (input.startBy ?? input.scheduledAt.getTime() + catchUpMs)) held.delete(runId);
419
399
  return [...held.values()];
420
400
  },
421
401
  wake(input) {
@@ -436,6 +416,7 @@ async function installProcessScheduleRuntime(options) {
436
416
  return;
437
417
  }
438
418
  const runId = toRunId("static", entry.name, input.scheduledAt);
419
+ let logged = false;
439
420
  try {
440
421
  if (await claims.run(runId, (onExecution) => executeStaticSchedule({
441
422
  claimed: true,
@@ -443,19 +424,24 @@ async function installProcessScheduleRuntime(options) {
443
424
  definition,
444
425
  name: entry.name,
445
426
  onExecution,
427
+ onRunLogged: () => {
428
+ logged = true;
429
+ },
446
430
  scheduledAt: input.scheduledAt,
447
431
  waitUntil
448
432
  })) === "held") held.set(runId, {
449
433
  scheduleId: input.scheduleId,
450
- scheduledAt: input.scheduledAt
434
+ scheduledAt: input.scheduledAt,
435
+ startBy: input.scheduledAt.getTime() + catchUpMs + leaseTtlMs + minuteMs
451
436
  });
452
437
  else held.delete(runId);
453
438
  } catch (error) {
454
439
  held.set(runId, {
440
+ ...held.get(runId),
455
441
  scheduleId: input.scheduleId,
456
442
  scheduledAt: input.scheduledAt
457
443
  });
458
- throw error;
444
+ throw logged ? markLoggedScheduleError(error) : error;
459
445
  }
460
446
  })();
461
447
  activeWakes.add(wake);
@@ -463,14 +449,7 @@ async function installProcessScheduleRuntime(options) {
463
449
  return wake;
464
450
  }
465
451
  });
466
- /**
467
- * Catch-up starts after the newest cron-triggered run, also when that run did not finish. A run that is still pending
468
- * or running inside the catch-up window lost its process, as when every server restarts after a crash. Try those
469
- * occurrences again at each scan, through the claim: they run when the lease of their process ends and no process
470
- * finished them.
471
- */
472
452
  async function recoverUnfinishedOccurrences() {
473
- const catchUpMs = options.catchUpMs ?? 36e5;
474
453
  if (catchUpMs <= 0) return;
475
454
  const currentMinute = Math.floor((options.now?.() ?? /* @__PURE__ */ new Date()).getTime() / minuteMs) * minuteMs;
476
455
  const since = currentMinute - catchUpMs;
@@ -484,7 +463,7 @@ async function installProcessScheduleRuntime(options) {
484
463
  scheduleId: entry.name
485
464
  });
486
465
  for (const run of runs) {
487
- if (run.scheduledAt.getTime() < since || !run.id.startsWith("srun_static_")) continue;
466
+ if (run.scheduledAt.getTime() < since) continue;
488
467
  if (run.status !== "pending" && run.status !== "running") continue;
489
468
  held.set(run.id, {
490
469
  scheduleId: entry.name,
@@ -1,2 +1,2 @@
1
- import { a as getScheduleRuntimeRegistry, c as registerProcessScheduleDefinitions, d as setScheduleRunStore, f as setScheduleRuntimeRegistry, i as getScheduleRunStore, l as resetScheduleRuntime, n as getProcessScheduleDefinitions, o as getStartedScheduleRuntime, p as setStartedScheduleRuntime, r as getScheduleOccurrenceClaims, s as loadScheduleDefinition, t as StartedScheduleRuntime, u as setScheduleOccurrenceClaims } from "../state-Do2wV4Tx.js";
2
- export { StartedScheduleRuntime, getProcessScheduleDefinitions, getScheduleOccurrenceClaims, getScheduleRunStore, getScheduleRuntimeRegistry, getStartedScheduleRuntime, loadScheduleDefinition, registerProcessScheduleDefinitions, resetScheduleRuntime, setScheduleOccurrenceClaims, setScheduleRunStore, setScheduleRuntimeRegistry, setStartedScheduleRuntime };
1
+ import { a as getScheduleRunStore, c as loadScheduleDefinition, d as setHostScheduleInventory, f as setScheduleOccurrenceClaims, h as setStartedScheduleRuntime, i as getScheduleOccurrenceClaims, l as registerProcessScheduleDefinitions, m as setScheduleRuntimeRegistry, n as getHostScheduleInventory, o as getScheduleRuntimeRegistry, p as setScheduleRunStore, r as getProcessScheduleDefinitions, s as getStartedScheduleRuntime, t as StartedScheduleRuntime, u as resetScheduleRuntime } from "../state-CJKAhskJ.js";
2
+ export { StartedScheduleRuntime, getHostScheduleInventory, getProcessScheduleDefinitions, getScheduleOccurrenceClaims, getScheduleRunStore, getScheduleRuntimeRegistry, getStartedScheduleRuntime, loadScheduleDefinition, registerProcessScheduleDefinitions, resetScheduleRuntime, setHostScheduleInventory, setScheduleOccurrenceClaims, setScheduleRunStore, setScheduleRuntimeRegistry, setStartedScheduleRuntime };
@@ -1,2 +1,2 @@
1
- import { a as getStartedScheduleRuntime, c as resetScheduleRuntime, d as setScheduleRuntimeRegistry, f as setStartedScheduleRuntime, i as getScheduleRuntimeRegistry, l as setScheduleOccurrenceClaims, n as getScheduleOccurrenceClaims, o as loadScheduleDefinition, r as getScheduleRunStore, s as registerProcessScheduleDefinitions, t as getProcessScheduleDefinitions, u as setScheduleRunStore } from "../state-B-Fuyfb4.js";
2
- export { getProcessScheduleDefinitions, getScheduleOccurrenceClaims, getScheduleRunStore, getScheduleRuntimeRegistry, getStartedScheduleRuntime, loadScheduleDefinition, registerProcessScheduleDefinitions, resetScheduleRuntime, setScheduleOccurrenceClaims, setScheduleRunStore, setScheduleRuntimeRegistry, setStartedScheduleRuntime };
1
+ import { a as getScheduleRuntimeRegistry, c as registerProcessScheduleDefinitions, d as setScheduleOccurrenceClaims, f as setScheduleRunStore, i as getScheduleRunStore, l as resetScheduleRuntime, m as setStartedScheduleRuntime, n as getProcessScheduleDefinitions, o as getStartedScheduleRuntime, p as setScheduleRuntimeRegistry, r as getScheduleOccurrenceClaims, s as loadScheduleDefinition, t as getHostScheduleInventory, u as setHostScheduleInventory } from "../state-BjWnxyhv.js";
2
+ export { getHostScheduleInventory, getProcessScheduleDefinitions, getScheduleOccurrenceClaims, getScheduleRunStore, getScheduleRuntimeRegistry, getStartedScheduleRuntime, loadScheduleDefinition, registerProcessScheduleDefinitions, resetScheduleRuntime, setHostScheduleInventory, setScheduleOccurrenceClaims, setScheduleRunStore, setScheduleRuntimeRegistry, setStartedScheduleRuntime };
@@ -1,73 +1,2 @@
1
- import { a as ScheduleDefinitionRegistry, n as ScheduleDefinition, u as ScheduleRunContext } from "../types-Cw5LjPuc.js";
2
- //#region src/runtime/static.d.ts
3
- export interface ExecuteStaticScheduleOptions {
4
- cron: string;
5
- definition: ScheduleDefinition;
6
- name: string;
7
- scheduledAt?: Date;
8
- waitUntil?: (promise: PromiseLike<unknown>) => void;
9
- }
10
- export interface ExecuteMatchingStaticSchedulesOptions {
11
- cron: string;
12
- /** Cron per Schedule name that the host registered in place of the Definition's cron. */
13
- cronOverrides?: Readonly<Record<string, string>>;
14
- registry: ScheduleDefinitionRegistry;
15
- scheduledAt?: Date;
16
- /**
17
- * UTC cron that the host registered for each Schedule with a `timeZone`. A wake runs such a Schedule only when its
18
- * own cron is due in its time zone at that minute. `cronOverrides` wins over this map.
19
- */
20
- timeZoneCrons?: Readonly<Record<string, string>>;
21
- waitUntil?: (promise: PromiseLike<unknown>) => void;
22
- }
23
- export interface ExecuteCloudflareStaticSchedulesOptions {
24
- /** Cron per Schedule name that the host registered in place of the Definition's cron. */
25
- cronOverrides?: Readonly<Record<string, string>>;
26
- registry: ScheduleDefinitionRegistry;
27
- /** UTC cron that the host registered for each Schedule with a `timeZone`. */
28
- timeZoneCrons?: Readonly<Record<string, string>>;
29
- waitUntil?: (promise: PromiseLike<unknown>) => void;
30
- }
31
- interface CloudflareScheduledEventLike {
32
- [key: string]: unknown;
33
- controller?: {
34
- cron?: string;
35
- scheduledTime?: number | string | Date;
36
- };
37
- cron?: string;
38
- scheduledTime?: number | string | Date;
39
- }
40
- export interface StaticScheduleRun extends ScheduleRunContext {
41
- cron: string;
42
- scheduleId: string;
43
- }
44
- export declare function missingScheduleDefinitionError(name: string): Error;
45
- /**
46
- * Checks the `Authorization` header of a Vercel Cron request against `CRON_SECRET` in constant time.
47
- */
48
- export declare function isScheduleCronAuthorized(authorization: string | null | undefined, cronSecret: string): boolean;
49
- export declare function normalizeCron(cron: string): string;
50
- export declare function normalizeScheduleRuntimeError(error: unknown): Error;
51
- /**
52
- * Estimates a wake minute from callback time when the host supplies no scheduled timestamp. This is the newest UTC
53
- * cron match within one day, or the current minute when none matches. It cannot identify a delayed or retried wake
54
- * after another cron match; callers must not treat it as the provider's occurrence identity.
55
- */
56
- export declare function scheduledWakeTime(cron: string, now?: Date): Date;
57
- /**
58
- * Returns `true` when a host wake at `scheduledAt` is an occurrence of the Definition's cron in its `timeZone`. The host
59
- * runs a wider UTC cron for a time-zoned Schedule, so the runtime skips the wakes that are not local occurrences.
60
- */
61
- export declare function isTimeZoneWakeDue(definition: ScheduleDefinition & {
62
- cron: string;
63
- }, name: string, scheduledAt: Date): boolean;
64
- export declare function createStaticScheduleRun(options: Omit<ExecuteStaticScheduleOptions, "definition" | "waitUntil"> & {
65
- waitUntil: NonNullable<ExecuteStaticScheduleOptions["waitUntil"]>;
66
- }): StaticScheduleRun;
67
- export declare function executeStaticSchedule(options: ExecuteStaticScheduleOptions): Promise<unknown>;
68
- export declare function executeMatchingStaticSchedules(options: ExecuteMatchingStaticSchedulesOptions): Promise<unknown[]>;
69
- export declare function executeCloudflareStaticSchedules(event: CloudflareScheduledEventLike, options: ExecuteCloudflareStaticSchedulesOptions): Promise<unknown[]>;
70
- export declare function unwrapScheduleDefinition(loaded: unknown): (ScheduleDefinition & {
71
- cron: string;
72
- }) | undefined;
73
- //#endregion
1
+ import { _ as unwrapScheduleDefinition, a as createStaticScheduleRun, c as executeStaticSchedule, d as logScheduleRuntimeError, f as markLoggedScheduleError, g as scheduledWakeTime, h as normalizeScheduleRuntimeError, i as StaticScheduleRun, l as isScheduleCronAuthorized, m as normalizeCron, n as ExecuteMatchingStaticSchedulesOptions, o as executeCloudflareStaticSchedules, p as missingScheduleDefinitionError, r as ExecuteStaticScheduleOptions, s as executeMatchingStaticSchedules, t as ExecuteCloudflareStaticSchedulesOptions, u as isTimeZoneWakeDue, v as cronWithWeekdayNames } from "../static-CcBWx1kU.js";
2
+ export { ExecuteCloudflareStaticSchedulesOptions, ExecuteMatchingStaticSchedulesOptions, ExecuteStaticScheduleOptions, StaticScheduleRun, createStaticScheduleRun, cronWithWeekdayNames, executeCloudflareStaticSchedules, executeMatchingStaticSchedules, executeStaticSchedule, isScheduleCronAuthorized, isTimeZoneWakeDue, logScheduleRuntimeError, markLoggedScheduleError, missingScheduleDefinitionError, normalizeCron, normalizeScheduleRuntimeError, scheduledWakeTime, unwrapScheduleDefinition };
@@ -1,2 +1,3 @@
1
- import { a as isScheduleCronAuthorized, c as normalizeCron, d as unwrapScheduleDefinition, i as executeStaticSchedule, l as normalizeScheduleRuntimeError, n as executeCloudflareStaticSchedules, o as isTimeZoneWakeDue, r as executeMatchingStaticSchedules, s as missingScheduleDefinitionError, t as createStaticScheduleRun, u as scheduledWakeTime } from "../static-DQwzzvPg.js";
2
- export { createStaticScheduleRun, executeCloudflareStaticSchedules, executeMatchingStaticSchedules, executeStaticSchedule, isScheduleCronAuthorized, isTimeZoneWakeDue, missingScheduleDefinitionError, normalizeCron, normalizeScheduleRuntimeError, scheduledWakeTime, unwrapScheduleDefinition };
1
+ import { a as isScheduleCronAuthorized, c as markLoggedScheduleError, d as normalizeScheduleRuntimeError, f as scheduledWakeTime, i as executeStaticSchedule, l as missingScheduleDefinitionError, n as executeCloudflareStaticSchedules, o as isTimeZoneWakeDue, p as unwrapScheduleDefinition, r as executeMatchingStaticSchedules, s as logScheduleRuntimeError, t as createStaticScheduleRun, u as normalizeCron } from "../static-BgoOCoe5.js";
2
+ import { t as cronWithWeekdayNames } from "../due-n120-_nz.js";
3
+ export { createStaticScheduleRun, cronWithWeekdayNames, executeCloudflareStaticSchedules, executeMatchingStaticSchedules, executeStaticSchedule, isScheduleCronAuthorized, isTimeZoneWakeDue, logScheduleRuntimeError, markLoggedScheduleError, missingScheduleDefinitionError, normalizeCron, normalizeScheduleRuntimeError, scheduledWakeTime, unwrapScheduleDefinition };
package/dist/runtime.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  /// <reference path="./registry-module.d.ts" />
2
2
  import { a as ScheduleDefinitionRegistry, b as StartedScheduleStore, c as ScheduleRunAttemptRecord, f as ScheduleRunListOptions, g as ScheduleRunStore, i as ScheduleDefinitionOptions, n as ScheduleDefinition, o as ScheduleHandler, p as ScheduleRunRecord, s as ScheduleRegistryDefinition, u as ScheduleRunContext } from "./types-Cw5LjPuc.js";
3
- import { a as createScheduleRun, c as runScheduleFrom, n as createKVScheduleRunStore, o as executeSchedule, r as createMemoryScheduleRunStore, s as executeStaticSchedule, t as KVScheduleStoreOptions } from "./store-Df0-fzCl.js";
4
- import { n as createScheduleKVStorage, t as ScheduleKVStorage } from "./kv-storage-C0KZZB6v.js";
5
- import { normalizeCron, unwrapScheduleDefinition } from "./runtime/static.js";
6
- import { d as setScheduleRunStore, i as getScheduleRunStore, l as resetScheduleRuntime } from "./state-Do2wV4Tx.js";
3
+ import { a as createScheduleRun, c as runScheduleFrom, n as createKVScheduleRunStore, o as executeSchedule, r as createMemoryScheduleRunStore, s as executeStaticSchedule, t as KVScheduleStoreOptions } from "./store-CZHZfttA.js";
4
+ import { n as createScheduleKVStorage, t as ScheduleKVStorage } from "./kv-storage-Bm9aYLfZ.js";
5
+ import { _ as unwrapScheduleDefinition, m as normalizeCron } from "./static-CcBWx1kU.js";
6
+ import { a as getScheduleRunStore, p as setScheduleRunStore, u as resetScheduleRuntime } from "./state-CJKAhskJ.js";
7
7
  //#region src/runtime/started.d.ts
8
8
  interface InstallStartedSchedulesOptions {
9
9
  /**
package/dist/runtime.js CHANGED
@@ -1,6 +1,6 @@
1
- import { a as runScheduleFrom, i as executeStaticSchedule, n as createScheduleRun, r as executeSchedule } from "./started-errors-p7cu_rI7.js";
2
- import { c as resetScheduleRuntime, m as createMemoryScheduleRunStore, p as createKVScheduleRunStore, r as getScheduleRunStore, u as setScheduleRunStore } from "./state-B-Fuyfb4.js";
3
- import { c as normalizeCron, d as unwrapScheduleDefinition } from "./static-DQwzzvPg.js";
4
- import { t as createScheduleKVStorage } from "./kv-storage-iJChCS5A.js";
5
- import { i as runStartedSchedules, n as createMemoryStartedScheduleStore, r as installStartedSchedules, t as createKVStartedScheduleStore } from "./started-BuGmnus4.js";
1
+ import { p as unwrapScheduleDefinition, u as normalizeCron } from "./static-BgoOCoe5.js";
2
+ import { a as executeStaticSchedule, c as runScheduleFrom, i as executeSchedule, n as createScheduleRun } from "./started-errors-BMg04lL3.js";
3
+ import { f as setScheduleRunStore, g as createMemoryScheduleRunStore, h as createKVScheduleRunStore, i as getScheduleRunStore, l as resetScheduleRuntime } from "./state-BjWnxyhv.js";
4
+ import { t as createScheduleKVStorage } from "./kv-storage-2kZtP2CC.js";
5
+ import { i as runStartedSchedules, n as createMemoryStartedScheduleStore, r as installStartedSchedules, t as createKVStartedScheduleStore } from "./started-BXdWMdji.js";
6
6
  export { createKVScheduleRunStore, createKVStartedScheduleStore, createMemoryScheduleRunStore, createMemoryStartedScheduleStore, createScheduleKVStorage, createScheduleRun, executeSchedule, executeStaticSchedule, getScheduleRunStore, installStartedSchedules, normalizeCron, resetScheduleRuntime, runScheduleFrom, runStartedSchedules, setScheduleRunStore, unwrapScheduleDefinition };
@@ -1,8 +1,8 @@
1
1
  import { t as isIanaTimeZone } from "./time-zone-SBldrUgt.js";
2
2
  import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
3
- import { r as parseScheduledAt } from "./wait-until-Dy4Bn3ZN.js";
4
- import { s as randomId, t as startedScheduleErrors } from "./started-errors-p7cu_rI7.js";
5
- import { a as getStartedScheduleRuntime } from "./state-B-Fuyfb4.js";
3
+ import { y as parseScheduledAt } from "./static-BgoOCoe5.js";
4
+ import { t as startedScheduleErrors, u as randomId } from "./started-errors-BMg04lL3.js";
5
+ import { o as getStartedScheduleRuntime } from "./state-BjWnxyhv.js";
6
6
  import { parseCronExpression } from "cron-schedule";
7
7
  //#region src/started.ts
8
8
  const optionKeys = /* @__PURE__ */ new Set([
@@ -51,7 +51,6 @@ function isFiveFieldCron(cron) {
51
51
  return false;
52
52
  }
53
53
  }
54
- /** Reads the options once at the boundary. The returned record is what the store keeps. */
55
54
  function parseOptions(name, options) {
56
55
  if (!isRecordOrFunction(options)) return invalid("pass an object with `at` or `cron`.");
57
56
  const unknownKey = Object.keys(options).find((key) => !optionKeys.has(key));
@@ -1,7 +1,8 @@
1
1
  import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
2
- import { o as toRunId, r as executeSchedule, t as startedScheduleErrors } from "./started-errors-p7cu_rI7.js";
3
- import { a as getStartedScheduleRuntime, f as setStartedScheduleRuntime, g as keySegments, h as joinKey, n as getScheduleOccurrenceClaims } from "./state-B-Fuyfb4.js";
4
- import { t as isScheduleDue } from "./due-BVMRQ93v.js";
2
+ import { _ as errorCode, v as logFailure } from "./static-BgoOCoe5.js";
3
+ import { i as executeSchedule, l as toRunId, t as startedScheduleErrors } from "./started-errors-BMg04lL3.js";
4
+ import { n as isScheduleDue } from "./due-n120-_nz.js";
5
+ import { _ as joinKey, m as setStartedScheduleRuntime, o as getStartedScheduleRuntime, r as getScheduleOccurrenceClaims, v as keySegments } from "./state-BjWnxyhv.js";
5
6
  import { normalizeRuntimeDiagnosticError } from "@vite-hub/runtime";
6
7
  //#region src/runtime/started.ts
7
8
  const minuteMs = 6e4;
@@ -99,7 +100,6 @@ function unwrapStartableDefinition(loaded) {
99
100
  const candidate = isRecordOrFunction(loaded) && Object.hasOwn(loaded, "default") ? loaded.default : loaded;
100
101
  return isRecordOrFunction(candidate) && typeof candidate.handler === "function" && !Object.hasOwn(candidate, "cron") ? candidate : void 0;
101
102
  }
102
- /** The minutes in `[first, last]` when `schedule` is due, after it was created. A one-time Schedule is due once `at` passed. */
103
103
  function dueMinutes(schedule, first, last) {
104
104
  if (schedule.at) return schedule.at.getTime() <= last ? [schedule.at] : [];
105
105
  const due = [];
@@ -114,7 +114,6 @@ function dueMinutes(schedule, first, last) {
114
114
  }
115
115
  return due;
116
116
  }
117
- /** Runs one occurrence of a started Schedule. Resolves `false` when another process holds it, so a later tick tries again. */
118
117
  async function runOccurrence(runtime, schedule, scheduledAt, waitUntil) {
119
118
  const definition = unwrapStartableDefinition(await (Object.hasOwn(runtime.registry, schedule.name) ? runtime.registry[schedule.name] : void 0)?.());
120
119
  if (!definition) {
@@ -169,6 +168,8 @@ async function runStartedSchedules(context) {
169
168
  })));
170
169
  const held = runtime.held ??= /* @__PURE__ */ new Map();
171
170
  const byId = new Map(schedules.map((schedule) => [schedule.id, schedule]));
171
+ const failing = runtime.failing ??= /* @__PURE__ */ new Map();
172
+ for (const id of failing.keys()) if (!byId.has(id)) failing.delete(id);
172
173
  for (const [runId, entry] of held) {
173
174
  const schedule = byId.get(entry.scheduleId);
174
175
  if (!schedule) held.delete(runId);
@@ -187,13 +188,30 @@ async function runStartedSchedules(context) {
187
188
  scheduleId: schedule.id,
188
189
  scheduledAt
189
190
  });
191
+ failing.delete(schedule.id);
190
192
  return;
191
193
  }
192
194
  held.set(runId, {
193
195
  scheduleId: schedule.id,
194
196
  scheduledAt
195
197
  });
196
- console.error(`[vitehub:schedule] Started Schedule "${schedule.id}" of "${schedule.name}" failed.`, normalizeRuntimeDiagnosticError(result.reason, { includeStack: true }));
198
+ const cause = errorCode(result.reason) ?? (result.reason instanceof Error ? result.reason.message : String(result.reason));
199
+ if (failing.get(schedule.id) === cause) return;
200
+ failing.set(schedule.id, cause);
201
+ logFailure({
202
+ field: "schedule",
203
+ fields: {
204
+ op: "started",
205
+ name: schedule.name,
206
+ id: schedule.id
207
+ },
208
+ level: "error",
209
+ message: "Started Schedule failed",
210
+ error: result.reason,
211
+ waitUntil: (promise) => context.waitUntil(promise)
212
+ }, () => {
213
+ console.error(`[vitehub:schedule] Started Schedule "${schedule.id}" of "${schedule.name}" failed.`, normalizeRuntimeDiagnosticError(result.reason, { includeStack: true }));
214
+ });
197
215
  });
198
216
  if (results.every((result) => result.status === "fulfilled")) runtime.checkedThrough = Math.max(runtime.checkedThrough ?? minute, minute);
199
217
  }
@@ -1,7 +1,9 @@
1
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 { r as getScheduleRunStore } from "./state-B-Fuyfb4.js";
4
- import { defineErrors, serializeResponse, toResponse } from "@vite-hub/runtime";
2
+ import { S as createScheduleError, _ as errorCode, b as scheduleIdempotencyKey, c as markLoggedScheduleError, d as normalizeScheduleRuntimeError, g as emitLogEvent, h as logScheduleRun, m as runWithScheduleWaitUntil, x as validateScheduledAt, y as parseScheduledAt } from "./static-BgoOCoe5.js";
3
+ import { i as getScheduleRunStore } from "./state-BjWnxyhv.js";
4
+ import { defineErrors } from "@vite-hub/runtime";
5
+ import { serializeResponse, toResponse } from "@vite-hub/runtime/internal/response";
6
+ import { emitRunFailed, toRunFailedError } from "@vite-hub/runtime/internal/run-failed";
5
7
  import { runInRunScopes } from "@vite-hub/runtime/internal/run-scope";
6
8
  //#region ../internal/src/runtime/random.ts
7
9
  function randomId(prefix) {
@@ -29,6 +31,10 @@ function toRunError(error) {
29
31
  return { message: "[unprintable thrown value]" };
30
32
  }
31
33
  }
34
+ function errorCodeField(error) {
35
+ const code = errorCode(error);
36
+ return code ? { code } : {};
37
+ }
32
38
  function requireUpdatedRun(run) {
33
39
  if (!run) throw createScheduleError("SCHEDULE_RUN_NOT_FOUND");
34
40
  return run;
@@ -165,20 +171,64 @@ async function executeSchedule(options) {
165
171
  }
166
172
  const attempt = await startAttempt(run, runStore);
167
173
  options.onExecution?.();
174
+ const runLog = {
175
+ name: run.target,
176
+ ...run.scheduleId === run.target ? {} : { id: run.scheduleId },
177
+ runId: run.id,
178
+ source: normalizeRunSource(options.source),
179
+ scheduledAt: run.scheduledAt,
180
+ attempt: run.attemptCount + 1
181
+ };
182
+ const waitUntil = options.waitUntil ? { waitUntil: (promise) => options.waitUntil?.(promise) } : {};
183
+ const recordRun = async (write) => {
184
+ try {
185
+ return await write();
186
+ } catch (error) {
187
+ throw emitLogEvent({
188
+ field: "schedule",
189
+ fields: {
190
+ op: "record-run",
191
+ name: run.target,
192
+ runId: run.id,
193
+ ...errorCodeField(error)
194
+ },
195
+ level: "error",
196
+ message: "Schedule could not record a finished run",
197
+ ...waitUntil
198
+ }) ? markLoggedScheduleError(error) : error;
199
+ }
200
+ };
201
+ const startedAt = performance.now();
202
+ let response;
168
203
  try {
169
204
  const value = await runInRunScopes(() => runWithScheduleWaitUntil((waitUntil) => options.definition.handler(toHandlerContext(run, attempt, waitUntil)), options.waitUntil));
170
- return await completeRun(run, attempt, await serializeResponse(toResponse(value)), runStore);
205
+ response = await serializeResponse(toResponse(value));
171
206
  } catch (error) {
172
- const failed = await failRun(run, attempt, error, runStore);
207
+ const logged = logScheduleRun(runLog, startedAt, "failure", {
208
+ error: normalizeScheduleRuntimeError(error),
209
+ ...waitUntil
210
+ });
211
+ const failed = await recordRun(() => failRun(run, attempt, error, runStore));
212
+ await emitRunFailed({
213
+ event: "schedule.failed",
214
+ schedule: failed.scheduleId,
215
+ runId: failed.id,
216
+ error: toRunFailedError(error),
217
+ failedAt: (failed.completedAt ?? /* @__PURE__ */ new Date()).toISOString()
218
+ });
173
219
  if (options.captureHandlerFailure) return failed;
220
+ if (logged) options.onRunLogged?.();
174
221
  throw error;
175
222
  }
223
+ logScheduleRun(runLog, startedAt, "success", waitUntil);
224
+ return await recordRun(() => completeRun(run, attempt, response, runStore));
176
225
  }
177
226
  async function executeStaticSchedule(options) {
178
227
  return await executeSchedule({
179
228
  ...options.claimed ? { claimed: true } : {},
180
229
  definition: options.definition,
181
230
  onExecution: options.onExecution,
231
+ ...options.onRunLogged ? { onRunLogged: options.onRunLogged } : {},
182
232
  scheduleId: options.name,
183
233
  source: "static",
184
234
  scheduledAt: options.scheduledAt,
@@ -195,29 +245,26 @@ async function loadStaticScheduleDefinition(name, registry) {
195
245
  const record = isRecordOrFunction(loaded) ? loaded : void 0;
196
246
  return record && isStaticScheduleDefinition(record) ? record : record && Object.hasOwn(record, "default") && isStaticScheduleDefinition(record.default) ? record.default : void 0;
197
247
  }
198
- /** Runs a manually dispatchable static Schedule Definition of `registry` immediately. */
199
- async function runScheduleFrom(registry, name, options = {}) {
248
+ async function resolveManualSchedule(registry, name) {
200
249
  const definition = typeof name === "string" && name ? await loadStaticScheduleDefinition(name, registry) : void 0;
201
250
  if (!definition) throw createScheduleError("SCHEDULE_DEFINITION_NOT_FOUND");
202
251
  if (definition.options?.manual !== true) throw createScheduleError("SCHEDULE_MANUAL_RUN_DISABLED");
203
- const scheduledAt = parseScheduledAt(options.scheduledAt);
204
- const runStore = getScheduleRunStore();
205
- const runIdSuffix = randomId("manual");
206
- try {
207
- return await executeSchedule({
208
- definition,
209
- runIdSuffix,
210
- runStore,
211
- scheduleId: name,
212
- source: "manual",
213
- scheduledAt,
214
- target: name
215
- });
216
- } catch (error) {
217
- const run = await runStore.getRun(toRunId("manual", name, scheduledAt, runIdSuffix));
218
- if (run?.status === "failed") return run;
219
- throw error;
220
- }
252
+ return definition;
253
+ }
254
+ function executeManualSchedule(definition, name, scheduledAt) {
255
+ return executeSchedule({
256
+ captureHandlerFailure: true,
257
+ definition,
258
+ runIdSuffix: randomId("manual"),
259
+ scheduleId: name,
260
+ scheduledAt,
261
+ source: "manual",
262
+ target: name
263
+ });
264
+ }
265
+ /** Runs a manually dispatchable static Schedule Definition of `registry` immediately. */
266
+ async function runScheduleFrom(registry, name, options = {}) {
267
+ return await executeManualSchedule(await resolveManualSchedule(registry, name), name, parseScheduledAt(options.scheduledAt));
221
268
  }
222
269
  //#endregion
223
270
  //#region src/started-errors.ts
@@ -247,4 +294,4 @@ const startedScheduleErrors = /*#__PURE__*/ defineErrors({
247
294
  }
248
295
  });
249
296
  //#endregion
250
- export { runScheduleFrom as a, executeStaticSchedule as i, createScheduleRun as n, toRunId as o, executeSchedule as r, randomId as s, startedScheduleErrors as t };
297
+ 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 };
@@ -0,0 +1,5 @@
1
+ //#region src/runtime/started-name.ts
2
+ /** Name of the Schedule that runs due started Schedules each minute. Discovery adds it when a Definition has no `cron`. */
3
+ const startedSchedulesTickName = "vitehub/started-schedules";
4
+ //#endregion
5
+ export { startedSchedulesTickName as t };