// PEP-231: products and addresses without the Mac — redeploy of healthy versions on the same // commits (`peppa deploy redeploy`), the server's Cloudflare tunnel and the DNS sync (mock-cloudflare), // compose services for Bugsink on the server and cloudflared. import assert from "node:assert/strict"; import { execFile } from "node:child_process"; import { mkdtempSync, readFileSync } 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"; import { events, releases } from "@peppa/db"; import { and, eq } from "drizzle-orm"; import { MockCloudflare } from "../src/mock-cloudflare.ts"; import { MockGitea } from "../src/mock-gitea.ts"; import { core, db, runner, teardown } from "./helpers.ts"; const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); const run = promisify(execFile); let n = 0; async function proj(slug?: string) { n++; return core.createProject(db, { slug: slug ?? `mock-edge-${n}`, key: `MED${String.fromCharCode(64 + n)}`, name: `Edge ${n}`, giteaOwner: "peppa-bot", giteaRepo: slug ?? `mock-edge-${n}`, workspacePath: `/tmp/mock-edge-${n}` }); } const fakeGitea = () => { const tags: Array<{ repo: string; tag: string; sha: string; message: string }> = []; return { tags, client: { createTag: async (_o: string, repo: string, tag: string, sha: string, message: string) => void tags.push({ repo, tag, sha, message }) } as never }; }; after(teardown); describe("PEP-231: продукты перевыкатываются на тех же коммитах", () => { test("Scenario: Перевыкатка всех проектов", async () => { const p = await proj(); await db.insert(releases).values([ { projectId: p.id, env: "staging", sha: "abc1234", status: "healthy", host: `${p.slug}-staging.telecom.quest`, tasks: [] }, { projectId: p.id, env: "prod", sha: "abc1234", status: "healthy", host: `${p.slug}-prod.telecom.quest`, tasks: [] }, { projectId: p.id, env: "preview", sha: "fff0000", status: "healthy", host: `${p.slug}-pr3.telecom.quest`, prNumber: 3, tasks: [] }, ]); const g = fakeGitea(); const tags = await runner.redeployProject(db, p, { client: g.client, reason: "move", event: "product_redeploy" }); assert.equal(tags.length, 2, "staging and prod, not the preview"); assert.match(g.tags[0]!.tag, /^deploy-staging-\d{17}$/); assert.match(g.tags[1]!.tag, /^deploy-prod-\d{17}$/); assert.deepEqual(g.tags.map((t) => t.sha), ["abc1234", "abc1234"]); const ev = await db.select().from(events).where(and(eq(events.projectId, p.id), eq(events.type, "product_redeploy"))); assert.equal(ev.length, 1); }); test("Scenario: Пробный запуск", async () => { const p = await proj(); await db.insert(releases).values({ projectId: p.id, env: "staging", sha: "bcd2345", status: "healthy", host: null, tasks: [] }); const g = fakeGitea(); const plan = await runner.redeployProject(db, p, { client: g.client, reason: "move", event: "product_redeploy", dryRun: true }); assert.equal(plan.length, 1); assert.match(plan[0]!, /^deploy-staging-\d{17} → bcd2345$/); assert.equal(g.tags.length, 0); }); test("Scenario: Выкладка уже идёт", async () => { const p = await proj(); await db.insert(releases).values([ { projectId: p.id, env: "staging", sha: "cde3456", status: "healthy", tasks: [] }, { projectId: p.id, env: "prod", sha: "cde3456", status: "healthy", tasks: [] }, { projectId: p.id, env: "staging", sha: "def4567", status: "deploying", tasks: [] }, ]); const g = fakeGitea(); await runner.redeployProject(db, p, { client: g.client, reason: "move", event: "product_redeploy" }); assert.deepEqual(g.tags.map((t) => t.tag.replace(/-\d+$/, "")), ["deploy-prod"]); }); test("CLI peppa deploy redeploy --all через mock-gitea ставит теги", async () => { const gitea = await new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-edge-")), "gitea")).start(); try { gitea.addUser({ id: 9001, login: "peppa-bot", token: "mock-bot-token" } as never); const p = await proj("mock-edge-cli"); gitea.addRepo("peppa-bot", "mock-edge-cli", { files: { "README.md": "x" } }); const sha = gitea.sha("peppa-bot", "mock-edge-cli", "main"); await db.insert(releases).values({ projectId: p.id, env: "staging", sha, status: "healthy", tasks: [] }); const { stdout } = await run(join(ROOT, "packages/cli/bin/peppa"), ["deploy", "redeploy", p.key], { env: { ...process.env, GITEA_URL: gitea.url, GITEA_TOKEN: "mock-bot-token" } }); assert.match(stdout, new RegExp(`${p.key}: deploy-staging-\\d{17}`)); const dry = await run(join(ROOT, "packages/cli/bin/peppa"), ["deploy", "redeploy", "--all", "--dry-run"], { env: { ...process.env, GITEA_URL: gitea.url, GITEA_TOKEN: "mock-bot-token" } }); assert.match(dry.stdout, /\(dry run\)/); } finally { await gitea.stop(); } }); }); describe("PEP-231: адреса ведут на туннель сервера", () => { let cf: MockCloudflare; let tunnel: string; let macTunnel: string; let cfg: NonNullable>; before(async () => { cf = await new MockCloudflare().start(); macTunnel = cf.addTunnel("mac", [{ hostname: "git.telecom.quest", service: "http://localhost:3000" }, { service: "http://localhost:80" }]); tunnel = cf.addTunnel("peppa-server"); cfg = core.edgeConfig({ ...cf.env(tunnel), PEPPA_WEB_URL: "https://peppa.telecom.quest" })!; }); after(() => cf.stop()); test("edgeHosts: адрес платформы, Bugsink, staging/prod проектов, недавние выкладки, один уровень", async () => { const p = await proj("mrv"); await db.insert(releases).values([ { projectId: p.id, env: "preview", sha: "1", status: "healthy", host: "mrv-pr7.telecom.quest", tasks: [] }, { projectId: p.id, env: "preview", sha: "2", status: "healthy", host: "a.b.telecom.quest", tasks: [] }, { projectId: p.id, env: "preview", sha: "3", status: "healthy", host: "other.example.com", tasks: [] }, ]); const hosts = await core.edgeHosts(db, "telecom.quest", { env: { PEPPA_WEB_URL: "https://peppa.telecom.quest", PEPPA_PLATFORM_KEY: "PEP" } }); for (const h of ["peppa.telecom.quest", "bugsink.telecom.quest", "mrv-staging.telecom.quest", "mrv-prod.telecom.quest", "mrv-pr7.telecom.quest"]) assert.ok(hosts.includes(h), h); assert.ok(!hosts.includes("a.b.telecom.quest"), "Scenario: Имя глубже одного уровня"); assert.ok(!hosts.includes("other.example.com")); }); test("Scenario: Новой записи нет; Адрес смотрел на туннель Mac; Чужая запись", async () => { cf.addRecord({ type: "CNAME", name: "peppa.telecom.quest", content: `${macTunnel}.cfargotunnel.com`, proxied: true }); cf.addRecord({ type: "A", name: "bugsink.telecom.quest", content: "1.2.3.4" }); const hosts = ["bugsink.telecom.quest", "mrv-staging.telecom.quest", "peppa.telecom.quest"]; const dry = await core.syncEdge(cfg, hosts, { dryRun: true }); assert.equal(dry.ingress, "planned"); assert.deepEqual(dry.created, ["mrv-staging.telecom.quest"]); assert.equal(cf.records.length, 2, "dry run changes nothing"); assert.deepEqual(cf.tunnels.get(tunnel)!.config.ingress, []); const r = await core.syncEdge(cfg, hosts); assert.equal(r.ingress, "set"); assert.deepEqual(cf.tunnels.get(tunnel)!.config.ingress, [{ service: "http://127.0.0.1:8880" }]); assert.equal(cf.tunnels.get(macTunnel)!.config.ingress.length, 2, "the Mac's tunnel is not touched"); const rec = (name: string) => cf.records.find((x) => x.name === name)!; assert.deepEqual([rec("mrv-staging.telecom.quest").type, rec("mrv-staging.telecom.quest").content, rec("mrv-staging.telecom.quest").proxied], ["CNAME", `${tunnel}.cfargotunnel.com`, true]); assert.equal(rec("peppa.telecom.quest").content, `${tunnel}.cfargotunnel.com`); assert.deepEqual(r.moved, [{ host: "peppa.telecom.quest", from: `${macTunnel}.cfargotunnel.com` }]); assert.equal(rec("bugsink.telecom.quest").content, "1.2.3.4"); assert.deepEqual(r.conflicts.map((c) => c.host), ["bugsink.telecom.quest"]); const again = await core.syncEdge(cfg, hosts); assert.equal(again.ingress, "ok"); assert.deepEqual([again.created, again.moved, again.ok], [[], [], ["mrv-staging.telecom.quest", "peppa.telecom.quest"]]); }); test("ошибка Cloudflare — понятное исключение без токена", async () => { await assert.rejects(core.syncEdge({ ...cfg, token: "wrong-secret-token" }, ["x.telecom.quest"]), (e: Error) => /Authentication error/.test(e.message) && !e.message.includes("wrong-secret-token")); cf.down = true; try { await assert.rejects(core.syncEdge(cfg, ["x.telecom.quest"]), /Internal error/); } finally { cf.down = false; } }); test("Scenario: Cloudflare не настроен — тик вачдога ничего не спрашивает", async () => { const before = cf.calls.length; for (const k of ["CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID", "CLOUDFLARE_ZONE_ID", "CLOUDFLARE_TUNNEL_ID"]) delete process.env[k]; assert.equal(await runner.edgeDnsTick(db, { force: true }), null); assert.equal(core.edgeConfig({ ...cf.env(tunnel), PEPPA_EDGE_DNS: "off" }), null); assert.equal(cf.calls.length, before); }); test("тик вачдога с настройкой — сверка, раз в 5 минут", async () => { Object.assign(process.env, cf.env(tunnel)); try { const r = await runner.edgeDnsTick(db, { force: true }); assert.ok(r); assert.ok(cf.records.some((x) => x.name === "mrv-prod.telecom.quest" && x.comment === core.EDGE_COMMENT)); assert.equal(await runner.edgeDnsTick(db), null, "throttled"); } finally { for (const k of Object.keys(cf.env(tunnel))) delete process.env[k]; } }); test("CLI peppa edge tunnel: токен в файл 0600, в выводе только id", async () => { const env = { ...process.env, CLOUDFLARE_API_URL: cf.url, CLOUDFLARE_API_TOKEN: cf.token, CLOUDFLARE_ACCOUNT_ID: cf.accountId }; const { stdout } = await run(join(ROOT, "packages/cli/bin/peppa"), ["edge", "tunnel", "peppa-new"], { env }); const id = /CLOUDFLARE_TUNNEL_ID=([\w-]+)/.exec(stdout)?.[1]; assert.ok(id && cf.tunnels.has(id)); const secret = cf.tunnels.get(id)!.token; assert.ok(!stdout.includes(secret)); const file = join(process.env.PEPPA_HOME!, "cloudflared", "token"); assert.equal(readFileSync(file, "utf8"), secret); const { statSync } = await import("node:fs"); assert.equal(statSync(file).mode & 0o777, 0o600); }); }); describe("PEP-231: compose для сервера", () => { const compose = readFileSync(join(ROOT, "infra/docker-compose.yml"), "utf8"); const block = (name: string) => { const m = new RegExp(`\\n ${name}:\\n([\\s\\S]*?)(?=\\n [a-z-]+:\\n|\\nvolumes:)`).exec(compose); assert.ok(m, name); return m[1]!; }; test("Bugsink в сети Traefik с маршрутом по меткам выше маршрутов проектов", () => { const b = block("bugsink"); assert.match(b, /traefik_default/); assert.match(b, /traefik\.http\.routers\.peppa-bugsink\.rule=Host\(`\$\{BUGSINK_HOST:-bugsink\.telecom\.quest\}`\)/); assert.match(b, /priority=100000/); }); test("cloudflared — только в профиле edge, токен файлом", () => { const c = block("cloudflared"); assert.match(c, /profiles: \[edge\]/); assert.match(c, /--token-file/); assert.match(c, /network_mode: host/); }); });