387 lines
15 KiB
TypeScript
387 lines
15 KiB
TypeScript
// PEP-221: long history outside the main database (see the change's design.md).
|
|
// · `history.db` (PEPPA_HISTORY_DB, default $PEPPA_HOME/history.db, like observe.db of PEP-202):
|
|
// `journal` — «who did what», `journalDays` (90); `metric_events` — status changes of stories and
|
|
// limit hits for the project metrics, `metricsDays` (365);
|
|
// · `$PEPPA_HOME/archive/<checks|releases>/<YYYY-MM-DD>.jsonl.gz` — log tails of checks and releases,
|
|
// `logDays` (7), one gzip member appended per batch.
|
|
// The main database's events are copied by a cursor kept in history.db itself (moved in the same
|
|
// transaction as the rows), so a rerun neither loses nor duplicates anything.
|
|
import { DatabaseSync } from "node:sqlite";
|
|
import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
|
import { gunzipSync, gzipSync } from "node:zlib";
|
|
import { dirname, join } from "node:path";
|
|
import { peppaHome } from "@peppa/shared";
|
|
import type { Db } from "@peppa/db";
|
|
|
|
const DAY = 86_400_000;
|
|
/** Events younger than this are not copied yet: the cursor must never pass a row still being written. */
|
|
const SETTLE_MS = 10 * 60_000;
|
|
export const HISTORY_BATCH = 5000;
|
|
const MAX_BATCHES = 20;
|
|
|
|
const SCHEMA = [
|
|
`CREATE TABLE journal (
|
|
id INTEGER PRIMARY KEY,
|
|
project_id INTEGER NOT NULL,
|
|
project_key TEXT NOT NULL,
|
|
task_id INTEGER,
|
|
task_key TEXT,
|
|
session_id INTEGER,
|
|
type TEXT NOT NULL,
|
|
payload TEXT,
|
|
actor_kind TEXT,
|
|
actor_channel TEXT,
|
|
actor_user_id INTEGER,
|
|
actor_login TEXT,
|
|
actor_client TEXT,
|
|
created_at INTEGER NOT NULL
|
|
)`,
|
|
`CREATE INDEX journal_project ON journal (project_id, id)`,
|
|
`CREATE INDEX journal_task ON journal (task_id, id)`,
|
|
`CREATE INDEX journal_created ON journal (created_at)`,
|
|
`CREATE INDEX journal_user ON journal (actor_user_id, created_at)`,
|
|
`CREATE TABLE metric_events (
|
|
event_id INTEGER PRIMARY KEY,
|
|
project_id INTEGER NOT NULL,
|
|
task_id INTEGER,
|
|
type TEXT NOT NULL,
|
|
from_status TEXT,
|
|
to_status TEXT,
|
|
error TEXT,
|
|
at INTEGER NOT NULL
|
|
)`,
|
|
`CREATE INDEX metric_events_project ON metric_events (project_id, type, at)`,
|
|
`CREATE INDEX metric_events_at ON metric_events (at)`,
|
|
`CREATE TABLE history_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
|
|
];
|
|
const MIGRATIONS: string[][] = [SCHEMA];
|
|
|
|
const opened = new Map<string, DatabaseSync>();
|
|
|
|
export const historyDbPath = () => process.env.PEPPA_HISTORY_DB ?? join(peppaHome(), "history.db");
|
|
export const archiveDir = () => join(dirname(historyDbPath()), "archive");
|
|
|
|
/** The history database of this process (opened and migrated on first use). */
|
|
export function historyDb(): DatabaseSync {
|
|
const path = historyDbPath();
|
|
const known = opened.get(path);
|
|
if (known) return known;
|
|
mkdirSync(dirname(path), { recursive: true });
|
|
const db = new DatabaseSync(path);
|
|
db.exec("PRAGMA busy_timeout = 5000");
|
|
db.exec("PRAGMA journal_mode = WAL");
|
|
db.exec("PRAGMA synchronous = NORMAL");
|
|
const version = Number((db.prepare("PRAGMA user_version").get() as { user_version: number }).user_version);
|
|
for (let v = version; v < MIGRATIONS.length; v++) {
|
|
db.exec("BEGIN IMMEDIATE");
|
|
try {
|
|
for (const sql of MIGRATIONS[v]!) db.exec(sql);
|
|
db.exec(`PRAGMA user_version = ${v + 1}`);
|
|
db.exec("COMMIT");
|
|
} catch (e) {
|
|
db.exec("ROLLBACK");
|
|
throw e;
|
|
}
|
|
}
|
|
opened.set(path, db);
|
|
return db;
|
|
}
|
|
|
|
/** Tests: forget opened files. */
|
|
export function closeHistoryDb(): void {
|
|
for (const db of opened.values()) db.close();
|
|
opened.clear();
|
|
}
|
|
|
|
/** Opened only if the file exists: readers must not create an empty archive on a fresh system. */
|
|
function historyIfAny(): DatabaseSync | null {
|
|
if (!opened.has(historyDbPath()) && !existsSync(historyDbPath())) return null;
|
|
return historyDb();
|
|
}
|
|
|
|
const meta = (h: DatabaseSync, key: string): string | null => (h.prepare("SELECT value FROM history_meta WHERE key = ?").get(key) as { value: string } | undefined)?.value ?? null;
|
|
const setMeta = (h: DatabaseSync, key: string, value: string) => h.prepare("INSERT INTO history_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(key, value);
|
|
|
|
/** The id of the last main-database event already in the archive (0 — nothing yet). */
|
|
export const historyCursor = (): number => Number(meta(historyDb(), "events.cursor") ?? 0);
|
|
|
|
type MainEvent = {
|
|
id: number;
|
|
project_id: number;
|
|
project_key: string;
|
|
task_id: number | null;
|
|
task_number: number | null;
|
|
session_id: number | null;
|
|
type: string;
|
|
payload: string | null;
|
|
actor_kind: string | null;
|
|
actor_channel: string | null;
|
|
actor_user_id: number | null;
|
|
login: string | null;
|
|
client: string | null;
|
|
actor_client_id: string | null;
|
|
created_at: number;
|
|
};
|
|
|
|
const LIMIT_TYPES = new Set(["usage_limit", "stop_failure"]);
|
|
|
|
/**
|
|
* Copies events of the main database (except `skipTypes` — the work journal) into `journal` and
|
|
* `metric_events`, in id order, in batches. Returns how many rows were copied.
|
|
*/
|
|
export function archiveEvents(db: Db, o: { now?: Date; skipTypes?: readonly string[] } = {}): number {
|
|
const h = historyDb();
|
|
const main = db.$client.db;
|
|
const settled = (o.now ?? new Date()).getTime() - SETTLE_MS;
|
|
const skip = new Set(o.skipTypes ?? []);
|
|
const select = main.prepare(
|
|
`SELECT e.id, e.project_id, p.key AS project_key, e.task_id, t.number AS task_number, e.session_id, e.type, e.payload,
|
|
e.actor_kind, e.actor_channel, e.actor_user_id, u.login, c.name AS client, e.actor_client_id, e.created_at
|
|
FROM events e JOIN projects p ON p.id = e.project_id
|
|
LEFT JOIN tasks t ON t.id = e.task_id
|
|
LEFT JOIN users u ON u.id = e.actor_user_id
|
|
LEFT JOIN oauth_clients c ON c.id = e.actor_client_id
|
|
WHERE e.id > ? ORDER BY e.id LIMIT ${HISTORY_BATCH}`,
|
|
);
|
|
const insJournal = h.prepare(
|
|
`INSERT OR IGNORE INTO journal (id, project_id, project_key, task_id, task_key, session_id, type, payload, actor_kind, actor_channel, actor_user_id, actor_login, actor_client, created_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
);
|
|
const insMetric = h.prepare(`INSERT OR IGNORE INTO metric_events (event_id, project_id, task_id, type, from_status, to_status, error, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
let copied = 0;
|
|
for (let b = 0; b < MAX_BATCHES; b++) {
|
|
const cursor = historyCursor();
|
|
const rows = select.all(cursor) as unknown as MainEvent[];
|
|
if (!rows.length) break;
|
|
let last = cursor;
|
|
let stopped = false;
|
|
h.exec("BEGIN IMMEDIATE");
|
|
try {
|
|
for (const r of rows) {
|
|
if (Number(r.created_at) > settled) {
|
|
stopped = true;
|
|
break;
|
|
}
|
|
last = Number(r.id);
|
|
if (skip.has(r.type)) continue;
|
|
const taskKey = r.task_number != null ? `${r.project_key}-${r.task_number}` : null;
|
|
insJournal.run(r.id, r.project_id, r.project_key, r.task_id, taskKey, r.session_id, r.type, r.payload, r.actor_kind, r.actor_channel, r.actor_user_id, r.login, r.client ?? r.actor_client_id, r.created_at);
|
|
copied++;
|
|
let p: { from?: { status?: string }; to?: { status?: string }; error?: string } | null = null;
|
|
try {
|
|
p = r.payload ? JSON.parse(r.payload) : null;
|
|
} catch {}
|
|
if (r.type === "task_updated" && p?.to?.status) insMetric.run(r.id, r.project_id, r.task_id, r.type, p.from?.status ?? null, p.to.status, null, r.created_at);
|
|
else if (LIMIT_TYPES.has(r.type)) insMetric.run(r.id, r.project_id, r.task_id, r.type, null, null, typeof p?.error === "string" ? p.error : null, r.created_at);
|
|
}
|
|
if (last > cursor) setMeta(h, "events.cursor", String(last));
|
|
h.exec("COMMIT");
|
|
} catch (e) {
|
|
h.exec("ROLLBACK");
|
|
throw e;
|
|
}
|
|
if (stopped || rows.length < HISTORY_BATCH) break;
|
|
}
|
|
return copied;
|
|
}
|
|
|
|
/** Drops archive rows past their terms. */
|
|
export function expireHistory(o: { now?: Date; journalDays: number; metricsDays: number }): { journal: number; metrics: number } {
|
|
const h = historyIfAny();
|
|
if (!h) return { journal: 0, metrics: 0 };
|
|
const now = (o.now ?? new Date()).getTime();
|
|
const journal = Number(h.prepare("DELETE FROM journal WHERE created_at < ?").run(now - o.journalDays * DAY).changes);
|
|
const metrics = Number(h.prepare("DELETE FROM metric_events WHERE at < ?").run(now - o.metricsDays * DAY).changes);
|
|
return { journal, metrics };
|
|
}
|
|
|
|
// ── readers ──────────────────────────────────────────────────────────────────
|
|
|
|
export interface HistoryJournalRow {
|
|
id: number;
|
|
projectId: number;
|
|
projectKey: string;
|
|
taskId: number | null;
|
|
taskKey: string | null;
|
|
sessionId: number | null;
|
|
type: string;
|
|
payload: unknown;
|
|
actorKind: string | null;
|
|
actorChannel: string | null;
|
|
actorUserId: number | null;
|
|
actorLogin: string | null;
|
|
actorClient: string | null;
|
|
createdAt: Date;
|
|
}
|
|
|
|
export interface HistoryJournalFilter {
|
|
projectIds?: number[];
|
|
projectId?: number;
|
|
taskId?: number;
|
|
actorKind?: string;
|
|
channel?: string;
|
|
excludeTypes?: string[];
|
|
before?: number;
|
|
limit?: number;
|
|
}
|
|
|
|
const parse = (s: string | null): unknown => {
|
|
if (s == null) return null;
|
|
try {
|
|
return JSON.parse(s);
|
|
} catch {
|
|
return s;
|
|
}
|
|
};
|
|
|
|
/** Archived journal rows, newest first, with the same filters as `listJournal`. */
|
|
export function historyJournal(f: HistoryJournalFilter = {}): HistoryJournalRow[] {
|
|
if (f.projectIds && !f.projectIds.length) return [];
|
|
const h = historyIfAny();
|
|
if (!h) return [];
|
|
const where: string[] = [];
|
|
const args: (number | string)[] = [];
|
|
if (f.projectIds) {
|
|
where.push(`project_id IN (${f.projectIds.map(() => "?").join(",")})`);
|
|
args.push(...f.projectIds);
|
|
}
|
|
if (f.projectId != null) where.push("project_id = ?"), args.push(f.projectId);
|
|
if (f.taskId != null) where.push("task_id = ?"), args.push(f.taskId);
|
|
if (f.actorKind) where.push("actor_kind = ?"), args.push(f.actorKind);
|
|
if (f.channel) where.push("actor_channel = ?"), args.push(f.channel);
|
|
if (f.before) where.push("id < ?"), args.push(f.before);
|
|
if (f.excludeTypes?.length) {
|
|
where.push(`type NOT IN (${f.excludeTypes.map(() => "?").join(",")})`);
|
|
args.push(...f.excludeTypes);
|
|
}
|
|
const rows = h
|
|
.prepare(`SELECT * FROM journal ${where.length ? `WHERE ${where.join(" AND ")}` : ""} ORDER BY id DESC LIMIT ?`)
|
|
.all(...args, Math.min(f.limit ?? 100, 500)) as Record<string, unknown>[];
|
|
return rows.map((r) => ({
|
|
id: Number(r.id),
|
|
projectId: Number(r.project_id),
|
|
projectKey: String(r.project_key),
|
|
taskId: r.task_id == null ? null : Number(r.task_id),
|
|
taskKey: (r.task_key as string | null) ?? null,
|
|
sessionId: r.session_id == null ? null : Number(r.session_id),
|
|
type: String(r.type),
|
|
payload: parse(r.payload as string | null),
|
|
actorKind: (r.actor_kind as string | null) ?? null,
|
|
actorChannel: (r.actor_channel as string | null) ?? null,
|
|
actorUserId: r.actor_user_id == null ? null : Number(r.actor_user_id),
|
|
actorLogin: (r.actor_login as string | null) ?? null,
|
|
actorClient: (r.actor_client as string | null) ?? null,
|
|
createdAt: new Date(Number(r.created_at)),
|
|
}));
|
|
}
|
|
|
|
export interface MetricEvent {
|
|
eventId: number;
|
|
taskId: number | null;
|
|
type: string;
|
|
fromStatus: string | null;
|
|
toStatus: string | null;
|
|
error: string | null;
|
|
at: Date;
|
|
}
|
|
|
|
/** Archived facts for the project metrics: status changes (whole term) and limit hits since `since`. */
|
|
export function historyMetricEvents(projectId: number, o: { since?: Date } = {}): MetricEvent[] {
|
|
const h = historyIfAny();
|
|
if (!h) return [];
|
|
const rows = h
|
|
.prepare(`SELECT * FROM metric_events WHERE project_id = ? AND (type = 'task_updated' OR at >= ?) ORDER BY event_id`)
|
|
.all(projectId, o.since?.getTime() ?? 0) as Record<string, unknown>[];
|
|
return rows.map((r) => ({
|
|
eventId: Number(r.event_id),
|
|
taskId: r.task_id == null ? null : Number(r.task_id),
|
|
type: String(r.type),
|
|
fromStatus: (r.from_status as string | null) ?? null,
|
|
toStatus: (r.to_status as string | null) ?? null,
|
|
error: (r.error as string | null) ?? null,
|
|
at: new Date(Number(r.at)),
|
|
}));
|
|
}
|
|
|
|
/** Last archived activity of every project and every person (the superadmin's dashboard). */
|
|
export function historyLastActivity(): { projects: Map<number, Date>; users: Map<number, Date> } {
|
|
const h = historyIfAny();
|
|
if (!h) return { projects: new Map(), users: new Map() };
|
|
const ps = h.prepare("SELECT project_id AS k, max(created_at) AS at FROM journal GROUP BY project_id").all() as { k: number; at: number }[];
|
|
const us = h.prepare("SELECT actor_user_id AS k, max(created_at) AS at FROM journal WHERE actor_user_id IS NOT NULL GROUP BY actor_user_id").all() as { k: number; at: number }[];
|
|
const map = (xs: { k: number; at: number }[]) => new Map(xs.map((x) => [Number(x.k), new Date(Number(x.at))]));
|
|
return { projects: map(ps), users: map(us) };
|
|
}
|
|
|
|
// ── log tails ────────────────────────────────────────────────────────────────
|
|
|
|
export type LogKind = "checks" | "releases";
|
|
export interface ArchivedLog {
|
|
id: number;
|
|
projectId: number;
|
|
taskId?: number | null;
|
|
sha?: string | null;
|
|
check?: string | null;
|
|
env?: string | null;
|
|
state?: string | null;
|
|
at: number;
|
|
log: string;
|
|
}
|
|
|
|
const dayOf = (ms: number) => new Date(ms).toISOString().slice(0, 10);
|
|
const logFile = (kind: LogKind, day: string) => join(archiveDir(), kind, `${day}.jsonl.gz`);
|
|
|
|
/** Appends log tails to the day files (one gzip member per day per call). */
|
|
export function archiveLogs(kind: LogKind, rows: ArchivedLog[]): void {
|
|
const byDay = new Map<string, string[]>();
|
|
for (const r of rows) {
|
|
const day = dayOf(r.at);
|
|
byDay.set(day, [...(byDay.get(day) ?? []), JSON.stringify(r)]);
|
|
}
|
|
for (const [day, lines] of byDay) {
|
|
const file = logFile(kind, day);
|
|
mkdirSync(dirname(file), { recursive: true });
|
|
appendFileSync(file, gzipSync(lines.join("\n") + "\n"));
|
|
}
|
|
}
|
|
|
|
function readDay(kind: LogKind, day: string): ArchivedLog[] {
|
|
const file = logFile(kind, day);
|
|
if (!existsSync(file)) return [];
|
|
try {
|
|
return gunzipSync(readFileSync(file))
|
|
.toString("utf8")
|
|
.split("\n")
|
|
.filter(Boolean)
|
|
.map((l) => JSON.parse(l) as ArchivedLog);
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
/** The archived tail of check run / release `id` written around `at` (that day or the next). */
|
|
export function archivedLog(kind: LogKind, id: number, at: Date | number): string | null {
|
|
const ms = typeof at === "number" ? at : at.getTime();
|
|
let found: string | null = null;
|
|
for (const day of [dayOf(ms), dayOf(ms + DAY)]) for (const r of readDay(kind, day)) if (r.id === id) found = r.log; // the last copy wins
|
|
return found;
|
|
}
|
|
|
|
/** Removes day files older than `days`. */
|
|
export function expireLogs(o: { now?: Date; days: number }): number {
|
|
const cut = dayOf((o.now ?? new Date()).getTime() - o.days * DAY);
|
|
let n = 0;
|
|
for (const kind of ["checks", "releases"] as const) {
|
|
const dir = join(archiveDir(), kind);
|
|
if (!existsSync(dir)) continue;
|
|
for (const f of readdirSync(dir)) {
|
|
const m = /^(\d{4}-\d{2}-\d{2})\.jsonl\.gz$/.exec(f);
|
|
if (m && m[1]! < cut) {
|
|
rmSync(join(dir, f), { force: true });
|
|
n++;
|
|
}
|
|
}
|
|
}
|
|
return n;
|
|
}
|