ShtukbaseStandard
包文件→ .shtukbase/packages/schedule/lib/schedule.ts

lib/schedule.ts

130 行, 6.6 KB.

文件按包中的原样显示:代码及其注释不做翻译。

  1. // The schedule of automations: a trigger `{kind: schedule, cron: "0 7 * * *"}`, `{kind: schedule, every: 6h}` or
  2. // `{kind: clock, at: "07:00"}` → when the automation is due, judged by the run journal. Pure functions plus the
  3. // readers of automations and runs. Cron is the classic five fields, read in the machine's time zone or in
  4. // `trigger.tz` (an IANA name such as UTC).
  5. import { type Project, type Rec, map, normPath, recordsOf, text, time } from '../../agents/lib/factlib.ts';
  6. export const KINDS = ['schedule', 'clock'];
  7. export type Sched = { cron: number[][]; tz: string; source: string } | { every: number; source: string };
  8. const RANGES: [number, number][] = [[0, 59], [0, 23], [1, 31], [1, 12], [0, 7]];
  9. /** One cron field → the sorted values it allows, or an error text. */
  10. function field(s: string, [lo, hi]: [number, number]): number[] | string {
  11. const out = new Set<number>();
  12. for (const part of s.split(',')) {
  13. const m = /^(\*|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(part);
  14. if (!m) return `"${part}" is not a cron field`;
  15. const step = m[4] ? Number(m[4]) : 1;
  16. const a = m[1] === '*' ? lo : Number(m[2]);
  17. const b = m[1] === '*' ? hi : m[3] ? Number(m[3]) : m[4] ? hi : a;
  18. if (step < 1 || a < lo || b > hi || a > b) return `"${part}" is outside ${lo}–${hi}`;
  19. for (let v = a; v <= b; v += step) out.add(v);
  20. }
  21. return [...out].sort((x, y) => x - y);
  22. }
  23. /** A cron line of five fields → the allowed values per field, or an error text. Sunday is 0 or 7. */
  24. export function parseCron(line: string): number[][] | string {
  25. const parts = line.trim().split(/\s+/);
  26. if (parts.length !== 5) return `the cron line has ${parts.length} fields, but 5 are needed (minute hour day month weekday)`;
  27. const out: number[][] = [];
  28. for (let i = 0; i < 5; i++) {
  29. const f = field(parts[i], RANGES[i]);
  30. if (typeof f === 'string') return f;
  31. out.push(i === 4 ? [...new Set(f.map((d) => d % 7))] : f);
  32. }
  33. return out;
  34. }
  35. /** `15m`, `6h`, `1d` → milliseconds, or null. */
  36. export function parseEvery(v: string): number | null {
  37. const m = /^(\d+)\s*(m|min|h|d)$/.exec(v.trim());
  38. if (!m || Number(m[1]) < 1) return null;
  39. return Number(m[1]) * { m: 60_000, min: 60_000, h: 3_600_000, d: 86_400_000 }[m[2] as 'm']!;
  40. }
  41. /** The schedule of an automation's trigger, or an error text; null when the trigger is not a schedule. */
  42. export function schedOf(trigger: unknown): Sched | string | null {
  43. const t = map(trigger);
  44. if (!t || !KINDS.includes(text(t.kind))) return null;
  45. const tz = text(t.tz);
  46. if (tz) {
  47. try {
  48. new Intl.DateTimeFormat('en', { timeZone: tz });
  49. } catch {
  50. return `the time zone "${tz}" is unknown`;
  51. }
  52. }
  53. if (text(t.cron)) {
  54. const c = parseCron(text(t.cron));
  55. return typeof c === 'string' ? c : { cron: c, tz, source: `cron ${text(t.cron)}` };
  56. }
  57. if (text(t.at)) {
  58. const m = /^(\d{1,2}):(\d{2})$/.exec(text(t.at));
  59. if (!m || Number(m[1]) > 23 || Number(m[2]) > 59) return `at: "${text(t.at)}" is not a time HH:MM`;
  60. return { cron: [[Number(m[2])], [Number(m[1])], field('*', RANGES[2]) as number[], field('*', RANGES[3]) as number[], [0, 1, 2, 3, 4, 5, 6]], tz, source: `every day at ${text(t.at)}` };
  61. }
  62. if (text(t.every)) {
  63. const ms = parseEvery(text(t.every));
  64. return ms === null ? `every: "${text(t.every)}" is not a span (15m, 6h, 1d)` : { every: ms, source: `every ${text(t.every)}` };
  65. }
  66. return 'a schedule without cron, every or at';
  67. }
  68. /** Minute, hour, day of month, month, day of week of an instant, in a time zone ('' = the machine's). */
  69. function partsAt(ms: number, tz: string): number[] {
  70. const d = new Date(ms);
  71. if (!tz) return [d.getMinutes(), d.getHours(), d.getDate(), d.getMonth() + 1, d.getDay()];
  72. const f = Object.fromEntries(new Intl.DateTimeFormat('en-US', {
  73. timeZone: tz, hourCycle: 'h23', minute: 'numeric', hour: 'numeric', day: 'numeric', month: 'numeric', weekday: 'short',
  74. }).formatToParts(d).map((p) => [p.type, p.value]));
  75. return [Number(f.minute), Number(f.hour), Number(f.day), Number(f.month), ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(f.weekday)];
  76. }
  77. /** Does a cron schedule fire at this minute. Day of month and day of week: either matches when both are limited. */
  78. function fires(c: number[][], p: number[]): boolean {
  79. if (!c[0].includes(p[0]) || !c[1].includes(p[1]) || !c[3].includes(p[3])) return false;
  80. const domAll = c[2].length === 31, dowAll = c[4].length === 7;
  81. if (domAll || dowAll) return c[2].includes(p[2]) && c[4].includes(p[4]);
  82. return c[2].includes(p[2]) || c[4].includes(p[4]);
  83. }
  84. /** The last firing at or before `nowMs` (searched up to 400 days back), or null. */
  85. export function prevFire(s: { cron: number[][]; tz: string }, nowMs: number): number | null {
  86. let t = Math.floor(nowMs / 60_000) * 60_000;
  87. for (let i = 0; i < 400 * 1440; i++, t -= 60_000) if (fires(s.cron, partsAt(t, s.tz))) return t;
  88. return null;
  89. }
  90. /** The next firing after `nowMs` (up to 400 days ahead), or null. */
  91. export function nextFire(s: { cron: number[][]; tz: string }, nowMs: number): number | null {
  92. let t = Math.floor(nowMs / 60_000) * 60_000 + 60_000;
  93. for (let i = 0; i < 400 * 1440; i++, t += 60_000) if (fires(s.cron, partsAt(t, s.tz))) return t;
  94. return null;
  95. }
  96. /** The runs of an automation and the instant each one served: its `slot`, else its `started`. */
  97. export function runsOf(p: Project, auto: Rec): { rec: Rec; at: number }[] {
  98. return recordsOf(p, 'RUN')
  99. .filter((r) => normPath(r.fm.automation, null, r.id) === auto.id)
  100. .map((r) => ({ rec: r, at: time(r.fm.slot) ?? time(r.fm.started) }))
  101. .filter((x): x is { rec: Rec; at: number } => x.at !== null);
  102. }
  103. export const iso = (ms: number) => new Date(ms).toISOString().replace(/\.\d+Z$/, 'Z');
  104. /** Is the automation due at `nowMs`, and which slot the run serves. */
  105. export function due(s: Sched, runs: { at: number }[], nowMs: number): { due: boolean; slot: number; why: string } {
  106. const last = runs.length ? Math.max(...runs.map((r) => r.at)) : null;
  107. if ('every' in s) {
  108. if (last === null || nowMs - last >= s.every) return { due: true, slot: nowMs, why: last === null ? 'has not run yet' : `${Math.round((nowMs - last) / 60_000)} min have passed` };
  109. return { due: false, slot: nowMs, why: `not yet: last ${iso(last)}, next ${iso(last + s.every)}` };
  110. }
  111. const slot = prevFire(s, nowMs);
  112. if (slot === null) return { due: false, slot: nowMs, why: 'the schedule has not fired in the last 400 days' };
  113. if (last === null || last < slot) return { due: true, slot, why: `due ${iso(slot)}` };
  114. const next = nextFire(s, nowMs);
  115. return { due: false, slot, why: `not yet: last ${iso(last)}, next ${next === null ? '—' : iso(next)}` };
  116. }