Open History to see the last commit
1import 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 return DateTime.add(from, { milliseconds: schedule.everyMs });
18 }
19
20 const time = parseTimeOfDay(schedule.timeOfDay);
21 if (time === null) return null;
22 const weekdays =
23 schedule.weekdays && schedule.weekdays.length > 0 ? new Set(schedule.weekdays) : null;
24 for (let offset = 0; offset <= 7; offset += 1) {
25 const candidate = DateTime.setParts(DateTime.add(from, { days: offset }), {
26 hour: time.hour,
27 minute: time.minute,
28 second: 0,
29 millisecond: 0,
30 });
31 if (DateTime.toEpochMillis(candidate) <= DateTime.toEpochMillis(from)) continue;
32 if (weekdays !== null && !weekdays.has(DateTime.toParts(candidate).weekDay)) continue;
33 return candidate;
34 }
35 return null;
36}
37
38/**
39 * Canonical form of a weekday mask, mirroring how `nextScheduledRunAt` reads
40 * it: order and duplicates are irrelevant, and an empty/omitted mask means the
41 * same as explicitly listing all seven days — daily.
42 */
43function weekdayKey(weekdays: ReadonlyArray<number> | undefined): string {
44 const unique = [...new Set(weekdays ?? [])].toSorted((x, y) => x - y);
45 if (unique.length === 0 || unique.length === 7) return "daily";
46 return unique.join(",");
47}
48
49/** Semantic equality for schedules: true iff both fire at the same times. */
50export function isSameSchedule(a: ScheduledTaskSchedule, b: ScheduledTaskSchedule): boolean {
51 if (a.type === "interval") {
52 return b.type === "interval" && a.everyMs === b.everyMs;
53 }
54 return (
55 b.type === "fixed_time" &&
56 a.timeOfDay === b.timeOfDay &&
57 weekdayKey(a.weekdays) === weekdayKey(b.weekdays)
58 );
59}
60
61/**
62 * How late a fixed-time run may fire before it counts as missed. Covers poll
63 * jitter and short sleeps, while a server booted hours after the slot skips
64 * to the next occurrence instead of firing stale work at a random time.
65 */
66export const MISSED_FIXED_TIME_GRACE_MS = 10 * MINUTE_MS;
67
68/**
69 * True when a due fixed-time run was missed by more than the grace window and
70 * should be rescheduled to its next occurrence instead of firing now.
71 * Interval schedules are never considered missed: an overdue interval task
72 * catching up with a single run is the desired behaviour.
73 */
74export function isMissedFixedTimeRun(
75 schedule: ScheduledTaskSchedule,
76 dueAt: DateTime.DateTime,
77 now: DateTime.DateTime,
78): boolean {
79 if (schedule.type !== "fixed_time") return false;
80 return DateTime.toEpochMillis(now) - DateTime.toEpochMillis(dueAt) > MISSED_FIXED_TIME_GRACE_MS;
81}
82
83export function describeSchedule(schedule: ScheduledTaskSchedule): string {
84 if (schedule.type === "interval") {
85 const minutes = schedule.everyMs / MINUTE_MS;
86 if (Number.isInteger(minutes)) {
87 return `Every ${minutes === 1 ? "minute" : `${minutes} minutes`}`;
88 }
89 return `Every ${Math.round(schedule.everyMs / 1000)} seconds`;
90 }
91
92 const weekdayCount = schedule.weekdays?.length ?? 0;
93 const days =
94 weekdayCount === 0
95 ? "day"
96 : weekdayCount === 5 && schedule.weekdays?.every((day) => day >= 1 && day <= 5)
97 ? "weekday"
98 : "selected day";
99 return `At ${schedule.timeOfDay} every ${days}`;
100}