Каркас 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,18 @@
import type { CommonSettings } from "../settings/index.js";
/** Уведомление ИТ-команде в Slack. Без настроек itAlerts возвращает false (вызывающий пишет в лог). */
export async function itNotify(
settings: Pick<CommonSettings, "itAlerts">,
text: string,
fetchFn: typeof fetch = fetch,
): Promise<boolean> {
const cfg = settings.itAlerts;
if (!cfg) return false;
const res = await fetchFn("https://slack.com/api/chat.postMessage", {
method: "POST",
headers: { "content-type": "application/json", authorization: `Bearer ${cfg.slackBotToken}` },
body: JSON.stringify({ channel: cfg.slackChannelId, text }),
});
const body = (await res.json()) as { ok?: boolean };
return res.ok && body.ok === true;
}

View File

@@ -0,0 +1,50 @@
import { DateTime } from "luxon";
export const TZ = "America/New_York";
/** Сегодняшняя дата (yyyy-mm-dd) в часовом поясе Tampa. */
export function todayIn(now: Date, tz = TZ): string {
return DateTime.fromJSDate(now, { zone: tz }).toISODate()!;
}
/** Понедельник и воскресенье недели, содержащей дату (ISO, пн-вс). */
export function weekBounds(date: string): { start: string; end: string } {
const d = DateTime.fromISO(date, { zone: "utc" });
return { start: d.startOf("week").toISODate()!, end: d.endOf("week").toISODate()! };
}
export function addDays(date: string, n: number): string {
return DateTime.fromISO(date, { zone: "utc" }).plus({ days: n }).toISODate()!;
}
/** Рабочий день: пн-пт и не в списке нерабочих дат (праздники/ручные выходные из calendar_day). */
export function isWorkday(date: string, nonWorkdays: ReadonlySet<string>): boolean {
const wd = DateTime.fromISO(date, { zone: "utc" }).weekday; // 1..7
return wd <= 5 && !nonWorkdays.has(date);
}
/** Дата через n рабочих дней после date. n = 0 - сама дата, если рабочая, иначе следующая рабочая. */
export function addWorkDays(date: string, n: number, nonWorkdays: ReadonlySet<string>): string {
let d = date;
if (n === 0) {
while (!isWorkday(d, nonWorkdays)) d = addDays(d, 1);
return d;
}
let left = n;
while (left > 0) {
d = addDays(d, 1);
if (isWorkday(d, nonWorkdays)) left--;
}
return d;
}
/** Сколько рабочих дней после from до to включительно. Для to <= from - 0. */
export function workDaysBetween(from: string, to: string, nonWorkdays: ReadonlySet<string>): number {
let n = 0;
let d = from;
while (d < to) {
d = addDays(d, 1);
if (isWorkday(d, nonWorkdays)) n++;
}
return n;
}

View File

@@ -0,0 +1,19 @@
import { DateTime } from "luxon";
/** Момент (UTC) для локальной даты yyyy-mm-dd и времени HH:MM в часовом поясе tz. */
export function zonedToUtc(date: string, hhmm: string, tz: string): Date {
const [h, m] = hhmm.split(":").map(Number) as [number, number];
const dt = DateTime.fromISO(date, { zone: tz }).set({ hour: h, minute: m, second: 0, millisecond: 0 });
return dt.toJSDate();
}
/** Локальная дата yyyy-mm-dd момента now в часовом поясе tz. */
export function localDate(now: Date, tz: string): string {
return DateTime.fromJSDate(now, { zone: tz }).toISODate()!;
}
const DAY_NAMES = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] as const;
/** Название дня недели (mon..sun) для даты yyyy-mm-dd. */
export function dayName(date: string): (typeof DAY_NAMES)[number] {
return DAY_NAMES[DateTime.fromISO(date, { zone: "utc" }).weekday - 1]!;
}

View File

@@ -0,0 +1,60 @@
import { describe, expect, it } from "vitest";
import { addWorkDays, isWorkday, todayIn, weekBounds, workDaysBetween } from "./calendar/index.js";
import { evaluateFreshness, type FreshnessRow } from "./mirror-access/index.js";
describe("calendar", () => {
const holidays = new Set(["2026-11-26"]); // четверг (День благодарения)
it("выходные и праздники - нерабочие", () => {
expect(isWorkday("2026-10-10", holidays)).toBe(false); // суббота
expect(isWorkday("2026-11-26", holidays)).toBe(false);
expect(isWorkday("2026-10-12", holidays)).toBe(true); // понедельник
});
it("addWorkDays пропускает выходные и праздники", () => {
expect(addWorkDays("2026-10-09", 1, holidays)).toBe("2026-10-12"); // пт -> пн
expect(addWorkDays("2026-11-25", 1, holidays)).toBe("2026-11-27"); // ср -> пт через праздник
expect(addWorkDays("2026-10-10", 0, holidays)).toBe("2026-10-12");
});
it("workDaysBetween", () => {
expect(workDaysBetween("2026-10-09", "2026-10-16", holidays)).toBe(5);
expect(workDaysBetween("2026-10-16", "2026-10-09", holidays)).toBe(0);
});
it("todayIn учитывает часовой пояс Tampa", () => {
expect(todayIn(new Date("2026-10-11T02:00:00Z"))).toBe("2026-10-10"); // ещё вечер 10-го в Tampa
});
it("weekBounds: пн-вс", () => {
expect(weekBounds("2026-10-14")).toEqual({ start: "2026-10-12", end: "2026-10-18" });
});
});
describe("evaluateFreshness", () => {
const now = new Date("2026-10-11T12:00:00Z");
const row = (table_name: string, minutesAgo: number, status: "ok" | "error" = "ok", error_message: string | null = null): FreshnessRow => ({
table_name,
snapshot_ts: new Date(now.getTime() - minutesAgo * 60000),
status,
error_message,
});
it("свежая таблица без ошибки - ok", () => {
expect(evaluateFreshness([row("jt_task", 30)], ["jt_task"], now, 90)[0]!.ok).toBe(true);
});
it("таблица без снапшота - no_snapshot", () => {
expect(evaluateFreshness([], ["jt_task"], now, 90)[0]).toMatchObject({ ok: false, reason: "no_snapshot" });
});
it("устаревшая - stale", () => {
expect(evaluateFreshness([row("jt_task", 120)], ["jt_task"], now, 90)[0]).toMatchObject({ ok: false, reason: "stale" });
});
it("используется последний снапшот: старая ошибка, новая успешная загрузка - ok", () => {
const rows = [row("jt_task", 100, "error", "boom"), row("jt_task", 10)];
expect(evaluateFreshness(rows, ["jt_task"], now, 90)[0]!.ok).toBe(true);
});
it("последний снапшот с ошибкой - error", () => {
const rows = [row("jt_task", 100), row("jt_task", 10, "error", "boom")];
expect(evaluateFreshness(rows, ["jt_task"], now, 90)[0]).toMatchObject({ ok: false, reason: "error", message: "boom" });
});
it("ошибка в чужой таблице не влияет на нужные", () => {
const rows = [row("jt_task", 10), row("new_source_table", 5, "error", "no access")];
const res = evaluateFreshness(rows, ["jt_task"], now, 90);
expect(res.every((r) => r.ok)).toBe(true);
});
});

View File

@@ -0,0 +1,49 @@
import { readdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import pg from "pg";
export type Pool = pg.Pool;
export type Queryable = Pick<pg.Pool, "query">;
export function createPool(url: string, max = 5): Pool {
return new pg.Pool({ connectionString: url, max });
}
/** Выполняет fn в транзакции. */
export async function withTx<T>(pool: Pool, fn: (c: pg.PoolClient) => Promise<T>): Promise<T> {
const c = await pool.connect();
try {
await c.query("begin");
const r = await fn(c);
await c.query("commit");
return r;
} catch (e) {
await c.query("rollback").catch(() => undefined);
throw e;
} finally {
c.release();
}
}
/** Применяет *.sql из папки по порядку имён; журнал - таблица schema_migrations. Возвращает применённые. */
export async function migrate(pool: Pool, dir: string = migrationsDir): Promise<string[]> {
await pool.query(
"create table if not exists schema_migrations (name text primary key, applied_at timestamptz not null default now())",
);
const applied = new Set((await pool.query("select name from schema_migrations")).rows.map((r) => r.name as string));
const done: string[] = [];
for (const file of readdirSync(dir).filter((f) => f.endsWith(".sql")).sort()) {
if (applied.has(file)) continue;
const sql = readFileSync(join(dir, file), "utf8");
await withTx(pool, async (c) => {
await c.query(sql);
await c.query("insert into schema_migrations (name) values ($1)", [file]);
});
done.push(file);
}
return done;
}
/** Папка migrations пакета khb_common (работает и из src, и из dist). */
export const migrationsDir = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "migrations");

View File

@@ -0,0 +1,8 @@
export * from "./settings/index.js";
export * from "./logging/index.js";
export * from "./db/index.js";
export * from "./calendar/index.js";
export * from "./mirror-access/index.js";
export * from "./alerts/index.js";
export * from "./calendar/zoned.js";
export * from "./testing/index.js";

View File

@@ -0,0 +1,6 @@
import { pino, type Logger } from "pino";
export function createLogger(name: string, level = "info"): Logger {
return pino({ name, level });
}
export type { Logger };

View File

@@ -0,0 +1,9 @@
import { createPool, migrate } from "./db/index.js";
import { commonSchema, readSettingsFile } from "./settings/index.js";
/** CLI: применить миграции из packages/khb_common/migrations к БД из settings.json5 (common.database.url). */
const common = commonSchema.parse(readSettingsFile().common);
const pool = createPool(common.database.url, 1);
const applied = await migrate(pool);
console.log(applied.length ? `применены миграции: ${applied.join(", ")}` : "миграции актуальны");
await pool.end();

View File

@@ -0,0 +1,45 @@
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { createTestDb, testDatabaseUrl, type TestDb } from "./testing/index.js";
const url = testDatabaseUrl();
const d = url ? describe : describe.skip;
d("миграции (временная БД)", () => {
let db: TestDb;
beforeAll(async () => {
db = await createTestDb(url!);
});
afterAll(async () => {
await db?.drop();
});
it("создают все таблицы, двойники _hist и представление", async () => {
const { rows } = await db.pool.query("select table_name from information_schema.tables where table_schema = 'public'");
const names = new Set(rows.map((r) => r.table_name as string));
for (const t of [
"jt_job", "jt_job_hist", "jt_task", "jt_task_hist", "jt_task_dependency_hist", "jt_task_assignment_hist",
"sync_source", "sync_snapshot", "sync_table_status", "purchase_task_ref", "calendar_day", "person",
"construction_manager", "assistant_project", "reminder_history", "sched_run", "ap_input_package",
"ap_input_package_item", "ap_agent_invocation", "active_task_list", "active_task", "v_agent_input",
])
expect(names.has(t), t).toBe(true);
});
it("справочник закупок засеян 9 реальными названиями", async () => {
const { rows } = await db.pool.query("select count(*)::int as n from purchase_task_ref");
expect(rows[0].n).toBe(9);
});
it("у всех таблиц включён RLS", async () => {
const { rows } = await db.pool.query(
"select relname from pg_class c join pg_namespace n on n.oid = c.relnamespace where n.nspname = 'public' and c.relkind = 'r' and not c.relrowsecurity and relname <> 'schema_migrations'",
);
expect(rows).toEqual([]);
});
it("sched_run: повторный старт в ту же минуту невозможен", async () => {
const q = "insert into sched_run (job_name, scheduled_minute, status) values ('j', '2026-10-11T10:00:00Z', 'started')";
await db.pool.query(q);
await expect(db.pool.query(q)).rejects.toThrow(/duplicate key/);
});
});

View File

@@ -0,0 +1,74 @@
import type { Queryable } from "../db/index.js";
export interface TableState {
table: string;
ok: boolean;
reason?: "no_snapshot" | "error" | "stale";
snapshotTs?: Date;
message?: string;
}
export interface FreshnessRow {
table_name: string;
snapshot_ts: Date;
status: "ok" | "error";
error_message: string | null;
}
/**
* Чистая проверка: для каждой таблицы берётся ПОСЛЕДНИЙ снапшот, в который она вошла;
* он должен быть без ошибки по этой таблице и не старше maxAgeMinutes.
*/
export function evaluateFreshness(
rows: FreshnessRow[],
tables: string[],
now: Date,
maxAgeMinutes: number,
): TableState[] {
return tables.map((table): TableState => {
const mine = rows.filter((r) => r.table_name === table);
if (mine.length === 0) return { table, ok: false, reason: "no_snapshot" };
const last = mine.reduce((a, b) => (b.snapshot_ts > a.snapshot_ts ? b : a));
if (last.status === "error")
return { table, ok: false, reason: "error", snapshotTs: last.snapshot_ts, message: last.error_message ?? undefined };
const ageMin = (now.getTime() - last.snapshot_ts.getTime()) / 60000;
if (ageMin > maxAgeMinutes) return { table, ok: false, reason: "stale", snapshotTs: last.snapshot_ts };
return { table, ok: true, snapshotTs: last.snapshot_ts };
});
}
export class MirrorNotReadyError extends Error {
constructor(public readonly failing: TableState[]) {
super(
"Зеркала не готовы: " + failing.map((f) => `${f.table}(${f.reason}${f.message ? ": " + f.message : ""})`).join(", "),
);
}
}
/** Проверяет таблицы-зеркала из списка; native-таблицы сюда передавать не нужно. */
export async function checkFreshTables(
db: Queryable,
tables: string[],
maxAgeMinutes = 90,
now = new Date(),
): Promise<TableState[]> {
const { rows } = await db.query<FreshnessRow>(
`select distinct on (table_name) table_name, snapshot_ts, status, error_message
from sync_table_status where table_name = any($1) order by table_name, snapshot_ts desc`,
[tables],
);
return evaluateFreshness(rows, tables, now, maxAgeMinutes);
}
/** Бросает MirrorNotReadyError, если хотя бы одна из таблиц не готова. */
export async function requireFreshTables(
db: Queryable,
tables: string[],
maxAgeMinutes = 90,
now = new Date(),
): Promise<TableState[]> {
const states = await checkFreshTables(db, tables, maxAgeMinutes, now);
const failing = states.filter((s) => !s.ok);
if (failing.length) throw new MirrorNotReadyError(failing);
return states;
}

View File

@@ -0,0 +1,49 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import JSON5 from "json5";
import { z } from "zod";
/** Секция common - общая для всех сервисов. */
export const commonSchema = z.object({
timezone: z.string().default("America/New_York"),
database: z.object({ url: z.string().min(1) }),
logLevel: z.string().default("info"),
itAlerts: z.object({ slackChannelId: z.string(), slackBotToken: z.string() }).optional(),
});
export type CommonSettings = z.infer<typeof commonSchema>;
export const jobtreadSchema = z.object({ organizationId: z.string(), grantKey: z.string().min(1) });
export type JobtreadSettings = z.infer<typeof jobtreadSchema>;
/** Читает единый settings.json5 (путь: аргумент, env KHB_SETTINGS, либо settings.json5 вверх от cwd). */
export function readSettingsFile(path?: string): Record<string, unknown> {
const file = path ?? process.env.KHB_SETTINGS ?? findUp("settings.json5");
return JSON5.parse(readFileSync(file, "utf8")) as Record<string, unknown>;
}
function findUp(name: string): string {
let dir = process.cwd();
for (let i = 0; i < 6; i++) {
const candidate = resolve(dir, name);
try {
readFileSync(candidate);
return candidate;
} catch {
dir = resolve(dir, "..");
}
}
throw new Error(`${name} не найден (задайте KHB_SETTINGS)`);
}
/** Загружает и проверяет секции: common и секцию сервиса. */
export function loadServiceSettings<T>(
section: string,
sectionSchema: { parse(value: unknown): T },
raw: Record<string, unknown> = readSettingsFile(),
): { common: CommonSettings; service: T; raw: Record<string, unknown> } {
return {
common: commonSchema.parse(raw.common),
service: sectionSchema.parse(raw[section]),
raw,
};
}

View File

@@ -0,0 +1,45 @@
import { randomBytes } from "node:crypto";
import pg from "pg";
import { createPool, migrate, type Pool } from "../db/index.js";
import { readSettingsFile } from "../settings/index.js";
export interface TestDb {
pool: Pool;
name: string;
drop(): Promise<void>;
}
/** Адрес серверной БД из settings.json5 (или KHB_TEST_DATABASE_URL); null - БД недоступна, интеграционные тесты пропускаются. */
export function testDatabaseUrl(): string | null {
if (process.env.KHB_TEST_DATABASE_URL) return process.env.KHB_TEST_DATABASE_URL;
try {
const url = (readSettingsFile().common as { database?: { url?: string } } | undefined)?.database?.url;
return url || null;
} catch {
return null;
}
}
/** Создаёт временную базу llmtest_<random>, применяет миграции, возвращает пул и drop(). */
export async function createTestDb(baseUrl: string): Promise<TestDb> {
const name = `llmtest_${randomBytes(4).toString("hex")}`;
const admin = new pg.Client({ connectionString: baseUrl });
await admin.connect();
await admin.query(`create database ${name}`);
await admin.end();
const u = new URL(baseUrl);
u.pathname = `/${name}`;
const pool = createPool(u.toString(), 4);
await migrate(pool);
return {
pool,
name,
async drop() {
await pool.end();
const a = new pg.Client({ connectionString: baseUrl });
await a.connect();
await a.query(`drop database if exists ${name} with (force)`);
await a.end();
},
};
}