1use std::io;
22use std::path::{Path, PathBuf};
23
24const SCRIPT: &str = include_str!("../../../scripts/build-slot/build-slot.sh");
25const SHIM_SH: &str = include_str!("../../../scripts/build-slot/shim");
26const SHIM_CMD: &str = include_str!("../../../scripts/build-slot/shim.cmd");
27
28const SHIMMED_TOOLS: [&str; 5] = ["cargo", "task", "npm", "npx", "docker"];
30
31const VERSION_PREFIX: &str = "# build-slot-version:";
32const SHIM_MARKER: &str = "agentmux-build-slot-shim";
34
35pub fn script_path(home: &Path) -> PathBuf {
37 home.join(".agentmux").join("shared").join("locks").join("build-slot.sh")
38}
39
40pub fn shim_dir(home: &Path) -> PathBuf {
42 home.join(".agentmux").join("tools").join("bin")
43}
44
45const STALE_SECS: u64 = 90;
47
48#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
50pub struct SlotHolder {
51 pub agent: String,
53 pub since_ms: u64,
55 pub reason: String,
57 pub command: String,
59 #[serde(default)]
61 pub token: String,
62 #[serde(default)]
65 pub pid: Option<u32>,
66 #[serde(default)]
68 pub winpid: Option<u32>,
69}
70
71impl SlotHolder {
72 pub fn process_id(&self) -> Option<u32> {
76 if cfg!(windows) { self.winpid } else { self.pid }.filter(|p| *p > 1)
77 }
78}
79
80pub fn lock_dir() -> Option<PathBuf> {
83 match std::env::var_os("AGENTMUX_BUILD_SLOT_DIR").filter(|d| !d.is_empty()) {
84 Some(dir) => Some(PathBuf::from(dir)),
85 None => dirs::home_dir().map(|h| h.join(".agentmux").join("shared").join("locks").join("build")),
86 }
87}
88
89pub fn holder() -> Option<SlotHolder> {
91 let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?.as_secs();
92 read_holder(&lock_dir()?, now)
93}
94
95pub fn read_holder(root: &Path, now_secs: u64) -> Option<SlotHolder> {
98 let slot = root.join("slot");
99 let text = std::fs::read_to_string(slot.join("owner")).ok()?;
100 let alive_at = [slot.join("heartbeat"), slot.clone()]
101 .iter()
102 .find_map(|p| std::fs::metadata(p).ok()?.modified().ok())?
103 .duration_since(std::time::UNIX_EPOCH)
104 .ok()?
105 .as_secs();
106 if now_secs.saturating_sub(alive_at) > STALE_SECS {
107 return None;
108 }
109 let field = |key: &str| text.lines().find_map(|l| l.strip_prefix(key)?.strip_prefix('=')).map(str::trim);
110 let agent = field("agent").filter(|a| !a.is_empty())?.to_string();
111 let start: u64 = field("start")?.parse().ok()?;
112 let reason = field("reason").filter(|r| !r.is_empty()).or_else(|| field("cmd")).unwrap_or_default().to_string();
113 let command: String = field("cmd").unwrap_or_default().chars().take(120).collect();
114 let number = |key: &str| field(key).and_then(|v| v.parse::<u32>().ok());
115 Some(SlotHolder {
116 agent,
117 since_ms: start.saturating_mul(1000),
118 reason,
119 command,
120 token: field("token").unwrap_or_default().to_string(),
121 pid: number("pid"),
122 winpid: number("winpid"),
123 })
124}
125
126fn idle_path(root: &Path) -> PathBuf {
129 root.join("slot").join("idle")
130}
131
132pub fn write_idle(root: &Path, token: &str, since_secs: u64) -> io::Result<()> {
136 let owner = std::fs::read_to_string(root.join("slot").join("owner")).unwrap_or_default();
137 if !owner.lines().any(|l| l.strip_prefix("token=").is_some_and(|t| t.trim() == token)) {
138 return Ok(());
139 }
140 std::fs::write(idle_path(root), format!("token={token}\nidle_since={since_secs}\n"))
141}
142
143pub fn clear_idle(root: &Path) {
145 let _ = std::fs::remove_file(idle_path(root));
146}
147
148pub fn shim_function_env(home: &Path, off: bool) -> Vec<(String, String)> {
161 if off {
162 return Vec::new();
163 }
164 let dir = shim_dir(home).to_string_lossy().replace('\\', "/");
165 if dir.chars().any(|c| matches!(c, '"' | '$' | '`' | '\\' | '\n' | '\r')) {
167 return Vec::new();
168 }
169 SHIMMED_TOOLS
170 .iter()
171 .filter(|tool| std::fs::read_to_string(shim_dir(home).join(tool)).is_ok_and(|t| t.contains(SHIM_MARKER)))
172 .map(|tool| (format!("BASH_FUNC_{tool}%%"), format!("() {{ \"{dir}/{tool}\" \"$@\"\n}}")))
173 .collect()
174}
175
176pub fn shim_function_env_for_current_user() -> Vec<(String, String)> {
179 let off = std::env::var_os("AGENTMUX_BUILD_SLOT_OFF").is_some_and(|v| !v.is_empty());
180 dirs::home_dir().map(|h| shim_function_env(&h, off)).unwrap_or_default()
181}
182
183#[derive(Debug, Default, PartialEq, Eq)]
185pub struct Installed {
186 pub written: Vec<String>,
188 pub foreign: Vec<String>,
190}
191
192pub fn install_for_current_user() -> io::Result<Installed> {
196 let isolated = std::env::var_os("AGENTMUX_HOME_OVERRIDE").is_some_and(|v| !v.is_empty());
197 install_unless_isolated(isolated, dirs::home_dir().as_deref())
198}
199
200fn install_unless_isolated(isolated: bool, home: Option<&Path>) -> io::Result<Installed> {
203 match home {
204 Some(home) if !isolated => install(home),
205 _ => Ok(Installed::default()),
206 }
207}
208
209pub fn install(home: &Path) -> io::Result<Installed> {
211 let mut done = Installed::default();
212
213 let script = lf(SCRIPT);
214 let script_dest = script_path(home);
215 let installed_version = std::fs::read_to_string(&script_dest).ok().and_then(|t| version_of(&t));
216 let embedded_version = version_of(&script);
217 if !script_dest.exists() || installed_version.is_none() || embedded_version > installed_version {
218 write_executable(&script_dest, &script)?;
219 done.written.push("build-slot.sh".to_string());
220 }
221
222 let dir = shim_dir(home);
223 let (sh, cmd) = (lf(SHIM_SH), crlf(SHIM_CMD));
224 let files = SHIMMED_TOOLS.iter().flat_map(|t| [(t.to_string(), &sh), (format!("{t}.cmd"), &cmd)]);
225 for (name, text) in files {
226 let text = text.as_str();
227 let dest = dir.join(&name);
228 match std::fs::read_to_string(&dest) {
229 Ok(existing) if existing == text => {}
230 Ok(existing) if existing.contains(SHIM_MARKER) => {
231 write_executable(&dest, text)?;
232 done.written.push(name.clone());
233 }
234 Ok(_) => done.foreign.push(name.clone()),
235 Err(e) if e.kind() == io::ErrorKind::NotFound => {
236 write_executable(&dest, text)?;
237 done.written.push(name.clone());
238 }
239 Err(e) if e.kind() == io::ErrorKind::InvalidData => done.foreign.push(name.clone()),
241 Err(e) => return Err(e),
242 }
243 }
244 Ok(done)
245}
246
247fn version_of(text: &str) -> Option<u32> {
249 text.lines()
250 .find_map(|l| l.strip_prefix(VERSION_PREFIX))
251 .and_then(|v| v.trim().parse().ok())
252}
253
254fn lf(text: &str) -> String {
256 text.replace("\r\n", "\n")
257}
258
259fn crlf(text: &str) -> String {
261 lf(text).replace('\n', "\r\n")
262}
263
264fn write_executable(dest: &Path, text: &str) -> io::Result<()> {
267 let dir = dest.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no parent"))?;
268 std::fs::create_dir_all(dir)?;
269 let tmp = dir.join(format!(".{}.{}.tmp", dest.file_name().and_then(|n| n.to_str()).unwrap_or("f"), std::process::id()));
270 std::fs::write(&tmp, text)?;
271 #[cfg(unix)]
272 {
273 use std::os::unix::fs::PermissionsExt;
274 std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))?;
275 }
276 std::fs::rename(&tmp, dest).inspect_err(|_| {
277 let _ = std::fs::remove_file(&tmp);
278 })
279}
280
281#[cfg(test)]
282mod tests {
283 use super::*;
284
285 fn home() -> tempfile::TempDir {
286 tempfile::tempdir().unwrap()
287 }
288
289 fn write_slot(root: &Path, owner: &str, heartbeat: bool) {
290 let slot = root.join("slot");
291 std::fs::create_dir_all(&slot).unwrap();
292 std::fs::write(slot.join("owner"), owner).unwrap();
293 if heartbeat {
294 std::fs::write(slot.join("heartbeat"), "").unwrap();
295 }
296 }
297
298 fn now_secs() -> u64 {
299 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs()
300 }
301
302 #[test]
303 fn the_holder_is_read_from_the_owner_file_and_a_dead_one_is_not_a_holder() {
304 let h = home();
305 let root = h.path();
306 assert_eq!(read_holder(root, now_secs()), None, "no slot: free");
307 write_slot(root, "agent=Lazo\npid=1\ntoken=t\nstart=1792830000\ncwd=/x\ncmd=/c/bin/cargo test -p x\nreason=cargo test\n", true);
308 assert_eq!(
309 read_holder(root, now_secs()),
310 Some(SlotHolder {
311 agent: "Lazo".into(),
312 since_ms: 1_792_830_000_000,
313 reason: "cargo test".into(),
314 command: "/c/bin/cargo test -p x".into(),
315 token: "t".into(),
316 pid: Some(1),
317 winpid: None,
318 })
319 );
320 write_slot(root, "agent=Lazo\npid=77\nwinpid=4242\ntoken=t\nstart=1792830000\ncmd=x\n", true);
321 let holder = read_holder(root, now_secs()).unwrap();
322 assert_eq!((holder.pid, holder.winpid), (Some(77), Some(4242)));
323 let expected = if cfg!(windows) { Some(4242) } else { Some(77) };
324 assert_eq!(holder.process_id(), expected, "the Windows id on Windows, the pid elsewhere");
325 write_slot(root, "agent=Lazo\npid=1\ntoken=t\nstart=1792830000\ncmd=x\n", true);
326 assert_eq!(read_holder(root, now_secs()).unwrap().process_id(), None, "a pid of 1 is no process of ours");
327 assert_eq!(read_holder(root, now_secs() + 10 * 60), None, "no heartbeat for minutes: its holder died");
328 write_slot(root, "agent=Manoz\nstart=1792830001\ncmd=npm run build\n", true);
329 assert_eq!(read_holder(root, now_secs()).unwrap().reason, "npm run build", "no reason: the command line");
330 write_slot(root, "agent=Manoz\n", true);
331 assert_eq!(read_holder(root, now_secs()), None, "an owner file still being written names no start");
332 write_slot(root, "", false);
333 assert_eq!(read_holder(root, now_secs()), None);
334 }
335
336 #[test]
337 fn the_embedded_files_are_what_the_installer_expects() {
338 assert!(version_of(SCRIPT).is_some(), "build-slot.sh needs a `# build-slot-version: N` line");
339 assert!(SHIM_SH.contains(SHIM_MARKER), "the cargo shim must carry its marker");
340 assert!(SHIM_CMD.contains(SHIM_MARKER), "the cargo.cmd shim must carry its marker");
341 assert!(!lf(SCRIPT).contains('\r') && !lf(SHIM_SH).contains('\r'));
342 let lines: Vec<&str> = SCRIPT.lines().filter(|l| !l.trim().is_empty()).collect();
345 assert_eq!(lines.last().copied(), Some("main \"$@\"; exit $?"), "the script must end by calling main");
346 assert!(lines.contains(&"main() {"), "the script body must be one function");
347 assert!(crlf(SHIM_CMD).contains("\r\n") && !crlf(SHIM_CMD).replace("\r\n", "").contains('\n'));
348 }
349
350 #[test]
353 fn an_isolated_instance_installs_nothing_in_the_real_home() {
354 let real = home();
355 assert_eq!(install_unless_isolated(true, Some(real.path())).unwrap(), Installed::default());
356 assert!(!real.path().join(".agentmux").exists(), "nothing at all was created under the home");
357 assert_eq!(install_unless_isolated(false, None).unwrap(), Installed::default(), "no home: nothing to install into");
358 let done = install_unless_isolated(false, Some(real.path())).unwrap();
359 assert!(done.written.contains(&"build-slot.sh".to_string()) && done.written.contains(&"npm".to_string()));
360 assert!(script_path(real.path()).exists(), "a normal instance still installs");
361 }
362
363 #[test]
364 fn an_empty_home_gets_the_script_and_both_shims_once() {
365 let h = home();
366 let first = install(h.path()).unwrap();
367 assert_eq!(
368 first.written,
369 vec!["build-slot.sh", "cargo", "cargo.cmd", "task", "task.cmd", "npm", "npm.cmd", "npx", "npx.cmd", "docker", "docker.cmd"]
370 );
371 assert!(first.foreign.is_empty());
372 assert_eq!(install(h.path()).unwrap(), Installed::default(), "the second call finds nothing to do");
373 assert_eq!(std::fs::read_to_string(shim_dir(h.path()).join("cargo.cmd")).unwrap(), crlf(SHIM_CMD));
374 }
375
376 #[test]
377 fn a_cargo_that_is_not_the_shim_is_left_alone() {
378 let h = home();
379 let dir = shim_dir(h.path());
380 std::fs::create_dir_all(&dir).unwrap();
381 std::fs::write(dir.join("cargo"), "#!/bin/sh\necho mine\n").unwrap();
382 let done = install(h.path()).unwrap();
383 assert_eq!(done.foreign, vec!["cargo"]);
384 assert_eq!(std::fs::read_to_string(dir.join("cargo")).unwrap(), "#!/bin/sh\necho mine\n");
385 assert!(done.written.contains(&"cargo.cmd".to_string()), "the other shims are still installed");
386 assert!(done.written.contains(&"task".to_string()), "the other tools' shims are still installed");
387 }
388
389 #[test]
390 fn an_older_shim_is_replaced_and_a_newer_script_is_kept() {
391 let h = home();
392 install(h.path()).unwrap();
393 let dir = shim_dir(h.path());
394 std::fs::write(dir.join("cargo"), "#!/bin/sh\n# agentmux-build-slot-shim v0\n").unwrap();
395 let newer = "#!/bin/bash\n# build-slot-version: 999\necho newer channel\n";
396 std::fs::write(script_path(h.path()), newer).unwrap();
397 let done = install(h.path()).unwrap();
398 assert_eq!(done.written, vec!["cargo"]);
399 assert_eq!(std::fs::read_to_string(script_path(h.path())).unwrap(), newer, "no downgrade");
400 }
401
402 #[test]
403 fn an_unversioned_or_older_script_is_replaced() {
404 let h = home();
405 install(h.path()).unwrap();
406 std::fs::write(script_path(h.path()), "#!/bin/bash\n# written by hand, no version\n").unwrap();
407 assert_eq!(install(h.path()).unwrap().written, vec!["build-slot.sh"]);
408 std::fs::write(script_path(h.path()), "#!/bin/bash\n# build-slot-version: 0\n").unwrap();
409 assert_eq!(install(h.path()).unwrap().written, vec!["build-slot.sh"]);
410 }
411
412 fn bash() -> Option<PathBuf> {
415 if cfg!(windows) {
416 let git = std::env::var_os("ProgramFiles").map(|p| PathBuf::from(p).join("Git").join("bin").join("bash.exe"))?;
417 git.exists().then_some(git)
418 } else {
419 Some(PathBuf::from("bash"))
420 }
421 }
422
423 fn run_tool_env(tool: &str, with_slot: bool, off: bool, args: &[&str], env: &[(&str, &str)]) -> Option<String> {
425 run_tool_in(tool, with_slot, off, args, env, &["proj/package.json", "proj/Cargo.toml"], "proj").map(|(out, _)| out)
427 }
428
429 fn run_tool_in(
433 tool: &str,
434 with_slot: bool,
435 off: bool,
436 args: &[&str],
437 env: &[(&str, &str)],
438 files: &[&str],
439 cwd: &str,
440 ) -> Option<(String, tempfile::TempDir)> {
441 let bash = bash()?;
442 let h = home();
443 for f in files {
444 let path = h.path().join(f);
445 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
446 std::fs::write(&path, "{}").unwrap();
447 }
448 let cwd = h.path().join(cwd);
449 std::fs::create_dir_all(&cwd).unwrap();
450 let real_dir = h.path().join("real");
451 let shim = shim_dir(h.path());
452 std::fs::create_dir_all(&real_dir).unwrap();
453 std::fs::create_dir_all(&shim).unwrap();
454 let real = real_dir.join(tool);
455 std::fs::write(&real, "#!/usr/bin/env bash\necho \"REAL $*\"\n").unwrap();
456 std::fs::write(shim.join(tool), lf(SHIM_SH)).unwrap();
457 if with_slot {
458 std::fs::create_dir_all(script_path(h.path()).parent().unwrap()).unwrap();
459 std::fs::write(script_path(h.path()), "#!/usr/bin/env bash\necho \"SLOT $*\"\n").unwrap();
460 }
461 #[cfg(unix)]
462 {
463 use std::os::unix::fs::PermissionsExt;
464 std::fs::set_permissions(&real, std::fs::Permissions::from_mode(0o755)).unwrap();
465 }
466 let sep = if cfg!(windows) { ";" } else { ":" };
467 let path = format!("{}{sep}{}{sep}{}", shim.display(), real_dir.display(), std::env::var("PATH").unwrap_or_default());
468 let mut cmd = std::process::Command::new(bash);
469 cmd.arg(shim.join(tool)).args(args).env("PATH", path).env("HOME", h.path()).env_remove("AGENTMUX_BUILD_SLOT_DIR").current_dir(&cwd);
470 if off {
471 cmd.env("AGENTMUX_BUILD_SLOT_OFF", "1");
472 }
473 cmd.envs(env.iter().copied());
474 #[cfg(windows)]
475 {
476 use crate::win32::NoWindow;
477 cmd.no_window();
478 }
479 let out = cmd.output().unwrap();
480 Some((String::from_utf8_lossy(&out.stdout).replace("\r\n", "\n").trim().to_string(), h))
481 }
482
483 fn run_tool(tool: &str, with_slot: bool, off: bool, args: &[&str]) -> Option<String> {
484 run_tool_env(tool, with_slot, off, args, &[])
485 }
486
487 fn run_shim(with_slot: bool, off: bool, args: &[&str]) -> Option<String> {
488 run_tool("cargo", with_slot, off, args)
489 }
490
491 fn contains_all(out: &str, parts: &[&str]) -> bool {
492 parts.iter().all(|p| out.contains(p))
493 }
494
495 #[test]
496 fn a_heavy_subcommand_goes_through_the_slot_and_a_light_one_does_not() {
497 let Some(test) = run_shim(true, false, &["test", "-p", "x"]) else { return };
498 assert!(test.starts_with("SLOT --reason cargo test -- "), "got {test:?}");
499 assert!(contains_all(&test, &["real", "cargo test -p x"]), "got {test:?}");
500 let nightly = run_shim(true, false, &["+nightly", "--locked", "check"]).unwrap();
501 assert!(nightly.starts_with("SLOT --reason cargo check -- "), "got {nightly:?}");
502 for args in [
503 &["-C", "dir", "test"][..],
504 &["-Z", "unstable-options", "test"][..],
505 &["--config", "build.jobs=2", "test"][..],
506 &["--color", "never", "test"][..],
507 &["--config=build.jobs=2", "-Zunstable-options", "test"][..],
508 ] {
509 let out = run_shim(true, false, args).unwrap();
510 assert!(out.starts_with("SLOT --reason cargo test -- "), "{args:?} should be slotted, got {out:?}");
511 }
512 assert_eq!(run_shim(true, false, &["metadata"]).unwrap(), "REAL metadata");
513 assert_eq!(run_shim(true, false, &["-C", "dir", "metadata"]).unwrap(), "REAL -C dir metadata");
514 assert_eq!(run_shim(true, false, &["run", "-p", "srv"]).unwrap(), "REAL run -p srv", "run keeps running, so it is not slotted");
515 assert_eq!(run_shim(true, false, &[]).unwrap(), "REAL");
516 }
517
518 fn slotted(tool: &str, args: &[&str]) -> Option<bool> {
520 run_tool(tool, true, false, args).map(|out| out.starts_with("SLOT "))
521 }
522
523 #[test]
524 fn task_npm_npx_and_docker_slot_their_heavy_commands_only() {
525 if bash().is_none() {
526 return;
527 }
528 let heavy: &[(&str, &[&str])] = &[
529 ("task", &["package"]),
530 ("task", &["package:portable"]),
531 ("task", &["--verbose", "build:backend"]),
532 ("task", &["-d", "x", "bundle:windows"]),
533 ("task", &["check:doc-status", "package"]),
534 ("npm", &["run", "build"]),
535 ("npm", &["run", "--silent", "package:portable"]),
536 ("npm", &["run", "test:e2e"]),
537 ("npm", &["test"]),
538 ("npm", &["run", "coverage"]),
539 ("npm", &["run", "--workspace", "child", "coverage"]),
540 ("npm", &["run", "--prefix", "/p", "build"]),
541 ("npm", &["--workspace", "child", "run", "-w", "x", "package"]),
542 ("npx", &["vite", "build"]),
543 ("npx", &["vitest", "run", "x.test.ts"]),
544 ("npx", &["vitest"]),
545 ("docker", &["build", "-t", "x", "."]),
546 ("docker", &["buildx", "build", "."]),
547 ("docker", &["compose", "up", "--build"]),
548 ("docker", &["--context", "c", "build", "."]),
549 ];
550 for (tool, args) in heavy {
551 assert_eq!(slotted(tool, args), Some(true), "{tool} {args:?} should be slotted");
552 }
553 let light: &[(&str, &[&str])] = &[
554 ("task", &["dev"]),
555 ("task", &["run"]),
556 ("task", &["check:doc-status"]),
557 ("task", &["changeset", "--", "patch", "package"]),
558 ("task", &[]),
559 ("npm", &["install"]),
560 ("npm", &["ci"]),
561 ("npm", &["run", "lint:scss"]),
562 ("npm", &["run", "dev"]),
563 ("npm", &["run", "--workspace", "build", "lint:scss"]),
564 ("npm", &[]),
565 ("npx", &["tsc", "--noEmit"]),
566 ("npx", &["vite"]),
567 ("docker", &["run", "--rm", "x"]),
568 ("docker", &["ps"]),
569 ("docker", &["compose", "up"]),
570 ("docker", &["--version"]),
571 ];
572 for (tool, args) in light {
573 assert_eq!(slotted(tool, args), Some(false), "{tool} {args:?} should run directly");
574 }
575 let out = run_tool("task", true, false, &["package", "--force"]).unwrap();
577 assert!(out.starts_with("SLOT --reason task package -- "), "got {out:?}");
578 assert!(contains_all(&out, &["real", "task package --force"]), "got {out:?}");
579 assert_eq!(run_tool("npm", true, true, &["run", "build"]).unwrap(), "REAL run build", "the opt-out works for every tool");
580 assert_eq!(run_tool("docker", false, false, &["build", "."]).unwrap(), "REAL build .", "no lock script: docker still runs");
581 }
582
583 #[test]
586 fn with_a_terminal_only_a_one_shot_test_run_is_slotted() {
587 if bash().is_none() {
588 return;
589 }
590 let with_tty = |tool: &str, args: &[&str]| {
591 run_tool_env(tool, true, false, args, &[("BUILD_SLOT_ASSUME_TTY", "1")]).map(|o| o.starts_with("SLOT "))
592 };
593 for (tool, args) in [
594 ("npm", &["test", "--", "--run"][..]),
595 ("npm", &["run", "test", "--", "--run"][..]),
596 ("npx", &["vitest", "--run"][..]),
597 ("npx", &["vitest", "run"][..]),
598 ("npm", &["run", "build"][..]),
599 ] {
600 assert_eq!(with_tty(tool, args), Some(true), "{tool} {args:?} should be slotted with a terminal");
601 }
602 for (tool, args) in [
603 ("npm", &["test"][..]),
604 ("npm", &["run", "test"][..]),
605 ("npx", &["vitest"][..]),
606 ("npm", &["test", "--", "--coverage"][..]),
607 ("npx", &["vitest", "--coverage"][..]),
608 ] {
609 assert_eq!(with_tty(tool, args), Some(false), "{tool} {args:?} watches with a terminal, so it is not slotted");
610 }
611 }
612
613 fn npm_in(files: &[&str], cwd: &str, tool: &str, args: &[&str]) -> Option<(bool, String)> {
616 let (out, home) = run_tool_in(tool, true, false, args, &[], files, cwd)?;
617 let log = std::fs::read_to_string(home.path().join(".agentmux/shared/locks/build/unqueued.log")).unwrap_or_default();
618 Some((out.starts_with("SLOT "), log))
619 }
620
621 #[test]
625 fn npm_and_npx_queue_only_in_a_tree_with_a_cargo_toml() {
626 if bash().is_none() {
627 return;
628 }
629 let rust = &["agentmux/package.json", "agentmux/Cargo.toml"][..];
630 let site = &["site/package.json"][..];
631 for (tool, args) in [("npm", &["run", "build"][..]), ("npx", &["vite", "build"][..]), ("npm", &["test"][..])] {
632 let (slotted, log) = npm_in(rust, "agentmux", tool, args).unwrap();
633 assert!(slotted && log.is_empty(), "{tool} {args:?} beside a Cargo.toml queues, and says nothing: {log:?}");
634 let (slotted, log) = npm_in(site, "site", tool, args).unwrap();
635 assert!(!slotted, "{tool} {args:?} in a site repo runs at once");
636 assert!(log.trim_end().ends_with("not queued: no Cargo.toml") && log.contains(&format!("{tool}")), "one line for it: {log:?}");
637 assert_eq!(log.lines().count(), 1, "{log:?}");
638 }
639 let (_, log) = npm_in(site, "site", "npm", &["run", "build"]).unwrap();
641 let fields: Vec<&str> = log.trim_end().split('\t').collect();
642 assert_eq!(fields.len(), 5, "{log:?}");
643 assert!(fields[0].parse::<u64>().is_ok() && fields[2] == "npm run build" && fields[3].ends_with("/site"), "{fields:?}");
644 let nested = &["agentmux/Cargo.toml", "agentmux/widgets/clock/package.json"][..];
647 assert_eq!(npm_in(nested, "agentmux/widgets/clock", "npm", &["run", "build"]).unwrap().0, true, "nested in the tree: queued");
648 assert_eq!(npm_in(site, "site", "npm", &["run", "build"]).unwrap().0, false);
650 let deep = &["site/package.json", "site/src/deep/x.ts"][..];
651 assert_eq!(npm_in(deep, "site/src/deep", "npm", &["run", "build"]).unwrap().0, false, "the nearest package.json is found from a subfolder");
652 let both = &["agentmux/package.json", "agentmux/Cargo.toml", "site/package.json"][..];
654 assert_eq!(npm_in(both, "agentmux", "npm", &["run", "build", "--prefix", "../site"]).unwrap().0, false, "--prefix to a site");
655 assert_eq!(npm_in(both, "site", "npm", &["--prefix=../agentmux", "run", "build"]).unwrap().0, true, "--prefix=dir to the Rust tree");
656 assert_eq!(npm_in(&[], "nowhere", "npx", &["vite", "build"]).unwrap().0, true);
658 let (slotted, log) = npm_in(site, "site", "npm", &["install"]).unwrap();
660 assert!(!slotted && log.is_empty(), "a light command is not a skipped queue: {log:?}");
661 let (out, home) = run_tool_in("cargo", true, false, &["test"], &[], site, "site").unwrap();
662 assert!(out.starts_with("SLOT "), "cargo queues wherever it is run: {out}");
663 assert!(!home.path().join(".agentmux/shared/locks/build/unqueued.log").exists());
664 }
665
666 fn run_slot(bash: &Path, script: &Path, root: &Path, args: &[&str]) -> std::process::Output {
668 let mut cmd = std::process::Command::new(bash);
669 cmd.arg(script).args(args).env("AGENTMUX_BUILD_SLOT_DIR", root).env_remove("BUILD_SLOT_HELD").env("BUILD_SLOT_POLL", "1");
670 #[cfg(windows)]
671 {
672 use crate::win32::NoWindow;
673 cmd.no_window();
674 }
675 cmd.output().unwrap()
676 }
677
678 #[test]
680 fn a_run_is_recorded_in_the_history_and_summarised() {
681 let Some(bash) = bash() else { return };
682 let h = home();
683 let script = h.path().join("build-slot.sh");
684 std::fs::write(&script, lf(SCRIPT)).unwrap();
685 let root = h.path().join("slot dir");
686 let run = |args: &[&str]| run_slot(&bash, &script, &root, args);
687 assert_eq!(run(&["--reason", "cargo test", "--", "true"]).status.code(), Some(0));
688 assert_eq!(run(&["--reason", "task package", "--", "sh", "-c", "exit 3"]).status.code(), Some(3));
689 let log = std::fs::read_to_string(root.join("history.log")).unwrap();
690 let rows: Vec<Vec<&str>> = log.lines().map(|l| l.split('\t').collect()).collect();
691 assert_eq!(rows.len(), 2, "one line per run: {log:?}");
692 assert!(rows.iter().all(|r| r.len() == 6), "epoch, agent, reason, waited, held, exit: {log:?}");
693 assert_eq!((rows[0][2], rows[0][5]), ("cargo test", "0"));
694 assert_eq!((rows[1][2], rows[1][5]), ("task package", "3"), "the wrapped command's exit code is recorded");
695 let summary = String::from_utf8_lossy(&run(&["history"]).stdout).to_string();
696 assert!(summary.starts_with("runs: 2,"), "got {summary:?}");
697 assert!(contains_all(&summary, &["cargo test", "task package"]), "got {summary:?}");
698 }
699
700 #[test]
703 fn an_interrupted_run_is_recorded_and_a_long_log_rotates() {
704 let Some(bash) = bash() else { return };
705 let h = home();
706 let script = h.path().join("build-slot.sh");
707 std::fs::write(&script, lf(SCRIPT)).unwrap();
708 let root = h.path().join("slot dir");
709 let run = |args: &[&str]| run_slot(&bash, &script, &root, args);
710 let out = run(&["--reason", "cargo test", "--", "bash", "-c", "kill -TERM $PPID; sleep 1"]);
712 assert_eq!(out.status.code(), Some(130));
713 let log = std::fs::read_to_string(root.join("history.log")).unwrap();
714 let rows: Vec<Vec<&str>> = log.lines().map(|l| l.split('\t').collect()).collect();
715 assert_eq!(rows.len(), 1, "recorded once, not twice: {log:?}");
716 assert_eq!((rows[0][2], rows[0][5]), ("cargo test", "130"));
717 assert!(!root.join("slot").exists(), "the slot is freed");
718
719 let filler = "1\tx\told\t0\t0\t0\n".repeat(2001);
720 std::fs::write(root.join("history.log"), filler).unwrap();
721 assert_eq!(run(&["--reason", "task package", "--", "true"]).status.code(), Some(0));
722 assert!(root.join("history.log.1").exists(), "past 2000 lines the log is renamed aside");
723 assert!(!root.join("history.log").exists(), "and the next append starts a new file");
724 let summary = String::from_utf8_lossy(&run(&["history"]).stdout).to_string();
725 assert!(summary.starts_with("runs: 2002,"), "history reads both generations: {summary:?}");
726 }
727
728 #[test]
729 fn shim_functions_are_offered_for_every_installed_shim_and_nothing_else() {
730 let h = home();
731 assert!(shim_function_env(h.path(), false).is_empty(), "no shims installed: no functions");
732 install(h.path()).unwrap();
733 let env = shim_function_env(h.path(), false);
734 let names: Vec<&str> = env.iter().map(|(k, _)| k.as_str()).collect();
735 assert_eq!(names, ["BASH_FUNC_cargo%%", "BASH_FUNC_task%%", "BASH_FUNC_npm%%", "BASH_FUNC_npx%%", "BASH_FUNC_docker%%"]);
736 let dir = shim_dir(h.path()).to_string_lossy().replace('\\', "/");
737 assert_eq!(env[0].1, format!("() {{ \"{dir}/cargo\" \"$@\"\n}}"));
738 assert!(shim_function_env(h.path(), true).is_empty(), "the opt-out switches them off");
739 std::fs::write(shim_dir(h.path()).join("cargo"), "#!/bin/sh\necho mine\n").unwrap();
741 let env = shim_function_env(h.path(), false);
742 assert!(env.iter().all(|(k, _)| k != "BASH_FUNC_cargo%%") && env.len() == 4);
743 }
744
745 #[test]
749 fn a_cargo_earlier_on_the_path_still_goes_through_the_slot_with_the_functions() {
750 let Some(bash) = bash() else { return };
751 let h = home();
752 install(h.path()).unwrap();
753 std::fs::write(script_path(h.path()), "#!/usr/bin/env bash\necho \"SLOT $*\"\n").unwrap();
756 let (user_bin, real_dir) = (h.path().join("userbin"), h.path().join("real"));
757 for (dir, text) in [(&user_bin, "BYPASS"), (&real_dir, "REAL")] {
758 std::fs::create_dir_all(dir).unwrap();
759 std::fs::write(dir.join("cargo"), format!("#!/usr/bin/env bash\necho {text}\n")).unwrap();
760 #[cfg(unix)]
761 {
762 use std::os::unix::fs::PermissionsExt;
763 std::fs::set_permissions(dir.join("cargo"), std::fs::Permissions::from_mode(0o755)).unwrap();
764 }
765 }
766 let sep = if cfg!(windows) { ";" } else { ":" };
767 let path = format!("{}{sep}{}{sep}{}{sep}{}", user_bin.display(), shim_dir(h.path()).display(), real_dir.display(), std::env::var("PATH").unwrap_or_default());
768 let run = |with_functions: bool| {
769 let mut cmd = std::process::Command::new(&bash);
770 cmd.args(["-c", "cargo test -p x"]).env("PATH", &path).env("HOME", h.path()).env_remove("BUILD_SLOT_HELD").env_remove("AGENTMUX_BUILD_SLOT_OFF");
771 if with_functions {
772 cmd.envs(shim_function_env(h.path(), false));
773 }
774 #[cfg(windows)]
775 {
776 use crate::win32::NoWindow;
777 cmd.no_window();
778 }
779 String::from_utf8_lossy(&cmd.output().unwrap().stdout).replace("\r\n", "\n").trim().to_string()
780 };
781 assert_eq!(run(false), "BYPASS", "without the functions the earlier cargo wins, which is the bug");
782 let out = run(true);
783 assert!(out.starts_with("SLOT --reason cargo test -- "), "got {out:?}");
784 assert!(out.contains("userbin") && out.ends_with("cargo test -p x"), "the slot runs the cargo the shell would have found, the one in the user's bin: {out:?}");
785 }
786
787 #[test]
790 fn the_tool_a_shim_runs_finds_the_shims_first() {
791 let Some(bash) = bash() else { return };
792 let h = home();
793 let (shim, real_dir) = (shim_dir(h.path()), h.path().join("real"));
794 std::fs::create_dir_all(&shim).unwrap();
795 std::fs::create_dir_all(&real_dir).unwrap();
796 std::fs::write(shim.join("task"), lf(SHIM_SH)).unwrap();
797 std::fs::write(real_dir.join("task"), "#!/usr/bin/env bash\necho \"FIRST ${PATH%%:*}\"\n").unwrap();
798 #[cfg(unix)]
799 {
800 use std::os::unix::fs::PermissionsExt;
801 std::fs::set_permissions(real_dir.join("task"), std::fs::Permissions::from_mode(0o755)).unwrap();
802 }
803 let sep = if cfg!(windows) { ";" } else { ":" };
804 let path = format!("{}{sep}{}{sep}{}", real_dir.display(), shim.display(), std::env::var("PATH").unwrap_or_default());
806 let mut cmd = std::process::Command::new(bash);
807 cmd.arg(shim.join("task")).arg("dev").env("PATH", path).env("HOME", h.path()).env("AGENTMUX_BUILD_SLOT_OFF", "1");
808 #[cfg(windows)]
809 {
810 use crate::win32::NoWindow;
811 cmd.no_window();
812 }
813 let out = String::from_utf8_lossy(&cmd.output().unwrap().stdout).replace("\r\n", "\n").trim().to_string();
814 assert!(out.starts_with("FIRST ") && out.ends_with(".agentmux/tools/bin"), "got {out:?}");
815 }
816
817 fn spawn_slot(bash: &Path, script: &Path, root: &Path, limit: Option<&str>, args: &[&str]) -> std::process::Child {
818 let env: Vec<(&str, &str)> = limit.map(|n| ("BUILD_SLOT_MAX", n)).into_iter().collect();
819 spawn_slot_env(bash, script, root, &env, args)
820 }
821
822 #[test]
825 fn a_limit_of_two_lets_two_runs_hold_a_slot_and_a_third_waits() {
826 let Some(bash) = bash() else { return };
827 let h = home();
828 let script = h.path().join("build-slot.sh");
829 std::fs::write(&script, lf(SCRIPT)).unwrap();
830 let root = h.path().join("locks");
831 let status = |limit: Option<&str>| {
832 let out = spawn_slot(&bash, &script, &root, limit, &["status"]).wait_with_output().unwrap();
833 String::from_utf8_lossy(&out.stdout).replace("\r\n", "\n")
834 };
835
836 let until = |limit: Option<&str>, want: &[&str]| {
838 let mut last = String::new();
839 for _ in 0..60 {
840 last = status(limit);
841 if contains_all(&last, want) {
842 return last;
843 }
844 std::thread::sleep(std::time::Duration::from_millis(500));
845 }
846 panic!("never saw {want:?} in the status; the last was {last:?}");
847 };
848
849 let first = spawn_slot(&bash, &script, &root, None, &["--", "sleep", "10"]);
851 until(None, &["slot: HELD"]);
852 let second = spawn_slot(&bash, &script, &root, None, &["--", "true"]);
853 let s = until(None, &["slot: HELD", "queued #1"]);
854 assert!(!s.contains("slot-2"), "one slot: the second waits, it does not take another: {s:?}");
855 let second = second.wait_with_output().unwrap();
856 assert_eq!(second.status.code(), Some(0));
857 let waited = String::from_utf8_lossy(&second.stderr).to_string();
858 assert!(contains_all(&waited, &["waiting for the build slot", "has waited", "slot: HELD by"]), "got {waited:?}");
859 first.wait_with_output().unwrap();
860
861 std::fs::write(root.join("limit"), "2\n").unwrap();
863 let a = spawn_slot(&bash, &script, &root, None, &["--", "sleep", "10"]);
864 until(None, &["slots: 1 of 2 in use"]);
865 let b = spawn_slot(&bash, &script, &root, None, &["--", "sleep", "10"]);
866 until(None, &["slot: HELD", "slot-2: HELD", "slots: 2 of 2 in use"]);
867 let c = spawn_slot(&bash, &script, &root, None, &["--", "true"]);
868 until(None, &["slots: 2 of 2 in use", "queued #1"]);
869 assert_eq!(c.wait_with_output().unwrap().status.code(), Some(0), "the third runs once one is released");
870 a.wait_with_output().unwrap();
871 b.wait_with_output().unwrap();
872 }
873
874 #[test]
877 fn a_nested_call_inside_a_held_slot_does_not_wait_for_itself() {
878 let Some(bash) = bash() else { return };
879 let h = home();
880 let script = h.path().join("build-slot.sh");
881 std::fs::write(&script, lf(SCRIPT)).unwrap();
882 let root = h.path().join("locks");
883 let outer = format!("bash '{}' -- echo inner", script.to_string_lossy().replace('\\', "/"));
884 let out = spawn_slot(&bash, &script, &root, None, &["--", "bash", "-c", &outer]);
885 let started = std::time::Instant::now();
886 let out = out.wait_with_output().unwrap();
887 assert!(started.elapsed() < std::time::Duration::from_secs(20), "the nested call waited for its own slot");
888 assert_eq!(out.status.code(), Some(0));
889 assert!(String::from_utf8_lossy(&out.stdout).contains("inner"));
890 let holder = spawn_slot(&bash, &script, &root, None, &["--", "sleep", "4"]);
892 std::thread::sleep(std::time::Duration::from_millis(1500));
893 let mut nested = std::process::Command::new(&bash);
894 nested.arg(&script).args(["--", "echo", "ran"]).env("AGENTMUX_BUILD_SLOT_DIR", &root).env("BUILD_SLOT_HELD", "1");
895 #[cfg(windows)]
896 {
897 use crate::win32::NoWindow;
898 nested.no_window();
899 }
900 let started = std::time::Instant::now();
901 let out = nested.output().unwrap();
902 assert!(started.elapsed() < std::time::Duration::from_secs(3), "a nested call queued behind another holder");
903 assert!(String::from_utf8_lossy(&out.stdout).contains("ran"));
904 holder.wait_with_output().unwrap();
905 }
906
907 #[test]
909 fn an_unusable_lock_folder_runs_the_command_with_a_warning() {
910 let Some(bash) = bash() else { return };
911 let h = home();
912 let script = h.path().join("build-slot.sh");
913 std::fs::write(&script, lf(SCRIPT)).unwrap();
914 let blocker = h.path().join("not-a-folder");
916 std::fs::write(&blocker, "x").unwrap();
917 let root = blocker.join("locks");
918 let started = std::time::Instant::now();
919 let out = spawn_slot(&bash, &script, &root, None, &["--", "sh", "-c", "echo ran; exit 7"]).wait_with_output().unwrap();
920 assert!(started.elapsed() < std::time::Duration::from_secs(10), "it must not wait for a lock it can't take");
921 assert_eq!(out.status.code(), Some(7), "the command's own exit code");
922 assert!(String::from_utf8_lossy(&out.stdout).contains("ran"));
923 assert!(String::from_utf8_lossy(&out.stderr).contains("running without the build slot"), "{:?}", String::from_utf8_lossy(&out.stderr));
924 }
925
926 #[test]
927 fn the_shim_fails_open() {
928 if bash().is_none() {
929 return;
930 }
931 assert_eq!(run_shim(false, false, &["test"]).unwrap(), "REAL test", "no lock script: cargo still runs");
932 assert_eq!(run_shim(true, true, &["test"]).unwrap(), "REAL test", "AGENTMUX_BUILD_SLOT_OFF skips the slot");
933 }
934
935 #[test]
941 fn a_wait_started_by_a_native_parent_waits_instead_of_leaving() {
942 let Some(bash) = bash() else { return };
943 let h = home();
944 let script = h.path().join("build-slot.sh");
945 std::fs::write(&script, lf(SCRIPT)).unwrap();
946 let root = h.path().join("slots");
948 let slot = root.join("slot");
949 std::fs::create_dir_all(&slot).unwrap();
950 std::fs::write(slot.join("owner"), "agent=other\ntoken=t\nstart=1\ncwd=/\ncmd=cargo test\n").unwrap();
951 std::fs::write(slot.join("heartbeat"), "").unwrap();
952 let mut cmd = std::process::Command::new(bash);
953 cmd.arg(&script)
954 .args(["--", "echo", "never"])
955 .env("AGENTMUX_BUILD_SLOT_DIR", &root)
956 .env_remove("BUILD_SLOT_HELD")
959 .env("BUILD_SLOT_POLL", "1")
960 .env("BUILD_SLOT_MAX_WAIT", "3");
961 #[cfg(windows)]
962 {
963 use crate::win32::NoWindow;
964 cmd.no_window();
965 }
966 let out = cmd.output().unwrap();
967 let err = String::from_utf8_lossy(&out.stderr);
968 assert!(!err.contains("is gone"), "the wait took its parent for gone: {err}");
969 assert_eq!(out.status.code(), Some(75), "it should wait out BUILD_SLOT_MAX_WAIT and give up: {err}");
970 assert!(!String::from_utf8_lossy(&out.stdout).contains("never"), "the command must not run while the slot is held");
971 }
972
973 fn spawn_slot_env(bash: &Path, script: &Path, root: &Path, env: &[(&str, &str)], args: &[&str]) -> std::process::Child {
975 let mut cmd = std::process::Command::new(bash);
976 cmd.arg(script)
977 .args(args)
978 .env("AGENTMUX_BUILD_SLOT_DIR", root)
979 .env_remove("BUILD_SLOT_HELD")
980 .env_remove("BUILD_SLOT_MAX")
981 .env("BUILD_SLOT_POLL", "1")
982 .envs(env.iter().copied())
983 .stdin(std::process::Stdio::null())
984 .stdout(std::process::Stdio::piped())
985 .stderr(std::process::Stdio::piped());
986 #[cfg(windows)]
987 {
988 use crate::win32::NoWindow;
989 cmd.no_window();
990 }
991 cmd.spawn().unwrap()
992 }
993
994 fn queue_tickets(root: &Path) -> Vec<(String, String)> {
995 let mut tickets: Vec<(String, String)> = std::fs::read_dir(root.join("queue"))
996 .map(|d| {
997 d.filter_map(|e| e.ok())
998 .filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
999 .map(|e| (e.file_name().to_string_lossy().to_string(), std::fs::read_to_string(e.path()).unwrap_or_default()))
1000 .collect()
1001 })
1002 .unwrap_or_default();
1003 tickets.sort();
1004 tickets
1005 }
1006
1007 fn wait_for(what: &str, mut ok: impl FnMut() -> bool) {
1009 for _ in 0..120 {
1010 if ok() {
1011 return;
1012 }
1013 std::thread::sleep(std::time::Duration::from_millis(250));
1014 }
1015 panic!("never saw {what}");
1016 }
1017
1018 #[test]
1021 fn status_says_a_holder_is_idle_only_when_srv_flagged_that_run() {
1022 let Some(bash) = bash() else { return };
1023 let h = home();
1024 let script = h.path().join("build-slot.sh");
1025 std::fs::write(&script, lf(SCRIPT)).unwrap();
1026 let root = h.path().join("locks");
1027 let status = || {
1028 let out = spawn_slot(&bash, &script, &root, None, &["status"]).wait_with_output().unwrap();
1029 String::from_utf8_lossy(&out.stdout).replace("\r\n", "\n")
1030 };
1031 let mut holder = spawn_slot(&bash, &script, &root, None, &["--", "sleep", "90"]);
1032 wait_for("the holder", || read_holder(&root, now_secs()).is_some());
1033 let held = read_holder(&root, now_secs()).expect("a live holder");
1034 assert!(held.pid.is_some_and(|p| p > 1), "the owner file names the script's pid: {held:?}");
1035 if cfg!(windows) {
1036 assert!(held.winpid.is_some_and(|p| p > 1), "Git Bash records its Windows process id: {held:?}");
1037 }
1038 let busy = status();
1039 assert!(busy.contains("HELD by") && !busy.contains("idle"), "a holder srv has not flagged is not idle: {busy}");
1040
1041 write_idle(&root, "some-other-run", now_secs() - 5 * 60).unwrap();
1042 assert!(!root.join("slot").join("idle").exists(), "a note for another run is not written onto this one");
1043 std::fs::write(root.join("slot").join("idle"), format!("token=an-earlier-run\nidle_since={}\n", now_secs() - 5 * 60)).unwrap();
1044 assert!(!status().contains("idle"), "a note an earlier holder left is not this holder's");
1045
1046 write_idle(&root, &held.token, now_secs() - 12 * 60).unwrap();
1047 let idle = status();
1048 assert!(
1049 idle.contains("idle for 12 min, no CPU") && idle.contains("not stopped"),
1050 "got {idle}; owner {:?}; idle file {:?}",
1051 std::fs::read_to_string(root.join("slot").join("owner")),
1052 std::fs::read_to_string(root.join("slot").join("idle"))
1053 );
1054 clear_idle(&root);
1055 assert!(!status().contains("idle"), "work removes the note");
1056 let _ = holder.kill();
1057 let _ = holder.wait();
1058 }
1059
1060 #[test]
1066 fn a_slow_waiter_keeps_its_place_in_the_line() {
1067 let Some(bash) = bash() else { return };
1068 let h = home();
1069 let script = h.path().join("build-slot.sh");
1070 std::fs::write(&script, lf(SCRIPT)).unwrap();
1071 let root = h.path().join("locks");
1072 let order = h.path().join("order.txt");
1073 let append = |who: &str| format!("echo {who} >> \"{}\"", order.to_string_lossy().replace('\\', "/"));
1074
1075 let holder = spawn_slot(&bash, &script, &root, None, &["--", "sleep", "8"]);
1076 wait_for("the holder", || root.join("slot").join("owner").exists());
1077 wait_for("the holder's ticket to go", || queue_tickets(&root).is_empty());
1078 let limit = [("BUILD_SLOT_TICKET_STALE_SECS", "2")];
1079 let slow = [("BUILD_SLOT_TICKET_STALE_SECS", "2"), ("BUILD_SLOT_POLL", "4")];
1080 let a = spawn_slot_env(&bash, &script, &root, &slow, &["--", "bash", "-c", &append("A")]);
1081 wait_for("A's ticket", || queue_tickets(&root).len() == 1);
1082 std::thread::sleep(std::time::Duration::from_millis(2200));
1084 let b = spawn_slot_env(&bash, &script, &root, &limit, &["--", "bash", "-c", &append("B")]);
1085 assert_eq!(a.wait_with_output().unwrap().status.code(), Some(0));
1086 assert_eq!(b.wait_with_output().unwrap().status.code(), Some(0));
1087 holder.wait_with_output().unwrap();
1088 let ran = std::fs::read_to_string(&order).unwrap().replace("\r\n", "\n");
1089 assert_eq!(ran, "A\nB\n", "A arrived first and must run first, even though its loop is slow");
1090 }
1091
1092 #[test]
1095 fn the_ticket_of_a_waiter_that_is_gone_is_dropped() {
1096 let Some(bash) = bash() else { return };
1097 let h = home();
1098 let script = h.path().join("build-slot.sh");
1099 std::fs::write(&script, lf(SCRIPT)).unwrap();
1100 let root = h.path().join("locks");
1101 std::fs::create_dir_all(root.join("queue")).unwrap();
1102 let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
1103 let ticket = root.join("queue").join(format!("{}-2147483000", now - 300));
1105 std::fs::write(&ticket, "gone: cargo test\n").unwrap();
1106 let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
1107 std::fs::File::options().write(true).open(&ticket).unwrap().set_modified(old).unwrap();
1108 let out = spawn_slot_env(&bash, &script, &root, &[("BUILD_SLOT_MAX_WAIT", "150")], &["--", "echo", "ran"])
1111 .wait_with_output()
1112 .unwrap();
1113 assert_eq!(out.status.code(), Some(0), "{}", String::from_utf8_lossy(&out.stderr));
1114 assert!(String::from_utf8_lossy(&out.stdout).contains("ran"));
1115 assert!(!ticket.exists(), "the dead waiter's ticket is removed");
1116 }
1117
1118 #[test]
1121 fn a_ticket_that_goes_missing_comes_back_in_the_same_place() {
1122 let Some(bash) = bash() else { return };
1123 let h = home();
1124 let script = h.path().join("build-slot.sh");
1125 std::fs::write(&script, lf(SCRIPT)).unwrap();
1126 let root = h.path().join("locks");
1127 let holder = spawn_slot(&bash, &script, &root, None, &["--", "sleep", "9"]);
1128 wait_for("the holder", || root.join("slot").join("owner").exists());
1129 wait_for("the holder's ticket to go", || queue_tickets(&root).is_empty());
1131 let waiter = spawn_slot(&bash, &script, &root, None, &["--", "true"]);
1132 wait_for("the waiter's ticket", || {
1133 let t = queue_tickets(&root);
1134 t.len() == 1 && !t[0].1.is_empty()
1135 });
1136 let (name, text) = queue_tickets(&root).remove(0);
1137 assert!(text.contains("true"), "the ticket says who waits and for what: {text:?}");
1138 std::fs::remove_file(root.join("queue").join(&name)).unwrap();
1139 wait_for("the ticket again", || !queue_tickets(&root).is_empty());
1140 assert_eq!(queue_tickets(&root), vec![(name, text)], "back under its own name, with its text");
1141 assert_eq!(waiter.wait_with_output().unwrap().status.code(), Some(0));
1142 holder.wait_with_output().unwrap();
1143 }
1144
1145 #[test]
1147 fn status_lists_the_waiters_in_line_and_never_an_empty_entry() {
1148 let Some(bash) = bash() else { return };
1149 let h = home();
1150 let script = h.path().join("build-slot.sh");
1151 std::fs::write(&script, lf(SCRIPT)).unwrap();
1152 let root = h.path().join("locks");
1153 std::fs::create_dir_all(root.join("queue")).unwrap();
1154 let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
1155 std::fs::write(root.join("queue").join(format!("{}-4242", now - 5)), "lazo: cargo test\n").unwrap();
1156 std::fs::write(root.join("queue").join(format!("{}-4343", now - 4)), "").unwrap();
1157 let out = spawn_slot(&bash, &script, &root, None, &["status"]).wait_with_output().unwrap();
1158 let text = String::from_utf8_lossy(&out.stdout).replace("\r\n", "\n");
1159 assert!(text.contains("queued #1: lazo: cargo test"), "got {text:?}");
1160 assert!(text.contains("queued #2: (waiter pid 4343)"), "got {text:?}");
1161 }
1162}