118 lines
6.0 KiB
TypeScript
118 lines
6.0 KiB
TypeScript
// PEP-244: an agent's container does not outlive its session — removed when the tmux session is
|
|
// gone, and the watchdog's sweep removes `peppa-s<id>` containers of finished or missing sessions.
|
|
import assert from "node:assert/strict";
|
|
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join, resolve } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { after, before, beforeEach, describe, test } from "node:test";
|
|
import { and, eq } from "drizzle-orm";
|
|
import { events } from "@peppa/db";
|
|
import { core, db, project, runner, teardown, tick, type TestProject } from "./helpers.ts";
|
|
|
|
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
|
const state = mkdtempSync(join(tmpdir(), "mock-docker-orphans-"));
|
|
process.env.PEPPA_DOCKER_BIN = join(ROOT, "packages/testkit/bin/mock-docker");
|
|
process.env.MOCK_DOCKER_STATE = state;
|
|
// helpers.ts turns the sweep off for other suites.
|
|
process.env.PEPPA_ORPHAN_CONTAINERS = "on";
|
|
|
|
const row = (name: string) => [`id-${name}`, name, "", ""].join("\t");
|
|
function run(...names: string[]) {
|
|
mkdirSync(join(state, "containers"), { recursive: true });
|
|
writeFileSync(join(state, "ps"), names.map((n) => `${row(n)}\n`).join(""));
|
|
for (const n of names) writeFileSync(join(state, "containers", n), "peppa/runner:latest\n");
|
|
}
|
|
const running = () => (existsSync(join(state, "ps")) ? readFileSync(join(state, "ps"), "utf8").split("\n").filter(Boolean).map((l) => l.split("\t")[1]) : []);
|
|
const removed = () => (existsSync(join(state, "removed")) ? readFileSync(join(state, "removed"), "utf8").trim().split("\n").filter(Boolean) : []);
|
|
const evs = (sessionId: number, type: string) => db.select().from(events).where(and(eq(events.sessionId, sessionId), eq(events.type, type)));
|
|
|
|
let p: TestProject;
|
|
let projectId: number;
|
|
|
|
async function session(status: "running" | "failed" | "done", container = true) {
|
|
const s = await core.createSession(db, { projectId });
|
|
await core.updateSession(db, s.id, { tmuxName: `peppa-pep244-s${s.id}`, status, container: container ? `peppa-s${s.id}` : null, ...(status === "running" ? {} : { endedAt: new Date() }) });
|
|
return s.id;
|
|
}
|
|
|
|
before(async () => {
|
|
p = await project({ turns: [] });
|
|
projectId = (await core.getProject(db, p.key)).id;
|
|
});
|
|
after(teardown);
|
|
beforeEach(() => {
|
|
for (const f of ["ps", "removed", "calls.log"]) writeFileSync(join(state, f), "");
|
|
});
|
|
|
|
describe("PEP-244: containers of agents", () => {
|
|
test("Пропавшая сессия теряет контейнер", async () => {
|
|
const id = await session("running");
|
|
run(`peppa-s${id}`);
|
|
await tick();
|
|
assert.ok(removed().includes(`peppa-s${id}`), "the container of the gone session is removed");
|
|
assert.equal((await evs(id, "tmux_gone")).length, 1);
|
|
assert.ok(!running().includes(`peppa-s${id}`));
|
|
});
|
|
|
|
test("Сверка убирает сироту; Свежая сирота ждёт второй сверки", async () => {
|
|
const failed = await session("failed");
|
|
const live = await session("running");
|
|
const missing = 999_001;
|
|
run(`peppa-s${failed}`, `peppa-s${missing}`, `peppa-s${live}`);
|
|
const seen = new Map<string, number>();
|
|
const t0 = new Date("2026-11-23T10:00:00Z");
|
|
const first = await runner.orphanContainersTick(db, { now: t0, seen });
|
|
assert.deepEqual(first, [], "a fresh orphan waits for the second check");
|
|
assert.deepEqual(removed(), []);
|
|
|
|
const soon = await runner.orphanContainersTick(db, { now: new Date(t0.getTime() + 30_000), seen });
|
|
assert.deepEqual(soon, [], "less than a minute apart — still waits");
|
|
|
|
const r = await runner.orphanContainersTick(db, { now: new Date(t0.getTime() + 61_000), seen });
|
|
assert.deepEqual(r.map((x) => x.container).sort(), [`peppa-s${failed}`, `peppa-s${missing}`].sort());
|
|
assert.deepEqual(running(), [`peppa-s${live}`], "the live session's container keeps running");
|
|
const ev = await evs(failed, "container_orphan_removed");
|
|
assert.equal(ev.length, 1);
|
|
assert.equal((ev[0]!.payload as { container: string }).container, `peppa-s${failed}`);
|
|
assert.equal(seen.size, 0);
|
|
});
|
|
|
|
test("Контейнер, снова получивший живую сессию, не удаляется", async () => {
|
|
const id = await session("failed");
|
|
run(`peppa-s${id}`);
|
|
const seen = new Map<string, number>();
|
|
const t0 = new Date("2026-11-23T11:00:00Z");
|
|
await runner.orphanContainersTick(db, { now: t0, seen });
|
|
// A resume reuses the name: the session runs again before the next check.
|
|
await core.updateSession(db, id, { status: "running", endedAt: null });
|
|
await runner.orphanContainersTick(db, { now: new Date(t0.getTime() + 61_000), seen });
|
|
await core.updateSession(db, id, { status: "failed", endedAt: new Date() });
|
|
const r = await runner.orphanContainersTick(db, { now: new Date(t0.getTime() + 122_000), seen });
|
|
assert.deepEqual(r, [], "the mark was dropped while the session lived — the grace starts over");
|
|
assert.deepEqual(running(), [`peppa-s${id}`]);
|
|
await core.updateSession(db, id, { status: "done" });
|
|
});
|
|
|
|
test("Чужие контейнеры не трогаются", async () => {
|
|
run("peppa-web", "shop-prod-web-1", "peppa-s12x", "peppa-server");
|
|
const seen = new Map<string, number>();
|
|
const t0 = new Date("2026-11-23T12:00:00Z");
|
|
await runner.orphanContainersTick(db, { now: t0, seen });
|
|
const r = await runner.orphanContainersTick(db, { now: new Date(t0.getTime() + 61_000), seen });
|
|
assert.deepEqual(r, []);
|
|
assert.deepEqual(running(), ["peppa-web", "shop-prod-web-1", "peppa-s12x", "peppa-server"]);
|
|
});
|
|
|
|
test("docker не отвечает — сверка не падает", async () => {
|
|
process.env.MOCK_DOCKER_PS_FAIL = "1";
|
|
const lines: string[] = [];
|
|
try {
|
|
assert.deepEqual(await runner.orphanContainersTick(db, { seen: new Map(), log: (l) => void lines.push(l) }), []);
|
|
} finally {
|
|
delete process.env.MOCK_DOCKER_PS_FAIL;
|
|
}
|
|
assert.ok(lines.some((l) => l.includes("docker ps")));
|
|
});
|
|
});
|