// PEP-320: one `act_runner daemon` per registration. infra/act-runner/supervise.sh wrote the pid of // `sed` (the pipeline tail) into .pid, and register.sh removed .pid without stopping the old daemon — // after two re-registrations three daemons shared /data/runners/peppa-bot. // The scripts run here for real with a fake act_runner (mock-act-runner), paths via environment. import assert from "node:assert/strict"; import { type ChildProcess, execFile, spawn } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, symlinkSync, 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, before, describe, test } from "node:test"; const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); const SCRIPTS = join(ROOT, "infra/act-runner"); const hasProc = existsSync("/proc/self/cwd"); const run = promisify(execFile); const tmp = realpathSync(mkdtempSync(join(tmpdir(), "mock-act-runner-"))); const runners = join(tmp, "runners"); const bin = join(tmp, "bin"); const dir = join(runners, "peppa-bot"); const env = { ...process.env, PEPPA_RUNNERS_DIR: runners, PEPPA_ACT_RUNNER_BIN: join(bin, "act_runner"), PEPPA_ACT_RUNNER_CONFIG: "/dev/null", PEPPA_RUNNER_BIN_DIR: bin, PEPPA_SUPERVISE_INTERVAL: "1", PEPPA_RUNNER_STOP_WAIT: "20", PEPPA_RUNNER_TOKEN: "mock-token", GITEA_INSTANCE_URL: "http://mock-gitea:3000", }; /** Live `act_runner daemon` processes whose working directory is `cwd` (as supervise.sh sees them). */ function daemons(cwd: string): number[] { const out: number[] = []; for (const n of readdirSync("/proc")) { if (!/^\d+$/.test(n)) continue; try { if (readlinkSync(`/proc/${n}/cwd`) !== cwd) continue; const args = readFileSync(`/proc/${n}/cmdline`, "utf8").split("\0"); if (args.some((a) => a.includes("act_runner")) && args.includes("daemon")) out.push(Number(n)); } catch {} } return out; } const pidFile = () => Number(readFileSync(join(dir, ".pid"), "utf8").trim()); async function until(what: string, ok: () => boolean, ms = 15_000) { const end = Date.now() + ms; while (Date.now() < end) { if (ok()) return; await new Promise((r) => setTimeout(r, 100)); } assert.fail(`timeout: ${what}; daemons ${JSON.stringify(daemons(dir))}, log:\n${log}`); } /** Exactly one daemon, the one in .pid, and it stays so over two supervise passes. */ async function oneDaemon(what: string) { await until(what, () => { const d = daemons(dir); try { return d.length === 1 && d[0] === pidFile(); } catch { return false; } }); await new Promise((r) => setTimeout(r, 2_500)); const d = daemons(dir); assert.deepEqual(d, [pidFile()], `${what}: still one daemon after two passes`); return d[0]; } const register = () => run("sh", [join(SCRIPTS, "register.sh"), "peppa-bot"], { env }); let supervise: ChildProcess | undefined; let extra: ChildProcess | undefined; let log = ""; describe("PEP-320: один демон исполнителя проверок на регистрацию", { skip: !hasProc && "needs /proc (Linux)" }, () => { before(() => { mkdirSync(bin, { recursive: true }); mkdirSync(runners, { recursive: true }); symlinkSync(join(ROOT, "packages/testkit/bin/mock-act-runner"), join(bin, "act_runner")); supervise = spawn("sh", [join(SCRIPTS, "supervise.sh")], { env, detached: true, stdio: ["ignore", "pipe", "pipe"] }); supervise.stdout!.on("data", (b) => { log += b; }); supervise.stderr!.on("data", (b) => { log += b; }); }); after(() => { try { if (supervise?.pid) process.kill(-supervise.pid, "SIGKILL"); } catch {} try { extra?.kill("SIGKILL"); } catch {} for (const p of daemons(dir)) try { process.kill(p, "SIGKILL"); } catch {} rmSync(tmp, { recursive: true, force: true }); }); test("Первая регистрация — демон поднят, в .pid его номер, журнал с именем регистрации", async () => { await register(); const pid = await oneDaemon("first registration"); await until("log line with the registration name", () => log.includes(`[peppa-bot] mock daemon ${pid} declare successfully`)); assert.ok(existsSync(join(bin, "peppa-runner-register")), "the register wrapper is installed"); }); test("Две перерегистрации подряд — работает один демон, прежний остановлен мягко", async () => { const first = pidFile(); await register(); await register(); const pid = await oneDaemon("two re-registrations"); assert.notEqual(pid, first, "a new daemon for the new registration"); assert.match(log, new RegExp(`mock daemon ${first} stopping gracefully`), "old daemon got SIGTERM"); }); test("Упавший демон поднимается заново", async () => { const old = pidFile(); process.kill(old, "SIGKILL"); await until("a new daemon after the crash", () => daemons(dir).some((p) => p !== old)); const pid = await oneDaemon("after crash"); assert.notEqual(pid, old); }); test("Лишний демон в том же каталоге останавливается, демон из .pid остаётся", async () => { const kept = pidFile(); extra = spawn(join(bin, "act_runner"), ["daemon", "--config", "/dev/null"], { cwd: dir, stdio: "ignore" }); await until("extra daemon visible", () => daemons(dir).includes(extra!.pid!)); await until("extra daemon stopped", () => !daemons(dir).includes(extra!.pid!)); assert.equal(await oneDaemon("after extra"), kept); }); test("Регистрацию подменили, не остановив демона, — прежний заменён", async () => { const old = pidFile(); writeFileSync(join(dir, ".runner"), '{"uuid":"mock-replaced-by-hand"}\n'); await until("old daemon replaced", () => !daemons(dir).includes(old) && daemons(dir).length === 1); assert.notEqual(await oneDaemon("after .runner replaced"), old); }); });