Repository Public
1#!/usr/bin/env node2// End-to-end harness. Creates a throw-away database, starts the real Go control-api (127.0.0.1:8750, origin3// http://localhost:8750) in front of the built Next app (8753), bootstraps the owner with mccctl, runs Playwright,4// then stops what it started (by PID) and drops the database.5// pnpm e2e full run (rebuilds the Go binaries and the web app first)6// pnpm e2e -- --grep sse extra arguments go to Playwright7// MCC_E2E_SKIP_BUILD=1 reuse existing binaries and .next output8// MCC_E2E_SCREENSHOTS=1 also (re)generate docs/screenshots/web9import { execFileSync, spawn } from "node:child_process";10import { existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";11import { tmpdir } from "node:os";12import { dirname, join, resolve } from "node:path";13import { fileURLToPath } from "node:url";14import { randomBytes } from "node:crypto";1516const here = dirname(fileURLToPath(import.meta.url));17const web = resolve(here, "..");18const repo = resolve(web, "../..");19const BIN = "/tmp/mcc-web";20const API_PORT = 8750;21const WEB_PORT = 8753;22const ORIGIN = `http://localhost:${API_PORT}`;23const db = `mcc_e2e_${randomBytes(4).toString("hex")}`;24const dbUrl = `postgres://127.0.0.1/${db}?sslmode=disable`;25const secrets = mkdtempSync(join(tmpdir(), "mcc-e2e-secrets-"));26const stateFile = join(web, "test-results", "e2e-state.json");27const logDir = join(web, "test-results", "logs");28const skipBuild = process.env.MCC_E2E_SKIP_BUILD === "1";2930const log = (m) => console.log(`[e2e] ${m}`);31const sh = (cmd, args, opts = {}) => execFileSync(cmd, args, { stdio: ["ignore", "pipe", "pipe"], encoding: "utf8", ...opts });3233const apiEnv = {34 ...process.env,35 MCC_ENV: "dev",36 MCC_DATABASE_URL: dbUrl,37 MCC_SECRETS_DIR: secrets,38 MCC_API_LISTEN: `127.0.0.1:${API_PORT}`,39 MCC_PUBLIC_ORIGIN: ORIGIN,40 MCC_RP_ID: "localhost",41 MCC_WEB_UPSTREAM: `http://127.0.0.1:${WEB_PORT}`,42};4344const pids = new Set();45function start(name, cmd, args, env, cwd) {46 mkdirSync(logDir, { recursive: true });47 const out = openSync(join(logDir, `${name}.log`), "a");48 const child = spawn(cmd, args, { env, cwd, stdio: ["ignore", out, out] });49 pids.add(child.pid);50 child.on("exit", () => pids.delete(child.pid));51 return child;52}53async function waitFor(url, what, ms = 60_000) {54 const end = Date.now() + ms;55 for (;;) {56 try {57 const r = await fetch(url, { redirect: "manual" });58 if (r.status < 500) return;59 } catch { /* not up yet */ }60 if (Date.now() > end) throw new Error(`${what} did not answer at ${url}`);61 await new Promise((r) => setTimeout(r, 250));62 }63}64function portBusy(port) {65 try {66 return sh("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"]).trim() !== "";67 } catch {68 return false;69 }70}7172let code = 1;73try {74 for (const p of [API_PORT, WEB_PORT]) if (portBusy(p)) throw new Error(`port ${p} is already in use`);75 mkdirSync(dirname(stateFile), { recursive: true });76 rmSync(logDir, { recursive: true, force: true });7778 if (!skipBuild) {79 log("building control-api and mccctl");80 try {81 mkdirSync(BIN, { recursive: true });82 sh("go", ["build", "-o", `${BIN}/control-api`, "./cmd/control-api"], { cwd: join(repo, "services") });83 sh("go", ["build", "-o", `${BIN}/mccctl`, "./cmd/mccctl"], { cwd: join(repo, "services") });84 } catch (e) {85 if (!existsSync(`${BIN}/control-api`)) throw e;86 log(`WARNING: backend build failed, reusing the previous binaries\n${String(e.stderr ?? e).slice(0, 2000)}`);87 }88 log("building the web app");89 sh("pnpm", ["build"], { cwd: web });90 }91 if (!existsSync(join(web, ".next/standalone/apps/web/server.js"))) throw new Error("web build missing: run pnpm build");9293 log(`database ${db}`);94 sh("createdb", ["-h", "127.0.0.1", db]);9596 start("web", process.execPath, [join(web, "scripts/start.mjs")], { ...process.env, MCC_WEB_PORT: String(WEB_PORT) }, web);97 const api = start("control-api", `${BIN}/control-api`, [], apiEnv, repo);98 await waitFor(`${ORIGIN}/api/v1/health/ready`, "control-api");99 await waitFor(`${ORIGIN}/signin`, "web through control-api");100101 const boot = sh(`${BIN}/mccctl`, ["bootstrap-owner", "--handle", "e2e-owner", "--name", "E2E Owner"], { env: apiEnv });102 const setupUrl = boot.match(/https?:\/\/\S+\/setup#\S+/)?.[0];103 if (!setupUrl) throw new Error("mccctl did not print a setup link");104105 writeFileSync(stateFile, JSON.stringify({ origin: ORIGIN, db, dbUrl, ownerSetupUrl: setupUrl, apiPid: api.pid, apiBin: `${BIN}/control-api`, apiEnv: Object.fromEntries(Object.entries(apiEnv).filter(([k]) => k.startsWith("MCC_"))), logDir }, null, 2), { mode: 0o600 });106107 log("running Playwright");108 const pw = spawn(join(web, "node_modules/.bin/playwright"), ["test", "--config", join(web, "playwright.config.ts"), ...process.argv.slice(2)], {109 cwd: web,110 stdio: "inherit",111 env: { ...process.env, MCC_E2E_STATE: stateFile, MCC_E2E_ORIGIN: ORIGIN },112 });113 code = await new Promise((r) => pw.on("exit", (c) => r(c ?? 1)));114} catch (e) {115 console.error(`[e2e] ${e.stack ?? e}`);116 code = 1;117} finally {118 // a spec may have restarted control-api: its current PID is in the state file119 try {120 const s = JSON.parse(readFileSync(stateFile, "utf8"));121 if (s.apiPid) pids.add(s.apiPid);122 } catch { /* no state */ }123 for (const pid of pids) {124 try { process.kill(pid, "SIGTERM"); } catch { /* already gone */ }125 }126 await new Promise((r) => setTimeout(r, 800));127 try { sh("dropdb", ["-h", "127.0.0.1", "--if-exists", "--force", db]); log(`dropped ${db}`); } catch (e) { console.error(`[e2e] could not drop ${db}: ${e.message}`); }128 rmSync(secrets, { recursive: true, force: true });129 rmSync(stateFile, { force: true });130}131process.exit(code);132