// PEP-291: a service's log goes to $PEPPA_HOME/logs/.log too — it survives a redeploy; // daily and size rotation, 7 days and 200 MB per service. import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync, utimesSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { describe, test } from "node:test"; import { RotatingLog, serviceLogFiles } from "@peppa/core"; const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); const fresh = () => mkdtempSync(join(tmpdir(), "service-log-")); const clock = (iso: string) => { const c = { t: new Date(iso) }; return { c, now: () => c.t }; }; const MB = 1024 * 1024; describe("service log (PEP-291)", () => { test("Строки до выкатки на месте: новый процесс дописывает тот же файл", () => { const dir = fresh(); const { now } = clock("2026-11-25T09:00:00Z"); const before = new RotatingLog("watchdog", { dir, now }); before.write("tick ok\n"); before.close(); // The old file's mtime is "today" in the clock, as after a redeploy the same day. utimesSync(join(dir, "watchdog.log"), new Date("2026-11-25T09:00:00Z"), new Date("2026-11-25T09:00:00Z")); const after = new RotatingLog("watchdog", { dir, now: () => new Date("2026-11-25T10:37:00Z") }); after.write("started\n"); after.close(); assert.equal(readFileSync(join(dir, "watchdog.log"), "utf8"), "tick ok\nstarted\n"); }); test("Новый день: вчерашние строки уходят в файл с датой", () => { const dir = fresh(); const { c, now } = clock("2026-11-25T23:59:00Z"); const log = new RotatingLog("bot", { dir, now }); log.write("вчера\n"); c.t = new Date("2026-11-26T00:01:00Z"); log.write("сегодня\n"); log.close(); assert.equal(readFileSync(join(dir, "bot.log.2026-11-25"), "utf8"), "вчера\n"); assert.equal(readFileSync(join(dir, "bot.log"), "utf8"), "сегодня\n"); }); test("Новый день после перезапуска: день файла берётся из его времени", () => { const dir = fresh(); writeFileSync(join(dir, "bot.log"), "до выкатки\n"); utimesSync(join(dir, "bot.log"), new Date("2026-11-25T20:00:00Z"), new Date("2026-11-25T20:00:00Z")); const log = new RotatingLog("bot", { dir, now: () => new Date("2026-11-26T08:00:00Z") }); log.write("после\n"); log.close(); assert.equal(readFileSync(join(dir, "bot.log.2026-11-25"), "utf8"), "до выкатки\n"); assert.equal(readFileSync(join(dir, "bot.log"), "utf8"), "после\n"); }); test("Размер: файл больше четверти предела уходит в ротацию с номером", () => { const dir = fresh(); const { now } = clock("2026-11-26T10:00:00Z"); const log = new RotatingLog("web", { dir, now, maxBytes: 400 }); for (let i = 0; i < 5; i++) log.write(`${"x".repeat(59)}\n`); // 60 bytes each, a file holds 100 log.close(); const files = serviceLogFiles("web", dir); assert.deepEqual(files.map((f) => f.name), ["web.log.2026-11-26", "web.log.2026-11-26.1", "web.log.2026-11-26.2", "web.log.2026-11-26.3", "web.log"]); assert.ok(files.every((f) => f.size <= 100)); assert.equal(files.reduce((s, f) => s + f.size, 0), 300); }); test("Старые файлы удаляются: старше 7 дней", () => { const dir = fresh(); writeFileSync(join(dir, "web.log.2026-11-18"), "old\n"); writeFileSync(join(dir, "web.log.2026-11-20"), "kept\n"); writeFileSync(join(dir, "web.log"), "y\n"); utimesSync(join(dir, "web.log"), new Date("2026-11-25T12:00:00Z"), new Date("2026-11-25T12:00:00Z")); writeFileSync(join(dir, "webhook.log.2026-11-01"), "other service\n"); const log = new RotatingLog("web", { dir, now: () => new Date("2026-11-26T01:00:00Z") }); log.write("z\n"); log.close(); assert.equal(existsSync(join(dir, "web.log.2026-11-18")), false); assert.equal(existsSync(join(dir, "web.log.2026-11-20")), true); assert.equal(existsSync(join(dir, "web.log.2026-11-25")), true); assert.equal(existsSync(join(dir, "webhook.log.2026-11-01")), true, "another service's files are not touched"); }); test("Предел размера: самые старые файлы удаляются, пока всё не уложится", () => { const dir = fresh(); // Scaled down: limit 200 "MB" = 200 bytes; rotated files already 190, the live one grows to 50. for (const [d, n] of [["2026-11-21", 60], ["2026-11-22", 60], ["2026-11-23", 70]] as const) writeFileSync(join(dir, `api.log.${d}`), "a".repeat(n)); const { c, now } = clock("2026-11-24T10:00:00Z"); const log = new RotatingLog("api", { dir, now, maxBytes: 200 }); log.write("b".repeat(50)); c.t = new Date("2026-11-25T10:00:00Z"); log.write("c"); log.close(); const files = serviceLogFiles("api", dir); assert.ok(files.reduce((s, f) => s + f.size, 0) <= 200); assert.deepEqual(files.map((f) => f.name), ["api.log.2026-11-22", "api.log.2026-11-23", "api.log.2026-11-24", "api.log"]); }); test("Сервис: stdout и stderr в файле, вывод как раньше; без прав на каталог сервис работает", () => { const home = fresh(); const script = `import { installServiceLog } from "@peppa/core"; const p = installServiceLog("bot"); console.log("hello " + JSON.stringify(p)); console.error("oops"); process.stdout.write(Buffer.from("raw\\n"));`; const run = (env: Record) => execFileSync(process.execPath, ["--input-type=module", "-e", script], { cwd: join(ROOT, "packages/testkit"), env: { ...process.env, ...env }, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); const out = run({ PEPPA_HOME: home }); assert.match(out, /hello/); const file = readFileSync(join(home, "logs", "bot.log"), "utf8"); assert.match(file, /hello ".*bot\.log"\noops\nraw\n/); const ro = fresh(); mkdirSync(join(ro, "logs")); chmodSync(join(ro, "logs"), 0o500); const out2 = run({ PEPPA_HOME: ro }); assert.match(out2, /hello/); assert.match(out2, /raw/, "the service keeps writing to stdout"); if (process.getuid?.() !== 0) assert.deepEqual(readdirSync(join(ro, "logs")), []); const off = fresh(); run({ PEPPA_HOME: off, PEPPA_SERVICE_LOG: "off" }); assert.equal(existsSync(join(off, "logs")), false); }); });