1use crate::git;
9use crate::ui::{error_sign, valid_sign, warning_sign};
10use std::path::Path;
11use std::process::{Command, Stdio};
12use std::sync::OnceLock;
13
14static OVERRIDE: OnceLock<Vec<String>> = OnceLock::new();
25
26static NOT_THE_INDEX: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
45
46pub fn override_file_set(files: Vec<String>) {
49 NOT_THE_INDEX.store(true, std::sync::atomic::Ordering::SeqCst);
53 let _ = OVERRIDE.set(files);
54}
55
56pub fn not_the_index() -> bool {
58 NOT_THE_INDEX.load(std::sync::atomic::Ordering::SeqCst)
59}
60
61const DOC_EXTS: &[&str] = &[".md", ".mdx", ".rst", ".adoc"];
65
66pub fn staged_docs_only() -> bool {
73 if not_the_index() {
74 return false;
75 }
76 let Some(raw) = git::stdout_paths(&["diff", "--cached", "--no-renames", "--name-status"])
77 else {
78 return false;
79 };
80 !raw.is_empty()
81 && raw.len() % 2 == 0
82 && raw.chunks(2).all(|pair| {
83 pair[0] == "M"
84 && !pair[1].starts_with("adr/")
85 && DOC_EXTS.iter().any(|e| pair[1].ends_with(e))
86 })
87}
88
89pub fn staged_files(exts: &[&str]) -> Vec<String> {
100 if let Some(all) = OVERRIDE.get() {
101 return all
102 .iter()
103 .filter(|f| exts.is_empty() || exts.iter().any(|e| f.ends_with(e)))
104 .cloned()
105 .collect();
106 }
107 static INDEX: OnceLock<Vec<String>> = OnceLock::new();
108 INDEX
109 .get_or_init(|| {
110 match git::stdout_paths(&["diff", "--diff-filter=d", "--cached", "--name-only"]) {
111 Some(files) => files,
112 None => {
119 warn(
120 "git would not list the staged files — the checks are judging \
121 an EMPTY set, not a verified one",
122 );
123 Vec::new()
124 }
125 }
126 })
127 .iter()
128 .filter(|f| exts.is_empty() || exts.iter().any(|e| f.ends_with(e)))
129 .cloned()
130 .collect()
131}
132
133pub fn tracked_files() -> Option<Vec<String>> {
156 static TRACKED: OnceLock<Option<Vec<String>>> = OnceLock::new();
157 TRACKED
158 .get_or_init(|| match git::stdout_paths(&["ls-files"]) {
159 Some(files) => Some(files),
160 None => {
161 warn(
162 "git would not list the repository's files — opt-in gated checks \
163 will run rather than be skipped on an unverified answer",
164 );
165 None
166 }
167 })
168 .clone()
169}
170
171pub fn repo_root() -> String {
183 static ROOT: OnceLock<String> = OnceLock::new();
186 ROOT.get_or_init(|| {
187 git::stdout(&["rev-parse", "--show-toplevel"]).unwrap_or_else(|| ".".into())
188 })
189 .clone()
190}
191
192pub fn repo_root_checked() -> Result<String, String> {
208 git::stdout(&["rev-parse", "--show-toplevel"])
209 .filter(|s| !s.is_empty())
210 .ok_or_else(|| "not inside a git repository".to_string())
211}
212
213#[derive(Debug, Clone, PartialEq, Eq)]
215pub(crate) enum Ambient {
216 Path { path: String, version: Version },
218 Npx { version: String },
221}
222
223#[derive(Debug, Clone, PartialEq, Eq)]
225pub(crate) enum Version {
226 Known(String),
227 Unknown,
229 TimedOut,
231}
232
233pub(crate) const PROBE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(5);
238
239pub(crate) fn pinned_tool(root: &str, tool: &str) -> Option<String> {
243 if let Some(p) = in_bin_dir(&format!("{root}/node_modules/.bin"), tool) {
247 return Some(p);
248 }
249 let common = git::stdout(&["rev-parse", "--path-format=absolute", "--git-common-dir"])?;
250 let main = Path::new(&common).parent()?;
251 in_bin_dir(&main.join("node_modules/.bin").to_string_lossy(), tool)
252}
253
254enum Found {
256 Tool(Vec<String>, Ambient),
257 NpxHung,
259 Nothing,
260}
261
262fn ambient_tool(root: &str, tool: &str) -> Found {
265 if let Some(path) = which(tool) {
266 let argv = vec![path.clone()];
267 let version = probe_version(&argv, root);
268 return Found::Tool(argv, Ambient::Path { path, version });
269 }
270 if which("npx").is_none() {
275 return Found::Nothing;
276 }
277 let npx = vec![program("npx"), "--no-install".to_string(), tool.to_string()];
278 match probe_version(&npx, root) {
279 Version::Known(version) => Found::Tool(npx, Ambient::Npx { version }),
280 Version::TimedOut => Found::NpxHung,
281 Version::Unknown => Found::Nothing,
283 }
284}
285
286fn probe_version(argv: &[String], root: &str) -> Version {
290 static NEVER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
291 let mut probe = argv.to_vec();
292 probe.push("--version".to_string());
293 let deadline = std::time::Instant::now() + PROBE_DEADLINE;
296 match crate::tree_run::run_output(&probe, Path::new(root), deadline, &NEVER) {
297 Ok(out) => version_in(&out).map_or(Version::Unknown, Version::Known),
298 Err(crate::tree_run::TreeRun::TimedOut) => Version::TimedOut,
299 Err(_) => Version::Unknown,
300 }
301}
302
303fn version_in(out: &str) -> Option<String> {
308 out.lines().find_map(|line| {
309 let word = line.trim_start();
310 let word = word.strip_prefix('v').unwrap_or(word);
311 let end = word
312 .find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+')))
313 .unwrap_or(word.len());
314 let v = &word[..end];
315 let mut parts = v.splitn(3, '.');
316 let whole = |p: Option<&str>| {
317 p.is_some_and(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()))
318 };
319 let (major, minor) = (parts.next(), parts.next());
320 let patch_starts = parts
321 .next()
322 .is_some_and(|s| s.starts_with(|c: char| c.is_ascii_digit()));
323 (whole(major) && whole(minor) && patch_starts).then(|| v.to_string())
324 })
325}
326
327#[derive(Debug, Clone, PartialEq, Eq)]
331pub(crate) enum JsTool {
332 Pinned(Vec<String>),
334 Ambient { argv: Vec<String>, ambient: Ambient },
337 NotInstalled,
340 NpxHung,
342 Missing,
344}
345
346pub(crate) struct JsUse {
349 pub(crate) tool: JsTool,
350 name: &'static str,
351 manager: crate::snapshot_prep::Manager,
352}
353
354pub(crate) fn resolve_js_tool(root: &str, name: &'static str) -> JsUse {
358 let manifest = std::fs::read_to_string(Path::new(root).join("package.json")).ok();
359 let manager = manifest
360 .as_deref()
361 .and_then(crate::snapshot_prep::declared_manager)
362 .or_else(|| crate::snapshot_prep::Manager::from_root_lockfile(Path::new(root)))
363 .unwrap_or(crate::snapshot_prep::Manager::Npm);
364 let tool = if let Some(p) = pinned_tool(root, name) {
365 JsTool::Pinned(vec![p])
366 } else if manifest
367 .as_deref()
368 .is_some_and(|text| package_json_declares(text, name))
369 {
370 JsTool::NotInstalled
371 } else {
372 match ambient_tool(root, name) {
373 Found::Tool(argv, ambient) => JsTool::Ambient { argv, ambient },
374 Found::NpxHung => JsTool::NpxHung,
375 Found::Nothing => JsTool::Missing,
376 }
377 };
378 JsUse {
379 tool,
380 name,
381 manager,
382 }
383}
384
385impl JsUse {
386 pub(crate) fn warn_ambient(&self, ambient: &Ambient) {
390 let name = self.name;
391 let (from, version) = match ambient {
392 Ambient::Npx { version } => {
393 ("npx's cache".to_string(), Version::Known(version.clone()))
394 }
395 Ambient::Path { path, version } => (path.clone(), version.clone()),
396 };
397 let secs = PROBE_DEADLINE.as_secs();
398 let (named, pin, note) = match &version {
399 Version::Known(v) => (format!("{name} {v}"), format!("{name}@{v}"), ""),
400 Version::Unknown => (
401 format!("{name} (unknown version)"),
402 name.to_string(),
403 " (latest, not necessarily this one)",
404 ),
405 Version::TimedOut => (
406 format!("{name} (no --version in {secs} s)"),
407 name.to_string(),
408 " (latest, not necessarily this one)",
409 ),
410 };
411 warn(&format!(
412 "{} from {} is not in the root package.json",
413 crate::ui::sanitize(&named),
414 crate::ui::sanitize(&from)
415 ));
416 warn(&format!(
417 "Pin it: {}{note}",
418 hl(&self.manager.add_dev_command(&pin))
419 ));
420 }
421
422 pub(crate) fn warn_unavailable(&self) {
425 let name = self.name;
426 match &self.tool {
427 JsTool::NotInstalled => warn(&format!(
428 "{name} is in package.json but not installed: run {}",
429 hl(&format!("{} install", self.manager.tool()))
430 )),
431 JsTool::NpxHung => warn(&format!(
432 "npx --no-install {name} --version did not answer in {} s. Pin it: {}",
433 PROBE_DEADLINE.as_secs(),
434 hl(&self.manager.add_dev_command(name))
435 )),
436 JsTool::Missing => warn(&format!(
439 "{name} config found but no {name} binary. Run {}",
440 hl(&self.manager.add_dev_command(name))
441 )),
442 JsTool::Pinned(_) | JsTool::Ambient { .. } => {}
443 }
444 }
445}
446
447fn package_json_declares(text: &str, tool: &str) -> bool {
456 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
457 let mut p = JsonWalk {
458 b: text.as_bytes(),
459 i: 0,
460 depth: 0,
461 };
462 p.declares(tool).unwrap_or(false)
463}
464
465const MAX_JSON_DEPTH: u16 = 128;
469
470struct JsonWalk<'a> {
471 b: &'a [u8],
472 i: usize,
473 depth: u16,
474}
475
476impl JsonWalk<'_> {
477 fn ws(&mut self) {
478 while self.b.get(self.i).is_some_and(u8::is_ascii_whitespace) {
479 self.i += 1;
480 }
481 }
482
483 fn eat(&mut self, c: u8) -> Option<()> {
484 self.ws();
485 (self.b.get(self.i) == Some(&c)).then(|| self.i += 1)
486 }
487
488 fn string(&mut self) -> Option<&[u8]> {
490 self.eat(b'"')?;
491 let start = self.i;
492 loop {
493 match *self.b.get(self.i)? {
494 b'\\' => self.i += 2,
495 b'"' => {
496 self.i += 1;
497 return self.b.get(start..self.i - 1);
498 }
499 _ => self.i += 1,
500 }
501 }
502 }
503
504 fn value(&mut self) -> Option<()> {
505 self.ws();
506 match *self.b.get(self.i)? {
507 b'"' => self.string().map(|_| ()),
508 b'{' => self.nested(|w| w.object(|_, w| w.value())),
509 b'[' => self.nested(|w| {
510 w.i += 1;
511 if w.eat(b']').is_some() {
512 return Some(());
513 }
514 loop {
515 w.value()?;
516 if w.eat(b',').is_none() {
517 return w.eat(b']');
518 }
519 }
520 }),
521 _ => {
522 let start = self.i;
523 while self
524 .b
525 .get(self.i)
526 .is_some_and(|c| !matches!(c, b',' | b'}' | b']') && !c.is_ascii_whitespace())
527 {
528 self.i += 1;
529 }
530 (self.i > start).then_some(())
531 }
532 }
533 }
534
535 fn nested(&mut self, f: impl FnOnce(&mut Self) -> Option<()>) -> Option<()> {
537 if self.depth >= MAX_JSON_DEPTH {
538 return None;
539 }
540 self.depth += 1;
541 let r = f(self);
542 self.depth -= 1;
543 r
544 }
545
546 fn object(&mut self, mut member: impl FnMut(&[u8], &mut Self) -> Option<()>) -> Option<()> {
549 self.eat(b'{')?;
550 if self.eat(b'}').is_some() {
551 return Some(());
552 }
553 loop {
554 let key = self.string()?.to_vec();
555 self.eat(b':')?;
556 member(&key, self)?;
557 if self.eat(b',').is_none() {
558 return self.eat(b'}');
559 }
560 }
561 }
562
563 fn declares(&mut self, tool: &str) -> Option<bool> {
564 let mut found = false;
565 self.object(|key, w| {
566 if key == b"dependencies" || key == b"devDependencies" {
567 w.ws();
568 if w.b.get(w.i) == Some(&b'{') {
569 return w.object(|dep, w2| {
570 found |= dep == tool.as_bytes();
571 w2.value()
572 });
573 }
574 }
575 w.value()
576 })?;
577 self.ws();
578 (self.i == self.b.len()).then_some(found)
580 }
581}
582
583pub fn which(tool: &str) -> Option<String> {
591 which_on(&std::env::var_os("PATH")?, tool)
592}
593
594pub fn which_on(path: &std::ffi::OsStr, tool: &str) -> Option<String> {
607 let exts: Vec<String> = if cfg!(windows) {
608 std::env::var("PATHEXT")
609 .unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into())
610 .split(';')
611 .filter(|e| !e.is_empty())
612 .map(|e| e.to_lowercase())
613 .collect()
614 } else {
615 Vec::new()
616 };
617 for dir in std::env::split_paths(path) {
618 for e in &exts {
624 let c = dir.join(format!("{tool}{e}"));
625 if c.is_file() {
626 return Some(c.to_string_lossy().into_owned());
627 }
628 }
629 let bare = dir.join(tool);
630 if bare.is_file() {
631 return Some(bare.to_string_lossy().into_owned());
632 }
633 }
634 None
635}
636
637fn in_bin_dir(dir: &str, tool: &str) -> Option<String> {
639 let bare = Path::new(dir).join(tool);
640 if bare.is_file() {
641 return Some(bare.to_string_lossy().into_owned());
642 }
643 if cfg!(windows) {
644 for e in [".cmd", ".exe", ".bat", ".ps1"] {
645 let c = Path::new(dir).join(format!("{tool}{e}"));
646 if c.is_file() {
647 return Some(c.to_string_lossy().into_owned());
648 }
649 }
650 }
651 None
652}
653
654pub fn program(name: &str) -> String {
664 which(name).unwrap_or_else(|| name.to_string())
665}
666
667pub fn first_existing(root: &str, names: &[&str]) -> Option<String> {
670 names
671 .iter()
672 .find(|n| Path::new(root).join(n).exists())
673 .map(|n| (*n).to_string())
674}
675
676pub fn strip_git_env(cmd: &mut Command) {
690 for (k, _) in std::env::vars_os() {
691 let key = k.to_string_lossy();
692 if key.starts_with("GIT_") {
693 cmd.env_remove(&k);
694 }
695 }
696 cmd.env_remove(INDEX_ENV);
700 cmd.env_remove(INDEX_GIT_DIR_ENV);
701}
702
703pub const INDEX_ENV: &str = "GREENGATE_INDEX_FILE";
706pub const INDEX_GIT_DIR_ENV: &str = "GREENGATE_INDEX_GIT_DIR";
710
711#[derive(Debug, Clone, PartialEq, Eq)]
713pub struct CommitIndex {
714 pub file: std::path::PathBuf,
715 pub git_dir: std::path::PathBuf,
716}
717
718#[derive(Debug, Clone, PartialEq, Eq)]
720pub enum IndexLookupError {
721 CurrentDir(String),
723 Git { args: String, why: String },
725}
726
727impl std::fmt::Display for IndexLookupError {
728 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
729 match self {
730 Self::CurrentDir(e) => write!(f, "current directory: {e}"),
731 Self::Git { args, why } => write!(f, "git {args} failed: {why}"),
732 }
733 }
734}
735
736pub fn commit_index() -> Result<CommitIndex, IndexLookupError> {
743 let here = std::env::current_dir().map_err(|e| IndexLookupError::CurrentDir(e.to_string()))?;
744 let absolute = |p: std::path::PathBuf| if p.is_absolute() { p } else { here.join(p) };
745 let git_path = |args: &[&str]| -> Result<std::path::PathBuf, IndexLookupError> {
746 let out = crate::git::stdout_raw_or_why(args).map_err(|why| IndexLookupError::Git {
747 args: args.join(" "),
748 why,
749 })?;
750 Ok(path_from_bytes(strip_one_newline(out)))
751 };
752 let file = match std::env::var_os("GIT_INDEX_FILE").filter(|v| !v.is_empty()) {
753 Some(named) => std::path::PathBuf::from(named),
754 None => git_path(&["rev-parse", "--git-path", "index"])?,
755 };
756 let git_dir = git_path(&["rev-parse", "--absolute-git-dir"])?;
757 Ok(CommitIndex {
758 file: absolute(file),
759 git_dir,
760 })
761}
762
763fn strip_one_newline(mut out: Vec<u8>) -> Vec<u8> {
766 if out.last() == Some(&b'\n') {
767 out.pop();
768 }
769 out
770}
771
772#[cfg(unix)]
773fn path_from_bytes(bytes: Vec<u8>) -> std::path::PathBuf {
774 use std::os::unix::ffi::OsStringExt;
775 std::path::PathBuf::from(std::ffi::OsString::from_vec(bytes))
776}
777
778#[cfg(not(unix))]
779fn path_from_bytes(bytes: Vec<u8>) -> std::path::PathBuf {
780 std::path::PathBuf::from(String::from_utf8_lossy(&bytes).into_owned())
781}
782
783pub fn check_timeout(settings: &crate::config::Settings) -> u64 {
793 *settings.timeout.get_or_init(|| {
794 crate::config::integer_or(settings, "greengate.timeout", 3600, 0..=86_400) as u64
795 })
796}
797
798pub fn idle_timeout(settings: &crate::config::Settings) -> u64 {
812 *settings.idle.get_or_init(|| {
813 crate::config::integer_or(settings, "greengate.idleTimeout", 120, 0..=86_400) as u64
814 })
815}
816
817pub fn idle_cpu_credit(settings: &crate::config::Settings) -> bool {
822 *settings
823 .idle_cpu
824 .get_or_init(|| crate::config::boolean_or(settings, "greengate.idleCpuCredit", true))
825}
826
827pub fn lock_wait(settings: &crate::config::Settings) -> LockWait {
834 match *settings.lock_wait.get_or_init(|| {
835 crate::config::integer_or(settings, "greengate.lockWait", 600, 0..=86_400) as u64
836 }) {
837 0 => LockWait::UntilCeiling,
838 s => LockWait::Secs(s),
839 }
840}
841
842#[derive(Debug, Clone, Copy, PartialEq, Eq)]
844pub enum LockWait {
845 Secs(u64),
846 UntilCeiling,
850}
851
852pub(crate) fn unique_name(prefix: &str) -> String {
868 use std::collections::hash_map::RandomState;
869 use std::hash::{BuildHasher, Hash, Hasher};
870
871 let pid = std::process::id();
872 let mut hasher = RandomState::new().build_hasher();
873 pid.hash(&mut hasher);
874 std::time::SystemTime::now()
875 .duration_since(std::time::UNIX_EPOCH)
876 .unwrap_or_default()
877 .as_nanos()
878 .hash(&mut hasher);
879 format!("{prefix}-{pid}-{:016x}", hasher.finish())
880}
881
882pub fn human_secs(secs: u64) -> String {
884 match secs {
885 s if s < 60 => format!("{s}s"),
886 s if s < 3600 => format!("{}m{:02}s", s / 60, s % 60),
887 s => format!("{}h{:02}m", s / 3600, (s % 3600) / 60),
888 }
889}
890
891pub const LAST_LINE_CHARS: usize = 200;
893
894pub const BUSY_MILLI_CORES: u32 = 100;
898
899#[derive(Debug, Clone, Copy, PartialEq, Eq)]
901pub enum CpuState {
902 Off = 0,
905 Waiting = 1,
908 Measuring = 2,
910 Unavailable = 3,
912}
913
914pub struct Activity {
924 base: std::time::Instant,
925 last_out: std::sync::atomic::AtomicU64,
926 last_busy: std::sync::atomic::AtomicU64,
927 measured_since: std::sync::atomic::AtomicU64,
930 last_measured: std::sync::atomic::AtomicU64,
932 rate_milli: std::sync::atomic::AtomicU32,
933 interval_ms: std::sync::atomic::AtomicU32,
934 cpu: std::sync::atomic::AtomicU8,
935 wait_since: std::sync::atomic::AtomicU64,
938 wait_kind: std::sync::atomic::AtomicU8,
940 waited_ns: std::sync::atomic::AtomicU64,
943 last_wait_kind: std::sync::atomic::AtomicU8,
946 budget_secs: std::sync::atomic::AtomicU32,
950 load_avg_milli: std::sync::atomic::AtomicU32,
952 load_cores: std::sync::atomic::AtomicU32,
953 load_factor_milli: std::sync::atomic::AtomicU32,
954 last_line: std::sync::Mutex<String>,
957}
958
959impl Activity {
960 pub fn new() -> std::sync::Arc<Activity> {
961 std::sync::Arc::new(Activity {
962 base: std::time::Instant::now(),
963 last_out: Default::default(),
964 last_busy: Default::default(),
965 measured_since: Default::default(),
966 last_measured: Default::default(),
967 rate_milli: Default::default(),
968 interval_ms: Default::default(),
969 cpu: std::sync::atomic::AtomicU8::new(CpuState::Off as u8),
970 wait_since: Default::default(),
971 wait_kind: Default::default(),
972 waited_ns: Default::default(),
973 last_wait_kind: Default::default(),
974 budget_secs: Default::default(),
975 load_avg_milli: Default::default(),
976 load_cores: Default::default(),
977 load_factor_milli: Default::default(),
978 last_line: std::sync::Mutex::new(String::new()),
979 })
980 }
981
982 pub fn last_wait_kind(&self) -> Option<crate::hooks::wait::WaitKind> {
984 crate::hooks::wait::WaitKind::from_code(
985 self.last_wait_kind
986 .load(std::sync::atomic::Ordering::Relaxed),
987 )
988 }
989
990 pub fn stderr_line(&self, raw: &str) {
995 use std::sync::atomic::Ordering::Relaxed;
996 let line = crate::hooks::wait::strip_csi(raw);
997 if !line.trim().is_empty() {
998 let mut keep = self.last_line.lock().unwrap_or_else(|p| p.into_inner());
999 keep.clear();
1000 keep.extend(line.trim().chars().take(LAST_LINE_CHARS));
1001 }
1002 match crate::hooks::wait::marker(&line) {
1003 Some(kind) => {
1004 self.wait_kind.store(kind.code(), Relaxed);
1005 self.last_wait_kind.store(kind.code(), Relaxed);
1006 let _ = self
1009 .wait_since
1010 .compare_exchange(0, self.now() + 1, Relaxed, Relaxed);
1011 }
1012 None => self.end_wait(),
1013 }
1014 }
1015
1016 pub fn end_wait(&self) {
1019 use std::sync::atomic::Ordering::Relaxed;
1020 let since = self.wait_since.swap(0, Relaxed);
1021 if since != 0 {
1022 let spent = self.now().saturating_sub(since - 1);
1023 self.waited_ns.fetch_add(spent, Relaxed);
1024 }
1025 self.wait_kind.store(0, Relaxed);
1026 }
1027
1028 pub fn waiting(&self) -> Option<(crate::hooks::wait::WaitKind, std::time::Duration)> {
1030 use std::sync::atomic::Ordering::Relaxed;
1031 let since = self.wait_since.load(Relaxed);
1032 if since == 0 {
1033 return None;
1034 }
1035 let kind = crate::hooks::wait::WaitKind::from_code(self.wait_kind.load(Relaxed))?;
1036 Some((kind, self.since(since - 1)))
1037 }
1038
1039 pub fn waited_total(&self) -> std::time::Duration {
1042 use std::sync::atomic::Ordering::Relaxed;
1043 let banked = std::time::Duration::from_nanos(self.waited_ns.load(Relaxed));
1044 banked + self.waiting().map_or(std::time::Duration::ZERO, |(_, d)| d)
1045 }
1046
1047 pub fn last_line(&self) -> Option<String> {
1049 let keep = self.last_line.lock().unwrap_or_else(|p| p.into_inner());
1050 (!keep.is_empty()).then(|| keep.clone())
1051 }
1052
1053 pub fn set_load(&self, budget_secs: u64, load: crate::load::Load, factor_milli: u32) {
1055 use std::sync::atomic::Ordering::Relaxed;
1056 self.budget_secs
1057 .store(u32::try_from(budget_secs).unwrap_or(u32::MAX), Relaxed);
1058 self.load_avg_milli.store(load.avg1_milli, Relaxed);
1059 self.load_cores.store(load.cores, Relaxed);
1060 self.load_factor_milli.store(factor_milli, Relaxed);
1061 }
1062
1063 pub fn load_scale(&self) -> Option<(u64, crate::load::Load, u32)> {
1066 use std::sync::atomic::Ordering::Relaxed;
1067 let factor = self.load_factor_milli.load(Relaxed);
1068 if factor <= 1000 {
1069 return None;
1070 }
1071 Some((
1072 u64::from(self.budget_secs.load(Relaxed)),
1073 crate::load::Load {
1074 avg1_milli: self.load_avg_milli.load(Relaxed),
1075 cores: self.load_cores.load(Relaxed),
1076 },
1077 factor,
1078 ))
1079 }
1080 fn offset(&self, at: std::time::Instant) -> u64 {
1081 u64::try_from(at.saturating_duration_since(self.base).as_nanos()).unwrap_or(u64::MAX)
1082 }
1083 fn now(&self) -> u64 {
1084 self.offset(std::time::Instant::now())
1085 }
1086 fn since(&self, offset: u64) -> std::time::Duration {
1087 std::time::Duration::from_nanos(self.now().saturating_sub(offset))
1088 }
1089 pub fn touch(&self) {
1091 self.last_out
1092 .fetch_max(self.now(), std::sync::atomic::Ordering::Relaxed);
1093 }
1094 pub fn quiet_for(&self) -> std::time::Duration {
1097 self.since(self.last_out.load(std::sync::atomic::Ordering::Relaxed))
1098 }
1099 pub fn silence_for(&self) -> std::time::Duration {
1104 if self.waiting().is_some() {
1105 std::time::Duration::ZERO
1106 } else {
1107 self.quiet_for()
1108 }
1109 }
1110 pub fn still_for(&self) -> std::time::Duration {
1114 let busy = self.last_busy.load(std::sync::atomic::Ordering::Relaxed);
1115 self.silence_for().min(self.since(busy))
1116 }
1117 pub fn cpu_state(&self) -> CpuState {
1118 match self.cpu.load(std::sync::atomic::Ordering::Relaxed) {
1119 1 => CpuState::Waiting,
1120 2 => CpuState::Measuring,
1121 3 => CpuState::Unavailable,
1122 _ => CpuState::Off,
1123 }
1124 }
1125 fn set_cpu_state(&self, s: CpuState) {
1126 self.cpu
1127 .store(s as u8, std::sync::atomic::Ordering::Relaxed);
1128 }
1129 pub fn fresh_rate(&self) -> Option<u32> {
1133 if self.cpu_state() != CpuState::Measuring {
1134 return None;
1135 }
1136 let end = self
1137 .last_measured
1138 .load(std::sync::atomic::Ordering::Relaxed);
1139 if end == 0 {
1140 return None;
1141 }
1142 let every = u64::from(self.interval_ms.load(std::sync::atomic::Ordering::Relaxed));
1143 let stale = std::time::Duration::from_millis(2 * every.max(1));
1144 (self.since(end - 1) <= stale)
1145 .then(|| self.rate_milli.load(std::sync::atomic::Ordering::Relaxed))
1146 }
1147 pub fn verdict(&self) -> CpuVerdict {
1152 match self.cpu_state() {
1153 CpuState::Off => return CpuVerdict::NotSampled,
1154 CpuState::Waiting | CpuState::Unavailable => return CpuVerdict::Unmeasured,
1155 CpuState::Measuring => {}
1156 }
1157 if let Some(rate) = self.fresh_rate().filter(|r| *r >= BUSY_MILLI_CORES) {
1158 return CpuVerdict::BusyAtKill(rate);
1159 }
1160 let since = self
1161 .measured_since
1162 .load(std::sync::atomic::Ordering::Relaxed);
1163 match (since, self.fresh_rate()) {
1164 (s, Some(_)) if s != 0 => CpuVerdict::MeasuredIdle(self.since(s - 1).as_secs()),
1165 _ => CpuVerdict::Unmeasured,
1166 }
1167 }
1168 pub fn record(
1171 &self,
1172 obs: crate::proctree::Observation,
1173 at: std::time::Instant,
1174 interval: std::time::Duration,
1175 ) {
1176 use std::sync::atomic::Ordering::Relaxed;
1177 self.interval_ms.store(
1178 u32::try_from(interval.as_millis()).unwrap_or(u32::MAX),
1179 Relaxed,
1180 );
1181 match obs {
1182 crate::proctree::Observation::Baseline => {
1183 self.measured_since.store(self.offset(at) + 1, Relaxed);
1184 self.set_cpu_state(CpuState::Waiting);
1185 }
1186 crate::proctree::Observation::Window(w) => {
1187 let milli = w.milli_cores();
1188 self.rate_milli.store(milli, Relaxed);
1189 self.last_measured.store(self.offset(w.end) + 1, Relaxed);
1190 if milli >= BUSY_MILLI_CORES {
1191 self.last_busy.fetch_max(self.offset(w.start), Relaxed);
1194 }
1195 if w.gapped {
1196 self.measured_since.store(self.offset(w.end) + 1, Relaxed);
1200 }
1201 self.set_cpu_state(CpuState::Measuring);
1202 }
1203 crate::proctree::Observation::Skipped => {}
1206 crate::proctree::Observation::Unmeasured => {
1207 self.measured_since.store(0, Relaxed);
1208 self.set_cpu_state(CpuState::Unavailable);
1209 }
1210 }
1211 }
1212 pub fn enable_cpu(&self) {
1214 self.set_cpu_state(CpuState::Waiting);
1215 }
1216 pub fn gate(&self) -> CpuGate {
1219 match self.verdict() {
1220 CpuVerdict::NotSampled => CpuGate::NotSampled,
1221 CpuVerdict::MeasuredIdle(_) | CpuVerdict::BusyAtKill(_) => CpuGate::Measured,
1222 CpuVerdict::Unmeasured => CpuGate::Unmeasured,
1223 }
1224 }
1225}
1226
1227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1235pub enum CpuGate {
1236 NotSampled,
1237 Measured,
1238 Unmeasured,
1239}
1240
1241#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1243pub enum CpuVerdict {
1244 NotSampled,
1246 MeasuredIdle(u64),
1249 Unmeasured,
1251 BusyAtKill(u32),
1254}
1255
1256pub fn cores(milli: u32) -> String {
1258 format!("~{}.{} cores", milli / 1000, (milli % 1000) / 100)
1259}
1260
1261pub fn network_probe_budget(settings: &crate::config::Settings) -> u64 {
1269 match check_timeout(settings) {
1270 0 => 0,
1271 t => t.min(30),
1272 }
1273}
1274
1275#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1277pub enum Why {
1278 Ceiling(u64),
1280 Silence(u64),
1282 Waited(crate::hooks::wait::WaitKind, u64),
1285}
1286
1287#[derive(Debug, Clone)]
1290pub struct Killed {
1291 pub why: Why,
1292 pub ran_secs: u64,
1294 pub quiet_secs: Option<u64>,
1297 pub cpu: CpuVerdict,
1299 pub idle_secs: u64,
1303 pub waiting: Option<(crate::hooks::wait::WaitKind, u64)>,
1305 pub last_line: Option<String>,
1309 pub load: Option<(crate::load::Load, u32)>,
1312}
1313
1314#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1317pub struct Clocks {
1318 pub ceiling: Option<u64>,
1320 pub silence: Option<u64>,
1323 pub lock_wait: LockWait,
1325 pub extended: Option<u64>,
1329 pub scale: u64,
1332}
1333
1334impl Clocks {
1335 pub fn ceiling_only(wall_secs: u64) -> Clocks {
1337 Clocks {
1338 ceiling: (wall_secs > 0).then_some(wall_secs),
1339 silence: None,
1340 lock_wait: LockWait::UntilCeiling,
1341 extended: None,
1342 scale: 1,
1343 }
1344 }
1345
1346 pub fn from_settings(settings: &crate::config::Settings, idle_secs: u64) -> Clocks {
1349 let wall = check_timeout(settings);
1350 let scale = idle_load_scale(settings);
1351 Clocks {
1352 ceiling: (wall > 0).then_some(wall),
1353 silence: (idle_secs > 0).then_some(idle_secs),
1354 lock_wait: lock_wait(settings),
1355 extended: (idle_secs > 0).then(|| idle_secs.saturating_mul(scale)),
1356 scale,
1357 }
1358 }
1359}
1360
1361const LOAD_EVERY: std::time::Duration = std::time::Duration::from_secs(5);
1363
1364pub fn idle_load_scale(settings: &crate::config::Settings) -> u64 {
1371 *settings.idle_load_scale.get_or_init(|| {
1372 crate::config::host_integer_or(settings, "greengate.idleLoadScale", 4, 1..=16) as u64
1373 })
1374}
1375
1376pub enum Ran {
1378 Status(std::process::ExitStatus),
1379 TimedOut(Killed),
1381}
1382
1383pub fn status_within(
1396 settings: &crate::config::Settings,
1397 cmd: &mut Command,
1398) -> std::io::Result<Ran> {
1399 if crate::host_slots::before_spawn(settings)? {
1402 cmd.env(crate::host_slots::HELD_ENV, "held");
1403 }
1404 crate::host_slots::bound(cmd);
1405 status_within_secs(cmd, check_timeout(settings))
1406}
1407
1408pub fn status_within_secs(cmd: &mut Command, budget_secs: u64) -> std::io::Result<Ran> {
1412 if budget_secs == 0 {
1413 return cmd.status().map(Ran::Status);
1414 }
1415 let mut child = cmd.spawn()?;
1416 wait_within(&mut child, Clocks::ceiling_only(budget_secs), None)
1417}
1418
1419fn run_observed(
1424 settings: &crate::config::Settings,
1425 cmd: &mut Command,
1426 on_output: impl Fn(&[u8]) + Send + Sync + 'static,
1427 ceiling_left: Option<u64>,
1428) -> std::io::Result<Ran> {
1429 let shared = std::sync::Arc::new(on_output);
1430 let for_stdout = std::sync::Arc::clone(&shared);
1431 run_observed_split(
1432 settings,
1433 cmd,
1434 move |bytes| for_stdout(bytes),
1435 move |bytes| shared(bytes),
1436 ceiling_left,
1437 )
1438}
1439
1440type OnBytes = std::sync::Arc<dyn Fn(&[u8]) + Send + Sync>;
1441
1442fn run_observed_split(
1444 settings: &crate::config::Settings,
1445 cmd: &mut Command,
1446 on_stdout: impl Fn(&[u8]) + Send + Sync + 'static,
1447 on_stderr: impl Fn(&[u8]) + Send + Sync + 'static,
1448 ceiling_left: Option<u64>,
1449) -> std::io::Result<Ran> {
1450 if crate::host_slots::before_spawn(settings)? {
1453 cmd.env(crate::host_slots::HELD_ENV, "held");
1454 }
1455 crate::host_slots::bound(cmd);
1456 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
1457 let activity = Activity::new();
1458 let on_stdout: OnBytes = std::sync::Arc::new(on_stdout);
1459 let on_stderr: OnBytes = std::sync::Arc::new(on_stderr);
1460 let mut child = cmd.spawn()?;
1461 activity.touch();
1465 let mut readers = Vec::new();
1466 let pipes = [
1471 (
1472 child
1473 .stdout
1474 .take()
1475 .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
1476 false,
1477 on_stdout,
1478 ),
1479 (
1480 child
1481 .stderr
1482 .take()
1483 .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
1484 true,
1485 on_stderr,
1486 ),
1487 ];
1488 for (pipe, is_stderr, on_output) in pipes {
1489 let Some(pipe) = pipe else { continue };
1490 let activity = std::sync::Arc::clone(&activity);
1491 readers.push(std::thread::spawn(move || {
1492 let mut pipe = pipe;
1493 let mut chunk = [0u8; 4096];
1494 let mut framer = crate::hooks::wait::LineFramer::default();
1495 let mut pending: Vec<u8> = Vec::new();
1501 loop {
1502 match std::io::Read::read(&mut pipe, &mut chunk) {
1503 Ok(0) | Err(_) => break,
1504 Ok(n) => {
1505 activity.touch();
1506 if is_stderr {
1507 for line in framer.feed(&chunk[..n]) {
1508 activity.stderr_line(&line);
1509 }
1510 } else {
1511 activity.end_wait();
1512 }
1513 pending.extend_from_slice(&chunk[..n]);
1514 if let Some(end) = whole_lines(&pending) {
1515 on_output(&pending[..end]);
1516 pending.drain(..end);
1517 }
1518 }
1519 }
1520 }
1521 if !pending.is_empty() {
1522 on_output(&pending);
1523 }
1524 }));
1525 }
1526 let _attached = crate::live::current_sink()
1528 .map(|(stage, idx)| stage.attach(idx, std::sync::Arc::clone(&activity)));
1529 let idle = idle_timeout(settings);
1530 let sampler = (idle > 0 && idle_cpu_credit(settings) && crate::proctree::SUPPORTED)
1531 .then(|| CpuSampler::start(child.id(), std::sync::Arc::clone(&activity), idle));
1532 let mut clocks = Clocks::from_settings(settings, idle);
1533 if let Some(left) = ceiling_left {
1534 clocks.ceiling = Some(left.max(1));
1537 }
1538 let ran = wait_within(&mut child, clocks, Some(&activity));
1539 if let Some(s) = sampler {
1540 s.stop();
1541 }
1542 for r in readers {
1543 let _ = r.join();
1545 }
1546 if let Ok(Ran::Status(_)) = &ran {
1550 let waited = activity.waited_total();
1551 if waited >= std::time::Duration::from_secs(1) {
1552 let what = activity
1553 .last_wait_kind()
1554 .map_or("a lock", crate::hooks::wait::WaitKind::describe);
1555 say(&format!(
1556 " (waited {} for {what})",
1557 human_secs(waited.as_secs())
1558 ));
1559 }
1560 }
1561 ran
1562}
1563
1564struct CpuSampler {
1570 stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
1571 handle: std::thread::JoinHandle<()>,
1572}
1573
1574impl CpuSampler {
1575 fn start(pid: u32, activity: std::sync::Arc<Activity>, idle_secs: u64) -> CpuSampler {
1576 activity.enable_cpu();
1577 let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1578 let flag = std::sync::Arc::clone(&stop);
1579 let handle = std::thread::Builder::new()
1580 .name("greengate-cpu".into())
1581 .spawn(move || sample_loop(pid, &activity, idle_secs, &flag))
1582 .expect("spawn the CPU sampler thread");
1583 CpuSampler { stop, handle }
1584 }
1585
1586 fn stop(self) {
1590 self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
1591 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1);
1592 while !self.handle.is_finished() && std::time::Instant::now() < deadline {
1593 std::thread::sleep(std::time::Duration::from_millis(10));
1594 }
1595 if self.handle.is_finished() {
1596 let _ = self.handle.join();
1597 }
1598 }
1599}
1600
1601pub fn sampling_schedule(idle_secs: u64) -> (std::time::Duration, std::time::Duration) {
1606 let ms = std::time::Duration::from_millis;
1607 let budget = std::time::Duration::from_secs(idle_secs);
1608 let first = (budget / 3)
1609 .min(std::time::Duration::from_secs(30))
1610 .max(ms(250));
1611 let every = (budget / 4).clamp(ms(250), std::time::Duration::from_secs(10));
1612 (first, every)
1613}
1614
1615fn sample_loop(
1616 pid: u32,
1617 activity: &Activity,
1618 idle_secs: u64,
1619 stop: &std::sync::atomic::AtomicBool,
1620) {
1621 use std::sync::atomic::Ordering::Relaxed;
1622 let (first, every) = sampling_schedule(idle_secs);
1623 let mut limits = crate::proctree::Limits::default();
1624 if let Some(n) = std::env::var("GREENGATE_CPU_MAX_PROCS")
1627 .ok()
1628 .and_then(|v| v.trim().parse::<usize>().ok())
1629 {
1630 limits.max_procs = n;
1631 }
1632 let trace = std::env::var_os("GREENGATE_CPU_TRACE");
1633 let mut tracker = crate::proctree::Tracker::default();
1634 let nap = |d: std::time::Duration| {
1635 let until = std::time::Instant::now() + d;
1636 while !stop.load(Relaxed) && std::time::Instant::now() < until {
1637 std::thread::sleep(std::time::Duration::from_millis(50));
1638 }
1639 };
1640 while !stop.load(Relaxed) {
1641 if activity.silence_for() < first {
1644 tracker = crate::proctree::Tracker::default();
1647 nap(std::time::Duration::from_millis(100));
1648 continue;
1649 }
1650 let snap = crate::proctree::snapshot(pid, &tracker.seen(), &limits);
1651 let at = std::time::Instant::now();
1652 let traced = trace.as_ref().map(|_| match &snap {
1653 crate::proctree::Snapshot::Complete(procs) => procs.clone(),
1654 _ => Vec::new(),
1655 });
1656 let obs = tracker.observe(at, snap);
1657 if let (Some(path), Some(procs)) = (&trace, traced) {
1658 trace_sample(path, pid, &procs, &obs);
1659 }
1660 activity.record(obs, at, every);
1661 nap(every);
1662 }
1663}
1664
1665fn trace_sample(
1671 path: &std::ffi::OsStr,
1672 root: u32,
1673 procs: &[crate::proctree::Proc],
1674 obs: &crate::proctree::Observation,
1675) {
1676 use std::io::Write;
1677 let Ok(mut f) = std::fs::OpenOptions::new()
1678 .create(true)
1679 .append(true)
1680 .open(path)
1681 else {
1682 return;
1683 };
1684 let mut text = String::new();
1685 for p in procs {
1686 text.push_str(&format!(
1687 "{} {} {} {}\n",
1688 p.id.pid, p.id.start, p.ppid, p.cpu_ns
1689 ));
1690 }
1691 let obs = match obs {
1692 crate::proctree::Observation::Window(w) => {
1693 format!("window {} milli-cores", w.milli_cores())
1694 }
1695 other => format!("{other:?}").to_lowercase(),
1696 };
1697 text.push_str(&format!("# root {root} {obs}\n"));
1698 let _ = f.write_all(text.as_bytes());
1699}
1700
1701pub fn status_streamed(
1713 settings: &crate::config::Settings,
1714 cmd: &mut Command,
1715 retry: Retry,
1716) -> std::io::Result<Ran> {
1717 let Some((stage, idx)) = crate::live::current_sink() else {
1718 return status_within(settings, cmd);
1719 };
1720 if crate::live::watching() {
1721 cmd.env("FORCE_COLOR", "1")
1724 .env("CLICOLOR_FORCE", "1")
1725 .env("CARGO_TERM_COLOR", "always");
1726 }
1727 let first = run_observed(
1728 settings,
1729 cmd,
1730 {
1731 let stage = std::sync::Arc::clone(&stage);
1732 move |bytes| stage.append_raw(idx, bytes)
1733 },
1734 None,
1735 );
1736 stage.runner_exit(idx, exit_of(&first));
1737 let Ok(Ran::TimedOut(k)) = &first else {
1738 return first;
1739 };
1740 let Some(left) = retry_budget(retry, k, check_timeout(settings)) else {
1741 return first;
1742 };
1743 let what = crate::host_slots::current_check()
1746 .unwrap_or_else(|| cmd.get_program().to_string_lossy().into_owned());
1747 say(&format!(
1748 "{} was killed while it looked like it was waiting ({}); retrying once{}.",
1749 hl(&what),
1750 k.last_line.as_deref().unwrap_or(""),
1751 match left {
1752 Some(s) => format!(" with {} left", human_secs(s)),
1753 None => String::new(),
1754 }
1755 ));
1756 let second = run_observed(
1757 settings,
1758 cmd,
1759 {
1760 let stage = std::sync::Arc::clone(&stage);
1761 move |bytes| stage.append_raw(idx, bytes)
1762 },
1763 left,
1764 );
1765 stage.runner_exit(idx, exit_of(&second));
1766 second
1767}
1768
1769fn whole_lines(pending: &[u8]) -> Option<usize> {
1773 match pending.iter().rposition(|&b| b == b'\n') {
1774 Some(i) => Some(i + 1),
1775 None if pending.len() >= LINE_HOLD => Some(pending.len()),
1776 None => None,
1777 }
1778}
1779
1780const LINE_HOLD: usize = 64 * 1024;
1781
1782fn exit_of(ran: &std::io::Result<Ran>) -> Option<i32> {
1785 match ran {
1786 Ok(Ran::Status(s)) => s.code(),
1787 _ => None,
1788 }
1789}
1790
1791#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1793pub enum Retry {
1794 Once,
1796 Never,
1798}
1799
1800pub fn retry_budget(retry: Retry, k: &Killed, ceiling: u64) -> Option<Option<u64>> {
1806 if retry == Retry::Never || !matches!(k.why, Why::Silence(_)) {
1807 return None;
1808 }
1809 if !k
1810 .last_line
1811 .as_deref()
1812 .is_some_and(crate::hooks::wait::looks_like_wait)
1813 {
1814 return None;
1815 }
1816 if ceiling == 0 {
1817 return Some(None);
1818 }
1819 let left = ceiling.saturating_sub(k.ran_secs);
1820 (left >= k.idle_secs.max(1)).then_some(Some(left))
1821}
1822
1823pub fn capture_within(
1829 settings: &crate::config::Settings,
1830 cmd: &mut Command,
1831) -> Option<(Ran, String)> {
1832 let text = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
1833 let sink = std::sync::Arc::clone(&text);
1834 let ran = run_observed(
1835 settings,
1836 cmd,
1837 move |bytes| {
1838 sink.lock()
1839 .unwrap_or_else(|p| p.into_inner())
1840 .push_str(&String::from_utf8_lossy(bytes));
1841 },
1842 None,
1843 )
1844 .ok()?;
1845 let text = std::sync::Arc::try_unwrap(text)
1846 .map(|m| m.into_inner().unwrap_or_else(|p| p.into_inner()))
1847 .unwrap_or_default();
1848 Some((ran, text))
1849}
1850
1851pub struct CapturedOutput {
1853 pub ran: Ran,
1854 pub stdout: String,
1855 pub stderr: String,
1856}
1857
1858pub fn capture_stdout_within(
1864 settings: &crate::config::Settings,
1865 cmd: &mut Command,
1866) -> std::io::Result<CapturedOutput> {
1867 let out = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
1868 let err = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
1869 let (out_sink, err_sink) = (std::sync::Arc::clone(&out), std::sync::Arc::clone(&err));
1870 let ran = run_observed_split(
1871 settings,
1872 cmd,
1873 move |bytes| {
1874 out_sink
1875 .lock()
1876 .unwrap_or_else(|p| p.into_inner())
1877 .extend_from_slice(bytes);
1878 },
1879 move |bytes| {
1880 err_sink
1881 .lock()
1882 .unwrap_or_else(|p| p.into_inner())
1883 .extend_from_slice(bytes);
1884 },
1885 None,
1886 )?;
1887 let take = |sink: std::sync::Arc<std::sync::Mutex<Vec<u8>>>| {
1888 let bytes = std::mem::take(&mut *sink.lock().unwrap_or_else(|p| p.into_inner()));
1889 String::from_utf8_lossy(&bytes).into_owned()
1890 };
1891 Ok(CapturedOutput {
1892 ran,
1893 stdout: take(out),
1894 stderr: take(err),
1895 })
1896}
1897
1898pub(crate) fn wait_within(
1903 child: &mut std::process::Child,
1904 clocks: Clocks,
1905 activity: Option<&Activity>,
1906) -> std::io::Result<Ran> {
1907 let started = std::time::Instant::now();
1908 let clocks = match activity {
1909 Some(_) => clocks,
1910 None => Clocks {
1911 silence: None,
1912 extended: None,
1913 ..clocks
1914 },
1915 };
1916 if clocks.ceiling.is_none() && clocks.silence.is_none() {
1917 return child.wait().map(Ran::Status);
1918 }
1919 let mut live = clocks;
1923 let mut load: Option<(crate::load::Load, u32)> = None;
1924 let mut next_load = started;
1925 loop {
1926 if let Some(status) = child.try_wait()? {
1927 return Ok(Ran::Status(status));
1928 }
1929 let now = std::time::Instant::now();
1930 if let (Some(idle), Some(a)) = (clocks.silence, activity) {
1931 if clocks.scale > 1 && now >= next_load {
1932 next_load = now + LOAD_EVERY;
1933 if let Some(l) = crate::load::read() {
1934 let factor = l.factor_milli(clocks.scale);
1935 let applied = crate::load::scaled_budget(idle, l, clocks.scale, clocks.ceiling);
1936 live.silence = Some(applied);
1937 a.set_load(applied, l, factor);
1938 load = (factor > 1000).then_some((l, factor));
1939 }
1940 }
1941 }
1942 let quiet = activity.map(|a| a.still_for());
1945 let waiting = activity.and_then(Activity::waiting);
1946 let gate = activity.map_or(CpuGate::NotSampled, Activity::gate);
1947 let why = judge(now.duration_since(started), quiet, waiting, gate, &live);
1948 if let Some(why) = why {
1949 let _ = child.kill();
1950 let _ = child.wait();
1951 return Ok(Ran::TimedOut(Killed {
1952 why,
1953 ran_secs: now.duration_since(started).as_secs(),
1954 quiet_secs: activity.map(|a| a.quiet_for().as_secs()),
1957 cpu: activity.map_or(CpuVerdict::NotSampled, Activity::verdict),
1958 idle_secs: clocks.silence.unwrap_or(0),
1959 waiting: waiting.map(|(k, d)| (k, d.as_secs())),
1960 last_line: activity.and_then(Activity::last_line),
1961 load,
1962 }));
1963 }
1964 std::thread::sleep(std::time::Duration::from_millis(25));
1965 }
1966}
1967
1968pub fn judge(
1983 ran: std::time::Duration,
1984 quiet: Option<std::time::Duration>,
1985 waiting: Option<(crate::hooks::wait::WaitKind, std::time::Duration)>,
1986 cpu: CpuGate,
1987 clocks: &Clocks,
1988) -> Option<Why> {
1989 if let Some(wall) = clocks.ceiling {
1990 if ran >= std::time::Duration::from_secs(wall) {
1991 return Some(Why::Ceiling(wall));
1992 }
1993 }
1994 if let Some((kind, waited)) = waiting {
1995 let budget = match clocks.lock_wait {
1996 LockWait::Secs(s) => Some(s),
1997 LockWait::UntilCeiling if clocks.ceiling.is_some() => None,
1998 LockWait::UntilCeiling => clocks.extended,
1999 };
2000 return match budget {
2001 Some(b) if waited >= std::time::Duration::from_secs(b) => Some(Why::Waited(kind, b)),
2002 _ => None,
2003 };
2004 }
2005 let budget = match cpu {
2006 CpuGate::NotSampled | CpuGate::Measured => clocks.silence,
2007 CpuGate::Unmeasured => clocks.extended.or(clocks.silence),
2008 };
2009 if let (Some(idle), Some(q)) = (budget, quiet) {
2010 if q >= std::time::Duration::from_secs(idle) {
2011 return Some(Why::Silence(idle));
2012 }
2013 }
2014 None
2015}
2016
2017pub fn say_timed_out(what: &str, k: Killed) {
2023 match k.why {
2024 Why::Silence(budget) => {
2025 let stretched = match (k.cpu, k.load) {
2029 _ if budget == k.idle_secs => String::new(),
2030 (CpuVerdict::Unmeasured, _) => format!(
2031 " (the extended budget, {} × {}: its CPU could not be measured)",
2032 human_secs(k.idle_secs),
2033 hl("greengate.idleLoadScale")
2034 ),
2035 (_, Some((load, factor))) => format!(
2036 " ({} stretched {} by a load average of {} on {} cores — {})",
2037 human_secs(k.idle_secs),
2038 crate::load::factor_text(factor),
2039 load.avg1_text(),
2040 load.cores,
2041 hl("greengate.idleLoadScale")
2042 ),
2043 _ => String::new(),
2044 };
2045 fail(&match k.cpu {
2046 CpuVerdict::MeasuredIdle(covered) => format!(
2047 "{} printed nothing for {}{stretched} and did no measurable CPU work \
2048 (< 0.1 core) in the last {} of it; killed after {} — a tool this idle \
2049 is stuck, not slow. {} raises the silence budget (0 disables)",
2050 hl(what),
2051 human_secs(budget),
2052 human_secs(covered.max(1)),
2053 human_secs(k.ran_secs),
2054 hl("git config greengate.idleTimeout <secs>")
2055 ),
2056 _ => format!(
2057 "{} printed nothing for {}{stretched}{} and was killed after {} — a tool \
2058 this quiet is usually stuck, not slow. {} raises the silence budget (0 \
2059 disables)",
2060 hl(what),
2061 human_secs(budget),
2062 if k.cpu == CpuVerdict::Unmeasured && stretched.is_empty() {
2063 " (CPU not measured)"
2064 } else {
2065 ""
2066 },
2067 human_secs(k.ran_secs),
2068 hl("git config greengate.idleTimeout <secs>")
2069 ),
2070 })
2071 }
2072 Why::Waited(kind, budget) => fail(&format!(
2073 "{} waited {} for {} and was killed after {} — {}. {} raises the wait budget \
2074 (0: until the ceiling)",
2075 hl(what),
2076 human_secs(budget),
2077 kind.describe(),
2078 human_secs(k.ran_secs),
2079 kind.holders(),
2080 hl("git config greengate.lockWait <secs>")
2081 )),
2082 Why::Ceiling(budget) => {
2083 let verdict = match (k.quiet_secs, k.cpu) {
2084 (_, _) if k.waiting.is_some() => {
2085 let (kind, w) = k.waiting.expect("checked");
2086 format!(
2087 " It was waiting for {} for the last {} — {}.",
2088 kind.describe(),
2089 human_secs(w),
2090 kind.holders()
2091 )
2092 }
2093 (Some(q), CpuVerdict::BusyAtKill(m)) if k.idle_secs > 0 && q >= k.idle_secs => {
2094 format!(
2095 " It printed nothing for the last {} but kept its CPU busy ({}), so the \
2096 silence budget did not stop it: a busy loop, or a tool that prints only \
2097 at the end (give it a per-file reporter). {} kills quiet runs at the \
2098 silence budget whatever their CPU.",
2099 human_secs(q),
2100 cores(m),
2101 hl("git config greengate.idleCpuCredit false")
2102 )
2103 }
2104 (Some(q), CpuVerdict::Unmeasured) if k.idle_secs > 0 && q >= k.idle_secs => {
2105 format!(
2106 " It printed nothing for the last {} and its CPU could not be measured, \
2107 so only the extended silence budget applied. {} kills quiet runs at \
2108 the silence budget whatever their CPU.",
2109 human_secs(q),
2110 hl("git config greengate.idleCpuCredit false")
2111 )
2112 }
2113 (Some(q), _) if q < 30 => format!(
2114 " It was still printing ({} since its last line): slow, not stuck.",
2115 human_secs(q)
2116 ),
2117 (Some(q), _) => format!(" Its last output was {} ago.", human_secs(q)),
2118 (None, _) => String::new(),
2119 };
2120 fail(&format!(
2121 "{} timed out: ran for {} and was killed at the ceiling. {} raises it \
2122 (0 disables).{verdict}",
2123 hl(what),
2124 human_secs(budget),
2125 hl("git config greengate.timeout <secs>")
2126 ))
2127 }
2128 }
2129}
2130
2131pub fn bounded_success(settings: &crate::config::Settings, cmd: &mut Command, what: &str) -> bool {
2134 match status_streamed(settings, cmd, Retry::Once) {
2135 Ok(Ran::Status(s)) => s.success(),
2136 Ok(Ran::TimedOut(b)) => {
2137 say_timed_out(what, b);
2138 false
2139 }
2140 Err(_) => false,
2141 }
2142}
2143
2144pub fn run(
2146 settings: &crate::config::Settings,
2147 root: &str,
2148 argv: &[String],
2149 extra: &[String],
2150) -> bool {
2151 let Some((program, rest)) = argv.split_first() else {
2152 return true;
2153 };
2154 let mut cmd = Command::new(program);
2155 cmd.args(rest)
2156 .args(extra)
2157 .current_dir(root)
2158 .stdin(Stdio::null());
2159 strip_git_env(&mut cmd);
2160 bounded_success(settings, &mut cmd, program)
2161}
2162
2163pub fn run_quiet(
2169 settings: &crate::config::Settings,
2170 root: &str,
2171 argv: &[String],
2172 extra: &[String],
2173) -> bool {
2174 let Some((program, rest)) = argv.split_first() else {
2175 return true;
2176 };
2177 let mut cmd = Command::new(program);
2178 cmd.args(rest)
2179 .args(extra)
2180 .current_dir(root)
2181 .stdin(Stdio::null());
2182 strip_git_env(&mut cmd);
2183 match run_observed(settings, &mut cmd, |_| {}, None) {
2188 Ok(Ran::Status(s)) => s.success(),
2189 Ok(Ran::TimedOut(b)) => {
2190 say_timed_out(program, b);
2191 false
2192 }
2193 Err(_) => false,
2194 }
2195}
2196
2197pub fn fixing_enabled(settings: &crate::config::Settings) -> bool {
2205 !not_the_index() && fixing_requested(settings)
2207}
2208
2209pub fn fixing_requested(settings: &crate::config::Settings) -> bool {
2215 *settings
2216 .fixing
2217 .get_or_init(|| crate::config::boolean_or(settings, "greengate.fix", false))
2218}
2219
2220#[derive(Debug, Clone, PartialEq, Eq)]
2231pub enum Restaged {
2232 Nothing,
2234 Staged,
2236 Failed(Vec<String>),
2241}
2242
2243static INDEX_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
2252
2253pub fn restage(paths: &[String]) -> Restaged {
2260 if not_the_index() {
2263 return Restaged::Nothing;
2264 }
2265 let changed: Vec<String> = paths
2266 .iter()
2267 .filter(|p| !git::succeeds(&["diff", "--quiet", "--", p]))
2268 .cloned()
2269 .collect();
2270 if changed.is_empty() {
2271 return Restaged::Nothing;
2272 }
2273 let mut args = vec!["add", "--"];
2274 args.extend(changed.iter().map(String::as_str));
2275
2276 let _serialised = INDEX_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2277 const BACKOFF_MS: [u64; 3] = [50, 150, 400];
2283 if git::succeeds(&args) {
2284 return Restaged::Staged;
2285 }
2286 for wait in BACKOFF_MS {
2287 std::thread::sleep(std::time::Duration::from_millis(wait));
2288 if git::succeeds(&args) {
2289 return Restaged::Staged;
2290 }
2291 }
2292 Restaged::Failed(changed)
2293}
2294
2295pub fn ok(settings: &crate::config::Settings, msg: &str) {
2298 if crate::live::quiet(settings) {
2299 return;
2300 }
2301 crate::live::say(&format!("{} {msg}", valid_sign()));
2302}
2303pub fn fail(msg: &str) {
2304 if crate::host_slots::deferred_here() {
2308 return;
2309 }
2310 crate::live::say(&format!("{} {msg}", error_sign()));
2311}
2312pub fn warn(msg: &str) {
2313 if crate::host_slots::deferred_here() {
2317 return;
2318 }
2319 crate::live::say(&format!("{} {msg}", warning_sign()));
2320}
2321pub fn say(msg: &str) {
2324 crate::live::say(msg);
2325}
2326
2327pub fn hl(s: &str) -> String {
2329 crate::ui::highlight(s)
2330}
2331
2332#[cfg(test)]
2333mod tests {
2334
2335 #[cfg(unix)]
2339 #[test]
2340 fn capture_stdout_within_keeps_the_streams_apart() {
2341 let settings = crate::config::Settings::default();
2342 let mut cmd = std::process::Command::new(super::program("sh"));
2343 cmd.args([
2344 "-c",
2345 "printf '{\"a\":1}'; printf 'npm warn x\\n' >&2; exit 3",
2346 ]);
2347 let captured = super::capture_stdout_within(&settings, &mut cmd).expect("sh runs");
2348 assert_eq!(captured.stdout, "{\"a\":1}", "stdout alone");
2349 assert_eq!(captured.stderr, "npm warn x\n", "stderr alone");
2350 match captured.ran {
2351 super::Ran::Status(s) => assert_eq!(s.code(), Some(3), "the real exit status"),
2352 super::Ran::TimedOut(_) => panic!("a one-line child timed out"),
2353 }
2354 }
2355
2356 #[cfg(unix)]
2359 #[test]
2360 fn stderr_only_output_leaves_stdout_empty() {
2361 let settings = crate::config::Settings::default();
2362 let mut cmd = std::process::Command::new(super::program("sh"));
2363 cmd.args(["-c", "printf 'only a warning\\n' >&2"]);
2364 let captured = super::capture_stdout_within(&settings, &mut cmd).expect("sh runs");
2365 assert!(
2366 captured.stdout.is_empty(),
2367 "stdout must be empty, got {:?}",
2368 captured.stdout
2369 );
2370 assert_eq!(captured.stderr, "only a warning\n");
2371 assert!(matches!(captured.ran, super::Ran::Status(s) if s.success()));
2372 }
2373
2374 #[test]
2376 fn only_the_one_newline_git_prints_is_stripped() {
2377 assert_eq!(super::strip_one_newline(b"/r/.git\n".to_vec()), b"/r/.git");
2378 assert_eq!(super::strip_one_newline(b"/r/x\r\n".to_vec()), b"/r/x\r");
2379 assert_eq!(super::strip_one_newline(b"/r/x".to_vec()), b"/r/x");
2380 }
2381
2382 #[test]
2385 fn a_git_path_becomes_the_same_path() {
2386 assert_eq!(
2387 super::path_from_bytes(b"/r/.git/index".to_vec()),
2388 std::path::PathBuf::from("/r/.git/index")
2389 );
2390 }
2391
2392 #[test]
2393 fn a_lookup_error_says_git_s_reason() {
2394 let e = super::IndexLookupError::Git {
2395 args: "rev-parse --git-path index".into(),
2396 why: "fatal: not a git repository".into(),
2397 };
2398 assert_eq!(
2399 e.to_string(),
2400 "git rev-parse --git-path index failed: fatal: not a git repository"
2401 );
2402 }
2403
2404 fn window(
2408 start: std::time::Instant,
2409 end: std::time::Instant,
2410 milli: u64,
2411 ) -> crate::proctree::Observation {
2412 let wall = u64::try_from(end.duration_since(start).as_nanos())
2413 .unwrap_or(u64::MAX)
2414 .max(1);
2415 let gain = wall * milli / 1000;
2416 crate::proctree::Observation::Window(crate::proctree::Window {
2417 start,
2418 end,
2419 gain_ns: gain,
2420 gapped: false,
2421 })
2422 }
2423
2424 #[test]
2428 fn a_gapped_window_is_never_claimed_as_measured_idle() {
2429 use super::{Activity, CpuVerdict};
2430 use crate::proctree::{Observation, Window};
2431 let s = std::time::Duration::from_secs;
2432 let every = s(10);
2433 let a = Activity::new();
2434 a.enable_cpu();
2435 let t0 = std::time::Instant::now() - s(30);
2436 a.record(Observation::Baseline, t0, every);
2437 a.record(Observation::Skipped, t0 + s(10), every);
2438 let gap_end = std::time::Instant::now();
2439 a.record(
2440 Observation::Window(Window {
2441 start: t0,
2442 end: gap_end,
2443 gain_ns: 0,
2444 gapped: true,
2445 }),
2446 gap_end,
2447 every,
2448 );
2449 assert_eq!(a.verdict(), CpuVerdict::MeasuredIdle(0));
2451 assert_eq!(a.gate(), super::CpuGate::Measured);
2452
2453 let busy = Activity::new();
2454 busy.enable_cpu();
2455 busy.record(Observation::Baseline, t0, every);
2456 busy.record(Observation::Skipped, t0 + s(10), every);
2457 let now = std::time::Instant::now();
2458 busy.record(window_gapped(t0, now, 3000), now, every);
2459 assert_eq!(busy.verdict(), CpuVerdict::BusyAtKill(3000));
2460 assert!(busy.still_for() < s(1));
2461 }
2462
2463 fn window_gapped(
2464 start: std::time::Instant,
2465 end: std::time::Instant,
2466 milli: u64,
2467 ) -> crate::proctree::Observation {
2468 match window(start, end, milli) {
2469 crate::proctree::Observation::Window(w) => {
2470 crate::proctree::Observation::Window(crate::proctree::Window { gapped: true, ..w })
2471 }
2472 o => o,
2473 }
2474 }
2475
2476 #[test]
2479 fn the_sampling_schedule_follows_the_budget_within_floors() {
2480 use super::sampling_schedule;
2481 let ms = std::time::Duration::from_millis;
2482 let third = |secs: u64| std::time::Duration::from_secs(secs) / 3;
2483 assert_eq!(sampling_schedule(1), (third(1), ms(250)));
2484 assert_eq!(sampling_schedule(2), (third(2), ms(500)));
2485 assert_eq!(sampling_schedule(120), (ms(30_000), ms(10_000)));
2486 assert_eq!(sampling_schedule(0), (ms(250), ms(250)));
2487 }
2488
2489 #[test]
2492 fn busy_work_resets_the_still_time_but_not_the_output_silence() {
2493 use super::Activity;
2494 let a = Activity::new();
2495 a.touch();
2496 std::thread::sleep(std::time::Duration::from_millis(60));
2497 let quiet = a.quiet_for();
2498 assert!(a.still_for() >= quiet.saturating_sub(std::time::Duration::from_millis(5)));
2499 a.enable_cpu();
2500 let now = std::time::Instant::now();
2501 a.record(
2502 window(now - std::time::Duration::from_millis(10), now, 2000),
2503 now,
2504 std::time::Duration::from_secs(1),
2505 );
2506 assert!(a.still_for() < std::time::Duration::from_millis(40));
2507 assert!(a.quiet_for() >= std::time::Duration::from_millis(60));
2508 }
2509
2510 #[test]
2514 fn the_cpu_verdict_claims_only_what_was_measured() {
2515 use super::{Activity, CpuVerdict};
2516 use crate::proctree::Observation;
2517 let s = std::time::Duration::from_secs;
2518 let every = s(10);
2519
2520 let off = Activity::new();
2521 assert_eq!(off.verdict(), CpuVerdict::NotSampled);
2522
2523 let waiting = Activity::new();
2524 waiting.enable_cpu();
2525 assert_eq!(waiting.verdict(), CpuVerdict::Unmeasured);
2526
2527 let now = std::time::Instant::now();
2528 let before = now - s(1);
2529 let idle = Activity::new();
2531 idle.enable_cpu();
2532 let t0 = std::time::Instant::now();
2533 idle.record(Observation::Baseline, t0, every);
2534 std::thread::sleep(std::time::Duration::from_millis(1050));
2535 let t1 = std::time::Instant::now();
2536 idle.record(window(t0, t1, 20), t1, every);
2537 assert_eq!(idle.verdict(), CpuVerdict::MeasuredIdle(1));
2538
2539 let busy = Activity::new();
2540 busy.enable_cpu();
2541 busy.record(Observation::Baseline, before, every);
2542 busy.record(window(before, now, 3900), now, every);
2543 assert_eq!(busy.verdict(), CpuVerdict::BusyAtKill(3900));
2544
2545 let broken = Activity::new();
2546 broken.enable_cpu();
2547 broken.record(Observation::Baseline, before, every);
2548 broken.record(window(before, now, 20), now, every);
2549 broken.record(Observation::Unmeasured, now, every);
2550 assert_eq!(broken.verdict(), CpuVerdict::Unmeasured);
2551 assert_eq!(broken.gate(), super::CpuGate::Unmeasured);
2552 assert_eq!(off.gate(), super::CpuGate::NotSampled);
2553 assert_eq!(idle.gate(), super::CpuGate::Measured);
2554 assert_eq!(busy.gate(), super::CpuGate::Measured);
2555 }
2556
2557 #[test]
2560 fn a_stale_rate_expires() {
2561 use super::{Activity, CpuVerdict};
2562 use crate::proctree::Observation;
2563 let a = Activity::new();
2564 a.enable_cpu();
2565 let then = std::time::Instant::now();
2566 let tick = std::time::Duration::from_millis(5);
2567 let earlier = then - std::time::Duration::from_secs(1);
2568 a.record(Observation::Baseline, earlier, tick);
2569 a.record(window(earlier, then, 3000), then, tick);
2570 std::thread::sleep(std::time::Duration::from_millis(40));
2571 assert_eq!(a.fresh_rate(), None);
2572 assert_eq!(a.verdict(), CpuVerdict::Unmeasured);
2573 }
2574
2575 #[test]
2576 fn cores_read_as_one_decimal() {
2577 assert_eq!(super::cores(3900), "~3.9 cores");
2578 assert_eq!(super::cores(420), "~0.4 cores");
2579 assert_eq!(super::cores(100), "~0.1 cores");
2580 }
2581
2582 #[test]
2586 fn the_clocks_judge_silence_and_ceiling_separately() {
2587 use super::{judge, CpuGate, Why};
2588 use std::time::Duration as D;
2589 let s = D::from_secs;
2590 let c = |ceiling: Option<u64>, silence: Option<u64>| super::Clocks {
2591 ceiling,
2592 silence,
2593 lock_wait: super::LockWait::Secs(600),
2594 extended: silence,
2595 scale: 1,
2596 };
2597 assert_eq!(
2599 judge(
2600 s(900),
2601 Some(s(0)),
2602 None,
2603 CpuGate::NotSampled,
2604 &c(Some(3600), Some(5))
2605 ),
2606 None
2607 );
2608 assert_eq!(
2609 judge(
2610 s(900),
2611 Some(s(4)),
2612 None,
2613 CpuGate::NotSampled,
2614 &c(Some(3600), Some(5))
2615 ),
2616 None
2617 );
2618 assert_eq!(
2620 judge(
2621 s(30),
2622 Some(s(5)),
2623 None,
2624 CpuGate::NotSampled,
2625 &c(Some(3600), Some(5))
2626 ),
2627 Some(Why::Silence(5))
2628 );
2629 assert_eq!(
2631 judge(
2632 s(900),
2633 None,
2634 None,
2635 CpuGate::NotSampled,
2636 &c(Some(3600), Some(5))
2637 ),
2638 None
2639 );
2640 assert_eq!(
2642 judge(
2643 s(3600),
2644 Some(s(0)),
2645 None,
2646 CpuGate::NotSampled,
2647 &c(Some(3600), Some(120))
2648 ),
2649 Some(Why::Ceiling(3600))
2650 );
2651 assert_eq!(
2653 judge(
2654 s(3600),
2655 Some(s(600)),
2656 None,
2657 CpuGate::NotSampled,
2658 &c(Some(3600), Some(120))
2659 ),
2660 Some(Why::Ceiling(3600))
2661 );
2662 assert_eq!(
2664 judge(
2665 s(86_400),
2666 Some(s(86_400)),
2667 None,
2668 CpuGate::NotSampled,
2669 &c(None, None)
2670 ),
2671 None
2672 );
2673 assert_eq!(
2675 judge(
2676 s(86_400),
2677 Some(s(1)),
2678 None,
2679 CpuGate::NotSampled,
2680 &c(None, Some(120))
2681 ),
2682 None
2683 );
2684 }
2685
2686 #[test]
2690 fn a_declared_wait_answers_to_its_own_budget() {
2691 use super::{judge, Clocks, CpuGate, LockWait, Why};
2692 use crate::hooks::wait::{CargoLockWhat, WaitKind};
2693 use std::time::Duration as D;
2694 let s = D::from_secs;
2695 let kind = WaitKind::CargoLock(CargoLockWhat::BuildDirectory);
2696 let clocks = Clocks {
2697 ceiling: Some(3600),
2698 silence: Some(120),
2699 lock_wait: LockWait::Secs(600),
2700 extended: Some(480),
2701 scale: 4,
2702 };
2703 assert_eq!(
2705 judge(
2706 s(1300),
2707 Some(s(0)),
2708 Some((kind, s(599))),
2709 CpuGate::Measured,
2710 &clocks
2711 ),
2712 None
2713 );
2714 assert_eq!(
2716 judge(
2717 s(1300),
2718 Some(s(0)),
2719 Some((kind, s(600))),
2720 CpuGate::Measured,
2721 &clocks
2722 ),
2723 Some(Why::Waited(kind, 600))
2724 );
2725 assert_eq!(
2727 judge(
2728 s(3600),
2729 Some(s(0)),
2730 Some((kind, s(3000))),
2731 CpuGate::Measured,
2732 &clocks
2733 ),
2734 Some(Why::Ceiling(3600))
2735 );
2736 let until = Clocks {
2738 lock_wait: LockWait::UntilCeiling,
2739 ..clocks
2740 };
2741 assert_eq!(
2742 judge(
2743 s(3000),
2744 Some(s(0)),
2745 Some((kind, s(2900))),
2746 CpuGate::Measured,
2747 &until
2748 ),
2749 None
2750 );
2751 let open = Clocks {
2753 ceiling: None,
2754 ..until
2755 };
2756 assert_eq!(
2757 judge(
2758 s(3000),
2759 Some(s(0)),
2760 Some((kind, s(479))),
2761 CpuGate::Measured,
2762 &open
2763 ),
2764 None
2765 );
2766 assert_eq!(
2767 judge(
2768 s(3000),
2769 Some(s(0)),
2770 Some((kind, s(480))),
2771 CpuGate::Measured,
2772 &open
2773 ),
2774 Some(Why::Waited(kind, 480))
2775 );
2776 }
2777
2778 #[test]
2782 fn a_wait_like_silence_kill_earns_one_retry_under_the_remaining_ceiling() {
2783 use super::{retry_budget, CpuVerdict, Killed, Retry, Why};
2784 use crate::hooks::wait::{CargoLockWhat, WaitKind};
2785 let k = |why: Why, line: &str, ran: u64| Killed {
2786 why,
2787 ran_secs: ran,
2788 quiet_secs: Some(ran),
2789 cpu: CpuVerdict::MeasuredIdle(1),
2790 idle_secs: 120,
2791 waiting: None,
2792 last_line: Some(line.to_string()),
2793 load: None,
2794 };
2795 let wait = "waiting for lock on x";
2796 assert_eq!(
2797 retry_budget(Retry::Once, &k(Why::Silence(120), wait, 120), 3600),
2798 Some(Some(3480))
2799 );
2800 assert_eq!(
2801 retry_budget(Retry::Once, &k(Why::Silence(120), wait, 120), 0),
2802 Some(None)
2803 );
2804 assert_eq!(
2805 retry_budget(Retry::Never, &k(Why::Silence(120), wait, 120), 3600),
2806 None
2807 );
2808 assert_eq!(
2809 retry_budget(
2810 Retry::Once,
2811 &k(Why::Silence(120), "test_lock.py::x", 120),
2812 3600
2813 ),
2814 None
2815 );
2816 assert_eq!(
2817 retry_budget(Retry::Once, &k(Why::Ceiling(3600), wait, 3600), 3600),
2818 None
2819 );
2820 let waited = Why::Waited(WaitKind::CargoLock(CargoLockWhat::BuildDirectory), 600);
2821 assert_eq!(retry_budget(Retry::Once, &k(waited, wait, 700), 3600), None);
2822 assert_eq!(
2824 retry_budget(Retry::Once, &k(Why::Silence(120), wait, 3500), 3600),
2825 None
2826 );
2827 }
2828
2829 #[test]
2833 fn an_unmeasured_cpu_answers_to_the_extended_budget() {
2834 use super::{judge, Clocks, CpuGate, LockWait, Why};
2835 use std::time::Duration as D;
2836 let s = D::from_secs;
2837 let clocks = Clocks {
2838 ceiling: None,
2839 silence: Some(120),
2840 lock_wait: LockWait::Secs(600),
2841 extended: Some(480),
2842 scale: 4,
2843 };
2844 assert_eq!(
2845 judge(s(500), Some(s(300)), None, CpuGate::Unmeasured, &clocks),
2846 None
2847 );
2848 assert_eq!(
2849 judge(s(500), Some(s(479)), None, CpuGate::Unmeasured, &clocks),
2850 None
2851 );
2852 assert_eq!(
2853 judge(s(500), Some(s(480)), None, CpuGate::Unmeasured, &clocks),
2854 Some(Why::Silence(480))
2855 );
2856 assert_eq!(
2857 judge(s(500), Some(s(120)), None, CpuGate::Measured, &clocks),
2858 Some(Why::Silence(120))
2859 );
2860 assert_eq!(
2861 judge(s(500), Some(s(120)), None, CpuGate::NotSampled, &clocks),
2862 Some(Why::Silence(120))
2863 );
2864 let off = Clocks {
2866 silence: None,
2867 extended: None,
2868 ..clocks
2869 };
2870 assert_eq!(
2871 judge(s(86_400), Some(s(86_400)), None, CpuGate::Unmeasured, &off),
2872 None
2873 );
2874 }
2875
2876 #[test]
2880 fn a_marker_line_pauses_the_silence_clock_until_another_line() {
2881 use super::Activity;
2882 use crate::hooks::wait::{CargoLockWhat, WaitKind};
2883 let a = Activity::new();
2884 a.touch();
2885 assert_eq!(a.waiting(), None);
2886 a.stderr_line(" Blocking waiting for file lock on package cache");
2887 std::thread::sleep(std::time::Duration::from_millis(30));
2888 let (kind, waited) = a.waiting().expect("a wait is in progress");
2889 assert_eq!(kind, WaitKind::CargoLock(CargoLockWhat::PackageCache));
2890 assert!(waited >= std::time::Duration::from_millis(30));
2891 assert_eq!(a.silence_for(), std::time::Duration::ZERO);
2892 assert_eq!(a.still_for(), std::time::Duration::ZERO);
2893 assert!(a.quiet_for() >= std::time::Duration::from_millis(30));
2894 a.stderr_line("\u{1b}[1m Blocking\u{1b}[0m waiting for file lock on build directory");
2896 let (kind, again) = a.waiting().expect("still waiting");
2897 assert_eq!(kind, WaitKind::CargoLock(CargoLockWhat::BuildDirectory));
2898 assert!(again >= waited);
2899 a.touch();
2902 a.stderr_line(" Checking foo v0.1.0");
2903 assert_eq!(a.waiting(), None);
2904 assert!(a.waited_total() >= std::time::Duration::from_millis(30));
2905 assert_eq!(a.last_wait_kind(), Some(kind));
2906 assert_eq!(a.last_line().as_deref(), Some("Checking foo v0.1.0"));
2907 assert!(a.silence_for() < std::time::Duration::from_millis(20));
2908 a.stderr_line("Waiting to acquire write lock for `x`");
2910 assert!(a.waiting().is_some());
2911 a.end_wait();
2912 assert_eq!(a.waiting(), None);
2913 }
2914
2915 #[cfg(unix)]
2917 #[test]
2918 fn the_deadline_kills_a_sleeper_and_spares_a_finisher() {
2919 let started = std::time::Instant::now();
2920 let mut slow = Command::new(program("sleep"));
2921 slow.arg("300").stdin(Stdio::null());
2922 match status_within_secs(&mut slow, 1) {
2923 Ok(Ran::TimedOut(Killed {
2924 why: Why::Ceiling(1),
2925 quiet_secs: None,
2926 ..
2927 })) => {}
2928 other => panic!("expected TimedOut(1), got {:?}", other.map(|_| "ran")),
2929 }
2930 assert!(
2931 started.elapsed() < std::time::Duration::from_secs(60),
2932 "the kill did not happen at the deadline"
2933 );
2934
2935 let mut quick = Command::new(program("true"));
2936 quick.stdin(Stdio::null());
2937 match status_within_secs(&mut quick, 60) {
2938 Ok(Ran::Status(s)) => assert!(s.success()),
2939 other => panic!("expected a clean exit, got {:?}", other.map(|_| "?")),
2940 }
2941 }
2942
2943 use super::*;
2944
2945 #[test]
2946 fn which_finds_a_real_binary_and_not_a_fake_one() {
2947 assert!(which("git").is_some());
2948 assert!(which("definitely-not-a-real-binary-xyz").is_none());
2949 }
2950
2951 #[test]
2955 #[cfg(windows)]
2956 fn windows_prefers_an_executable_extension_over_a_bare_file() {
2957 let dir = std::env::temp_dir().join("greengate-which-order");
2958 let _ = std::fs::create_dir_all(&dir);
2959 std::fs::write(dir.join("faketool"), "#!/bin/sh\n").unwrap();
2960 std::fs::write(dir.join("faketool.cmd"), "@echo off\n").unwrap();
2961 let found = which_on(dir.as_os_str(), "faketool").unwrap();
2965 assert!(found.ends_with(".cmd"), "got {found}");
2966 let _ = std::fs::remove_dir_all(&dir);
2967 }
2968
2969 #[test]
2982 fn restage_distinguishes_nothing_from_failure() {
2983 let _cwd = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
2989 let outside = std::env::temp_dir()
2990 .join("greengate-restage-outside-any-repo")
2991 .to_string_lossy()
2992 .into_owned();
2993 assert_eq!(
2994 restage(std::slice::from_ref(&outside)),
2995 Restaged::Failed(vec![outside]),
2996 "a `git add` git refuses must report Failed, never Nothing"
2997 );
2998 assert_eq!(
2999 restage(&[]),
3000 Restaged::Nothing,
3001 "no paths is nothing to do, and nothing wrong"
3002 );
3003 }
3004
3005 #[test]
3021 fn no_hook_spawns_a_bare_program_name() {
3022 let needle = concat!("Command", "::new(");
3023 let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/src/hooks");
3024 let mut scanned = 0usize;
3025 for entry in std::fs::read_dir(dir).expect("hooks dir").flatten() {
3026 let path = entry.path();
3027 if path.extension().and_then(|e| e.to_str()) != Some("rs") {
3028 continue;
3029 }
3030 scanned += 1;
3031 let src = std::fs::read_to_string(&path).expect("read a hook module");
3032 for (n, line) in src.lines().enumerate() {
3033 if line.trim_start().starts_with("//") {
3034 continue;
3035 }
3036 let Some(after) = line.split_once(needle) else {
3037 continue;
3038 };
3039 assert!(
3040 !after.1.starts_with('"'),
3041 "{}:{} spawns a bare name — route it through `program()` or \
3042 the path `which()` already resolved: {}",
3043 path.display(),
3044 n + 1,
3045 line.trim()
3046 );
3047 }
3048 }
3049 assert!(
3050 scanned > 10,
3051 "the scan found almost nothing: {scanned} files"
3052 );
3053 }
3054
3055 #[test]
3056 fn first_existing_picks_the_earliest_present_name() {
3057 let dir = std::env::temp_dir().join("greengate-first-existing-test");
3058 let _ = std::fs::create_dir_all(&dir);
3059 let root = dir.to_string_lossy().into_owned();
3060 let _ = std::fs::write(dir.join("second"), "x");
3061 assert_eq!(
3062 first_existing(&root, &["first", "second", "third"]).as_deref(),
3063 Some("second")
3064 );
3065 assert_eq!(first_existing(&root, &["nope"]), None);
3066 let _ = std::fs::remove_dir_all(&dir);
3067 }
3068}
3069
3070#[cfg(test)]
3071mod js_tool_tests {
3072 use super::{package_json_declares, version_in};
3073
3074 #[test]
3075 fn package_json_declares_a_dev_dependency() {
3076 assert!(package_json_declares(
3077 r#"{"devDependencies":{"prettier":"3.9.10"}}"#,
3078 "prettier"
3079 ));
3080 assert!(package_json_declares(
3081 "{\n \"name\": \"x\",\n \"dependencies\": { \"eslint\": \"9.1.0\" }\n}\n",
3082 "eslint"
3083 ));
3084 assert!(package_json_declares(
3086 "\u{feff}{\"devDependencies\":{\"prettier\":\"3.9.10\"}}",
3087 "prettier"
3088 ));
3089 }
3090
3091 #[test]
3093 fn package_json_declares_gives_up_on_deep_nesting() {
3094 let deep = format!(
3095 "{{\"x\":{}{},\"devDependencies\":{{\"prettier\":\"3\"}}}}",
3096 "[".repeat(100_000),
3097 "]".repeat(100_000)
3098 );
3099 assert!(!package_json_declares(&deep, "prettier"));
3100 let fine = format!(
3101 "{{\"x\":{}{},\"devDependencies\":{{\"prettier\":\"3\"}}}}",
3102 "[".repeat(50),
3103 "]".repeat(50)
3104 );
3105 assert!(package_json_declares(&fine, "prettier"));
3106 }
3107
3108 #[test]
3109 fn package_json_declares_nothing_else() {
3110 let not = |text: &str| assert!(!package_json_declares(text, "prettier"), "{text}");
3111 not(r#"{"prettier":{"semi":false}}"#);
3113 not(r#"{"devDependencies":{"prettier-plugin-x":"1.0.0"}}"#);
3115 not(r#"{"peerDependencies":{"prettier":"3"}}"#);
3117 not(r#"{"optionalDependencies":{"prettier":"3"}}"#);
3118 not(r#"{"pnpm":{"overrides":{"prettier":"3"}}}"#);
3119 not(r#"{"scripts":{"prettier":"prettier --check ."}}"#);
3120 not(r#"{"metadata":{"devDependencies":{"prettier":"3"}}}"#);
3122 not(r#"{"list":[{"dependencies":{"prettier":"3"}}]}"#);
3123 not(r#"{"description":"say \"devDependencies\": {\"prettier\": 1}"}"#);
3125 not(r#"{"devDependencies":{"prettier":"3.9.10""#);
3127 not(r#"{"devDependencies":{"prettier":"3.9.10"}} trailing"#);
3128 not("");
3129 }
3130
3131 #[test]
3132 fn package_json_declares_past_escapes_and_nesting() {
3133 assert!(package_json_declares(
3134 r#"{"description":"a \"quoted\" {brace}","x":[1,{"y":null}],"devDependencies":{"a":"1","prettier":"^3"}}"#,
3135 "prettier"
3136 ));
3137 }
3138
3139 #[test]
3140 fn version_in_skips_warnings_and_strips_v() {
3141 assert_eq!(version_in("3.9.10\n").as_deref(), Some("3.9.10"));
3142 assert_eq!(version_in("v9.14.0").as_deref(), Some("9.14.0"));
3143 assert_eq!(
3144 version_in("npm warn exec The following package was not found\n3.9.10").as_deref(),
3145 Some("3.9.10")
3146 );
3147 assert_eq!(
3148 version_in("(node:1) Warning: x\n3.0.0-beta.1").as_deref(),
3149 Some("3.0.0-beta.1")
3150 );
3151 assert_eq!(version_in("3.9.10\u{1b}[2J").as_deref(), Some("3.9.10"));
3152 assert_eq!(version_in("no version here\n1.2"), None);
3153 assert_eq!(version_in(""), None);
3154 }
3155}