Каркас monorepo: scheduler, data_collector, khbuild_assistant_prep, khb_common; миграции; CI/CD
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
113
packages/khb_common/migrations/001_mirror_core.sql
Normal file
113
packages/khb_common/migrations/001_mirror_core.sql
Normal file
@@ -0,0 +1,113 @@
|
||||
-- Зеркалирование: технические таблицы и зеркала JobTread (docs/mirroring.md)
|
||||
create table sync_source (
|
||||
prefix text primary key,
|
||||
name text not null,
|
||||
last_snapshot_ts timestamptz,
|
||||
last_success_ts timestamptz,
|
||||
last_error_count int not null default 0,
|
||||
retention_policy jsonb
|
||||
);
|
||||
|
||||
create table sync_snapshot (
|
||||
started_at timestamptz primary key,
|
||||
source_prefix text not null references sync_source(prefix),
|
||||
finished_at timestamptz,
|
||||
requested_tables text[] not null,
|
||||
had_errors boolean not null default false,
|
||||
error_count int not null default 0,
|
||||
error_summary text
|
||||
);
|
||||
|
||||
create table sync_table_status (
|
||||
snapshot_ts timestamptz not null references sync_snapshot(started_at) on delete cascade,
|
||||
table_name text not null,
|
||||
status text not null check (status in ('ok','error')),
|
||||
row_count int,
|
||||
finished_at timestamptz,
|
||||
error_message text,
|
||||
primary key (snapshot_ts, table_name)
|
||||
);
|
||||
create index sync_table_status_table_idx on sync_table_status (table_name, snapshot_ts desc);
|
||||
|
||||
create table jt_job (
|
||||
id text primary key,
|
||||
number text,
|
||||
name text not null,
|
||||
status text,
|
||||
closed_on date,
|
||||
snapshot_ts timestamptz not null references sync_snapshot(started_at)
|
||||
);
|
||||
create table jt_membership (
|
||||
id text primary key,
|
||||
user_name text not null,
|
||||
role text,
|
||||
snapshot_ts timestamptz not null references sync_snapshot(started_at)
|
||||
);
|
||||
create table jt_task_type (
|
||||
id text primary key,
|
||||
name text not null,
|
||||
snapshot_ts timestamptz not null references sync_snapshot(started_at)
|
||||
);
|
||||
create table jt_task (
|
||||
id text primary key,
|
||||
job_id text,
|
||||
parent_task_id text,
|
||||
task_type_id text,
|
||||
name text not null,
|
||||
description text,
|
||||
start_date date,
|
||||
end_date date,
|
||||
progress numeric,
|
||||
is_todo boolean not null default false,
|
||||
is_group boolean not null default false,
|
||||
is_deleted boolean not null default false,
|
||||
snapshot_ts timestamptz not null references sync_snapshot(started_at)
|
||||
);
|
||||
create index jt_task_job_end_idx on jt_task (job_id, end_date);
|
||||
create index jt_task_todo_end_idx on jt_task (is_todo, end_date);
|
||||
create table jt_task_dependency (
|
||||
task_id text not null,
|
||||
depends_on_task_id text not null,
|
||||
snapshot_ts timestamptz not null references sync_snapshot(started_at),
|
||||
primary key (task_id, depends_on_task_id)
|
||||
);
|
||||
create table jt_task_assignment (
|
||||
task_id text not null,
|
||||
membership_id text not null,
|
||||
snapshot_ts timestamptz not null references sync_snapshot(started_at),
|
||||
primary key (task_id, membership_id)
|
||||
);
|
||||
|
||||
-- Двойники _hist: те же колонки, PK дополнительно включает snapshot_ts, без внешних ключей
|
||||
create table jt_job_hist (like jt_job);
|
||||
create table jt_membership_hist (like jt_membership);
|
||||
create table jt_task_type_hist (like jt_task_type);
|
||||
create table jt_task_hist (like jt_task);
|
||||
create table jt_task_dependency_hist (like jt_task_dependency);
|
||||
create table jt_task_assignment_hist (like jt_task_assignment);
|
||||
alter table jt_job_hist add primary key (id, snapshot_ts);
|
||||
alter table jt_membership_hist add primary key (id, snapshot_ts);
|
||||
alter table jt_task_type_hist add primary key (id, snapshot_ts);
|
||||
alter table jt_task_hist add primary key (id, snapshot_ts);
|
||||
alter table jt_task_dependency_hist add primary key (task_id, depends_on_task_id, snapshot_ts);
|
||||
alter table jt_task_assignment_hist add primary key (task_id, membership_id, snapshot_ts);
|
||||
create index jt_task_hist_snap_idx on jt_task_hist (snapshot_ts);
|
||||
|
||||
insert into sync_source (prefix, name) values ('jt', 'JobTread');
|
||||
|
||||
-- Supabase: таблицы в public доступны через REST; без политик RLS закрывает доступ anon/authenticated
|
||||
alter table sync_source enable row level security;
|
||||
alter table sync_snapshot enable row level security;
|
||||
alter table sync_table_status enable row level security;
|
||||
alter table jt_job enable row level security;
|
||||
alter table jt_membership enable row level security;
|
||||
alter table jt_task_type enable row level security;
|
||||
alter table jt_task enable row level security;
|
||||
alter table jt_task_dependency enable row level security;
|
||||
alter table jt_task_assignment enable row level security;
|
||||
alter table jt_job_hist enable row level security;
|
||||
alter table jt_membership_hist enable row level security;
|
||||
alter table jt_task_type_hist enable row level security;
|
||||
alter table jt_task_hist enable row level security;
|
||||
alter table jt_task_dependency_hist enable row level security;
|
||||
alter table jt_task_assignment_hist enable row level security;
|
||||
163
packages/khb_common/migrations/002_native_tables.sql
Normal file
163
packages/khb_common/migrations/002_native_tables.sql
Normal file
@@ -0,0 +1,163 @@
|
||||
-- Native-таблицы: люди, проекты ассистента, справочники, планировщик, пакеты входных данных, результаты агента
|
||||
create table person (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
display_name text not null,
|
||||
email text,
|
||||
jt_membership_id text,
|
||||
slack_user_id text,
|
||||
is_active boolean not null default true,
|
||||
note text
|
||||
);
|
||||
create table construction_manager (
|
||||
person_id uuid primary key references person(id),
|
||||
timezone text not null default 'America/New_York',
|
||||
is_active boolean not null default true,
|
||||
paused_until date
|
||||
);
|
||||
create table assistant_project (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
jt_job_id text not null unique,
|
||||
manager_person_id uuid not null references construction_manager(person_id),
|
||||
slack_channel_id text,
|
||||
mode text not null default 'test' check (mode in ('test','prod')),
|
||||
is_enabled boolean not null default true,
|
||||
created_at timestamptz not null default now()
|
||||
);
|
||||
create table purchase_task_ref (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
task_name text not null,
|
||||
note text,
|
||||
is_verified boolean not null default false,
|
||||
verified_by text,
|
||||
verified_at timestamptz
|
||||
);
|
||||
create unique index purchase_task_ref_name_uq on purchase_task_ref (lower(task_name));
|
||||
insert into purchase_task_ref (task_name, note) values
|
||||
('Purchase 0', 'реальное название из JobTread 2026-10-11'),
|
||||
('Purchase 0: Contract for Pilings Installation', 'реальное название из JobTread 2026-10-11'),
|
||||
('Purchase 1 order start', 'реальное название из JobTread 2026-10-11'),
|
||||
('Purchase 2 Start', 'реальное название из JobTread 2026-10-11'),
|
||||
('Purchase 3 Start', 'реальное название из JobTread 2026-10-11'),
|
||||
('Purchase 4 Start', 'реальное название из JobTread 2026-10-11'),
|
||||
('Purchase 4 Delivered', 'реальное название из JobTread 2026-10-11'),
|
||||
('Purchase 5 delivered', 'реальное название из JobTread 2026-10-11'),
|
||||
('Start Purchase 5', 'реальное название из JobTread 2026-10-11');
|
||||
|
||||
create table calendar_day (
|
||||
day date primary key,
|
||||
is_workday boolean not null,
|
||||
holiday_name text,
|
||||
source text not null check (source in ('nager','manual')),
|
||||
is_verified boolean not null default false,
|
||||
verified_by text,
|
||||
verified_at timestamptz,
|
||||
loaded_at timestamptz not null default now()
|
||||
);
|
||||
|
||||
create table reminder_history (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
assistant_project_id uuid not null references assistant_project(id),
|
||||
jt_task_id text,
|
||||
reminded_at timestamptz not null,
|
||||
reminder_text text,
|
||||
reply_at timestamptz,
|
||||
reply_summary text,
|
||||
reply_outcome text check (reply_outcome in ('done','rescheduled','no_answer','blocked','other'))
|
||||
);
|
||||
|
||||
create table sched_run (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
job_name text not null,
|
||||
scheduled_minute timestamptz not null,
|
||||
status text not null check (status in ('started','ok','error','missed','skipped')),
|
||||
noticed_at timestamptz not null default now(),
|
||||
finished_at timestamptz,
|
||||
http_status int,
|
||||
response_ref text,
|
||||
message text,
|
||||
unique (job_name, scheduled_minute)
|
||||
);
|
||||
|
||||
create table ap_input_package (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
assistant_project_id uuid not null references assistant_project(id),
|
||||
package_date date not null,
|
||||
kind text not null check (kind in ('morning','noon')),
|
||||
source_snapshot_ts timestamptz,
|
||||
content_hash text not null,
|
||||
item_count int not null,
|
||||
changed_since_morning boolean,
|
||||
created_at timestamptz not null default now(),
|
||||
unique (assistant_project_id, package_date, kind)
|
||||
);
|
||||
create table ap_input_package_item (
|
||||
id bigserial primary key,
|
||||
package_id uuid not null references ap_input_package(id) on delete cascade,
|
||||
input_no smallint not null check (input_no in (1,2,3,4,5,7)),
|
||||
jt_task_id text,
|
||||
name text not null,
|
||||
start_date date,
|
||||
end_date date,
|
||||
is_overdue boolean not null default false,
|
||||
is_purchase boolean not null default false,
|
||||
assignees text[] not null default '{}',
|
||||
related_task_id text,
|
||||
days_until_start int,
|
||||
payload jsonb
|
||||
);
|
||||
create index ap_input_package_item_idx on ap_input_package_item (package_id, input_no);
|
||||
create table ap_agent_invocation (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
package_id uuid not null references ap_input_package(id),
|
||||
reason text not null check (reason in ('morning','noon_changed')),
|
||||
requested_at timestamptz not null default now(),
|
||||
status text not null check (status in ('requested','accepted','failed')),
|
||||
http_status int,
|
||||
session_ref text,
|
||||
error text,
|
||||
attempt int not null default 1
|
||||
);
|
||||
|
||||
create table active_task_list (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
assistant_project_id uuid not null references assistant_project(id),
|
||||
package_id uuid not null references ap_input_package(id),
|
||||
list_date date not null,
|
||||
summary_text text,
|
||||
is_current boolean not null default true,
|
||||
created_at timestamptz not null default now()
|
||||
);
|
||||
create table active_task (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
list_id uuid not null references active_task_list(id) on delete cascade,
|
||||
rank int not null,
|
||||
jt_task_id text,
|
||||
title text not null,
|
||||
rationale text,
|
||||
importance text check (importance in ('high','medium','low')),
|
||||
remind_next boolean not null default false
|
||||
);
|
||||
|
||||
create view v_agent_input as
|
||||
select p.id as package_id, ap.id as assistant_project_id, j.name as project_name, ap.jt_job_id,
|
||||
per.display_name as manager_name, p.package_date, p.kind,
|
||||
i.input_no, i.jt_task_id, i.name, i.start_date, i.end_date, i.is_overdue, i.is_purchase,
|
||||
i.assignees, i.related_task_id, i.days_until_start, i.payload
|
||||
from ap_input_package p
|
||||
join assistant_project ap on ap.id = p.assistant_project_id
|
||||
join person per on per.id = ap.manager_person_id
|
||||
left join jt_job j on j.id = ap.jt_job_id
|
||||
join ap_input_package_item i on i.package_id = p.id;
|
||||
|
||||
alter table person enable row level security;
|
||||
alter table construction_manager enable row level security;
|
||||
alter table assistant_project enable row level security;
|
||||
alter table purchase_task_ref enable row level security;
|
||||
alter table calendar_day enable row level security;
|
||||
alter table reminder_history enable row level security;
|
||||
alter table sched_run enable row level security;
|
||||
alter table ap_input_package enable row level security;
|
||||
alter table ap_input_package_item enable row level security;
|
||||
alter table ap_agent_invocation enable row level security;
|
||||
alter table active_task_list enable row level security;
|
||||
alter table active_task enable row level security;
|
||||
10
packages/khb_common/package.json
Normal file
10
packages/khb_common/package.json
Normal file
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "khb_common",
|
||||
"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": {"pg":"^8.13.1","json5":"^2.2.3","zod":"^3.24.1","pino":"^9.5.0","luxon":"^3.5.0"}
|
||||
}
|
||||
18
packages/khb_common/src/alerts/index.ts
Normal file
18
packages/khb_common/src/alerts/index.ts
Normal 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;
|
||||
}
|
||||
50
packages/khb_common/src/calendar/index.ts
Normal file
50
packages/khb_common/src/calendar/index.ts
Normal 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;
|
||||
}
|
||||
19
packages/khb_common/src/calendar/zoned.ts
Normal file
19
packages/khb_common/src/calendar/zoned.ts
Normal 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]!;
|
||||
}
|
||||
60
packages/khb_common/src/common.test.ts
Normal file
60
packages/khb_common/src/common.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
49
packages/khb_common/src/db/index.ts
Normal file
49
packages/khb_common/src/db/index.ts
Normal 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");
|
||||
8
packages/khb_common/src/index.ts
Normal file
8
packages/khb_common/src/index.ts
Normal 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";
|
||||
6
packages/khb_common/src/logging/index.ts
Normal file
6
packages/khb_common/src/logging/index.ts
Normal 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 };
|
||||
9
packages/khb_common/src/migrate-cli.ts
Normal file
9
packages/khb_common/src/migrate-cli.ts
Normal 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();
|
||||
45
packages/khb_common/src/migrations.int.test.ts
Normal file
45
packages/khb_common/src/migrations.int.test.ts
Normal 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/);
|
||||
});
|
||||
});
|
||||
74
packages/khb_common/src/mirror-access/index.ts
Normal file
74
packages/khb_common/src/mirror-access/index.ts
Normal 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;
|
||||
}
|
||||
49
packages/khb_common/src/settings/index.ts
Normal file
49
packages/khb_common/src/settings/index.ts
Normal 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,
|
||||
};
|
||||
}
|
||||
45
packages/khb_common/src/testing/index.ts
Normal file
45
packages/khb_common/src/testing/index.ts
Normal 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();
|
||||
},
|
||||
};
|
||||
}
|
||||
6
packages/khb_common/tsconfig.json
Normal file
6
packages/khb_common/tsconfig.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": { "outDir": "dist", "rootDir": "src" },
|
||||
"include": ["src"],
|
||||
"exclude": ["src/**/*.test.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user