файл пакета→ .shtukbase/packages/schedule/lib/schedule.ts
lib/schedule.ts
130 строк, 6.6 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // The schedule of automations: a trigger `{kind: schedule, cron: "0 7 * * *"}`, `{kind: schedule, every: 6h}` or
- // `{kind: clock, at: "07:00"}` → when the automation is due, judged by the run journal. Pure functions plus the
- // readers of automations and runs. Cron is the classic five fields, read in the machine's time zone or in
- // `trigger.tz` (an IANA name such as UTC).
- import { type Project, type Rec, map, normPath, recordsOf, text, time } from '../../agents/lib/factlib.ts';
- export const KINDS = ['schedule', 'clock'];
- export type Sched = { cron: number[][]; tz: string; source: string } | { every: number; source: string };
- const RANGES: [number, number][] = [[0, 59], [0, 23], [1, 31], [1, 12], [0, 7]];
- /** One cron field → the sorted values it allows, or an error text. */
- function field(s: string, [lo, hi]: [number, number]): number[] | string {
- const out = new Set<number>();
- for (const part of s.split(',')) {
- const m = /^(\*|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(part);
- if (!m) return `"${part}" is not a cron field`;
- const step = m[4] ? Number(m[4]) : 1;
- const a = m[1] === '*' ? lo : Number(m[2]);
- const b = m[1] === '*' ? hi : m[3] ? Number(m[3]) : m[4] ? hi : a;
- if (step < 1 || a < lo || b > hi || a > b) return `"${part}" is outside ${lo}–${hi}`;
- for (let v = a; v <= b; v += step) out.add(v);
- }
- return [...out].sort((x, y) => x - y);
- }
- /** A cron line of five fields → the allowed values per field, or an error text. Sunday is 0 or 7. */
- export function parseCron(line: string): number[][] | string {
- const parts = line.trim().split(/\s+/);
- if (parts.length !== 5) return `the cron line has ${parts.length} fields, but 5 are needed (minute hour day month weekday)`;
- const out: number[][] = [];
- for (let i = 0; i < 5; i++) {
- const f = field(parts[i], RANGES[i]);
- if (typeof f === 'string') return f;
- out.push(i === 4 ? [...new Set(f.map((d) => d % 7))] : f);
- }
- return out;
- }
- /** `15m`, `6h`, `1d` → milliseconds, or null. */
- export function parseEvery(v: string): number | null {
- const m = /^(\d+)\s*(m|min|h|d)$/.exec(v.trim());
- if (!m || Number(m[1]) < 1) return null;
- return Number(m[1]) * { m: 60_000, min: 60_000, h: 3_600_000, d: 86_400_000 }[m[2] as 'm']!;
- }
- /** The schedule of an automation's trigger, or an error text; null when the trigger is not a schedule. */
- export function schedOf(trigger: unknown): Sched | string | null {
- const t = map(trigger);
- if (!t || !KINDS.includes(text(t.kind))) return null;
- const tz = text(t.tz);
- if (tz) {
- try {
- new Intl.DateTimeFormat('en', { timeZone: tz });
- } catch {
- return `the time zone "${tz}" is unknown`;
- }
- }
- if (text(t.cron)) {
- const c = parseCron(text(t.cron));
- return typeof c === 'string' ? c : { cron: c, tz, source: `cron ${text(t.cron)}` };
- }
- if (text(t.at)) {
- const m = /^(\d{1,2}):(\d{2})$/.exec(text(t.at));
- if (!m || Number(m[1]) > 23 || Number(m[2]) > 59) return `at: "${text(t.at)}" is not a time HH:MM`;
- 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)}` };
- }
- if (text(t.every)) {
- const ms = parseEvery(text(t.every));
- return ms === null ? `every: "${text(t.every)}" is not a span (15m, 6h, 1d)` : { every: ms, source: `every ${text(t.every)}` };
- }
- return 'a schedule without cron, every or at';
- }
- /** Minute, hour, day of month, month, day of week of an instant, in a time zone ('' = the machine's). */
- function partsAt(ms: number, tz: string): number[] {
- const d = new Date(ms);
- if (!tz) return [d.getMinutes(), d.getHours(), d.getDate(), d.getMonth() + 1, d.getDay()];
- const f = Object.fromEntries(new Intl.DateTimeFormat('en-US', {
- timeZone: tz, hourCycle: 'h23', minute: 'numeric', hour: 'numeric', day: 'numeric', month: 'numeric', weekday: 'short',
- }).formatToParts(d).map((p) => [p.type, p.value]));
- return [Number(f.minute), Number(f.hour), Number(f.day), Number(f.month), ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(f.weekday)];
- }
- /** Does a cron schedule fire at this minute. Day of month and day of week: either matches when both are limited. */
- function fires(c: number[][], p: number[]): boolean {
- if (!c[0].includes(p[0]) || !c[1].includes(p[1]) || !c[3].includes(p[3])) return false;
- const domAll = c[2].length === 31, dowAll = c[4].length === 7;
- if (domAll || dowAll) return c[2].includes(p[2]) && c[4].includes(p[4]);
- return c[2].includes(p[2]) || c[4].includes(p[4]);
- }
- /** The last firing at or before `nowMs` (searched up to 400 days back), or null. */
- export function prevFire(s: { cron: number[][]; tz: string }, nowMs: number): number | null {
- let t = Math.floor(nowMs / 60_000) * 60_000;
- for (let i = 0; i < 400 * 1440; i++, t -= 60_000) if (fires(s.cron, partsAt(t, s.tz))) return t;
- return null;
- }
- /** The next firing after `nowMs` (up to 400 days ahead), or null. */
- export function nextFire(s: { cron: number[][]; tz: string }, nowMs: number): number | null {
- let t = Math.floor(nowMs / 60_000) * 60_000 + 60_000;
- for (let i = 0; i < 400 * 1440; i++, t += 60_000) if (fires(s.cron, partsAt(t, s.tz))) return t;
- return null;
- }
- /** The runs of an automation and the instant each one served: its `slot`, else its `started`. */
- export function runsOf(p: Project, auto: Rec): { rec: Rec; at: number }[] {
- return recordsOf(p, 'RUN')
- .filter((r) => normPath(r.fm.automation, null, r.id) === auto.id)
- .map((r) => ({ rec: r, at: time(r.fm.slot) ?? time(r.fm.started) }))
- .filter((x): x is { rec: Rec; at: number } => x.at !== null);
- }
- export const iso = (ms: number) => new Date(ms).toISOString().replace(/\.\d+Z$/, 'Z');
- /** Is the automation due at `nowMs`, and which slot the run serves. */
- export function due(s: Sched, runs: { at: number }[], nowMs: number): { due: boolean; slot: number; why: string } {
- const last = runs.length ? Math.max(...runs.map((r) => r.at)) : null;
- if ('every' in s) {
- 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` };
- return { due: false, slot: nowMs, why: `not yet: last ${iso(last)}, next ${iso(last + s.every)}` };
- }
- const slot = prevFire(s, nowMs);
- if (slot === null) return { due: false, slot: nowMs, why: 'the schedule has not fired in the last 400 days' };
- if (last === null || last < slot) return { due: true, slot, why: `due ${iso(slot)}` };
- const next = nextFire(s, nowMs);
- return { due: false, slot, why: `not yet: last ${iso(last)}, next ${next === null ? '—' : iso(next)}` };
- }