Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"test": "node scripts/validation.mjs all",
"test:backend": "node scripts/validation.mjs backend",
"test:browser": "node scripts/validation.mjs browser",
"test:proxy": "node scripts/validation.mjs proxy",
"check": "npm test",
"bootstrap:test": "node scripts/bootstrap-test.mjs",
"check:backend": "npm run check:hosting && npm run check:boundaries && npm run check:client && npm run validate --workspace=factorize-docs && npm run check --workspace=factorize && npm run test:conditions-runtime && npm run test:hosting-runtime && npm run test:oauth-runtime && npm run test:rollback-runtime && npm run check --workspace=factorize-marketing && npm run check --workspace=factorize-tail-relay",
Expand Down
108 changes: 108 additions & 0 deletions scripts/portable-proxy-test-helpers.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { createServer } from "node:http";
import { spawn } from "node:child_process";
import process from "node:process";

const signalNumber = (signal) => ({
SIGHUP: 1,
SIGINT: 2,
SIGQUIT: 3,
SIGKILL: 9,
SIGTERM: 15,
})[signal] ?? 1;

function signalTree(child, signal) {
if (child.pid === undefined) return;
try {
if (process.platform !== "win32") process.kill(-child.pid, signal);
else child.kill(signal);
} catch (error) {
if (error.code !== "ESRCH") throw error;
}
}

/** Run a subprocess with a deadline, abort support, and process-group cleanup. */
export function runProcess(command, args = [], {
timeoutMs,
signal,
cwd,
env = process.env,
onSpawn,
onOutput,
} = {}) {
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new RangeError("timeoutMs must be positive");

return new Promise((resolve) => {
const child = spawn(command, args, {
cwd,
env,
detached: process.platform !== "win32",
stdio: ["ignore", "pipe", "pipe"],
});
let cause;
let forceKill;
let finished = false;
let childError;
let closed;

const cleanup = () => {
clearTimeout(deadline);
clearTimeout(forceKill);
signal?.removeEventListener("abort", abort);
};
const finish = (result) => {
if (finished) return;
finished = true;
cleanup();
resolve(result);
};
const terminate = (reason) => {
if (cause) return;
cause = reason;
signalTree(child, "SIGTERM");
forceKill = setTimeout(() => {
try { signalTree(child, "SIGKILL"); } catch (error) { childError ??= error; }
forceKill = undefined;
if (closed) complete();
}, 500);
};
const abort = () => terminate(signal.reason || "SIGTERM");
const deadline = setTimeout(() => terminate("timeout"), timeoutMs);

child.stdout.on("data", (chunk) => onOutput?.("stdout", chunk));
child.stderr.on("data", (chunk) => onOutput?.("stderr", chunk));
child.once("spawn", () => {
onSpawn?.(child);
if (signal?.aborted) abort();
});
child.once("error", (error) => { childError = error; });
const complete = () => {
if (!closed) return;
const { code, signal: childSignal } = closed;
if (cause === "timeout") finish({ code: 124, signal: childSignal, timedOut: true, error: childError });
else if (cause) finish({ code: 128 + signalNumber(cause), signal: cause, aborted: true, error: childError });
else finish({ code: childError ? 127 : (code ?? 1), signal: childSignal, error: childError });
};
child.once("close", (code, childSignal) => {
closed = { code, signal: childSignal };
if (!forceKill) complete();
});
signal?.addEventListener("abort", abort, { once: true });
});
}

/** Bind a local HTTP server to an OS-selected port for isolated tests. */
export async function createEphemeralHttpServer(handler, host = "127.0.0.1") {
const server = createServer(handler);
await new Promise((resolve, reject) => {
server.once("error", reject);
server.listen(0, host, resolve);
});
const address = server.address();
if (!address || typeof address === "string") throw new Error("Could not determine ephemeral server port");
return {
server,
port: address.port,
origin: `http://${host}:${address.port}`,
close: () => new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve())),
};
}
84 changes: 84 additions & 0 deletions scripts/validation-runner.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import process from "node:process";
import { createEphemeralHttpServer, runProcess } from "./portable-proxy-test-helpers.mjs";

const runNode = (source, options) => runProcess(process.execPath, ["--input-type=module", "-e", source], options);

function processIsRunning(pid) {
try {
process.kill(pid, 0);
if (process.platform === "linux") {
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
if (stat.slice(stat.lastIndexOf(")") + 2).startsWith("Z ")) return false;
}
return true;
} catch (error) {
if (error.code === "ESRCH") return false;
throw error;
}
}

test("subprocess exits normally and propagates its exit code", async () => {
const result = await runNode("process.exit(0)", { timeoutMs: 2_000 });
assert.equal(result.code, 0);
assert.equal(result.timedOut, undefined);
});

test("deadline fails and removes a hung child and grandchild process tree", async () => {
const source = `
const { spawn } = await import('node:child_process');
const grandchild = spawn(process.execPath, ['-e', "console.log('GRANDCHILD_READY ' + process.pid); setInterval(() => {}, 1000)"], { stdio: ['ignore', 'inherit', 'inherit'] });
console.log('CHILD_READY ' + process.pid);
setInterval(() => {}, 1000);
`;
const pids = {};
const result = await runNode(source, {
timeoutMs: 1_500,
onOutput: (_stream, chunk) => {
for (const line of chunk.toString().split("\n")) {
const match = /^(CHILD_READY|GRANDCHILD_READY) (\d+)$/.exec(line.trim());
if (match) pids[match[1]] = Number(match[2]);
}
},
});

assert.equal(result.code, 124);
assert.equal(result.timedOut, true);
assert.ok(pids.CHILD_READY, "child started before the deadline");
assert.ok(pids.GRANDCHILD_READY, "grandchild started before the deadline");
assert.equal(processIsRunning(pids.CHILD_READY), false, "child was reaped");
assert.equal(processIsRunning(pids.GRANDCHILD_READY), false, "grandchild was reaped");
});

test("abort signal stops the process tree and reports signal failure", async () => {
const controller = new AbortController();
let pid;
const result = await runNode("setInterval(() => {}, 1000)", {
timeoutMs: 5_000,
signal: controller.signal,
onSpawn: (child) => {
pid = child.pid;
controller.abort("SIGTERM");
},
});
assert.equal(result.code, 143);
assert.equal(result.aborted, true);
assert.equal(result.signal, "SIGTERM");
assert.equal(processIsRunning(pid), false);
});

test("ephemeral HTTP helper binds a reachable OS-selected local port", async () => {
const server = await createEphemeralHttpServer((_request, response) => {
response.writeHead(200, { "content-type": "text/plain" }).end("ready");
});
try {
assert.ok(server.port > 0);
const response = await fetch(server.origin, { signal: AbortSignal.timeout(3_000) });
assert.equal(response.status, 200);
assert.equal(await response.text(), "ready");
} finally {
await server.close();
}
});
87 changes: 58 additions & 29 deletions scripts/validation.mjs
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import { spawn } from "node:child_process";
import { access } from "node:fs/promises";
import process from "node:process";
import { runProcess } from "./portable-proxy-test-helpers.mjs";

const lane = process.argv[2] ?? "all";
const expectedNode = "24.12.0";
const suiteTimeoutMs = 540_000;
const lanes = {
backend: [
["generated contracts", "npm", ["run", "generate"]],
["generated contract drift", "git", ["diff", "--exit-code", "--", "packages/docs/openapi.yaml", "packages/api-client/src/schema.d.ts"]],
["application build", "npm", ["run", "build", "--workspace=factorize-app"]],
["backend checks", "npm", ["run", "check:backend"]],
["compiled app/API/PostgreSQL integration", "npm", ["run", "test:static-slice", "--workspace=factorize"]],
["generated contracts", "npm", ["run", "generate"], 90_000],
["generated contract drift", "git", ["diff", "--exit-code", "--", "packages/docs/openapi.yaml", "packages/api-client/src/schema.d.ts"], 15_000],
["application build", "npm", ["run", "build", "--workspace=factorize-app"], 90_000],
["backend checks", "npm", ["run", "check:backend"], 240_000],
["compiled app/API/PostgreSQL integration", "npm", ["run", "test:static-slice", "--workspace=factorize"], 90_000],
],
browser: [
["application build", "npm", ["run", "build", "--workspace=factorize-app"]],
["Chromium availability", process.execPath, ["scripts/validation.mjs", "--check-chromium"]],
["functional browser checks", "npm", ["run", "test:functional", "--workspace=factorize-app"]],
["application unit checks", "npm", ["test", "--workspace=factorize-app"]],
["application build", "npm", ["run", "build", "--workspace=factorize-app"], 90_000],
["Chromium availability", process.execPath, ["scripts/validation.mjs", "--check-chromium"], 15_000],
["functional browser checks", "npm", ["run", "test:functional", "--workspace=factorize-app"], 90_000],
["application unit checks", "npm", ["test", "--workspace=factorize-app"], 180_000],
],
proxy: [["portable proxy harness checks", process.execPath, ["--test", "scripts/validation-runner.test.mjs"], 30_000]],
};

if (lane === "--check-chromium") {
Expand All @@ -31,46 +33,73 @@ if (lane === "--check-chromium") {
process.exit(0);
}

if (!["all", "backend", "browser"].includes(lane)) {
console.error(`Unknown validation lane: ${lane}. Use all, backend, or browser.`);
if (!["all", "backend", "browser", "proxy"].includes(lane)) {
console.error(`Unknown validation lane: ${lane}. Use all, backend, browser, or proxy.`);
process.exit(2);
}

const results = [];
const run = (name, command, args) => new Promise((resolve) => {
const child = spawn(command, args, { stdio: "inherit", env: process.env });
child.on("error", (error) => { console.error(`${name}: ${error.message}`); resolve(127); });
child.on("exit", (code, signal) => resolve(code ?? (signal ? 1 : 0)));
});
const cancellation = new AbortController();
let receivedSignal;
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
process.once(signal, () => {
receivedSignal = signal;
console.error(`Validation interrupted by ${signal}; stopping the active process tree.`);
cancellation.abort(signal);
});
}
const suiteDeadline = setTimeout(() => {
console.error("Validation exceeded its 540 second suite deadline.");
cancellation.abort("timeout");
}, suiteTimeoutMs);

const run = async (name, command, args, timeoutMs) => {
const result = await runProcess(command, args, {
timeoutMs,
signal: cancellation.signal,
onOutput: (stream, chunk) => (stream === "stderr" ? process.stderr : process.stdout).write(chunk),
});
if (result.timedOut) console.error(`${name}: exceeded its ${timeoutMs}ms deadline; process tree stopped.`);
else if (result.aborted) console.error(`${name}: stopped after ${result.signal}.`);
else if (result.error) console.error(`${name}: ${result.error.message}`);
return result.code;
};

if (!/^v?24\.(1[2-9]|[2-9][0-9])\./.test(process.version)) {
console.error(`Node ${expectedNode} or newer in the 24.x line is required; found ${process.version}. Recover with: nvm install ${expectedNode} && nvm use ${expectedNode} && npm ci`);
process.exit(1);
}

if (lane !== "browser") {
if (lane === "all" || lane === "backend") {
const missing = ["DATABASE_URL", "AUTH_TEST_DATABASE_URL", "QUEUE_TEST_DATABASE_URL"].filter((name) => !process.env[name]);
if (missing.length) {
console.error(`Backend validation requires an isolated PostgreSQL database (${missing.join(", ")}). Recover with: npm run bootstrap:test`);
process.exit(1);
}
}

const selected = lane === "all" ? ["backend", "browser"] : [lane];
for (const selectedLane of selected) {
console.log(`\n=== ${selectedLane} validation ===`);
for (const [name, command, args] of lanes[selectedLane]) {
const code = await run(name, command, args);
results.push({ lane: selectedLane, name, status: code === 0 ? "passed" : "failed" });
if (code !== 0) {
for (const pending of lanes[selectedLane].slice(results.filter((item) => item.lane === selectedLane).length)) {
results.push({ lane: selectedLane, name: pending[0], status: "not run" });
const selected = lane === "all" ? ["backend", "browser", "proxy"] : [lane];
try {
for (const selectedLane of selected) {
console.log(`\n=== ${selectedLane} validation ===`);
for (const [name, command, args, timeoutMs] of lanes[selectedLane]) {
const code = await run(name, command, args, timeoutMs);
results.push({ lane: selectedLane, name, status: code === 0 ? "passed" : "failed" });
if (code !== 0) {
for (const pending of lanes[selectedLane].slice(results.filter((item) => item.lane === selectedLane).length)) {
results.push({ lane: selectedLane, name: pending[0], status: "not run" });
}
break;
}
break;
if (cancellation.signal.aborted) break;
}
if (cancellation.signal.aborted) break;
}
} finally {
clearTimeout(suiteDeadline);
}

console.log("\n=== validation summary ===");
for (const result of results) console.log(`${result.status.padEnd(8)} ${result.lane}: ${result.name}`);
if (results.some(({ status }) => status === "failed" || status === "not run")) process.exit(1);
if (receivedSignal) process.exit(128 + ({ SIGHUP: 1, SIGINT: 2, SIGTERM: 15 })[receivedSignal]);
if (results.some(({ status }) => status === "failed" || status === "not run") || cancellation.signal.aborted) process.exit(1);
Loading