Каркас 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:
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