Cotton code
281 lines · 14.4 KB · TypeScriptRaw
/** * node and pnpm on the Mac lanes — provisioned by the lane, never by whoever * last sat at the machine. * * The `ios` job runs `pnpm install` on a check Mac, and a Mac's runner is the * app's own `forgejo-runner`: a job gets the login environment, whose PATH * carries Homebrew's bin and nothing a lockfile installs. Every Cotton PR * before #880 was docs-only, so that step had never run on a Mac; the first * one that did (run 26) died `pnpm: command not found`, and the fix was a hand * `brew install node@22 pnpm` on three machines. `scripts/ci/setup-pnpm.sh` is * the durable form, on `setup-sccache.sh`'s pattern — pinned, digest-checked, * fetched into the lane's HOME once — and this file holds it there: * *   - the workflow runs it on the `ios` job BEFORE the first `pnpm` step; *   - the pnpm pin is READ from `package.json`'s `packageManager`, and the *     script carries a checksum for exactly that version (a bumped pin with a *     stale table refuses rather than fetching something unchecked); *   - the node pin's MAJOR is `.nvmrc`'s, because `.nvmrc` names a major only; *   - both digests are checked with the same two-tool ladder as sccache's; *   - the lane's bin goes on THIS shell's PATH as well as `$GITHUB_PATH`. * * The script's fetch branch is exercised by hand (a throwaway HOME, PATH * without node); a vitest that downloads 50 MB from nodejs.org on every run is * a test of the network. What runs here is the refusal path, which needs no * network: a `packageManager` the table does not name. */import { spawn, spawnSync } from "node:child_process";import { existsSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync, utimesSync } from "node:fs";import { tmpdir } from "node:os";import { join, resolve } from "node:path";import { parse as parseYaml } from "yaml";import { afterEach, describe, expect, it } from "vitest";const ROOT = resolve(__dirname, "../..");const SCRIPT = join(ROOT, "scripts/ci/setup-pnpm.sh");const source = readFileSync(SCRIPT, "utf8");const packageJson = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")) as {  packageManager?: string;};const nvmrc = readFileSync(join(ROOT, ".nvmrc"), "utf8").trim();type Step = { name?: string; run?: string; if?: string };let scratch: string | undefined;afterEach(() => {  if (scratch) rmSync(scratch, { recursive: true, force: true });  scratch = undefined;});describe("setup-pnpm.sh — the pins", () => {  it("reads pnpm's version from package.json's packageManager rather than restating it", () => {    expect(source).toMatch(/"packageManager"/);    expect(source).not.toMatch(/pnpm_version=[0-9]/);  });  it("carries a checksum for exactly the pnpm that package.json pins", () => {    const pin = packageJson.packageManager?.match(/^pnpm@([0-9][^+]*)/)?.[1];    expect(pin, "package.json pins pnpm").toBeTruthy();    const table = [...source.matchAll(/^\s*([0-9]+\.[0-9]+\.[0-9]+)\)\s*$/gm)].map((m) => m[1]);    expect(table).toContain(pin);    const shas = [...source.matchAll(/^\s*pnpm_sha512=([0-9a-f]{128})\s*$/gm)].map((m) => m[1]);    expect(shas.length).toBe(table.length);  });  it("pins a node whose major is .nvmrc's", () => {    const version = source.match(/^node_version=([0-9]+)\.[0-9]+\.[0-9]+$/m)?.[1];    expect(version, "the script pins an exact node").toBeTruthy();    expect(version).toBe(nvmrc);  });  it("names a node asset and a published sha256 for the check Macs", () => {    expect(source).toMatch(/Darwin\/arm64\)/);    expect(source).toMatch(/node_asset="node-v\$node_version-darwin-arm64"/);    const shas = [...source.matchAll(/^\s*node_sha256=([0-9a-f]{64})\s*$/gm)].map((m) => m[1]);    expect(shas.length).toBeGreaterThanOrEqual(1);    expect(new Set(shas).size).toBe(shas.length);    expect(source).toMatch(/no pinned node \$node_version asset/);  });  it("checks both digests with the same two-tool ladder as sccache, and never falls through a bad one", () => {    expect(source).toMatch(/command -v "sha\$\{bits\}sum"/);    expect(source).toMatch(/shasum -a "\$bits" -c -/);    expect(source).toMatch(/set -euo pipefail/);    expect(source).not.toMatch(/\|\|\s*true/);  });  it("puts the lane's bin on THIS shell's PATH as well as $GITHUB_PATH, ahead of Homebrew", () => {    expect(source).toMatch(/echo "\$bin" >> "\$GITHUB_PATH"/);    expect(source).toMatch(/export PATH="\$bin:\$PATH"/);  });  it("runs pnpm's own entry point through the lane's node, not whatever node PATH finds", () => {    expect(source).toMatch(/exec "\$bin\/node" "\$pnpm_home\/package\/bin\/pnpm\.cjs"/);  });});describe("setup-pnpm.sh — the refusal", () => {  it("refuses a packageManager the checksum table does not name, before touching the network", () => {    scratch = mkdtempSync(join(tmpdir(), "setup-pnpm-"));    const root = join(scratch, "repo");    // The script resolves the repo root from its own path, so a copy of it in    // a scratch tree reads the scratch tree's package.json.    const ci = join(root, "scripts", "ci");    spawnSync("mkdir", ["-p", ci]);    writeFileSync(join(ci, "setup-pnpm.sh"), source);    writeFileSync(join(root, "package.json"), JSON.stringify({ packageManager: "pnpm@0.0.1" }, null, 2));    const home = join(scratch, "home");    spawnSync("mkdir", ["-p", home]);    const result = spawnSync("bash", [join(ci, "setup-pnpm.sh")], {      encoding: "utf8",      env: { HOME: home, PATH: "/usr/bin:/bin" },    });    expect(result.status).toBe(1);    expect(result.stderr).toMatch(/no checksum for pnpm 0\.0\.1/);    expect(result.stdout).not.toMatch(/fetching/);  });  it("refuses a package.json with no packageManager pin", () => {    scratch = mkdtempSync(join(tmpdir(), "setup-pnpm-"));    const root = join(scratch, "repo");    const ci = join(root, "scripts", "ci");    spawnSync("mkdir", ["-p", ci]);    writeFileSync(join(ci, "setup-pnpm.sh"), source);    writeFileSync(join(root, "package.json"), JSON.stringify({ name: "x" }, null, 2));    const result = spawnSync("bash", [join(ci, "setup-pnpm.sh")], {      encoding: "utf8",      env: { HOME: join(scratch, "home"), PATH: "/usr/bin:/bin" },    });    expect(result.status).toBe(1);    expect(result.stderr).toMatch(/no `"packageManager"/);  });});describe("setup-pnpm.sh — four jobs at once on one machine", () => {  /**   * PR #1026's `rust` job (2026-09-27) died in setup with   * `ln: …/node/bin/node: File exists`: the Linux box starts four jobs at   * once, each runs this script against the same `$root`, and `ln -sfn` is   * an unlink and then a link — the second job's link landed in the gap the   * first had just made. The script now takes a per-root lock and replaces   * each link by rename. THE RACE IS RUN, not read: N copies of the script at   * once against one scratch HOME, where the pinned node and pnpm are already   * "installed" as stubs so no network is touched, and every copy has to exit   * 0 with the links pointing at the pinned node afterwards.   */  function scratchHome(): { home: string; script: string; nodeVersion: string; pnpmVersion: string } {    scratch = mkdtempSync(join(tmpdir(), "setup-pnpm-race-"));    const repo = join(scratch, "repo");    const ci = join(repo, "scripts", "ci");    spawnSync("mkdir", ["-p", ci]);    writeFileSync(join(ci, "setup-pnpm.sh"), source);    writeFileSync(join(repo, "package.json"), JSON.stringify({ packageManager: packageJson.packageManager }, null, 2));    const nodeVersion = source.match(/^node_version=(\S+)/m)![1];    const pnpmVersion = packageJson.packageManager!.replace(/^pnpm@/, "").replace(/\+.*$/, "");    const asset = process.platform === "darwin" ? `node-v${nodeVersion}-darwin-arm64` : `node-v${nodeVersion}-linux-x64`;    const home = join(scratch, "home");    const root = join(home, ".cache", "cottondb", "node");    const nodeHome = join(root, asset, "bin");    const pnpmHome = join(root, `pnpm-${pnpmVersion}`, "package", "bin");    spawnSync("mkdir", ["-p", nodeHome, pnpmHome]);    // A node that answers its own version, and pnpm's when asked to run pnpm.cjs.    writeFileSync(      join(nodeHome, "node"),      `#!/usr/bin/env bash\ncase "$*" in *pnpm.cjs*) echo "${pnpmVersion}";; *) echo "v${nodeVersion}";; esac\n`,      { mode: 0o755 },    );    for (const name of ["npm", "npx"]) writeFileSync(join(nodeHome, name), "#!/usr/bin/env bash\nexit 0\n", { mode: 0o755 });    writeFileSync(join(pnpmHome, "pnpm.cjs"), "// stub\n");    return { home, script: join(ci, "setup-pnpm.sh"), nodeVersion, pnpmVersion };  }  it("every copy exits 0 and the links all point at the pinned node — no `File exists`", async () => {    const { home, script, nodeVersion } = scratchHome();    const env = { HOME: home, PATH: "/usr/bin:/bin", GITHUB_PATH: join(home, "github-path") };    // Four provisioners share the production 300s lock budget. Five seconds    // tested host speed at load 60–136; this guard tests serialization and links.    const runs = await Promise.all(      Array.from({ length: 4 }, () =>        new Promise<{ status: number | null; out: string }>((resolve) => {          const child = spawn("bash", [script], { env });          let out = "";          child.stdout.on("data", (d) => (out += d));          child.stderr.on("data", (d) => (out += d));          child.on("close", (status) => resolve({ status, out }));        }),      ),    );    for (const run of runs) {      expect(run.status, run.out).toBe(0);      expect(run.out).not.toMatch(/File exists/);    }    const bin = join(home, ".cache", "cottondb", "node", "bin");    for (const name of ["node", "npm", "npx"]) {      expect(readlinkSync(join(bin, name))).toMatch(new RegExp(`node-v${nodeVersion.replace(/\\./g, "\\\\.")}-[a-z0-9-]+/bin/${name}$`));    }    expect(readFileSync(join(bin, "pnpm"), "utf8")).toContain("pnpm.cjs");    // Nothing staged is left behind, and the lock is released.    expect(readdirSync(bin).filter((f) => f.startsWith("."))).toEqual([]);    expect(existsSync(join(home, ".cache", "cottondb", "node.lock"))).toBe(false);  }, 330000);  it("clears a lock whose holder is dead rather than waiting on it", () => {    const { home, script } = scratchHome();    const lock = join(home, ".cache", "cottondb", "node.lock");    spawnSync("mkdir", ["-p", lock]);    // A pid no process has: the largest pid_max on macOS is 99998 and on    // Linux 4194304; a dead holder is what a killed job leaves behind.    writeFileSync(join(lock, "pid"), "4194303\n");    const result = spawnSync("bash", [script], {      encoding: "utf8",      env: { HOME: home, PATH: "/usr/bin:/bin", GITHUB_PATH: join(home, "github-path"), COTTON_SETUP_LOCK_WAIT_S: "5" },    });    expect(result.status, result.stdout + result.stderr).toBe(0);    expect(existsSync(lock)).toBe(false);  });  it("gives up on a live holder after the wait, in words that say what to clear", () => {    const { home, script } = scratchHome();    const lock = join(home, ".cache", "cottondb", "node.lock");    spawnSync("mkdir", ["-p", lock]);    writeFileSync(join(lock, "pid"), `${process.pid}\n`);    const result = spawnSync("bash", [script], {      encoding: "utf8",      env: { HOME: home, PATH: "/usr/bin:/bin", GITHUB_PATH: join(home, "github-path"), COTTON_SETUP_LOCK_WAIT_S: "2" },    });    expect(result.status).toBe(1);    expect(result.stderr).toMatch(/waited 2s on \d+ lock at .*node\.lock/);    expect(result.stderr).toMatch(/clear the directory by hand/);  });  // RULE: A lock directory with no pid file that is older than the orphan window is a provisioner killed between mkdir and writing its pid, and the next comer clears it instead of waiting the whole wait and failing every job on the machine.  it("clears a lock that has had no owner for the orphan window", () => {    const { home, script } = scratchHome();    const lock = join(home, ".cache", "cottondb", "node.lock");    spawnSync("mkdir", ["-p", lock]);    // Born a minute ago, never claimed.    const minuteAgo = new Date(Date.now() - 60_000);    utimesSync(lock, minuteAgo, minuteAgo);    const result = spawnSync("bash", [script], {      encoding: "utf8",      env: { HOME: home, PATH: "/usr/bin:/bin", GITHUB_PATH: join(home, "github-path"), COTTON_SETUP_LOCK_WAIT_S: "5", COTTON_SETUP_LOCK_ORPHAN_S: "30" },    });    expect(result.status, result.stdout + result.stderr).toBe(0);    expect(result.stdout).toMatch(/clearing a lock at .*node\.lock that has had no owner for 30s/);    expect(existsSync(lock)).toBe(false);  });  // RULE: A pidless lock YOUNGER than the orphan window is a holder mid-write and is waited on, not cleared — the reclaim never takes a lock a live provisioner made a moment ago.  it("waits on a fresh pidless lock rather than taking it", () => {    const { home, script } = scratchHome();    const lock = join(home, ".cache", "cottondb", "node.lock");    spawnSync("mkdir", ["-p", lock]);    const result = spawnSync("bash", [script], {      encoding: "utf8",      env: { HOME: home, PATH: "/usr/bin:/bin", GITHUB_PATH: join(home, "github-path"), COTTON_SETUP_LOCK_WAIT_S: "2", COTTON_SETUP_LOCK_ORPHAN_S: "30" },    });    expect(result.status).toBe(1);    expect(result.stderr).toMatch(/waited 2s on an ownerless lock at .*node\.lock/);    expect(existsSync(lock)).toBe(true);  });  // RULE: node and pnpm are unpacked into a private sibling and renamed into place, so their directories are whole or absent — never half a tarball at the pinned name after a killed job.  it("unpacks node and pnpm beside their names and renames them into place", () => {    expect(source).not.toMatch(/tar xzf "\$tmp\/node\.tar\.gz" -C "\$root"$/m);    expect(source).toMatch(/tar xzf "\$tmp\/node\.tar\.gz" -C "\$staged"/);    expect(source).toMatch(/mv "\$staged\/\$node_asset" "\$node_home"/);    expect(source).not.toMatch(/tar xzf "\$tmp\/pnpm\.tgz" -C "\$pnpm_home"/);    expect(source).toMatch(/tar xzf "\$tmp\/pnpm\.tgz" -C "\$staged"/);    expect(source).toMatch(/mv "\$staged" "\$pnpm_home"/);    // The unpacked node is checked BEFORE it takes the name.    expect(source).toMatch(/node_usable "\$staged\/\$node_asset\/bin\/node"\n\s*rm -rf "\$node_home"\n\s*mv/);  });  it("links by rename, never by unlink-then-link", () => {    expect(source).not.toMatch(/^\s*ln -sfn "\$node_home/m);    expect(source).toMatch(/link_into_bin node "\$node_home\/bin\/node"/);    expect(source).toMatch(/mv -f "\$staged" "\$bin\/\$name"/);    expect(source).toMatch(/with_setup_lock provision/);  });});