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
105 changes: 94 additions & 11 deletions plugins/bstack/scripts/cargo-lock.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
// together. Cargo's own lock covers compiling only, so worktrees sharing one target dir otherwise rebuild
// each other's test binaries between build and run (#153). Worktrees of one workspace also get the same
// build hashes, and cargo judges freshness by mtime, so a worktree whose sources are older than another's
// build would run that build: the wrapper marks this worktree's workspace sources as changed when another worktree built last.
// build would run that build. So each worktree builds its workspace crates into a build slot of its own,
// next to the dependencies all of them share: cargo names a workspace member's artifacts after the path of
// RUSTC_WORKSPACE_WRAPPER too, and every slot has that pass-through program at its own path. Clippy, whose
// cargo command sets that variable itself, gets the slot as a --cfg, which it records with its result. A
// worktree that takes a slot over has its workspace sources marked as changed; so has a command that
// cannot use a slot, when another worktree built last.
// Without a target dir, or for a cargo command that builds nothing, it only runs the command; `cargo run` takes no lock, as its app may run for hours.
// Usage: node cargo-lock.mjs cargo test --workspace --locked
import { spawn, spawnSync } from 'node:child_process';
Expand All @@ -15,6 +20,18 @@ import { buildsNothing, cargoSubcommand, configArgTargetDir, configFileTargetDir

const LOCK_NAME = '.bstack-cargo.lock';
const LAST_BUILDER_NAME = '.bstack-cargo.last';
const SLOTS_NAME = '.bstack-cargo.slots';
const SLOT_DIR = '.bstack-cargo-slots';
const SLOT_COUNT = Number(process.env.BSTACK_CARGO_SLOTS) || 6;
const EXE = process.platform === 'win32' ? '.exe' : '';
const BUILDS_WITH_RUSTC = /^(build|b|check|c|test|t|bench|doc|d|run|r|rustc)$/;
const PASS_THROUGH = `use std::process::{exit, Command};
fn main() {
let mut args = std::env::args_os().skip(1);
let rustc = args.next().expect("cargo passes rustc first");
exit(Command::new(rustc).args(args).status().expect("rustc starts").code().unwrap_or(1));
}
`;
const POLL_MS = 250;
const WORKSPACE_SOURCES = ['src', 'tests', 'benches', 'examples', 'build.rs', 'Cargo.toml'];
const say = msg => process.stderr.write(`bstack cargo-lock: ${msg}\n`);
Expand Down Expand Up @@ -123,21 +140,87 @@ function touch(entry, now) {
else if (stat) fs.utimesSync(entry, now, now);
}

function markSourcesChanged(program, args, target, { locked }) {
const { root, members } = workspaceOf(program, args);
const lastBuilder = path.join(target, LAST_BUILDER_NAME);
if (locked && root && readOrNull(lastBuilder) === root) return;
function touchSources(members) {
const now = new Date();
for (const member of members) {
for (const name of WORKSPACE_SOURCES) touch(path.join(member, name), now);
}
}

function markSourcesChanged({ root, members }, target, { locked }) {
const lastBuilder = path.join(target, LAST_BUILDER_NAME);
if (locked && root && readOrNull(lastBuilder) === root) return;
touchSources(members);
if (locked && root) fs.writeFileSync(lastBuilder, root);
else fs.rmSync(lastBuilder, { force: true });
}

function run(program, args, onSpawn = () => {}) {
// The slot of this workspace root, or the one unused longest. `taken` says its artifacts are another worktree's.
function slotOf(target, root) {
const file = path.join(target, SLOTS_NAME);
let slots = [];
try { slots = JSON.parse(fs.readFileSync(file, 'utf8')).slice(0, SLOT_COUNT); } catch { slots = []; }
const used = i => slots[i]?.used ?? 0;
const own = slots.findIndex(s => s?.root === root);
const oldest = slots.reduce((least, _, i) => (used(i) < used(least) ? i : least), 0);
const index = own >= 0 ? own : slots.length < SLOT_COUNT ? slots.length : oldest;
const from = own < 0 ? slots[index]?.root : undefined;
slots[index] = { root, used: Date.now() };
fs.writeFileSync(file, JSON.stringify(slots));
return { index, taken: own < 0, from };
}

// The pass-through program at the slot's own path, compiled once per target dir; null when rustc cannot build it.
function slotWrapper(target, index) {
const dir = path.join(target, SLOT_DIR);
const built = path.join(dir, `rustc-wrapper${EXE}`);
const mine = path.join(dir, String(index), `rustc-wrapper${EXE}`);
if (fs.existsSync(mine)) return mine;
fs.mkdirSync(path.dirname(mine), { recursive: true });
if (!fs.existsSync(built)) {
const source = path.join(dir, 'rustc-wrapper.rs');
fs.writeFileSync(source, PASS_THROUGH);
const rustc = spawnSync('rustc', ['-O', source, '-o', built], { cwd: dir, encoding: 'utf8' });
if (rustc.status !== 0) {
say(`no build slots, rustc could not build their wrapper: ${String(rustc.stderr || rustc.error?.message).trim().split(/\r?\n/)[0]}`);
return null;
}
}
fs.copyFileSync(built, mine);
return mine;
}

const clippyInSlot = (args, index) => [...args, ...(args.includes('--') ? [] : ['--']), `--cfg=bstack_slot_${index}`];

// What to run so that this worktree builds its own artifacts: the command in its slot, or as given with the sources marked.
async function ownBuild(program, args, target, { locked }) {
const subcommand = cargoSubcommand(args);
const workspace = workspaceOf(program, args);
const env = process.env;
const wraps = BUILDS_WITH_RUSTC.test(subcommand ?? '') && !env.RUSTC_WORKSPACE_WRAPPER && !env.CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER;
if (workspace.root && (wraps || subcommand === 'clippy')) {
const slotsLock = path.join(target, `${SLOTS_NAME}.lock`);
await acquire(slotsLock);
try {
const slot = slotOf(target, workspace.root);
const wrapper = wraps ? slotWrapper(target, slot.index) : null;
if (slot.taken) {
if (slot.from) say(`build slot ${slot.index} goes from ${slot.from} to ${workspace.root}, whose sources are marked as changed`);
touchSources(workspace.members);
}
if (wrapper) return { args, env: { ...env, RUSTC_WORKSPACE_WRAPPER: wrapper } };
if (!wraps) return { args: clippyInSlot(args, slot.index), env };
} finally {
release(slotsLock);
}
}
markSourcesChanged(workspace, target, { locked });
return { args, env };
}

function run(program, args, onSpawn = () => {}, env = process.env) {
return new Promise(resolve => {
const child = spawn(program, args, { stdio: 'inherit' });
const child = spawn(program, args, { stdio: 'inherit', env });
if (child.pid) onSpawn(child.pid);
process.on('SIGINT', () => {});
process.on('SIGTERM', () => child.kill('SIGTERM'));
Expand All @@ -157,13 +240,13 @@ async function main([program, ...args]) {
fs.mkdirSync(path.dirname(lock), { recursive: true });
if (isCargo(program) && holdsNoLock(cargoSubcommand(args))) {
say('cargo run takes no lock: the app it starts may run for hours, and cargo\'s own lock covers its build');
markSourcesChanged(program, args, path.dirname(lock), { locked: false });
return run(program, args);
const own = await ownBuild(program, args, path.dirname(lock), { locked: false });
return run(program, own.args, undefined, own.env);
}
await acquire(lock);
try {
if (isCargo(program)) markSourcesChanged(program, args, path.dirname(lock), { locked: true });
return await run(program, args, childPid => recordChild(lock, childPid));
const own = isCargo(program) ? await ownBuild(program, args, path.dirname(lock), { locked: true }) : { args, env: process.env };
return await run(program, own.args, childPid => recordChild(lock, childPid), own.env);
} finally {
release(lock);
}
Expand Down
95 changes: 77 additions & 18 deletions tests/cargo-lock.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ function envWith(targetDir) {
return targetDir ? { ...env, CARGO_TARGET_DIR: targetDir } : env;
}

function wrapped(args, { cwd, targetDir, onStderr = () => {} }) {
function wrapped(args, { cwd, targetDir, env = {}, onStderr = () => {} }) {
return new Promise(resolve => {
const child = spawn(process.execPath, [WRAPPER, ...args], { cwd, env: envWith(targetDir) });
const child = spawn(process.execPath, [WRAPPER, ...args], { cwd, env: { ...envWith(targetDir), ...env } });
let stdout = '';
let stderr = '';
child.stdout.on('data', d => { stdout += d; });
Expand Down Expand Up @@ -140,12 +140,12 @@ test('without CARGO_TARGET_DIR the wrapper only runs the command and passes its

const hasCargo = spawnSync('cargo', ['--version']).status === 0;

function crateWorktree(lib) {
function crateWorktree(lib, body = `"${lib}"`) {
const dir = tempDir('crate');
fs.mkdirSync(path.join(dir, 'src'));
fs.mkdirSync(path.join(dir, 'tests'));
fs.writeFileSync(path.join(dir, 'Cargo.toml'), '[package]\nname = "branchy"\nversion = "0.1.0"\nedition = "2021"\n');
fs.writeFileSync(path.join(dir, 'src', 'lib.rs'), `pub fn status() -> &'static str { "${lib}" }\n`);
fs.writeFileSync(path.join(dir, 'src', 'lib.rs'), `pub fn status() -> &'static str { ${body} }\n`);
fs.writeFileSync(path.join(dir, 'tests', 'own.rs'), '#[test]\nfn status_is_ok() { assert_eq!(branchy::status(), "ok"); }\n');
return dir;
}
Expand All @@ -162,36 +162,95 @@ test('real cargo: a test that fails only on one worktree fails there, also when
assert.match(second.stdout + second.stderr, /left: "broken"/);
});

test('real cargo: sources are marked changed only when another worktree built last, and never for cargo fmt', { skip: !hasCargo && 'cargo is not on PATH' }, async () => {
const libTime = dir => fs.statSync(path.join(dir, 'src', 'lib.rs')).mtimeMs;
const compiled = run => /Compiling branchy/.test(run.stderr);

test('real cargo: each worktree keeps its own build in the shared target, so going back to one builds nothing and marks nothing again', { skip: !hasCargo && 'cargo is not on PATH' }, async () => {
const target = tempDir('cargo-target');
const [passing, failing] = [crateWorktree('ok'), crateWorktree('broken')];
const cargoTest = cwd => wrapped(['cargo', 'test', '--offline'], { cwd, targetDir: target });
const firstRuns = [await cargoTest(passing), await cargoTest(failing)];
const inSlots = [libTime(passing), libTime(failing)];
const runs = [...firstRuns, await cargoTest(passing), await cargoTest(failing)];
assert.deepEqual(runs.map(r => r.code === 0), [true, false, true, false], runs.map(r => r.stderr).join('\n'));
assert.deepEqual(runs.map(compiled), [true, true, false, false]);
assert.deepEqual([libTime(passing), libTime(failing)], inSlots);
assert.equal(fs.existsSync(path.join(target, '.bstack-cargo.last')), false);
});

test('real cargo: with every slot in use, the worktree unused longest gives its slot up and the one that takes it is rebuilt from its own sources', { skip: !hasCargo && 'cargo is not on PATH' }, async () => {
const target = tempDir('cargo-target');
const [passing, failing] = [crateWorktree('ok'), crateWorktree('broken')];
const cargoTest = cwd => wrapped(['cargo', 'test', '--offline'], { cwd, targetDir: target, env: { BSTACK_CARGO_SLOTS: '1' } });
const first = await cargoTest(passing);
const written = libTime(failing);
await new Promise(r => setTimeout(r, 20));
const second = await cargoTest(failing);
const third = await cargoTest(passing);
assert.deepEqual([first, second, third].map(r => r.code === 0), [true, false, true], second.stderr + third.stderr);
assert.ok(libTime(failing) > written);
assert.match(second.stderr, /build slot 0 goes from .* to .*, whose sources are marked as changed/);
assert.deepEqual([second, third].map(compiled), [true, true]);
});

test('real cargo: a command outside the slots marks sources only when another worktree built last, and cargo fmt never does', { skip: !hasCargo && 'cargo is not on PATH' }, async () => {
const target = tempDir('cargo-target');
const [mine, other] = [crateWorktree('ok'), crateWorktree('ok')];
const lib = dir => fs.statSync(path.join(dir, 'src', 'lib.rs')).mtimeMs;
const cargo = (cwd, ...args) => wrapped(['cargo', ...args], { cwd, targetDir: target });
await cargo(mine, 'test', '--offline', '--quiet');
const afterFirst = lib(mine);
await cargo(mine, 'test', '--offline', '--quiet');
await cargo(mine, 'rustdoc', '--offline', '--quiet');
const afterFirst = libTime(mine);
await cargo(mine, 'rustdoc', '--offline', '--quiet');
await cargo(mine, 'fmt', '--version');
assert.equal(lib(mine), afterFirst);
await cargo(other, 'test', '--offline', '--quiet');
assert.equal(libTime(mine), afterFirst);
await cargo(other, 'rustdoc', '--offline', '--quiet');
await new Promise(r => setTimeout(r, 20));
await cargo(mine, 'test', '--offline', '--quiet');
assert.ok(lib(mine) > afterFirst);
await cargo(mine, 'rustdoc', '--offline', '--quiet');
assert.ok(libTime(mine) > afterFirst);
});

test('real cargo: a cargo run, which builds without the lock, leaves no last builder, so the next locked run marks its sources', { skip: !hasCargo && 'cargo is not on PATH' }, async () => {
test('real cargo: a cargo run builds in its worktree\'s slot without the lock and marks nothing after its first run', { skip: !hasCargo && 'cargo is not on PATH' }, async () => {
const target = tempDir('cargo-target');
const [mine, other] = [crateWorktree('ok'), crateWorktree('ok')];
for (const [dir, says] of [[mine, 'mine'], [other, 'other']]) fs.writeFileSync(path.join(dir, 'src', 'main.rs'), `fn main() { println!("${says}"); }\n`);
const cargoRun = cwd => wrapped(['cargo', 'run', '--offline', '--quiet'], { cwd, targetDir: target });
const firstRun = await cargoRun(mine);
const inSlot = libTime(mine);
const runs = [firstRun, await cargoRun(other), await cargoRun(mine)];
assert.deepEqual(runs.map(r => r.stdout.trim()), ['mine', 'other', 'mine'], runs.map(r => r.stderr).join('\n'));
assert.equal(libTime(mine), inSlot);
assert.equal(fs.existsSync(path.join(target, LOCK_NAME)), false);
});

test('real cargo: with a wrapper of the user\'s own, a cargo run, which builds without the lock, leaves no last builder, so the next locked run marks its sources', { skip: !hasCargo && 'cargo is not on PATH' }, async () => {
const target = tempDir('cargo-target');
const mine = crateWorktree('ok');
const lib = () => fs.statSync(path.join(mine, 'src', 'lib.rs')).mtimeMs;
const cargo = (...args) => wrapped(['cargo', ...args], { cwd: mine, targetDir: target });
await wrapped(['cargo', 'test', '--offline', '--quiet'], { cwd: mine, targetDir: target });
const ownWrapper = path.join(target, '.bstack-cargo-slots', process.platform === 'win32' ? 'rustc-wrapper.exe' : 'rustc-wrapper');
const cargo = (...args) => wrapped(['cargo', ...args], { cwd: mine, targetDir: target, env: { RUSTC_WORKSPACE_WRAPPER: ownWrapper } });
await cargo('test', '--offline', '--quiet');
assert.equal(fs.existsSync(path.join(target, '.bstack-cargo.last')), true);
await cargo('run', '--offline', '--quiet');
assert.equal(fs.existsSync(path.join(target, '.bstack-cargo.last')), false);
const afterRun = lib();
const afterRun = libTime(mine);
await new Promise(r => setTimeout(r, 20));
await cargo('test', '--offline', '--quiet');
assert.ok(lib() > afterRun);
assert.ok(libTime(mine) > afterRun);
});

const hasClippy = hasCargo && spawnSync('cargo', ['clippy', '--version']).status === 0;

test('real cargo: clippy reports each worktree\'s own code, also right after another worktree\'s clean run, and marks nothing after its first run', { skip: !hasClippy && 'cargo clippy is not installed' }, async () => {
const target = tempDir('cargo-target');
const flagged = crateWorktree('flagged', 'return "ok";');
const clean = crateWorktree('ok');
const clippy = cwd => wrapped(['cargo', 'clippy', '--offline', '--', '-D', 'warnings'], { cwd, targetDir: target });
const firstRuns = [await clippy(clean), await clippy(flagged)];
const inSlots = [libTime(clean), libTime(flagged)];
const runs = [...firstRuns, await clippy(clean), await clippy(flagged)];
assert.deepEqual(runs.map(r => r.code === 0), [true, false, true, false], runs.map(r => r.stderr).join('\n'));
assert.match(runs[1].stderr, /needless.return/);
assert.deepEqual([libTime(clean), libTime(flagged)], inSlots);
});
// A program named cargo that is node: `cargo run` then runs the file `run` in its working directory.
// Windows runs no script without a shell, so there it is node itself, else a stub that execs node.
function fakeCargo() {
Expand Down
Loading