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
6function 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 === "webhook") return null;
17 if (schedule.type === "interval") {
18 // Intervals advance elapsed time, including across daylight-saving changes.
19 return DateTime.addDuration(from, Math.max(schedule.everyMs, MIN_SCHEDULED_TASK_INTERVAL_MS));
20 }
21
22 const time = parseTimeOfDay(schedule.timeOfDay);
23 if (time === null) return null;
24 const weekdays =
25 schedule.weekdays && schedule.weekdays.length > 0 ? new Set(schedule.weekdays) : null;
26 for (let offset = 0; offset <= 7; offset += 1) {
27 const candidate = DateTime.setParts(DateTime.add(from, { days: offset }), {
28 hour: time.hour,
29 minute: time.minute,
30 second: 0,
31 millisecond: 0,
32 });
33 if (DateTime.toEpochMillis(candidate) <= DateTime.toEpochMillis(from)) continue;
34 if (weekdays !== null && !weekdays.has(DateTime.toParts(candidate).weekDay)) continue;
35 return candidate;
36 }
37 return null;
38}
39
40function weekdayKey(weekdays: ReadonlyArray<number> | undefined): string {
41 const unique = [...new Set(weekdays ?? [])].toSorted((x, y) => x - y);
42 if (unique.length === 0 || unique.length === 7) return "daily";
43 return unique.join(",");
44}
45
46export function isSameSchedule(a: ScheduledTaskSchedule, b: ScheduledTaskSchedule): boolean {
47 if (a.type === "interval") {
48 return b.type === "interval" && a.everyMs === b.everyMs;
49 }
50 if (a.type === "webhook") return b.type === "webhook";
51 if (b.type !== "fixed_time") return false;
52 // Compare parsed times so padded-hour edits do not reschedule pending runs.
53 const aTime = parseTimeOfDay(a.timeOfDay);
54 const bTime = parseTimeOfDay(b.timeOfDay);
55 return (
56 aTime !== null &&
57 bTime !== null &&
58 aTime.hour === bTime.hour &&
59 aTime.minute === bTime.minute &&
60 weekdayKey(a.weekdays) === weekdayKey(b.weekdays)
61 );
62}
63
64const MISSED_FIXED_TIME_GRACE_MS = 10 * MINUTE_MS;
65
66export function isMissedFixedTimeRun(
67 schedule: ScheduledTaskSchedule,
68 dueAt: DateTime.DateTime,
69 now: DateTime.DateTime,
70): boolean {
71 if (schedule.type !== "fixed_time") return false;
72 return DateTime.toEpochMillis(now) - DateTime.toEpochMillis(dueAt) > MISSED_FIXED_TIME_GRACE_MS;
73}