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, cfg: RetentionConfig = DEFAULT_RETENTION, now = new Date(), ): Promise { 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 | 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(); 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 }; }