peppa/packages/testkit/test/storage.test.ts
2026-11-15 15:56:55 +05:00

198 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-36: one SQLite file for every Peppa process — concurrent writers, live updates
// without Postgres NOTIFY, and the one-time move of the data from Postgres.
import assert from "node:assert/strict";
import { execFile, execFileSync } from "node:child_process";
import { existsSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { after, describe, test } from "node:test";
import { core, db, teardown } from "./helpers.ts";
import { createDb, events, projects, settings } from "@peppa/db";
import type { PeppaNotification } from "@peppa/core";
import { like, sql } from "drizzle-orm";
import postgres from "postgres";
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const WORKER = join(ROOT, "packages/testkit/src/storage-worker.ts");
const run = promisify(execFile);
const worker = (...args: string[]) => run(process.execPath, [WORKER, ...args], { env: process.env, encoding: "utf8" });
after(teardown);
describe("Одна база SQLite для всех процессов", () => {
test("Scenario: 20 процессов открывают базу одновременно и пишут — ни одной ошибки, ни одной потерянной записи", async () => {
const results = await Promise.allSettled(Array.from({ length: 20 }, (_, i) => worker("settings", "25", `p${i}`)));
const failed = results.filter((r) => r.status === "rejected");
assert.equal(failed.length, 0, failed.map((r) => String((r as PromiseRejectedResult).reason)).join("\n"));
const [{ n }] = await db.select({ n: sql<number>`count(*)` }).from(settings).where(like(settings.key, "storage:%"));
assert.equal(n, 20 * 25);
});
test("Scenario: задачи из разных процессов получают разные номера подряд", async () => {
const [p] = await db
.insert(projects)
.values({ slug: "storage", key: "STO", name: "STO", giteaOwner: "o", giteaRepo: "storage", workspacePath: "/tmp/storage" })
.returning();
const numbers = (await Promise.all(Array.from({ length: 10 }, () => worker("task", String(p!.id))))).map((r) => Number(r.stdout));
assert.deepEqual([...numbers].sort((a, b) => a - b), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
});
// drizzle's SQLite transactions are synchronous: with an async callback everything after the
// first await would silently run outside the transaction. The driver makes it a loud error.
test("транзакция с async-колбэком отклоняется с понятной ошибкой", async () => {
assert.throws(
() =>
db.transaction(async (tx) => {
await tx.insert(projects).values({ slug: "async", key: "ASY", name: "ASY", giteaOwner: "o", giteaRepo: "async", workspacePath: "/tmp/a" });
}),
/must be synchronous/,
);
});
});
describe("Живые обновления без Postgres", () => {
test("notify() будит подписчика по сокету", async () => {
const got: PeppaNotification[] = [];
const stop = await core.listenEvents("bot", (n) => got.push(n));
try {
await core.notify(db, { type: "question", questionId: 42 });
for (let i = 0; i < 40 && got.length === 0; i++) await new Promise((r) => setTimeout(r, 25));
assert.deepEqual(got, [{ type: "question", questionId: 42 }]);
} finally {
await stop();
}
});
test("Scenario: сокет подписки недоступен — запись другого процесса видна по data_version", async () => {
assert.ok(!existsSync(core.eventsSocket("bot")));
const t0 = Date.now();
await core.notify(db, { type: "progress", eventId: 1 }); // nobody listens: returns at once
assert.ok(Date.now() - t0 < 100);
const v = db.$client.dataVersion();
await worker("settings", "1", "dv");
assert.notEqual(db.$client.dataVersion(), v);
});
});
describe("Резервная копия базы", () => {
test("Scenario: ночная копия открывается сама по себе, копий не больше 7", async () => {
const dir = mkdtempSync(join(tmpdir(), "peppa-backups-"));
for (let d = 1; d <= 8; d++) writeFileSync(join(dir, `peppa-2026-10-0${d}.db`), "old");
const r = await core.backupDb(db, { dir, now: new Date("2026-11-13T03:00:00Z") });
assert.ok(r.file?.endsWith("peppa-2026-11-13.db"));
const copy = createDb(r.file!, { readOnly: true });
assert.equal((await copy.select().from(projects)).length, (await db.select().from(projects)).length);
copy.$client.close();
const left = readdirSync(dir).sort();
assert.equal(left.length, 7);
assert.equal(left.at(-1), "peppa-2026-11-13.db");
assert.deepEqual(await core.backupDb(db, { dir, now: new Date("2026-11-13T12:00:00Z") }), { skipped: true });
});
test("Scenario: копия не удалась — неполного файла нет, база работает", async () => {
const base = mkdtempSync(join(tmpdir(), "peppa-backups-"));
const dir = join(base, "not-a-dir");
writeFileSync(dir, "a file where the backup dir should be");
const logs: string[] = [];
const r = await core.backupDb(db, { dir, force: true, log: (m) => logs.push(m) });
assert.ok(r.error);
assert.match(logs.join("\n"), /Резервная копия базы Peppa FACTORY не сделана/);
assert.equal(readdirSync(base).length, 1);
await core.setSetting(db, "storage:after-backup", 1);
});
});
// The move needs a Postgres server to read from (Peppa's own on the dev machine, the host's in CI).
const PG = process.env.PEPPA_TEST_PG ?? "postgres://peppa:peppa@127.0.0.1:5433";
const pgReachable = await (async () => {
const c = postgres(`${PG}/postgres`, { max: 1, connect_timeout: 3, onnotice: () => {} });
try {
await c`select 1`;
return true;
} catch {
return false;
} finally {
await c.end({ timeout: 1 });
}
})();
describe("Перенос данных из Postgres", { skip: pgReachable ? false : `no Postgres at ${PG}` }, () => {
const name = `peppa_test_m2s_${process.pid}`;
const admin = () => postgres(`${PG}/postgres`, { max: 1, onnotice: () => {} });
const legacy = join(ROOT, "packages/cli/legacy-pg-migrations");
/** A Postgres database with the last Postgres schema of Peppa and some data. */
async function source(seed: (pg: postgres.Sql) => Promise<void>): Promise<string> {
const a = admin();
await a.unsafe(`drop database if exists ${name}`);
await a.unsafe(`create database ${name}`);
await a.end();
const pg = postgres(`${PG}/${name}`, { max: 1, onnotice: () => {} });
for (const f of readdirSync(legacy).filter((f) => f.endsWith(".sql")).sort())
for (const stmt of readFileSync(join(legacy, f), "utf8").split("--> statement-breakpoint")) if (stmt.trim()) await pg.unsafe(stmt);
await seed(pg);
await pg.end();
return `${PG}/${name}`;
}
after(async () => {
const a = admin();
await a.unsafe(`drop database if exists ${name}`);
await a.end();
});
test("Scenario: успешный перенос — строки, даты, JSON, boolean и id чата на месте", async () => {
const url = await source(async (pg) => {
await pg`insert into users (gitea_id, login, telegram_chat_id) values (1, 'mock-pm', 9007199254740991)`;
await pg`insert into projects (slug, key, name, gitea_owner, gitea_repo, workspace_path, owner_id, next_task_number) values ('pay', 'PAY', 'Pay', 'o', 'pay', '/tmp/pay', 1, 2)`;
await pg`insert into tasks (project_id, number, title, status) values (1, 1, 'Первая', 'in_progress')`;
await pg`insert into sessions (project_id, task_id, tmux_name, status) values (1, 1, 'peppa-PAY-1-s1', 'running')`;
await pg`insert into questions (project_id, task_id, session_id, kind, text, options, awaiting_hook) values (1, 1, 1, 'permission', 'Удалить build?', '["Да","Нет"]', true)`;
for (let i = 0; i < 107; i++) await pg`insert into events (project_id, task_id, type, payload) values (1, 1, 'progress', ${pg.json({ i })})`;
await pg`insert into telegram_outbox (dedupe_key, method, params, question_id, status, telegram_message_id) values ('q:1', 'sendMessage', ${pg.json({ chat_id: 4242, text: "?" })}, 1, 'sent', 77)`;
});
const file = join(mkdtempSync(join(tmpdir(), "peppa-m2s-")), "peppa.db");
const out = execFileSync(join(ROOT, "packages/cli/bin/peppa"), ["db", "migrate-to-sqlite", file], {
encoding: "utf8",
env: { ...process.env, DATABASE_URL: url },
});
assert.match(out, /перенесено, расхождений нет/);
assert.match(out, /events\s+107/);
const m = createDb(file);
const q = await m.query.questions.findFirst({ with: { session: true } });
assert.deepEqual(q!.options, ["Да", "Нет"]);
assert.equal(q!.awaitingHook, true);
assert.ok(q!.createdAt instanceof Date && Math.abs(q!.createdAt.getTime() - Date.now()) < 60_000);
assert.equal(q!.session!.tmuxName, "peppa-PAY-1-s1");
assert.equal((await m.query.users.findFirst())!.telegramChatId, 9007199254740991);
assert.equal((await m.select().from(events)).length, 107);
assert.equal((await core.questionByTelegramMessage(m, 4242, 77))?.id, q!.id); // json filter over migrated params
// The new file is a working Peppa database: numbering continues.
const t = await core.createTask(m, { projectId: 1, title: "Вторая" });
assert.equal(t.key, "PAY-2");
m.$client.close();
});
test("Scenario: расхождение — нарушение внешнего ключа, файла нет, Postgres не тронут", async () => {
const url = await source(async (pg) => {
await pg`insert into projects (slug, key, name, gitea_owner, gitea_repo, workspace_path) values ('pay', 'PAY', 'Pay', 'o', 'pay', '/tmp/pay')`;
await pg`alter table questions drop constraint questions_session_id_sessions_id_fk`;
await pg`insert into questions (project_id, session_id, kind, text) values (1, 999, 'question', 'Висящая ссылка')`;
});
const file = join(mkdtempSync(join(tmpdir(), "peppa-m2s-")), "peppa.db");
let err = "";
try {
execFileSync(join(ROOT, "packages/cli/bin/peppa"), ["db", "migrate-to-sqlite", file], { encoding: "utf8", stdio: "pipe", env: { ...process.env, DATABASE_URL: url } });
} catch (e) {
err = String((e as { stderr: string }).stderr);
assert.equal((e as { status: number }).status, 1);
}
assert.match(err, /questions: нарушение внешнего ключа/);
assert.ok(!existsSync(file) && !existsSync(`${file}.migrating`));
const pg = postgres(url, { max: 1, onnotice: () => {} });
assert.equal((await pg`select count(*)::int n from questions`)[0]!.n, 1);
await pg.end();
});
});