Files
khb_microservices/packages/scheduler/src/due-calculator.ts

82 lines
3.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { addDays, dayName, isWorkday, localDate, zonedToUtc } from "khb_common";
export type DaysSpec = "daily" | "workdays" | string[];
export interface JobSchedule {
name: string;
at?: string; // HH:MM по часовому поясу tz (ежедневный режим)
days: DaysSpec;
/** Интервальный режим: каждые N минут от полуночи по tz, в окне from-to (HH:MM, включительно). */
everyMinutes?: number;
from?: string;
to?: string;
}
const minutesOf = (hhmm: string): number => Number(hhmm.slice(0, 2)) * 60 + Number(hhmm.slice(3, 5));
/** Последняя сетка «каждые N минут» не позже now с учётом дней и окна. */
function lastDueInterval(job: JobSchedule, now: Date, tz: string, nonWorkdays: ReadonlySet<string>, lookbackDays: number): Date | null {
const step = job.everyMinutes! * 60_000;
const from = job.from ? minutesOf(job.from) : 0;
const to = job.to ? minutesOf(job.to) : 24 * 60;
let cursor = now.getTime();
const limit = now.getTime() - lookbackDays * 86_400_000;
while (cursor >= limit) {
const date = localDate(new Date(cursor), tz);
const dayStart = zonedToUtc(date, "00:00", tz).getTime();
const k = Math.floor((cursor - dayStart) / step);
const due = dayStart + k * step;
const minuteOfDay = Math.round((due - dayStart) / 60_000);
if (dayMatches(date, job.days, nonWorkdays) && minuteOfDay >= from && minuteOfDay <= to) return new Date(due);
// не подходит: идём к предыдущему узлу сетки (или к концу окна предыдущего дня)
cursor = due - 1;
if (minuteOfDay > to) cursor = dayStart + to * 60_000; // после окна - конец окна этого дня
else if (minuteOfDay < from || !dayMatches(date, job.days, nonWorkdays)) cursor = dayStart - 1; // раньше окна или не тот день - вчера
}
return null;
}
function dayMatches(date: string, days: DaysSpec, nonWorkdays: ReadonlySet<string>): boolean {
if (days === "daily") return true;
if (days === "workdays") return isWorkday(date, nonWorkdays);
return days.includes(dayName(date));
}
/**
* Последнее плановое время срабатывания задания, не позже now (ищем в пределах lookbackDays дней).
* Время возвращается округлённым до минуты (как задано в at).
*/
export function lastDue(
job: JobSchedule,
now: Date,
tz: string,
nonWorkdays: ReadonlySet<string>,
lookbackDays = 8,
): Date | null {
if (job.everyMinutes) return lastDueInterval(job, now, tz, nonWorkdays, lookbackDays);
if (!job.at) return null;
let date = localDate(now, tz);
for (let i = 0; i <= lookbackDays; i++) {
if (dayMatches(date, job.days, nonWorkdays)) {
const t = zonedToUtc(date, job.at, tz);
if (t.getTime() <= now.getTime()) return t;
}
date = addDays(date, -1);
}
return null;
}
export type TickAction = "none" | "start" | "missed";
/**
* Решение для задания на текущем тике:
* - нет планового времени или запись (job, scheduled_minute) уже есть -> none;
* - опоздание не больше graceSeconds -> start;
* - иначе -> missed (не запускаем, только фиксируем момент обнаружения пропуска).
*/
export function decide(due: Date | null, alreadyRecorded: boolean, now: Date, graceSeconds: number): TickAction {
if (!due || alreadyRecorded) return "none";
const lateSec = (now.getTime() - due.getTime()) / 1000;
return lateSec <= graceSeconds ? "start" : "missed";
}