Каркас 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:
52
packages/data_collector/src/retention/policy.test.ts
Normal file
52
packages/data_collector/src/retention/policy.test.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DEFAULT_RETENTION as C, nextLevel, planRetention, type SnapshotInfo } from "./policy.js";
|
||||
|
||||
const now = new Date("2026-10-11T12:00:00Z");
|
||||
const ago = (h: number) => new Date(now.getTime() - h * 3600_000);
|
||||
const snap = (h: number, hadErrors = false): SnapshotInfo => ({ startedAt: ago(h), hadErrors });
|
||||
const iso = (d: Date[]) => d.map((x) => x.toISOString());
|
||||
|
||||
describe("planRetention", () => {
|
||||
it("первые 24 часа хранятся все снапшоты", () => {
|
||||
expect(planRetention([snap(1), snap(5), snap(23)], now, C)).toEqual([]);
|
||||
});
|
||||
it("старше суток - не более одного в день (остаётся самый поздний за день)", () => {
|
||||
const s = [snap(30), snap(31), snap(36)]; // все 9 октября/10 октября UTC
|
||||
const del = planRetention(s, now, C);
|
||||
// 30ч назад = 10.10 06:00, 31ч = 10.10 05:00, 36ч = 10.10 00:00 -> остаётся 06:00
|
||||
expect(iso(del)).toEqual([ago(36).toISOString(), ago(31).toISOString()]);
|
||||
});
|
||||
it("успешные старше 370 дней удаляются", () => {
|
||||
expect(planRetention([snap(371 * 24)], now, C)).toHaveLength(1);
|
||||
expect(planRetention([snap(369 * 24)], now, C)).toHaveLength(0);
|
||||
});
|
||||
it("при сокращении (уровень 1 = 180 дней)", () => {
|
||||
expect(planRetention([snap(200 * 24)], now, C, 1)).toHaveLength(1);
|
||||
expect(planRetention([snap(200 * 24)], now, C, 0)).toHaveLength(0);
|
||||
expect(planRetention([snap(40 * 24)], now, C, 3)).toHaveLength(1); // 35 дней
|
||||
});
|
||||
it("сбойные не прореживаются до суток и живут 10 дней", () => {
|
||||
const s = [snap(30, true), snap(31, true), snap(9 * 24, true), snap(11 * 24, true)];
|
||||
const del = planRetention(s, now, C);
|
||||
expect(iso(del)).toEqual([ago(11 * 24).toISOString()]);
|
||||
});
|
||||
it("сбойных не более 20 в сутки - остаются последние", () => {
|
||||
const s = Array.from({ length: 25 }, (_, i) => ({ startedAt: new Date(now.getTime() - i * 60_000), hadErrors: true }));
|
||||
expect(planRetention(s, now, C)).toHaveLength(5);
|
||||
});
|
||||
it("защищённые снапшоты не удаляются", () => {
|
||||
const old = snap(400 * 24);
|
||||
expect(planRetention([old], now, C, 0, new Set([old.startedAt.getTime()]))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("nextLevel", () => {
|
||||
it("растёт при превышении лимита 30 GB до последней ступени", () => {
|
||||
expect(nextLevel(0, 31, C)).toBe(1);
|
||||
expect(nextLevel(3, 40, C)).toBe(3);
|
||||
});
|
||||
it("снижается при запасе и держится в зоне 27-30 GB", () => {
|
||||
expect(nextLevel(2, 20, C)).toBe(1);
|
||||
expect(nextLevel(2, 28, C)).toBe(2);
|
||||
});
|
||||
});
|
||||
69
packages/data_collector/src/retention/policy.ts
Normal file
69
packages/data_collector/src/retention/policy.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
export interface RetentionConfig {
|
||||
hourlyKeepHours: number;
|
||||
dailyKeepDays: number;
|
||||
dbSizeLimitGb: number;
|
||||
reducedDaysSteps: number[];
|
||||
failedKeepDays: number;
|
||||
failedMaxPerDay: number;
|
||||
}
|
||||
|
||||
export const DEFAULT_RETENTION: RetentionConfig = {
|
||||
hourlyKeepHours: 24,
|
||||
dailyKeepDays: 370,
|
||||
dbSizeLimitGb: 30,
|
||||
reducedDaysSteps: [180, 90, 35],
|
||||
failedKeepDays: 10,
|
||||
failedMaxPerDay: 20,
|
||||
};
|
||||
|
||||
export interface SnapshotInfo {
|
||||
startedAt: Date;
|
||||
hadErrors: boolean;
|
||||
}
|
||||
|
||||
const HOUR = 3600_000;
|
||||
const DAY = 24 * HOUR;
|
||||
const dayKey = (d: Date) => d.toISOString().slice(0, 10);
|
||||
|
||||
/**
|
||||
* Какие снапшоты удалить (docs/mirroring.md):
|
||||
* - успешные: первые hourlyKeepHours часов - все; дальше не более одного в сутки (последний за день), до keepDays дней, затем удаление;
|
||||
* - сбойные: не прореживаются до суток, хранятся failedKeepDays, не более failedMaxPerDay в сутки (остаются последние);
|
||||
* - level > 0 - срок хранения успешных сокращён ступенью reducedDaysSteps[level-1] (БД больше лимита).
|
||||
* protect - снапшоты, на которые ещё ссылается текущее состояние таблиц (их не удаляем).
|
||||
*/
|
||||
export function planRetention(
|
||||
snapshots: SnapshotInfo[],
|
||||
now: Date,
|
||||
cfg: RetentionConfig,
|
||||
level = 0,
|
||||
protect: ReadonlySet<number> = new Set(),
|
||||
): Date[] {
|
||||
const keepDays = level > 0 ? (cfg.reducedDaysSteps[Math.min(level, cfg.reducedDaysSteps.length) - 1] ?? cfg.dailyKeepDays) : cfg.dailyKeepDays;
|
||||
const toDelete = new Set<number>();
|
||||
const sorted = [...snapshots].sort((a, b) => b.startedAt.getTime() - a.startedAt.getTime()); // новые первыми
|
||||
|
||||
const okDayKept = new Set<string>();
|
||||
const failedPerDay = new Map<string, number>();
|
||||
for (const s of sorted) {
|
||||
const age = now.getTime() - s.startedAt.getTime();
|
||||
const key = dayKey(s.startedAt);
|
||||
if (s.hadErrors) {
|
||||
const n = (failedPerDay.get(key) ?? 0) + 1;
|
||||
failedPerDay.set(key, n);
|
||||
if (age > cfg.failedKeepDays * DAY || n > cfg.failedMaxPerDay) toDelete.add(s.startedAt.getTime());
|
||||
continue;
|
||||
}
|
||||
if (age <= cfg.hourlyKeepHours * HOUR) continue; // свежие - все
|
||||
if (age > keepDays * DAY || okDayKept.has(key)) toDelete.add(s.startedAt.getTime());
|
||||
else okDayKept.add(key);
|
||||
}
|
||||
return [...toDelete].filter((t) => !protect.has(t)).sort((a, b) => a - b).map((t) => new Date(t));
|
||||
}
|
||||
|
||||
/** Уровень сокращения срока: растёт на 1, пока БД больше лимита (до числа ступеней); падает при запасе 10%. */
|
||||
export function nextLevel(current: number, dbSizeGb: number, cfg: RetentionConfig): number {
|
||||
if (dbSizeGb > cfg.dbSizeLimitGb) return Math.min(current + 1, cfg.reducedDaysSteps.length);
|
||||
if (dbSizeGb < cfg.dbSizeLimitGb * 0.9) return Math.max(current - 1, 0);
|
||||
return current;
|
||||
}
|
||||
49
packages/data_collector/src/retention/run.ts
Normal file
49
packages/data_collector/src/retention/run.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import type { Pool } from "khb_common";
|
||||
import { DEFAULT_RETENTION, nextLevel, planRetention, type RetentionConfig } from "./policy.js";
|
||||
|
||||
export interface RetentionReport {
|
||||
deletedSnapshots: number;
|
||||
level: number;
|
||||
dbSizeGb: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Применяет правила хранения ко всем источникам: удаляет строки _hist и записи sync_snapshot.
|
||||
* Снапшоты, на которые ссылается текущая таблица зеркала, не удаляются.
|
||||
* tablesBySource: источник -> таблицы зеркала.
|
||||
*/
|
||||
export async function runRetention(
|
||||
pool: Pool,
|
||||
tablesBySource: Record<string, string[]>,
|
||||
cfg: RetentionConfig = DEFAULT_RETENTION,
|
||||
now = new Date(),
|
||||
): Promise<RetentionReport> {
|
||||
const sizeBytes = Number((await pool.query("select pg_database_size(current_database()) as s")).rows[0].s);
|
||||
const dbSizeGb = sizeBytes / 1024 ** 3;
|
||||
const { rows: srcRows } = await pool.query("select prefix, retention_policy from sync_source");
|
||||
let deleted = 0;
|
||||
let maxLevel = 0;
|
||||
|
||||
for (const src of srcRows as { prefix: string; retention_policy: { level?: number } & Partial<RetentionConfig> | null }[]) {
|
||||
const own = src.retention_policy ?? {};
|
||||
const sourceCfg: RetentionConfig = { ...cfg, ...own };
|
||||
const level = nextLevel(own.level ?? 0, dbSizeGb, sourceCfg);
|
||||
maxLevel = Math.max(maxLevel, level);
|
||||
await pool.query("update sync_source set retention_policy = coalesce(retention_policy, '{}'::jsonb) || jsonb_build_object('level', $2::int) where prefix = $1", [src.prefix, level]);
|
||||
|
||||
const tables = tablesBySource[src.prefix] ?? [];
|
||||
const snaps = (
|
||||
await pool.query("select started_at, had_errors from sync_snapshot where source_prefix = $1 and finished_at is not null", [src.prefix])
|
||||
).rows.map((r) => ({ startedAt: r.started_at as Date, hadErrors: r.had_errors as boolean }));
|
||||
const protect = new Set<number>();
|
||||
for (const t of tables) {
|
||||
for (const r of (await pool.query(`select distinct snapshot_ts from ${t}`)).rows) protect.add((r.snapshot_ts as Date).getTime());
|
||||
}
|
||||
const victims = planRetention(snaps, now, sourceCfg, level, protect);
|
||||
if (!victims.length) continue;
|
||||
for (const t of tables) await pool.query(`delete from ${t}_hist where snapshot_ts = any($1)`, [victims]);
|
||||
await pool.query("delete from sync_snapshot where started_at = any($1)", [victims]); // sync_table_status - каскадом
|
||||
deleted += victims.length;
|
||||
}
|
||||
return { deletedSnapshots: deleted, level: maxLevel, dbSizeGb };
|
||||
}
|
||||
Reference in New Issue
Block a user