Каркас monorepo: scheduler, data_collector, khbuild_assistant_prep, khb_common; миграции; CI/CD
Some checks failed
ci / test (push) Failing after 20s
ci / deploy (push) Has been skipped

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-11 09:44:50 +03:00
commit ebb1cb7950
101 changed files with 4971 additions and 0 deletions

View File

@@ -0,0 +1,11 @@
# API scheduler
HTTP на 127.0.0.1 (наружу - через Nginx), Bearer-токен из `settings.json5` (`scheduler.http.token`).
| Метод | Путь | Описание |
|---|---|---|
| GET | `/healthz` | `{ "ok": true, "db": true, "time": "<iso>" }` без авторизации |
| GET | `/status` | задания, их ближайшее плановое время и последняя запись `sched_run` |
| POST | `/jobs/:name/run` | ручной запуск задания вне расписания (запись в `sched_run` с `scheduled_minute = now` по минутам) |
Исходящие вызовы: HTTP на сервисы из `scheduler.services` (`baseUrl`, `token`), метод и путь - из описания задания.

View File

@@ -0,0 +1,16 @@
# Объекты микросервиса scheduler
Статус: **СОГЛАСОВАНО пользователем 2026-10-11**. Общие объекты - `/docs/data_objects/index.md`.
## Таблицы (схема `public`)
- [sched_run](sched_run.md) - журнал срабатываний заданий (запуск / пропуск / ошибка).
## API
- [api_objects](api_objects.md)
## Алгоритм тика (раз в `scheduler.tickSeconds`, по умолчанию 10 с)
1. Для каждого задания из `scheduler.jobs` вычислить последнее плановое время `scheduled_minute <= now` (по `at`, `days`, часовому поясу; для `workdays` - по `calendar_day`).
2. Если записи `(job_name, scheduled_minute)` ещё нет:
- `now - scheduled_minute <= missedGraceSeconds` -> вставить запись `started` и вызвать сервис (HTTP);
- иначе -> вставить запись `missed` (задание НЕ запускается, только лог момента, когда пропуск замечен).
3. Повторный старт в ту же минуту исключён уникальным ключом `(job_name, scheduled_minute)`.

View File

@@ -0,0 +1,17 @@
# sched_run
Журнал срабатываний заданий планировщика (запуск, пропуск, ошибка). Единственный источник правды о том, что и когда стартовало.
| Колонка | Тип | Null | Описание |
|---|---|---|---|
| id | uuid PK | нет | ID записи |
| job_name | text | нет | имя задания из `settings.json5` (`scheduler.jobs[].name`) |
| scheduled_minute | timestamptz | нет | плановая минута срабатывания (округлена до минуты, по расписанию) |
| status | text | нет | `started`, `ok`, `error`, `missed` |
| noticed_at | timestamptz | нет | когда планировщик заметил срабатывание (для `missed` - когда заметил пропуск) |
| finished_at | timestamptz | да | завершение вызова |
| http_status | int | да | код ответа вызванного сервиса |
| response_ref | text | да | ID запуска в вызванном сервисе (например `cr_run.id`) |
| message | text | да | ошибка или описание пропуска |
Уникальность: `(job_name, scheduled_minute)` - защита от повторного старта в ту же минуту (в том числе при нескольких экземплярах).

View File

@@ -0,0 +1,18 @@
{
"name": "scheduler",
"version": "0.1.0",
"private": true,
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc -p tsconfig.json",
"typecheck": "tsc -p tsconfig.json --noEmit",
"start": "node dist/main.js"
},
"dependencies": {
"fastify": "^5.2.0",
"khb_common": "workspace:*",
"zod": "3.24.1"
}
}

View File

@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import { decide, lastDue } from "./due-calculator.js";
const TZ = "America/New_York";
const none = new Set<string>();
describe("lastDue", () => {
it("06:00 Tampa (EDT = UTC-4) в тот же день после срабатывания", () => {
const due = lastDue({ name: "j", at: "06:00", days: "daily" }, new Date("2026-10-11T12:00:30Z"), TZ, none);
expect(due?.toISOString()).toBe("2026-10-11T10:00:00.000Z");
});
it("до времени срабатывания берётся вчерашнее", () => {
const due = lastDue({ name: "j", at: "06:00", days: "daily" }, new Date("2026-10-11T09:00:00Z"), TZ, none);
expect(due?.toISOString()).toBe("2026-10-10T10:00:00.000Z");
});
it("после перехода на зимнее время (EST = UTC-5)", () => {
const due = lastDue({ name: "j", at: "06:00", days: "daily" }, new Date("2026-11-10T12:00:00Z"), TZ, none);
expect(due?.toISOString()).toBe("2026-11-10T11:00:00.000Z");
});
it("workdays пропускает выходные: в субботу последнее - пятничное", () => {
const due = lastDue({ name: "j", at: "06:00", days: "workdays" }, new Date("2026-10-10T15:00:00Z"), TZ, none);
expect(due?.toISOString()).toBe("2026-10-09T10:00:00.000Z");
});
it("workdays учитывает праздники из календаря", () => {
const due = lastDue({ name: "j", at: "06:00", days: "workdays" }, new Date("2026-11-26T15:00:00Z"), TZ, new Set(["2026-11-26"]));
expect(due?.toISOString()).toBe("2026-11-25T11:00:00.000Z");
});
it("список дней недели", () => {
const due = lastDue({ name: "j", at: "10:00", days: ["mon", "fri"] }, new Date("2026-10-14T15:00:00Z"), TZ, none); // среда
expect(due?.toISOString()).toBe("2026-10-12T14:00:00.000Z"); // понедельник
});
});
describe("decide", () => {
const due = new Date("2026-10-11T10:00:00Z");
it("в пределах допуска - start", () => {
expect(decide(due, false, new Date("2026-10-11T10:00:10Z"), 60)).toBe("start");
});
it("повторный тик в ту же минуту - none (уже записано)", () => {
expect(decide(due, true, new Date("2026-10-11T10:00:20Z"), 60)).toBe("none");
});
it("позже допуска - missed (не запускаем)", () => {
expect(decide(due, false, new Date("2026-10-11T10:05:00Z"), 60)).toBe("missed");
});
it("нет планового времени - none", () => {
expect(decide(null, false, new Date(), 60)).toBe("none");
});
});

View File

@@ -0,0 +1,51 @@
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;
}
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 {
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";
}

View File

@@ -0,0 +1,54 @@
import Fastify, { type FastifyInstance } from "fastify";
import type { Pool } from "khb_common";
import { lastDue } from "./due-calculator.js";
import type { JobSettings } from "./settings.js";
export interface SchedulerApiDeps {
pool: Pool;
token: string;
jobs: JobSettings[];
tz: string;
nonWorkdays: () => Promise<ReadonlySet<string>>;
/** Ручной запуск: фиксирует запись и вызывает сервис; возвращает id записи sched_run или null (уже было в эту минуту). */
manualRun: (job: JobSettings) => Promise<string | null>;
}
export function buildApi(deps: SchedulerApiDeps): FastifyInstance {
const app = Fastify();
app.addHook("onRequest", async (req, reply) => {
if (req.url === "/healthz") return;
if (req.headers.authorization !== `Bearer ${deps.token}`) return reply.code(401).send({ error: "unauthorized" });
});
app.get("/healthz", async () => {
let db = false;
try {
await deps.pool.query("select 1");
db = true;
} catch {
/* db=false */
}
return { ok: db, db, time: new Date().toISOString() };
});
app.get("/status", async () => {
const nonWork = await deps.nonWorkdays();
const now = new Date();
const jobs = [];
for (const j of deps.jobs) {
const last = (
await deps.pool.query("select scheduled_minute, status, noticed_at, message from sched_run where job_name = $1 order by scheduled_minute desc limit 1", [j.name])
).rows[0] ?? null;
jobs.push({ name: j.name, at: j.at, days: j.days, lastDue: lastDue(j, now, deps.tz, nonWork)?.toISOString() ?? null, lastRun: last });
}
return { jobs };
});
app.post<{ Params: { name: string } }>("/jobs/:name/run", async (req, reply) => {
const job = deps.jobs.find((j) => j.name === req.params.name);
if (!job) return reply.code(404).send({ error: "unknown job" });
const id = await deps.manualRun(job);
return id ? reply.code(202).send({ runId: id }) : reply.code(409).send({ error: "уже запускалось в эту минуту" });
});
return app;
}

View File

@@ -0,0 +1,25 @@
import type { DispatchResult } from "./tick.js";
import type { JobSettings, SchedulerSettings } from "./settings.js";
/** HTTP-вызов сервиса по описанию задания (Bearer-токен сервиса из settings.scheduler.services). */
export function makeHttpDispatch(services: SchedulerSettings["services"], fetchFn: typeof fetch = fetch) {
return async (job: JobSettings): Promise<DispatchResult> => {
const svc = services[job.call.service];
if (!svc) return { httpStatus: 0, message: `неизвестный сервис ${job.call.service}` };
const res = await fetchFn(svc.baseUrl + job.call.path, {
method: job.call.method,
headers: { authorization: `Bearer ${svc.token}`, "content-type": "application/json" },
body: job.call.method === "POST" ? JSON.stringify(job.call.body ?? {}) : undefined,
signal: AbortSignal.timeout(30_000),
});
const text = await res.text();
let ref: string | undefined;
try {
const j = JSON.parse(text) as { snapshotTs?: string; runId?: string };
ref = j.snapshotTs ?? j.runId;
} catch {
/* ответ не JSON */
}
return { httpStatus: res.status, responseRef: ref, message: res.ok ? undefined : text.slice(0, 300) };
};
}

View File

@@ -0,0 +1,59 @@
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(); });

View File

@@ -0,0 +1,25 @@
import { z } from "zod";
const daysSchema = z.union([z.literal("daily"), z.literal("workdays"), z.array(z.enum(["mon", "tue", "wed", "thu", "fri", "sat", "sun"]))]);
export const jobSchema = z.object({
name: z.string(),
call: z.object({
service: z.string(),
method: z.enum(["GET", "POST"]).default("POST"),
path: z.string(),
body: z.unknown().optional(),
}),
at: z.string().regex(/^\d{2}:\d{2}$/),
days: daysSchema,
});
export const schedulerSchema = z.object({
tickSeconds: z.number().default(10),
missedGraceSeconds: z.number().default(60),
http: z.object({ host: z.string().default("127.0.0.1"), port: z.number(), token: z.string().min(1) }),
jobs: z.array(jobSchema),
services: z.record(z.object({ baseUrl: z.string(), token: z.string() })),
});
export type SchedulerSettings = z.infer<typeof schedulerSchema>;
export type JobSettings = z.infer<typeof jobSchema>;

View File

@@ -0,0 +1,52 @@
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { createLogger, createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
import { tick, type DispatchResult } from "./tick.js";
import type { JobSettings } from "./settings.js";
const url = testDatabaseUrl();
const d = url ? describe : describe.skip;
const log = createLogger("test", "silent");
const job: JobSettings = { name: "llmtest-job", at: "06:00", days: "daily", call: { service: "svc", method: "POST", path: "/runs" } };
d("тик планировщика (временная БД)", () => {
let db: TestDb;
let calls: string[];
const mk = (now: Date, dispatch?: () => Promise<DispatchResult>) => ({
pool: db.pool, jobs: [job], tz: "America/New_York", graceSeconds: 60, now: () => now,
nonWorkdays: async () => new Set<string>(), log,
dispatch: dispatch ?? (async () => { calls.push("call"); return { httpStatus: 202, responseRef: "ref-1" }; }),
});
beforeAll(async () => { db = await createTestDb(url!); });
afterAll(async () => { await db?.drop(); });
it("в нужное время стартует задание и пишет результат", async () => {
calls = [];
await Promise.all(await tick(mk(new Date("2026-10-11T10:00:10Z"))));
expect(calls).toHaveLength(1);
const { rows } = await db.pool.query("select status, http_status, response_ref from sched_run");
expect(rows).toEqual([{ status: "ok", http_status: 202, response_ref: "ref-1" }]);
});
it("повторный тик в ту же минуту не запускает задание снова", async () => {
calls = [];
await Promise.all(await tick(mk(new Date("2026-10-11T10:00:20Z"))));
expect(calls).toHaveLength(0);
expect((await db.pool.query("select count(*)::int n from sched_run")).rows[0].n).toBe(1);
});
it("пропущенное задание не запускается, момент обнаружения логируется", async () => {
calls = [];
await Promise.all(await tick(mk(new Date("2026-10-12T10:07:00Z")))); // сервис "проснулся" через 7 минут после 06:00
expect(calls).toHaveLength(0);
const { rows } = await db.pool.query("select status, message from sched_run where scheduled_minute = '2026-10-12T10:00:00Z'");
expect(rows[0].status).toBe("missed");
expect(rows[0].message).toContain("пропуск замечен");
});
it("ошибка вызова фиксируется как error", async () => {
await Promise.all(await tick(mk(new Date("2026-10-13T10:00:05Z"), async () => ({ httpStatus: 500, message: "boom" }))));
const { rows } = await db.pool.query("select status, message from sched_run where scheduled_minute = '2026-10-13T10:00:00Z'");
expect(rows[0]).toEqual({ status: "error", message: "boom" });
});
});

View File

@@ -0,0 +1,69 @@
import type { Logger, Pool } from "khb_common";
import { decide, lastDue } from "./due-calculator.js";
import type { JobSettings } from "./settings.js";
export interface DispatchResult {
httpStatus: number;
responseRef?: string;
message?: string;
}
export interface TickDeps {
pool: Pool;
jobs: JobSettings[];
tz: string;
graceSeconds: number;
now?: () => Date;
nonWorkdays: () => Promise<ReadonlySet<string>>;
dispatch: (job: JobSettings) => Promise<DispatchResult>;
log: Logger;
}
/** Фиксирует срабатывание в sched_run; false, если запись (job, minute) уже есть (повторный старт исключён). */
async function claim(pool: Pool, job: string, minute: Date, status: "started" | "missed", message?: string): Promise<string | null> {
const { rows } = await pool.query(
"insert into sched_run (job_name, scheduled_minute, status, message) values ($1,$2,$3,$4) on conflict (job_name, scheduled_minute) do nothing returning id",
[job, minute, status, message ?? null],
);
return rows[0]?.id ?? null;
}
async function run(deps: TickDeps, job: JobSettings, id: string): Promise<void> {
try {
const r = await deps.dispatch(job);
const ok = r.httpStatus >= 200 && r.httpStatus < 300;
await deps.pool.query(
"update sched_run set status = $2, finished_at = now(), http_status = $3, response_ref = $4, message = $5 where id = $1",
[id, ok ? "ok" : "error", r.httpStatus, r.responseRef ?? null, r.message ?? null],
);
if (!ok) deps.log.error({ job: job.name, ...r }, "вызов задания вернул ошибку");
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
await deps.pool.query("update sched_run set status = 'error', finished_at = now(), message = $2 where id = $1", [id, msg]);
deps.log.error({ job: job.name, err: msg }, "вызов задания упал");
}
}
/** Один тик: для каждого задания определяет, пора ли стартовать, пропущено ли оно, или уже обработано. Возвращает фоновые вызовы. */
export async function tick(deps: TickDeps): Promise<Promise<void>[]> {
const now = (deps.now ?? (() => new Date()))();
const nonWork = await deps.nonWorkdays();
const running: Promise<void>[] = [];
for (const job of deps.jobs) {
const due = lastDue(job, now, deps.tz, nonWork);
if (!due) continue;
const recorded = (
await deps.pool.query("select 1 from sched_run where job_name = $1 and scheduled_minute = $2", [job.name, due])
).rowCount! > 0;
const action = decide(due, recorded, now, deps.graceSeconds);
if (action === "start") {
const id = await claim(deps.pool, job.name, due, "started");
if (id) running.push(run(deps, job, id));
} else if (action === "missed") {
const lateSec = Math.round((now.getTime() - due.getTime()) / 1000);
const id = await claim(deps.pool, job.name, due, "missed", `пропуск замечен ${now.toISOString()}, опоздание ${lateSec} с; задание не запускалось`);
if (id) deps.log.warn({ job: job.name, due: due.toISOString(), lateSec }, "пропущенное задание не запускается");
}
}
return running;
}

View File

@@ -0,0 +1,6 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": { "outDir": "dist", "rootDir": "src" },
"include": ["src"],
"exclude": ["src/**/*.test.ts"]
}