Files
khb_microservices/packages/scheduler/src/main.ts
Yuri Yaryshev ebb1cb7950
Some checks failed
ci / test (push) Failing after 20s
ci / deploy (push) Has been skipped
Каркас monorepo: scheduler, data_collector, khbuild_assistant_prep, khb_common; миграции; CI/CD
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-11 09:44:55 +03:00

60 lines
2.7 KiB
TypeScript

import { createLogger, createPool, loadServiceSettings } from "khb_common";
import { buildApi } from "./http-api.js";
import { makeHttpDispatch } from "./http-dispatch.js";
import { schedulerSchema } from "./settings.js";
import { tick } from "./tick.js";
const { common, service } = loadServiceSettings("scheduler", schedulerSchema);
const log = createLogger("scheduler", common.logLevel);
const pool = createPool(common.database.url);
const dispatch = makeHttpDispatch(service.services);
// Нерабочие дни из native-таблицы calendar_day, кэш на 5 минут
let cache: { at: number; set: Set<string> } | null = null;
async function nonWorkdays(): Promise<ReadonlySet<string>> {
if (cache && Date.now() - cache.at < 300_000) return cache.set;
const { rows } = await pool.query("select to_char(day, 'YYYY-MM-DD') as d from calendar_day where not is_workday");
cache = { at: Date.now(), set: new Set(rows.map((r) => r.d as string)) };
return cache.set;
}
const deps = { pool, jobs: service.jobs, tz: common.timezone, graceSeconds: service.missedGraceSeconds, nonWorkdays, dispatch, log };
let busy = false;
const timer = setInterval(async () => {
if (busy) return;
busy = true;
try {
await tick(deps); // вызовы сервисов идут в фоне
} catch (e) {
log.error({ err: e instanceof Error ? e.message : String(e) }, "ошибка тика");
} finally {
busy = false;
}
}, service.tickSeconds * 1000);
const app = buildApi({
pool,
token: service.http.token,
jobs: service.jobs,
tz: common.timezone,
nonWorkdays,
manualRun: async (job) => {
const minute = new Date(Math.floor(Date.now() / 60000) * 60000);
const { rows } = await pool.query(
"insert into sched_run (job_name, scheduled_minute, status, message) values ($1,$2,'started','ручной запуск') on conflict (job_name, scheduled_minute) do nothing returning id",
[job.name, minute],
);
const id = rows[0]?.id as string | undefined;
if (!id) return null;
void dispatch(job).then(
(r) => pool.query("update sched_run set status = $2, finished_at = now(), http_status = $3, response_ref = $4, message = $5 where id = $1", [id, r.httpStatus >= 200 && r.httpStatus < 300 ? "ok" : "error", r.httpStatus, r.responseRef ?? null, r.message ?? "ручной запуск"]),
(e) => pool.query("update sched_run set status = 'error', finished_at = now(), message = $2 where id = $1", [id, String(e)]),
);
return id;
},
});
await app.listen({ host: service.http.host, port: service.http.port });
log.info({ tickSeconds: service.tickSeconds, jobs: service.jobs.length }, "scheduler запущен");
process.on("SIGTERM", () => { clearInterval(timer); void app.close(); });