Open History to see the last commit
1import { MIN_SCHEDULED_TASK_INTERVAL_MS, type ScheduledTaskSchedule } from "@t3tools/contracts";
2import * as DateTime from "effect/DateTime";
3
4const MINUTE_MS = 60_000;
5
6export function parseTimeOfDay(value: string): { hour: number; minute: number } | null {
7 const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(value.trim());
8 if (!match) return null;
9 return { hour: Number(match[1]), minute: Number(match[2]) };
10}
11
12export function nextScheduledRunAt(
13 schedule: ScheduledTaskSchedule,
14 from: DateTime.DateTime,
15): DateTime.DateTime | null {
16 if (schedule.type === "interval") {
17 // Persisted rows created before the one-minute floor remain readable, but
18 // they must not retain their old high-frequency execution rate.
19 return DateTime.add(from, {
20 milliseconds: Math.max(schedule.everyMs, MIN_SCHEDULED_TASK_INTERVAL_MS),
21 });
22 }
23
24 const time = parseTimeOfDay(schedule.timeOfDay);
25 if (time === null) return null;
26 const weekdays =
27 schedule.weekdays && schedule.weekdays.length > 0 ? new Set(schedule.weekdays) : null;
28 for (let offset = 0; offset <= 7; offset += 1) {
29 const candidate = DateTime.setParts(DateTime.add(from, { days: offset }), {
30 hour: time.hour,
31 minute: time.minute,
32 second: 0,
33 millisecond: 0,
34 });
35 if (DateTime.toEpochMillis(candidate) <= DateTime.toEpochMillis(from)) continue;
36 if (weekdays !== null && !weekdays.has(DateTime.toParts(candidate).weekDay)) continue;
37 return candidate;
38 }
39 return null;
40}
41
42/**
43 * Canonical form of a weekday mask, mirroring how `nextScheduledRunAt` reads
44 * it: order and duplicates are irrelevant, and an empty/omitted mask means the
45 * same as explicitly listing all seven days — daily.
46 */
47function weekdayKey(weekdays: ReadonlyArray<number> | undefined): string {
48 const unique = [...new Set(weekdays ?? [])].toSorted((x, y) => x - y);
49 if (unique.length === 0 || unique.length === 7) return "daily";
50 return unique.join(",");
51}
52
53/** Semantic equality for schedules: true iff both fire at the same times. */
54export function isSameSchedule(a: ScheduledTaskSchedule, b: ScheduledTaskSchedule): boolean {
55 if (a.type === "interval") {
56 return b.type === "interval" && a.everyMs === b.everyMs;
57 }
58 if (b.type !== "fixed_time") return false;
59 // The contract accepts padded and unpadded hours ("9:00" and "09:00"), so
60 // compare the parsed time — string equality would treat a format-only edit
61 // as a schedule change and recompute the pending run.
62 const aTime = parseTimeOfDay(a.timeOfDay);
63 const bTime = parseTimeOfDay(b.timeOfDay);
64 return (
65 aTime !== null &&
66 bTime !== null &&
67 aTime.hour === bTime.hour &&
68 aTime.minute === bTime.minute &&
69 weekdayKey(a.weekdays) === weekdayKey(b.weekdays)
70 );
71}
72
73/**
74 * How late a fixed-time run may fire before it counts as missed. Covers poll
75 * jitter and short sleeps, while a server booted hours after the slot skips
76 * to the next occurrence instead of firing stale work at a random time.
77 */
78const MISSED_FIXED_TIME_GRACE_MS = 10 * MINUTE_MS;
79
80/**
81 * True when a due fixed-time run was missed by more than the grace window and
82 * should be rescheduled to its next occurrence instead of firing now.
83 * Interval schedules are never considered missed: an overdue interval task
84 * catching up with a single run is the desired behaviour.
85 */
86export function isMissedFixedTimeRun(
87 schedule: ScheduledTaskSchedule,
88 dueAt: DateTime.DateTime,
89 now: DateTime.DateTime,
90): boolean {
91 if (schedule.type !== "fixed_time") return false;
92 return DateTime.toEpochMillis(now) - DateTime.toEpochMillis(dueAt) > MISSED_FIXED_TIME_GRACE_MS;
93}
94
95function describeSchedule(schedule: ScheduledTaskSchedule): string {
96 if (schedule.type === "interval") {
97 const minutes = schedule.everyMs / MINUTE_MS;
98 if (Number.isInteger(minutes)) {
99 return `Every ${minutes === 1 ? "minute" : `${minutes} minutes`}`;
100 }
101 return `Every ${Math.round(schedule.everyMs / 1000)} seconds`;
102 }
103
104 const weekdayCount = schedule.weekdays?.length ?? 0;
105 const days =
106 weekdayCount === 0
107 ? "day"
108 : weekdayCount === 5 && schedule.weekdays?.every((day) => day >= 1 && day <= 5)
109 ? "weekday"
110 : "selected day";
111 return `At ${schedule.timeOfDay} every ${days}`;
112}