Cotton code
103 lines · 6.2 KB · TypeScriptRaw
import { execFileSync, spawnSync } from "node:child_process";import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join, resolve } from "node:path";import { afterEach, expect, it } from "vitest";const script = resolve("scripts/cargo-target-guard.sh");const selector = resolve("scripts/ci/cargo-target-dir.sh");const made: string[] = [];const old = new Date("2020-01-01T00:00:00Z");function scratch() { const dir = mkdtempSync(join(tmpdir(), "shared-cargo-")); made.push(dir); return dir; }afterEach(() => { for (const dir of made.splice(0)) rmSync(dir, { recursive: true, force: true }); });function tree(contents = "pub fn value() -> u8 { 1 }\n") {  const root = scratch();  execFileSync("git", ["init", "-q"], { cwd: root });  mkdirSync(join(root, "scripts"), { recursive: true });  copyFileSync(script, join(root, "scripts/cargo-target-guard.sh"));  mkdirSync(join(root, "scripts/ci"));  copyFileSync(resolve("scripts/ci/with-cargo-lock.sh"), join(root, "scripts/ci/with-cargo-lock.sh"));  // with-cargo-lock.sh reads its caller's parent chain through the build policy.  mkdirSync(join(root, "scripts/lib"));  copyFileSync(resolve("scripts/lib/mac_disk_policy.py"), join(root, "scripts/lib/mac_disk_policy.py"));  const source = join(root, "crates/example/src/lib.rs");  mkdirSync(dirname(source), { recursive: true });  writeFileSync(source, contents); utimesSync(source, old, old);  return { root, source };}function guard(root: string, target: string, held = true, args: string[] = []) {  return spawnSync("bash", [join(root, "scripts/cargo-target-guard.sh"), ...args], {    cwd: root, encoding: "utf8", env: { ...process.env, CARGO_TARGET_DIR: target,      COTTON_CARGO_LOCK_HELD: held ? `${target}.lock` : "" },  });}// RULE: The build lock serializes shared-target compiles; every lane uses one target so a new worktree reuses the machine's warm dependencies.it("selects the same shared target for unrelated refs", () => {  const home = scratch();  const select = (ref: string) => execFileSync("bash", [selector, ref], { encoding: "utf8", env: { ...process.env, HOME: home } }).trim();  expect(select("main")).toBe(join(home, ".cache/cottondb/cargo-target/shared"));  expect(select("lane/other")).toBe(select("main"));});// RULE: Serialization prevents overlapping compiles; equal source contents share a freshness epoch across trees, while changed inputs invalidate older artifacts without wiping the cache.it("shares a freshness epoch across equal trees and advances it for changed inputs", () => {  const target = join(scratch(), "shared"); mkdirSync(target);  const artifact = join(target, "keep.rlib"); writeFileSync(artifact, "warm");  const first = tree(), same = tree(), changed = tree("pub fn value() -> u8 { 2 }\n");  expect(guard(first.root, target).status).toBe(0);  const warmed = statSync(first.source).mtimeMs;  expect(guard(first.root, target).status).toBe(0);  expect(statSync(first.source).mtimeMs).toBe(warmed);  expect(guard(same.root, target).status).toBe(0);  expect(statSync(same.source).mtimeMs).toBe(warmed);  expect(guard(changed.root, target).status).toBe(0);  expect(statSync(changed.source).mtimeMs).toBeGreaterThan(warmed);  expect(readFileSync(artifact, "utf8")).toBe("warm");  expect(guard(first.root, target).status).toBe(0);  expect(statSync(first.source).mtimeMs).toBeGreaterThan(old.getTime());});// RULE: Shared-target source preparation runs inside the same lock as the compile, so another lane cannot replace its freshness marker in between.it("refuses preparation without the shared target lock", () => {  const { root } = tree();  const result = guard(root, join(scratch(), "shared"), false);  expect(result.status).not.toBe(0);  expect(result.stderr).toMatch(/lock/);});// RULE: Nested Cargo commands borrow only a live ancestor's same-target lock, so FFI and build wrappers cannot deadlock on themselves or trust a daemon's stale marker.it("prepares under the lock and re-enters it for a nested command", () => {  const { root } = tree();  const target = join(scratch(), "shared");  const own = join(root, "scripts/cargo-target-guard.sh");  const result = spawnSync("bash", [own, "--run", "bash", own, "--run", "bash", "-c", 'printf "%s" "$COTTON_CARGO_LOCK_HELD"'], {    encoding: "utf8", timeout: 5000,    env: { ...process.env, CARGO_TARGET_DIR: target, COTTON_CARGO_LOCK_HELD: `${target}.lock`, COTTON_CARGO_LOCK_OWNER: "99999999" },  });  expect(result.status, result.stderr).toBe(0);  expect(result.stdout).toBe(`${target}.lock`);  // The guard records the resolved tree (macOS tmpdir is /var → /private/var).  expect(readFileSync(join(target, ".last-worktree"), "utf8").trim()).toBe(realpathSync(root));});// RULE: Every entry point takes the same lock for shared artifacts, even when a caller carries an obsolete per-branch lock setting.it("uses the target lock for a direct cargo-lock caller", () => {  const { root } = tree();  const target = join(scratch(), "shared");  const result = spawnSync("bash", [join(root, "scripts/ci/with-cargo-lock.sh"), "bash", "-c", 'printf "%s" "$COTTON_CARGO_LOCK_HELD"'], {    encoding: "utf8", timeout: 5000,    env: { ...process.env, CARGO_TARGET_DIR: target, COTTON_CARGO_LOCK: join(root, "obsolete.lock"), COTTON_CARGO_LOCK_HELD: "" },  });  expect(result.status, result.stderr).toBe(0);  expect(result.stdout).toBe(`${target}.lock`);});// RULE: An interrupted or partial build does not prove every crate was compiled; the next identical tree inherits the preparation epoch so older artifacts remain stale.it("keeps unbuilt artifacts stale when the next tree has identical inputs", () => {  const first = tree(), next = tree();  const target = join(scratch(), "shared"); mkdirSync(target);  const artifact = join(target, "unbuilt.rlib"); writeFileSync(artifact, "older build"); utimesSync(artifact, old, old);  expect(guard(first.root, target).status).toBe(0);  const epoch = statSync(first.source).mtimeMs;  expect(guard(next.root, target).status).toBe(0);  expect(statSync(next.source).mtimeMs).toBe(epoch);  expect(statSync(artifact).mtimeMs).toBeLessThan(epoch);});