Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Schedule.ts

104 lines3.8 KB

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]) };
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;
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(",");
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 return (
59 b.type === "fixed_time" &&
60 a.timeOfDay === b.timeOfDay &&
61 weekdayKey(a.weekdays) === weekdayKey(b.weekdays)
62 );
64​
65/**
66 * How late a fixed-time run may fire before it counts as missed. Covers poll
67 * jitter and short sleeps, while a server booted hours after the slot skips
68 * to the next occurrence instead of firing stale work at a random time.
69 */
70const MISSED_FIXED_TIME_GRACE_MS = 10 * MINUTE_MS;
71​
72/**
73 * True when a due fixed-time run was missed by more than the grace window and
74 * should be rescheduled to its next occurrence instead of firing now.
75 * Interval schedules are never considered missed: an overdue interval task
76 * catching up with a single run is the desired behaviour.
77 */
78export function isMissedFixedTimeRun(
79 schedule: ScheduledTaskSchedule,
80 dueAt: DateTime.DateTime,
81 now: DateTime.DateTime,
82): boolean {
83 if (schedule.type !== "fixed_time") return false;
84 return DateTime.toEpochMillis(now) - DateTime.toEpochMillis(dueAt) > MISSED_FIXED_TIME_GRACE_MS;
86​
87function describeSchedule(schedule: ScheduledTaskSchedule): string {
88 if (schedule.type === "interval") {
89 const minutes = schedule.everyMs / MINUTE_MS;
90 if (Number.isInteger(minutes)) {
91 return `Every ${minutes === 1 ? "minute" : `${minutes} minutes`}`;
92 }
93 return `Every ${Math.round(schedule.everyMs / 1000)} seconds`;
94 }
95​
96 const weekdayCount = schedule.weekdays?.length ?? 0;
97 const days =
98 weekdayCount === 0
99 ? "day"
100 : weekdayCount === 5 && schedule.weekdays?.every((day) => day >= 1 && day <= 5)
101 ? "weekday"
102 : "selected day";
103 return `At ${schedule.timeOfDay} every ${days}`;