/** * A TEST NEVER INVENTS A PORT. It asks the OS for one. * * Four fixtures under `apps/cotton-mac/__tests__` each computed their own port * from randomness and wrote it into an env file. A number chosen before the * bind is not a free port, it is a guess that two parallel test files * eventually make the same way — main's push run went red twice in three * merges over it, in two different files, and both times the message was about * sharing: the losing `startServer` threw EADDRINUSE, the Mac's controller * caught it (right, for a menu-bar app), and the fixture reported a missing * `deps`. * * The two spellings that do not guess: * - `PORT=0`, which the server reads as "take an ephemeral one" and reports * back as the port it actually bound (`RunningServer.port`); and * - a port the OS has just issued and released, for the fixtures that have * to NAME a port (the same one twice, or one that can go in a URL). That * was `reservedPort()` in the Mac's own test helpers; those fixtures went * with the Electron tree in step 3g and the Swift app's successors ask * through `PORT=0`, so the spelling now lives wherever the next fixture * needs it — the RULE is what this guard holds, not one helper. * * WHAT THIS LOOKS FOR is not one function. Keying on `Math.random()` caught the * spelling that happened and missed the likelier next ones — `crypto.randomInt` * is what somebody reaching for a *better* random reaches for, and the clock and * the pid are the two oldest port hacks in test fixtures. So the rule is the * shape: **a number derived from randomness, the clock or the process id * flowing into a port**, within a window that crosses lines, because two lines * is not an exotic spelling — it is what happens the moment the base is named. * * ABOUT THIS FILE'S OWN TEXT: the sweep searches every `__tests__` tree, this * one included, so the samples below are ASSEMBLED from fragments rather than * written out. Exempting this path would be the wrong fix — a path exemption is * a hole the next file can be moved into — and the last test here proves the * construction worked by running the sweep over this file's own text. * * THE SWIFT HALF is the second `describe` below, and it is the SAME rule with a * different way of being broken. The apps' fixtures do not compute a port at * all — they hand the server a data directory, and the port comes out of the * `env` file in it. A fixture that writes no `env` file has not asked for an * ephemeral port: it has taken `DEFAULT_PORT` (8790), which is a fixed port by * omission. `testAFirstRunStartsItsServerAndAnswersNoDatabase` did exactly that * — the `PORT=0` was in a helper every OTHER test in the file remembered to * call — and two PRs' runs (#731, #737) died of "Address already in use" the * moment a second suite ran on the same Mac. So the Swift rule is about WHERE * the seeding lives, not about a number: a fixture that starts the server * writes `PORT=0` from its `setUp`, where nothing has to remember it. */ import { execFileSync } from "node:child_process"; import { readFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); /** * Where a number that is not a port comes from. * * Assembled, so this file is not itself an offender by its letter. Each entry * is the text as it would be written. */ const SOURCES = [ "Math." + "random(", "crypto." + "randomInt(", "randomInt(", "Date." + "now(", "process." + "pid", "process." + "hrtime", "performance." + "now(", ]; /** * A port being SET — an assignment or an object key, not a mention. * * "names a port" is far too wide: a media test says `port` in a URL and a * timestamp test says the clock, and neither is this bug. What makes it this * bug is a derived number BECOMING a port. */ const ASSIGNS = [ String.raw`(^|[^A-Za-z])[Pp][Oo][Rr][Tt]\s*[:=]`, String.raw`[a-z]Port\s*[:=]`, String.raw`[Pp][Oo][Rr][Tt]=\$\{`, ]; const ASSIGN = new RegExp(ASSIGNS.join("|")); /** * EMPTY, and it should stay that way: there is no fixture that needs a port * nothing issued. An entry would be a path relative to the repo root, never a * prefix, and would need a reason better than "it usually works". */ const ALLOWED = new Set([]); /** Every tracked or untracked file under a `__tests__` tree — `scripts/__tests__` included. */ function testFiles(): string[] { return execFileSync("git", ["ls-files", "--cached", "--others", "--exclude-standard"], { cwd: REPO_ROOT, encoding: "utf8", maxBuffer: 32 * 1024 * 1024, }) .split("\n") .filter((path) => path.includes("__tests__/") && /\.(ts|tsx|js|mjs)$/.test(path)); } const hasSource = (text: string): boolean => SOURCES.some((source) => text.includes(source)); /** The rest of the statement a match opens: to the next `;`, `,` at a line end, or newline. */ function rhsAfter(text: string, from: number): string { const slice = text.slice(from, from + 400); const end = slice.search(/;|,\s*\n|\n/); return end === -1 ? slice : slice.slice(0, end); } /** * Names bound to a derived number — a declaration whose right-hand side reaches * one of the sources above. * * The two-line form is not an exotic spelling, it is what happens the moment * the base is named, so a port built out of one of these is the same bug as a * port built inline. Proximity alone was tried first and is too wide: a fixture * that reads the clock ten lines from a port it got honestly is not this bug. */ function derivedNames(text: string): string[] { const names: string[] = []; const declaration = /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/g; for (let match = declaration.exec(text); match !== null; match = declaration.exec(text)) { if (hasSource(rhsAfter(text, match.index + match[0].length))) names.push(match[1]); } return names; } /** Does this text derive a number and turn it into a port? */ export function invents(text: string): boolean { const derived = derivedNames(text); const assign = new RegExp(ASSIGNS.join("|"), "g"); for (let match = assign.exec(text); match !== null; match = assign.exec(text)) { const rhs = rhsAfter(text, match.index + match[0].length); if (hasSource(rhs)) return true; // `(? new RegExp(String.raw`(? !ALLOWED.has(path) && invents(readFileSync(join(REPO_ROOT, path), "utf8"))); } describe("no test invents a port", () => { // RULE: A test never picks a port number: it asks for port zero and reads back the port it was given. it("no fixture derives a port from randomness, the clock or the pid", () => { const found = offenders(); expect( found, `these fixtures compute a port instead of asking for one — write PORT=0, or take one from reservedPort():\n ${found.join("\n ")}`, ).toEqual([]); }); it("searches `scripts/__tests__/` too — the tree turbo never sees, and where this guard itself lives", () => { // The first version's pathspec was `scripts/**/__tests__/**`, which git // reads as wanting a directory in between: it reached `scripts/*/__tests__` // and nothing else, so `scripts/__tests__/` — where every script test in // this repo lives — was not searched at all. The proof was this guard's own // file, which spelled the offending line in full and passed. const files = testFiles(); expect(files).toContain("scripts/__tests__/no-invented-port.test.ts"); expect(files.some((path) => path.startsWith("apps/"))).toBe(true); }); it("catches every spelling of the shape, on one line or across three", () => { const P = "p" + "ort"; const rand = "Math." + "random()"; const samples = [ `const ${P} = 20000 + Math.floor(${rand} * 20000);`, `${P.toUpperCase()}: 20000 + Math.floor(${rand} * 20000),`, `const server${P[0].toUpperCase()}${P.slice(1)} = Math.floor(${rand} * 1000);`, `const ${P} = ` + "randomInt(" + "20000, 40000);", `const ${P} = ` + "crypto.randomInt(" + "20000, 40000);", `const ${P} = 20000 + (` + "Date.now()" + ` % 20000);`, `const ${P} = 20000 + (` + "process.pid" + ` % 1000);`, // The two-line form, which the line-oriented first version could not see. `const base = 20000;\nconst spread = Math.floor(${rand} * 20000);\nconst ${P} = base + spread;`, // And the one that writes it straight into the env file. "writeFileSync(envPath, `" + P.toUpperCase() + "=${20000 + Math.floor(" + rand + " * 20000)}`);", ]; for (const sample of samples) expect(invents(sample), sample).toBe(true); }); it("stays silent on legitimate arithmetic, which is the half worth keeping", () => { // The rule has to survive the things fixtures ACTUALLY do with randomness // and the clock. A guard that goes red on retry jitter gets an allow-list // entry, then another, and then it is a list rather than a rule. Each of // these was run against the sweep before it was written down. const rand = "Math." + "random()"; const clock = "Date." + "now()"; const pid = "process." + "pid"; for (const [what, sample] of [ ["retry jitter", `const jitter = Math.floor(${rand} * 250);\nawait sleep(backoffMs + jitter);`], ["exponential backoff beside a port", `const delay = Math.min(30_000, 2 ** attempt * 500) + ${rand} * 100;\nconst ${"p" + "ort"} = await reservedPort();`], ["a generated id", `const id = \`note-\${${clock}}-\${${rand}.toString(36).slice(2)}\`;`], ["a shuffle", `const shuffled = rows.sort(() => ${rand} - 0.5);\nconst ${"p" + "ort"} = 8790;`], ["a clock reading next to a port that was asked for", `const ${"p" + "ort"} = await reservedPort();\nconst startedAt = ${clock};`], ["a pid in a temp directory name", `const dir = mkdtempSync(join(tmpdir(), \`run-\${${pid}}-\`));\nconst ${"p" + "ort"} = 0;`], ["a URL that carries a port it did not invent", `const url = \`http://127.0.0.1:\${${"p" + "ort"}}/health\`;\nconst at = ${clock};`], ["a deadline beside a bound port", `const deadline = ${clock} + 5000;\nconst ${"p" + "ort"} = controller.status().port;`], ["the word inside another word", "const passport = issuePassport();"], ["a coin flip", `const support = ${rand} > 0.5;`], ] as const) { expect(invents(sample), what).toBe(false); } }); it("is not itself an offender — the samples above are assembled, not written", () => { // The construction, checked rather than asserted in a comment. If a future // edit spells one of these shapes out in full, this goes red HERE with a // sentence, rather than in the sweep above with a confusing self-report. expect(invents(readFileSync(join(REPO_ROOT, "scripts/__tests__/no-invented-port.test.ts"), "utf8"))).toBe(false); }); });