75 lines
2.7 KiB
TypeScript
75 lines
2.7 KiB
TypeScript
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;
|
|
}
|