171 lines
9.6 KiB
TypeScript
171 lines
9.6 KiB
TypeScript
// PEP-221: long history outside the main database. Tests are named after the spec scenarios.
|
||
import assert from "node:assert/strict";
|
||
import { after, describe, test } from "node:test";
|
||
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
||
import { join } from "node:path";
|
||
import { gzipSync } from "node:zlib";
|
||
// helpers must load first: it sets the isolated test env that runner modules read on load.
|
||
import { core, db, teardown } from "./helpers.ts";
|
||
import { checkRuns, events, tasks } from "@peppa/db";
|
||
import { eq, inArray } from "drizzle-orm";
|
||
|
||
after(teardown);
|
||
const DAY = 86_400_000;
|
||
const NOW = new Date();
|
||
const ago = (days: number) => new Date(NOW.getTime() - days * DAY);
|
||
let seq = 0;
|
||
|
||
async function fixture(status: "done" | "in_progress" = "done") {
|
||
const key = `H${String.fromCharCode(65 + seq++)}`;
|
||
const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: key, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: null });
|
||
const t = await core.createTask(db, { projectId: p.id, title: `Задача ${key}`, description: "x" });
|
||
await db.update(tasks).set({ status }).where(eq(tasks.id, t.task.id));
|
||
return { p, taskId: t.task.id, key: `${key}-${t.task.number}` };
|
||
}
|
||
const journalRows = () => Number((core.historyDb().prepare("SELECT count(*) AS n FROM journal").get() as { n: number }).n);
|
||
const mainIds = async (ids: number[]) => (await db.select({ id: events.id }).from(events).where(inArray(events.id, ids))).map((r) => r.id);
|
||
|
||
describe("PEP-221 history archive", () => {
|
||
test("Scenario: Событие закрытой задачи уходит в архив и удаляется из основной базы", async () => {
|
||
const { p, taskId, key } = await fixture("done");
|
||
const [e] = await db
|
||
.insert(events)
|
||
.values({ projectId: p.id, taskId, type: "task_updated", payload: { from: { status: "review" }, to: { status: "done" } }, actorKind: "system", actorChannel: "watchdog", createdAt: ago(10) })
|
||
.returning();
|
||
const r = await core.runRetention(db, { now: NOW });
|
||
assert.ok(r.archived!.events! >= 1);
|
||
assert.deepEqual(await mainIds([e!.id]), []);
|
||
const [row] = core.historyJournal({ taskId });
|
||
assert.equal(row?.id, e!.id);
|
||
assert.equal(row?.taskKey, key);
|
||
assert.equal(row?.actorKind, "system");
|
||
assert.deepEqual(row?.payload, { from: { status: "review" }, to: { status: "done" } });
|
||
});
|
||
|
||
test("Scenario: Повторный перенос ничего не дублирует", async () => {
|
||
const { p, taskId } = await fixture("done");
|
||
await db.insert(events).values([1, 2, 3].map((i) => ({ projectId: p.id, taskId, type: "started", payload: { i }, createdAt: ago(2) })));
|
||
await core.runRetention(db, { now: NOW });
|
||
const n = journalRows();
|
||
const cursor = core.historyCursor();
|
||
const again = await core.runRetention(db, { now: NOW });
|
||
assert.equal(again.archived!.events, 0);
|
||
assert.equal(journalRows(), n);
|
||
assert.equal(core.historyCursor(), cursor);
|
||
// A crash between commit and delete: the same rows copied again stay single.
|
||
assert.equal(core.archiveEvents(db, { now: NOW }), 0);
|
||
});
|
||
|
||
test("Scenario: Событие открытой задачи и комментарий остаются в основной базе", async () => {
|
||
const open = await fixture("in_progress");
|
||
const done = await fixture("done");
|
||
const rows = await db
|
||
.insert(events)
|
||
.values([
|
||
{ projectId: open.p.id, taskId: open.taskId, type: "task_updated", payload: { to: { status: "in_progress" } }, createdAt: ago(10) },
|
||
{ projectId: done.p.id, taskId: done.taskId, type: "pm_comment", payload: { text: "Поправьте шапку", login: "pm" }, createdAt: ago(10) },
|
||
])
|
||
.returning();
|
||
await core.runRetention(db, { now: NOW });
|
||
const ids = rows.map((r) => r.id);
|
||
assert.deepEqual((await mainIds(ids)).sort(), [...ids].sort());
|
||
assert.equal(core.historyJournal({ taskId: open.taskId }).length, 1);
|
||
assert.equal(core.historyJournal({ taskId: done.taskId }).length, 1);
|
||
});
|
||
|
||
test("Scenario: Свежие события и журнал работы в архив не попадают", async () => {
|
||
const { p, taskId } = await fixture("done");
|
||
const before = core.historyCursor();
|
||
const rows = await db
|
||
.insert(events)
|
||
.values([
|
||
{ projectId: p.id, taskId, type: "step", payload: {}, createdAt: ago(2) },
|
||
{ projectId: p.id, taskId, type: "started", payload: {}, createdAt: new Date(NOW.getTime() - 60_000) },
|
||
])
|
||
.returning();
|
||
await core.runRetention(db, { now: NOW });
|
||
assert.equal(core.historyJournal({ taskId }).length, 0, "шаг не переносится, свежее событие ждёт");
|
||
assert.ok(core.historyCursor() >= before && core.historyCursor() < rows[1]!.id, "курсор не перепрыгнул свежее событие");
|
||
assert.deepEqual(await mainIds([rows[1]!.id]), [rows[1]!.id]);
|
||
// The next run after it settles takes it.
|
||
assert.ok(core.archiveEvents(db, { now: new Date(NOW.getTime() + 11 * 60_000) }) >= 1);
|
||
assert.equal(core.historyJournal({ taskId }).length, 1);
|
||
});
|
||
|
||
test("Scenario: Журнал показывает событие, удалённое из основной базы", async () => {
|
||
const { p, taskId, key } = await fixture("done");
|
||
const [e] = await db.insert(events).values({ projectId: p.id, taskId, type: "repo_transferred", payload: { to: "org" }, actorKind: "user", actorChannel: "cli", createdAt: ago(20) }).returning();
|
||
const [fresh] = await db.insert(events).values({ projectId: p.id, type: "project_paused", payload: {}, createdAt: ago(1) }).returning();
|
||
await core.runRetention(db, { now: NOW });
|
||
assert.deepEqual(await mainIds([e!.id]), []);
|
||
const j = await core.listJournal(db, { projectId: p.id });
|
||
assert.deepEqual(
|
||
j.map((x) => x.id),
|
||
[fresh!.id, e!.id],
|
||
"без повторов, новые сверху",
|
||
);
|
||
assert.equal(j[1]!.taskKey, key);
|
||
assert.equal(core.actorLabel(j[1]!), "человек · CLI");
|
||
// Paging through `before` reaches the archive too.
|
||
assert.deepEqual((await core.listJournal(db, { projectId: p.id, before: fresh!.id })).map((x) => x.id), [e!.id]);
|
||
});
|
||
|
||
test("Scenario: Метрики считают задачу, история которой в архиве", async () => {
|
||
const { p, taskId } = await fixture("done");
|
||
const at = (h: number) => new Date(NOW.getTime() - h * 3_600_000);
|
||
// The cycle ended this week, but the main base keeps nothing of it.
|
||
const rows = await db
|
||
.insert(events)
|
||
.values([
|
||
{ projectId: p.id, taskId, type: "task_updated", payload: { from: { status: "backlog" }, to: { status: "in_progress" } }, createdAt: at(30) },
|
||
{ projectId: p.id, taskId, type: "task_updated", payload: { from: { status: "in_progress" }, to: { status: "done" } }, createdAt: at(20) },
|
||
{ projectId: p.id, taskId, type: "usage_limit", payload: {}, createdAt: at(25) },
|
||
])
|
||
.returning();
|
||
await core.runRetention(db, { now: NOW });
|
||
await db.delete(events).where(inArray(events.id, rows.map((r) => r.id)));
|
||
const m = await core.projectMetrics(db, p.id, { weeks: 2, now: NOW });
|
||
assert.equal(m.summary.done, 1);
|
||
assert.equal(Math.round(m.summary.cycleHoursMedian!), 10);
|
||
assert.equal(m.summary.limitHits, 1);
|
||
});
|
||
|
||
test("Scenario: Журнал старше срока удаляется из архива", async () => {
|
||
const { p } = await fixture("done");
|
||
const [e] = await db.insert(events).values({ projectId: p.id, type: "users_merged", payload: {}, createdAt: ago(100) }).returning();
|
||
await core.runRetention(db, { now: NOW });
|
||
assert.deepEqual(core.historyJournal({ projectId: p.id }).filter((x) => x.id === e!.id), []);
|
||
});
|
||
|
||
test("Scenario: Хвост упавшей проверки читается из архива", async () => {
|
||
const { p, taskId } = await fixture("done");
|
||
const updatedAt = ago(2);
|
||
const [run] = await db.insert(checkRuns).values({ projectId: p.id, taskId, sha: "f1", check: "test", state: "failure", logTail: "boom\nline 2", updatedAt, createdAt: updatedAt }).returning();
|
||
await core.runRetention(db, { now: NOW });
|
||
const [left] = await db.select().from(checkRuns).where(eq(checkRuns.id, run!.id));
|
||
assert.equal(left?.logTail ?? null, null, "в основной базе хвост стёрт");
|
||
assert.equal(core.archivedLog("checks", run!.id, updatedAt), "boom\nline 2");
|
||
// Two gzip members in one day file read as one.
|
||
core.archiveLogs("checks", [{ id: 999_999, projectId: p.id, at: updatedAt.getTime(), log: "second" }]);
|
||
assert.equal(core.archivedLog("checks", run!.id, updatedAt), "boom\nline 2");
|
||
assert.equal(core.archivedLog("checks", 999_999, updatedAt), "second");
|
||
});
|
||
|
||
test("Scenario: Старые файлы логов удаляются", async () => {
|
||
const dir = join(core.archiveDir(), "checks");
|
||
mkdirSync(dir, { recursive: true });
|
||
const old = join(dir, `${ago(10).toISOString().slice(0, 10)}.jsonl.gz`);
|
||
writeFileSync(old, gzipSync("{}\n"));
|
||
await core.runRetention(db, { now: NOW });
|
||
assert.equal(existsSync(old), false);
|
||
});
|
||
|
||
test("Scenario: Копия архива рядом с копией базы", async () => {
|
||
const dir = join(process.env.PEPPA_HOME!, "backups-test");
|
||
const r = await core.backupDb(db, { dir, force: true, now: NOW });
|
||
assert.ok(r.file && existsSync(r.file));
|
||
assert.ok(r.history && existsSync(r.history), "копия архива сделана");
|
||
assert.match(r.history!, /history-\d{4}-\d{2}-\d{2}\.db$/);
|
||
});
|
||
});
|