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 {
869 use std::collections::hash_map::RandomState;
870 use std::hash::{BuildHasher, Hash, Hasher};
871
872 let pid = std::process::id();
873 let mut hasher = RandomState::new().build_hasher();
874 pid.hash(&mut hasher);
875 std::time::SystemTime::now()
876 .duration_since(std::time::UNIX_EPOCH)
877 .unwrap_or_default()
878 .as_nanos()
879 .hash(&mut hasher);
880 format!("{prefix}-{pid}-{:016x}", hasher.finish())
881}
882
883pub fn human_secs(secs: u64) -> String {
885 match secs {
886 s if s < 60 => format!("{s}s"),
887 s if s < 3600 => format!("{}m{:02}s", s / 60, s % 60),
888 s => format!("{}h{:02}m", s / 3600, (s % 3600) / 60),
889 }
890}
891
892pub const LAST_LINE_CHARS: usize = 200;
894
895pub const BUSY_MILLI_CORES: u32 = 100;
899
900#[derive(Debug, Clone, Copy, PartialEq, Eq)]
902pub enum CpuState {
903 Off = 0,
906 Waiting = 1,
909 Measuring = 2,
911 Unavailable = 3,
913}
914
915pub struct Activity {
925 base: std::time::Instant,
926 last_out: std::sync::atomic::AtomicU64,
927 last_busy: std::sync::atomic::AtomicU64,
928 measured_since: std::sync::atomic::AtomicU64,
931 last_measured: std::sync::atomic::AtomicU64,
933 rate_milli: std::sync::atomic::AtomicU32,
934 interval_ms: std::sync::atomic::AtomicU32,
935 cpu: std::sync::atomic::AtomicU8,
936 wait_since: std::sync::atomic::AtomicU64,
939 wait_kind: std::sync::atomic::AtomicU8,
941 waited_ns: std::sync::atomic::AtomicU64,
944 last_wait_kind: std::sync::atomic::AtomicU8,
947 budget_secs: std::sync::atomic::AtomicU32,
951 load_avg_milli: std::sync::atomic::AtomicU32,
953 load_cores: std::sync::atomic::AtomicU32,
954 load_factor_milli: std::sync::atomic::AtomicU32,
955 last_line: std::sync::Mutex<String>,
958}
959
960impl Activity {
961 pub fn new() -> std::sync::Arc<Activity> {
962 std::sync::Arc::new(Activity {
963 base: std::time::Instant::now(),
964 last_out: Default::default(),
965 last_busy: Default::default(),
966 measured_since: Default::default(),
967 last_measured: Default::default(),
968 rate_milli: Default::default(),
969 interval_ms: Default::default(),
970 cpu: std::sync::atomic::AtomicU8::new(CpuState::Off as u8),
971 wait_since: Default::default(),
972 wait_kind: Default::default(),
973 waited_ns: Default::default(),
974 last_wait_kind: Default::default(),
975 budget_secs: Default::default(),
976 load_avg_milli: Default::default(),
977 load_cores: Default::default(),
978 load_factor_milli: Default::default(),
979 last_line: std::sync::Mutex::new(String::new()),
980 })
981 }
982
983 pub fn last_wait_kind(&self) -> Option<crate::hooks::wait::WaitKind> {
985 crate::hooks::wait::WaitKind::from_code(
986 self.last_wait_kind
987 .load(std::sync::atomic::Ordering::Relaxed),
988 )
989 }
990
991 pub fn stderr_line(&self, raw: &str) {
996 use std::sync::atomic::Ordering::Relaxed;
997 let line = crate::hooks::wait::strip_csi(raw);
998 if !line.trim().is_empty() {
999 let mut keep = self.last_line.lock().unwrap_or_else(|p| p.into_inner());
1000 keep.clear();
1001 keep.extend(line.trim().chars().take(LAST_LINE_CHARS));
1002 }
1003 match crate::hooks::wait::marker(&line) {
1004 Some(kind) => {
1005 self.wait_kind.store(kind.code(), Relaxed);
1006 self.last_wait_kind.store(kind.code(), Relaxed);
1007 let _ = self
1010 .wait_since
1011 .compare_exchange(0, self.now() + 1, Relaxed, Relaxed);
1012 }
1013 None => self.end_wait(),
1014 }
1015 }
1016
1017 pub fn end_wait(&self) {
1020 use std::sync::atomic::Ordering::Relaxed;
1021 let since = self.wait_since.swap(0, Relaxed);
1022 if since != 0 {
1023 let spent = self.now().saturating_sub(since - 1);
1024 self.waited_ns.fetch_add(spent, Relaxed);
1025 }
1026 self.wait_kind.store(0, Relaxed);
1027 }
1028
1029 pub fn waiting(&self) -> Option<(crate::hooks::wait::WaitKind, std::time::Duration)> {
1031 use std::sync::atomic::Ordering::Relaxed;
1032 let since = self.wait_since.load(Relaxed);
1033 if since == 0 {
1034 return None;
1035 }
1036 let kind = crate::hooks::wait::WaitKind::from_code(self.wait_kind.load(Relaxed))?;
1037 Some((kind, self.since(since - 1)))
1038 }
1039
1040 pub fn waited_total(&self) -> std::time::Duration {
1043 use std::sync::atomic::Ordering::Relaxed;
1044 let banked = std::time::Duration::from_nanos(self.waited_ns.load(Relaxed));
1045 banked + self.waiting().map_or(std::time::Duration::ZERO, |(_, d)| d)
1046 }
1047
1048 pub fn last_line(&self) -> Option<String> {
1050 let keep = self.last_line.lock().unwrap_or_else(|p| p.into_inner());
1051 (!keep.is_empty()).then(|| keep.clone())
1052 }
1053
1054 pub fn set_load(&self, budget_secs: u64, load: crate::load::Load, factor_milli: u32) {
1056 use std::sync::atomic::Ordering::Relaxed;
1057 self.budget_secs
1058 .store(u32::try_from(budget_secs).unwrap_or(u32::MAX), Relaxed);
1059 self.load_avg_milli.store(load.avg1_milli, Relaxed);
1060 self.load_cores.store(load.cores, Relaxed);
1061 self.load_factor_milli.store(factor_milli, Relaxed);
1062 }
1063
1064 pub fn load_scale(&self) -> Option<(u64, crate::load::Load, u32)> {
1067 use std::sync::atomic::Ordering::Relaxed;
1068 let factor = self.load_factor_milli.load(Relaxed);
1069 if factor <= 1000 {
1070 return None;
1071 }
1072 Some((
1073 u64::from(self.budget_secs.load(Relaxed)),
1074 crate::load::Load {
1075 avg1_milli: self.load_avg_milli.load(Relaxed),
1076 cores: self.load_cores.load(Relaxed),
1077 },
1078 factor,
1079 ))
1080 }
1081 fn offset(&self, at: std::time::Instant) -> u64 {
1082 u64::try_from(at.saturating_duration_since(self.base).as_nanos()).unwrap_or(u64::MAX)
1083 }
1084 fn now(&self) -> u64 {
1085 self.offset(std::time::Instant::now())
1086 }
1087 fn since(&self, offset: u64) -> std::time::Duration {
1088 std::time::Duration::from_nanos(self.now().saturating_sub(offset))
1089 }
1090 pub fn touch(&self) {
1092 self.last_out
1093 .fetch_max(self.now(), std::sync::atomic::Ordering::Relaxed);
1094 }
1095 pub fn quiet_for(&self) -> std::time::Duration {
1098 self.since(self.last_out.load(std::sync::atomic::Ordering::Relaxed))
1099 }
1100 pub fn silence_for(&self) -> std::time::Duration {
1105 if self.waiting().is_some() {
1106 std::time::Duration::ZERO
1107 } else {
1108 self.quiet_for()
1109 }
1110 }
1111 pub fn still_for(&self) -> std::time::Duration {
1115 let busy = self.last_busy.load(std::sync::atomic::Ordering::Relaxed);
1116 self.silence_for().min(self.since(busy))
1117 }
1118 pub fn cpu_state(&self) -> CpuState {
1119 match self.cpu.load(std::sync::atomic::Ordering::Relaxed) {
1120 1 => CpuState::Waiting,
1121 2 => CpuState::Measuring,
1122 3 => CpuState::Unavailable,
1123 _ => CpuState::Off,
1124 }
1125 }
1126 fn set_cpu_state(&self, s: CpuState) {
1127 self.cpu
1128 .store(s as u8, std::sync::atomic::Ordering::Relaxed);
1129 }
1130 pub fn fresh_rate(&self) -> Option<u32> {
1134 if self.cpu_state() != CpuState::Measuring {
1135 return None;
1136 }
1137 let end = self
1138 .last_measured
1139 .load(std::sync::atomic::Ordering::Relaxed);
1140 if end == 0 {
1141 return None;
1142 }
1143 let every = u64::from(self.interval_ms.load(std::sync::atomic::Ordering::Relaxed));
1144 let stale = std::time::Duration::from_millis(2 * every.max(1));
1145 (self.since(end - 1) <= stale)
1146 .then(|| self.rate_milli.load(std::sync::atomic::Ordering::Relaxed))
1147 }
1148 pub fn verdict(&self) -> CpuVerdict {
1153 match self.cpu_state() {
1154 CpuState::Off => return CpuVerdict::NotSampled,
1155 CpuState::Waiting | CpuState::Unavailable => return CpuVerdict::Unmeasured,
1156 CpuState::Measuring => {}
1157 }
1158 if let Some(rate) = self.fresh_rate().filter(|r| *r >= BUSY_MILLI_CORES) {
1159 return CpuVerdict::BusyAtKill(rate);
1160 }
1161 let since = self
1162 .measured_since
1163 .load(std::sync::atomic::Ordering::Relaxed);
1164 match (since, self.fresh_rate()) {
1165 (s, Some(_)) if s != 0 => CpuVerdict::MeasuredIdle(self.since(s - 1).as_secs()),
1166 _ => CpuVerdict::Unmeasured,
1167 }
1168 }
1169 pub fn record(
1172 &self,
1173 obs: crate::proctree::Observation,
1174 at: std::time::Instant,
1175 interval: std::time::Duration,
1176 ) {
1177 use std::sync::atomic::Ordering::Relaxed;
1178 self.interval_ms.store(
1179 u32::try_from(interval.as_millis()).unwrap_or(u32::MAX),
1180 Relaxed,
1181 );
1182 match obs {
1183 crate::proctree::Observation::Baseline => {
1184 self.measured_since.store(self.offset(at) + 1, Relaxed);
1185 self.set_cpu_state(CpuState::Waiting);
1186 }
1187 crate::proctree::Observation::Window(w) => {
1188 let milli = w.milli_cores();
1189 self.rate_milli.store(milli, Relaxed);
1190 self.last_measured.store(self.offset(w.end) + 1, Relaxed);
1191 if milli >= BUSY_MILLI_CORES {
1192 self.last_busy.fetch_max(self.offset(w.start), Relaxed);
1195 }
1196 if w.gapped {
1197 self.measured_since.store(self.offset(w.end) + 1, Relaxed);
1201 }
1202 self.set_cpu_state(CpuState::Measuring);
1203 }
1204 crate::proctree::Observation::Skipped => {}
1207 crate::proctree::Observation::Unmeasured => {
1208 self.measured_since.store(0, Relaxed);
1209 self.set_cpu_state(CpuState::Unavailable);
1210 }
1211 }
1212 }
1213 pub fn enable_cpu(&self) {
1215 self.set_cpu_state(CpuState::Waiting);
1216 }
1217 pub fn gate(&self) -> CpuGate {
1220 match self.verdict() {
1221 CpuVerdict::NotSampled => CpuGate::NotSampled,
1222 CpuVerdict::MeasuredIdle(_) | CpuVerdict::BusyAtKill(_) => CpuGate::Measured,
1223 CpuVerdict::Unmeasured => CpuGate::Unmeasured,
1224 }
1225 }
1226}
1227
1228#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1236pub enum CpuGate {
1237 NotSampled,
1238 Measured,
1239 Unmeasured,
1240}
1241
1242#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1244pub enum CpuVerdict {
1245 NotSampled,
1247 MeasuredIdle(u64),
1250 Unmeasured,
1252 BusyAtKill(u32),
1255}
1256
1257pub fn cores(milli: u32) -> String {
1259 format!("~{}.{} cores", milli / 1000, (milli % 1000) / 100)
1260}
1261
1262pub fn network_probe_budget(settings: &crate::config::Settings) -> u64 {
1270 match check_timeout(settings) {
1271 0 => 0,
1272 t => t.min(30),
1273 }
1274}
1275
1276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1278pub enum Why {
1279 Ceiling(u64),
1281 Silence(u64),
1283 Waited(crate::hooks::wait::WaitKind, u64),
1286}
1287
1288#[derive(Debug, Clone)]
1291pub struct Killed {
1292 pub why: Why,
1293 pub ran_secs: u64,
1295 pub quiet_secs: Option<u64>,
1298 pub cpu: CpuVerdict,
1300 pub idle_secs: u64,
1304 pub waiting: Option<(crate::hooks::wait::WaitKind, u64)>,
1306 pub last_line: Option<String>,
1310 pub load: Option<(crate::load::Load, u32)>,
1313}
1314
1315#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1318pub struct Clocks {
1319 pub ceiling: Option<u64>,
1321 pub silence: Option<u64>,
1324 pub lock_wait: LockWait,
1326 pub extended: Option<u64>,
1330 pub scale: u64,
1333}
1334
1335impl Clocks {
1336 pub fn ceiling_only(wall_secs: u64) -> Clocks {
1338 Clocks {
1339 ceiling: (wall_secs > 0).then_some(wall_secs),
1340 silence: None,
1341 lock_wait: LockWait::UntilCeiling,
1342 extended: None,
1343 scale: 1,
1344 }
1345 }
1346
1347 pub fn from_settings(settings: &crate::config::Settings, idle_secs: u64) -> Clocks {
1350 let wall = check_timeout(settings);
1351 let scale = idle_load_scale(settings);
1352 Clocks {
1353 ceiling: (wall > 0).then_some(wall),
1354 silence: (idle_secs > 0).then_some(idle_secs),
1355 lock_wait: lock_wait(settings),
1356 extended: (idle_secs > 0).then(|| idle_secs.saturating_mul(scale)),
1357 scale,
1358 }
1359 }
1360}
1361
1362const LOAD_EVERY: std::time::Duration = std::time::Duration::from_secs(5);
1364
1365pub fn idle_load_scale(settings: &crate::config::Settings) -> u64 {
1372 *settings.idle_load_scale.get_or_init(|| {
1373 crate::config::host_integer_or(settings, "greengate.idleLoadScale", 4, 1..=16) as u64
1374 })
1375}
1376
1377pub enum Ran {
1379 Status(std::process::ExitStatus),
1380 TimedOut(Killed),
1382}
1383
1384pub fn status_within(
1397 settings: &crate::config::Settings,
1398 cmd: &mut Command,
1399) -> std::io::Result<Ran> {
1400 if crate::host_slots::before_spawn(settings)? {
1403 cmd.env(crate::host_slots::HELD_ENV, "held");
1404 }
1405 crate::host_slots::bound(cmd);
1406 status_within_secs(cmd, check_timeout(settings))
1407}
1408
1409pub fn status_within_secs(cmd: &mut Command, budget_secs: u64) -> std::io::Result<Ran> {
1413 if budget_secs == 0 {
1414 return cmd.status().map(Ran::Status);
1415 }
1416 let mut child = cmd.spawn()?;
1417 wait_within(&mut child, Clocks::ceiling_only(budget_secs), None)
1418}
1419
1420fn run_observed(
1425 settings: &crate::config::Settings,
1426 cmd: &mut Command,
1427 on_output: impl Fn(&[u8]) + Send + Sync + 'static,
1428 ceiling_left: Option<u64>,
1429) -> std::io::Result<Ran> {
1430 let shared = std::sync::Arc::new(on_output);
1431 let for_stdout = std::sync::Arc::clone(&shared);
1432 run_observed_split(
1433 settings,
1434 cmd,
1435 move |bytes| for_stdout(bytes),
1436 move |bytes| shared(bytes),
1437 ceiling_left,
1438 )
1439}
1440
1441type OnBytes = std::sync::Arc<dyn Fn(&[u8]) + Send + Sync>;
1442
1443fn run_observed_split(
1445 settings: &crate::config::Settings,
1446 cmd: &mut Command,
1447 on_stdout: impl Fn(&[u8]) + Send + Sync + 'static,
1448 on_stderr: impl Fn(&[u8]) + Send + Sync + 'static,
1449 ceiling_left: Option<u64>,
1450) -> std::io::Result<Ran> {
1451 if crate::host_slots::before_spawn(settings)? {
1454 cmd.env(crate::host_slots::HELD_ENV, "held");
1455 }
1456 crate::host_slots::bound(cmd);
1457 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
1458 let activity = Activity::new();
1459 let on_stdout: OnBytes = std::sync::Arc::new(on_stdout);
1460 let on_stderr: OnBytes = std::sync::Arc::new(on_stderr);
1461 let mut child = cmd.spawn()?;
1462 activity.touch();
1466 let mut readers = Vec::new();
1467 let pipes = [
1472 (
1473 child
1474 .stdout
1475 .take()
1476 .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
1477 false,
1478 on_stdout,
1479 ),
1480 (
1481 child
1482 .stderr
1483 .take()
1484 .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
1485 true,
1486 on_stderr,
1487 ),
1488 ];
1489 for (pipe, is_stderr, on_output) in pipes {
1490 let Some(pipe) = pipe else { continue };
1491 let activity = std::sync::Arc::clone(&activity);
1492 readers.push(std::thread::spawn(move || {
1493 let mut pipe = pipe;
1494 let mut chunk = [0u8; 4096];
1495 let mut framer = crate::hooks::wait::LineFramer::default();
1496 let mut pending: Vec<u8> = Vec::new();
1502 loop {
1503 match std::io::Read::read(&mut pipe, &mut chunk) {
1504 Ok(0) | Err(_) => break,
1505 Ok(n) => {
1506 activity.touch();
1507 if is_stderr {
1508 for line in framer.feed(&chunk[..n]) {
1509 activity.stderr_line(&line);
1510 }
1511 } else {
1512 activity.end_wait();
1513 }
1514 pending.extend_from_slice(&chunk[..n]);
1515 if let Some(end) = whole_lines(&pending) {
1516 on_output(&pending[..end]);
1517 pending.drain(..end);
1518 }
1519 }
1520 }
1521 }
1522 if !pending.is_empty() {
1523 on_output(&pending);
1524 }
1525 }));
1526 }
1527 let _attached = crate::live::current_sink()
1529 .map(|(stage, idx)| stage.attach(idx, std::sync::Arc::clone(&activity)));
1530 let idle = idle_timeout(settings);
1531 let sampler = (idle > 0 && idle_cpu_credit(settings) && crate::proctree::SUPPORTED)
1532 .then(|| CpuSampler::start(child.id(), std::sync::Arc::clone(&activity), idle));
1533 let mut clocks = Clocks::from_settings(settings, idle);
1534 if let Some(left) = ceiling_left {
1535 clocks.ceiling = Some(left.max(1));
1538 }
1539 let ran = wait_within(&mut child, clocks, Some(&activity));
1540 if let Some(s) = sampler {
1541 s.stop();
1542 }
1543 for r in readers {
1544 let _ = r.join();
1546 }
1547 if let Ok(Ran::Status(_)) = &ran {
1551 let waited = activity.waited_total();
1552 if waited >= std::time::Duration::from_secs(1) {
1553 let what = activity
1554 .last_wait_kind()
1555 .map_or("a lock", crate::hooks::wait::WaitKind::describe);
1556 say(&format!(
1557 " (waited {} for {what})",
1558 human_secs(waited.as_secs())
1559 ));
1560 }
1561 }
1562 ran
1563}
1564
1565struct CpuSampler {
1571 stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
1572 handle: std::thread::JoinHandle<()>,
1573}
1574
1575impl CpuSampler {
1576 fn start(pid: u32, activity: std::sync::Arc<Activity>, idle_secs: u64) -> CpuSampler {
1577 activity.enable_cpu();
1578 let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1579 let flag = std::sync::Arc::clone(&stop);
1580 let handle = std::thread::Builder::new()
1581 .name("greengate-cpu".into())
1582 .spawn(move || sample_loop(pid, &activity, idle_secs, &flag))
1583 .expect("spawn the CPU sampler thread");
1584 CpuSampler { stop, handle }
1585 }
1586
1587 fn stop(self) {
1591 self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
1592 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1);
1593 while !self.handle.is_finished() && std::time::Instant::now() < deadline {
1594 std::thread::sleep(std::time::Duration::from_millis(10));
1595 }
1596 if self.handle.is_finished() {
1597 let _ = self.handle.join();
1598 }
1599 }
1600}
1601
1602pub fn sampling_schedule(idle_secs: u64) -> (std::time::Duration, std::time::Duration) {
1607 let ms = std::time::Duration::from_millis;
1608 let budget = std::time::Duration::from_secs(idle_secs);
1609 let first = (budget / 3)
1610 .min(std::time::Duration::from_secs(30))
1611 .max(ms(250));
1612 let every = (budget / 4).clamp(ms(250), std::time::Duration::from_secs(10));
1613 (first, every)
1614}
1615
1616fn sample_loop(
1617 pid: u32,
1618 activity: &Activity,
1619 idle_secs: u64,
1620 stop: &std::sync::atomic::AtomicBool,
1621) {
1622 use std::sync::atomic::Ordering::Relaxed;
1623 let (first, every) = sampling_schedule(idle_secs);
1624 let mut limits = crate::proctree::Limits::default();
1625 if let Some(n) = std::env::var("GREENGATE_CPU_MAX_PROCS")
1628 .ok()
1629 .and_then(|v| v.trim().parse::<usize>().ok())
1630 {
1631 limits.max_procs = n;
1632 }
1633 let trace = std::env::var_os("GREENGATE_CPU_TRACE");
1634 let mut tracker = crate::proctree::Tracker::default();
1635 let nap = |d: std::time::Duration| {
1636 let until = std::time::Instant::now() + d;
1637 while !stop.load(Relaxed) && std::time::Instant::now() < until {
1638 std::thread::sleep(std::time::Duration::from_millis(50));
1639 }
1640 };
1641 while !stop.load(Relaxed) {
1642 if activity.silence_for() < first {
1645 tracker = crate::proctree::Tracker::default();
1648 nap(std::time::Duration::from_millis(100));
1649 continue;
1650 }
1651 let snap = crate::proctree::snapshot(pid, &tracker.seen(), &limits);
1652 let at = std::time::Instant::now();
1653 let traced = trace.as_ref().map(|_| match &snap {
1654 crate::proctree::Snapshot::Complete(procs) => procs.clone(),
1655 _ => Vec::new(),
1656 });
1657 let obs = tracker.observe(at, snap);
1658 if let (Some(path), Some(procs)) = (&trace, traced) {
1659 trace_sample(path, pid, &procs, &obs);
1660 }
1661 activity.record(obs, at, every);
1662 nap(every);
1663 }
1664}
1665
1666fn trace_sample(
1672 path: &std::ffi::OsStr,
1673 root: u32,
1674 procs: &[crate::proctree::Proc],
1675 obs: &crate::proctree::Observation,
1676) {
1677 use std::io::Write;
1678 let Ok(mut f) = std::fs::OpenOptions::new()
1679 .create(true)
1680 .append(true)
1681 .open(path)
1682 else {
1683 return;
1684 };
1685 let mut text = String::new();
1686 for p in procs {
1687 text.push_str(&format!(
1688 "{} {} {} {}\n",
1689 p.id.pid, p.id.start, p.ppid, p.cpu_ns
1690 ));
1691 }
1692 let obs = match obs {
1693 crate::proctree::Observation::Window(w) => {
1694 format!("window {} milli-cores", w.milli_cores())
1695 }
1696 other => format!("{other:?}").to_lowercase(),
1697 };
1698 text.push_str(&format!("# root {root} {obs}\n"));
1699 let _ = f.write_all(text.as_bytes());
1700}
1701
1702pub fn status_streamed(
1714 settings: &crate::config::Settings,
1715 cmd: &mut Command,
1716 retry: Retry,
1717) -> std::io::Result<Ran> {
1718 let Some((stage, idx)) = crate::live::current_sink() else {
1719 return status_within(settings, cmd);
1720 };
1721 if crate::live::watching() {
1722 cmd.env("FORCE_COLOR", "1")
1725 .env("CLICOLOR_FORCE", "1")
1726 .env("CARGO_TERM_COLOR", "always");
1727 }
1728 let first = run_observed(
1729 settings,
1730 cmd,
1731 {
1732 let stage = std::sync::Arc::clone(&stage);
1733 move |bytes| stage.append_raw(idx, bytes)
1734 },
1735 None,
1736 );
1737 stage.runner_exit(idx, exit_of(&first));
1738 let Ok(Ran::TimedOut(k)) = &first else {
1739 return first;
1740 };
1741 let Some(left) = retry_budget(retry, k, check_timeout(settings)) else {
1742 return first;
1743 };
1744 let what = crate::host_slots::current_check()
1747 .unwrap_or_else(|| cmd.get_program().to_string_lossy().into_owned());
1748 say(&format!(
1749 "{} was killed while it looked like it was waiting ({}); retrying once{}.",
1750 hl(&what),
1751 k.last_line.as_deref().unwrap_or(""),
1752 match left {
1753 Some(s) => format!(" with {} left", human_secs(s)),
1754 None => String::new(),
1755 }
1756 ));
1757 let second = run_observed(
1758 settings,
1759 cmd,
1760 {
1761 let stage = std::sync::Arc::clone(&stage);
1762 move |bytes| stage.append_raw(idx, bytes)
1763 },
1764 left,
1765 );
1766 stage.runner_exit(idx, exit_of(&second));
1767 second
1768}
1769
1770fn whole_lines(pending: &[u8]) -> Option<usize> {
1774 match pending.iter().rposition(|&b| b == b'\n') {
1775 Some(i) => Some(i + 1),
1776 None if pending.len() >= LINE_HOLD => Some(pending.len()),
1777 None => None,
1778 }
1779}
1780
1781const LINE_HOLD: usize = 64 * 1024;
1782
1783fn exit_of(ran: &std::io::Result<Ran>) -> Option<i32> {
1786 match ran {
1787 Ok(Ran::Status(s)) => s.code(),
1788 _ => None,
1789 }
1790}
1791
1792#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1794pub enum Retry {
1795 Once,
1797 Never,
1799}
1800
1801pub fn retry_budget(retry: Retry, k: &Killed, ceiling: u64) -> Option<Option<u64>> {
1807 if retry == Retry::Never || !matches!(k.why, Why::Silence(_)) {
1808 return None;
1809 }
1810 if !k
1811 .last_line
1812 .as_deref()
1813 .is_some_and(crate::hooks::wait::looks_like_wait)
1814 {
1815 return None;
1816 }
1817 if ceiling == 0 {
1818 return Some(None);
1819 }
1820 let left = ceiling.saturating_sub(k.ran_secs);
1821 (left >= k.idle_secs.max(1)).then_some(Some(left))
1822}
1823
1824pub fn capture_within(
1830 settings: &crate::config::Settings,
1831 cmd: &mut Command,
1832) -> Option<(Ran, String)> {
1833 let text = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
1834 let sink = std::sync::Arc::clone(&text);
1835 let ran = run_observed(
1836 settings,
1837 cmd,
1838 move |bytes| {
1839 sink.lock()
1840 .unwrap_or_else(|p| p.into_inner())
1841 .push_str(&String::from_utf8_lossy(bytes));
1842 },
1843 None,
1844 )
1845 .ok()?;
1846 let text = std::sync::Arc::try_unwrap(text)
1847 .map(|m| m.into_inner().unwrap_or_else(|p| p.into_inner()))
1848 .unwrap_or_default();
1849 Some((ran, text))
1850}
1851
1852pub struct CapturedOutput {
1854 pub ran: Ran,
1855 pub stdout: String,
1856 pub stderr: String,
1857}
1858
1859pub fn capture_stdout_within(
1865 settings: &crate::config::Settings,
1866 cmd: &mut Command,
1867) -> std::io::Result<CapturedOutput> {
1868 let out = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
1869 let err = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
1870 let (out_sink, err_sink) = (std::sync::Arc::clone(&out), std::sync::Arc::clone(&err));
1871 let ran = run_observed_split(
1872 settings,
1873 cmd,
1874 move |bytes| {
1875 out_sink
1876 .lock()
1877 .unwrap_or_else(|p| p.into_inner())
1878 .extend_from_slice(bytes);
1879 },
1880 move |bytes| {
1881 err_sink
1882 .lock()
1883 .unwrap_or_else(|p| p.into_inner())
1884 .extend_from_slice(bytes);
1885 },
1886 None,
1887 )?;
1888 let take = |sink: std::sync::Arc<std::sync::Mutex<Vec<u8>>>| {
1889 let bytes = std::mem::take(&mut *sink.lock().unwrap_or_else(|p| p.into_inner()));
1890 String::from_utf8_lossy(&bytes).into_owned()
1891 };
1892 Ok(CapturedOutput {
1893 ran,
1894 stdout: take(out),
1895 stderr: take(err),
1896 })
1897}
1898
1899pub(crate) fn wait_within(
1904 child: &mut std::process::Child,
1905 clocks: Clocks,
1906 activity: Option<&Activity>,
1907) -> std::io::Result<Ran> {
1908 let started = std::time::Instant::now();
1909 let clocks = match activity {
1910 Some(_) => clocks,
1911 None => Clocks {
1912 silence: None,
1913 extended: None,
1914 ..clocks
1915 },
1916 };
1917 if clocks.ceiling.is_none() && clocks.silence.is_none() {
1918 return child.wait().map(Ran::Status);
1919 }
1920 let mut live = clocks;
1924 let mut load: Option<(crate::load::Load, u32)> = None;
1925 let mut next_load = started;
1926 loop {
1927 if let Some(status) = child.try_wait()? {
1928 return Ok(Ran::Status(status));
1929 }
1930 let now = std::time::Instant::now();
1931 if let (Some(idle), Some(a)) = (clocks.silence, activity) {
1932 if clocks.scale > 1 && now >= next_load {
1933 next_load = now + LOAD_EVERY;
1934 if let Some(l) = crate::load::read() {
1935 let factor = l.factor_milli(clocks.scale);
1936 let applied = crate::load::scaled_budget(idle, l, clocks.scale, clocks.ceiling);
1937 live.silence = Some(applied);
1938 a.set_load(applied, l, factor);
1939 load = (factor > 1000).then_some((l, factor));
1940 }
1941 }
1942 }
1943 let quiet = activity.map(|a| a.still_for());
1946 let waiting = activity.and_then(Activity::waiting);
1947 let gate = activity.map_or(CpuGate::NotSampled, Activity::gate);
1948 let why = judge(now.duration_since(started), quiet, waiting, gate, &live);
1949 if let Some(why) = why {
1950 let _ = child.kill();
1951 let _ = child.wait();
1952 return Ok(Ran::TimedOut(Killed {
1953 why,
1954 ran_secs: now.duration_since(started).as_secs(),
1955 quiet_secs: activity.map(|a| a.quiet_for().as_secs()),
1958 cpu: activity.map_or(CpuVerdict::NotSampled, Activity::verdict),
1959 idle_secs: clocks.silence.unwrap_or(0),
1960 waiting: waiting.map(|(k, d)| (k, d.as_secs())),
1961 last_line: activity.and_then(Activity::last_line),
1962 load,
1963 }));
1964 }
1965 std::thread::sleep(std::time::Duration::from_millis(25));
1966 }
1967}
1968
1969pub fn judge(
1984 ran: std::time::Duration,
1985 quiet: Option<std::time::Duration>,
1986 waiting: Option<(crate::hooks::wait::WaitKind, std::time::Duration)>,
1987 cpu: CpuGate,
1988 clocks: &Clocks,
1989) -> Option<Why> {
1990 if let Some(wall) = clocks.ceiling {
1991 if ran >= std::time::Duration::from_secs(wall) {
1992 return Some(Why::Ceiling(wall));
1993 }
1994 }
1995 if let Some((kind, waited)) = waiting {
1996 let budget = match clocks.lock_wait {
1997 LockWait::Secs(s) => Some(s),
1998 LockWait::UntilCeiling if clocks.ceiling.is_some() => None,
1999 LockWait::UntilCeiling => clocks.extended,
2000 };
2001 return match budget {
2002 Some(b) if waited >= std::time::Duration::from_secs(b) => Some(Why::Waited(kind, b)),
2003 _ => None,
2004 };
2005 }
2006 let budget = match cpu {
2007 CpuGate::NotSampled | CpuGate::Measured => clocks.silence,
2008 CpuGate::Unmeasured => clocks.extended.or(clocks.silence),
2009 };
2010 if let (Some(idle), Some(q)) = (budget, quiet) {
2011 if q >= std::time::Duration::from_secs(idle) {
2012 return Some(Why::Silence(idle));
2013 }
2014 }
2015 None
2016}
2017
2018pub fn say_timed_out(what: &str, k: Killed) {
2024 match k.why {
2025 Why::Silence(budget) => {
2026 let stretched = match (k.cpu, k.load) {
2030 _ if budget == k.idle_secs => String::new(),
2031 (CpuVerdict::Unmeasured, _) => format!(
2032 " (the extended budget, {} × {}: its CPU could not be measured)",
2033 human_secs(k.idle_secs),
2034 hl("greengate.idleLoadScale")
2035 ),
2036 (_, Some((load, factor))) => format!(
2037 " ({} stretched {} by a load average of {} on {} cores — {})",
2038 human_secs(k.idle_secs),
2039 crate::load::factor_text(factor),
2040 load.avg1_text(),
2041 load.cores,
2042 hl("greengate.idleLoadScale")
2043 ),
2044 _ => String::new(),
2045 };
2046 fail(&match k.cpu {
2047 CpuVerdict::MeasuredIdle(covered) => format!(
2048 "{} printed nothing for {}{stretched} and did no measurable CPU work \
2049 (< 0.1 core) in the last {} of it; killed after {} — a tool this idle \
2050 is stuck, not slow. {} raises the silence budget (0 disables)",
2051 hl(what),
2052 human_secs(budget),
2053 human_secs(covered.max(1)),
2054 human_secs(k.ran_secs),
2055 hl("git config greengate.idleTimeout <secs>")
2056 ),
2057 _ => format!(
2058 "{} printed nothing for {}{stretched}{} and was killed after {} — a tool \
2059 this quiet is usually stuck, not slow. {} raises the silence budget (0 \
2060 disables)",
2061 hl(what),
2062 human_secs(budget),
2063 if k.cpu == CpuVerdict::Unmeasured && stretched.is_empty() {
2064 " (CPU not measured)"
2065 } else {
2066 ""
2067 },
2068 human_secs(k.ran_secs),
2069 hl("git config greengate.idleTimeout <secs>")
2070 ),
2071 })
2072 }
2073 Why::Waited(kind, budget) => fail(&format!(
2074 "{} waited {} for {} and was killed after {} — {}. {} raises the wait budget \
2075 (0: until the ceiling)",
2076 hl(what),
2077 human_secs(budget),
2078 kind.describe(),
2079 human_secs(k.ran_secs),
2080 kind.holders(),
2081 hl("git config greengate.lockWait <secs>")
2082 )),
2083 Why::Ceiling(budget) => {
2084 let verdict = match (k.quiet_secs, k.cpu) {
2085 (_, _) if k.waiting.is_some() => {
2086 let (kind, w) = k.waiting.expect("checked");
2087 format!(
2088 " It was waiting for {} for the last {} — {}.",
2089 kind.describe(),
2090 human_secs(w),
2091 kind.holders()
2092 )
2093 }
2094 (Some(q), CpuVerdict::BusyAtKill(m)) if k.idle_secs > 0 && q >= k.idle_secs => {
2095 format!(
2096 " It printed nothing for the last {} but kept its CPU busy ({}), so the \
2097 silence budget did not stop it: a busy loop, or a tool that prints only \
2098 at the end (give it a per-file reporter). {} kills quiet runs at the \
2099 silence budget whatever their CPU.",
2100 human_secs(q),
2101 cores(m),
2102 hl("git config greengate.idleCpuCredit false")
2103 )
2104 }
2105 (Some(q), CpuVerdict::Unmeasured) if k.idle_secs > 0 && q >= k.idle_secs => {
2106 format!(
2107 " It printed nothing for the last {} and its CPU could not be measured, \
2108 so only the extended silence budget applied. {} kills quiet runs at \
2109 the silence budget whatever their CPU.",
2110 human_secs(q),
2111 hl("git config greengate.idleCpuCredit false")
2112 )
2113 }
2114 (Some(q), _) if q < 30 => format!(
2115 " It was still printing ({} since its last line): slow, not stuck.",
2116 human_secs(q)
2117 ),
2118 (Some(q), _) => format!(" Its last output was {} ago.", human_secs(q)),
2119 (None, _) => String::new(),
2120 };
2121 fail(&format!(
2122 "{} timed out: ran for {} and was killed at the ceiling. {} raises it \
2123 (0 disables).{verdict}",
2124 hl(what),
2125 human_secs(budget),
2126 hl("git config greengate.timeout <secs>")
2127 ))
2128 }
2129 }
2130}
2131
2132pub fn bounded_success(settings: &crate::config::Settings, cmd: &mut Command, what: &str) -> bool {
2135 match status_streamed(settings, cmd, Retry::Once) {
2136 Ok(Ran::Status(s)) => s.success(),
2137 Ok(Ran::TimedOut(b)) => {
2138 say_timed_out(what, b);
2139 false
2140 }
2141 Err(_) => false,
2142 }
2143}
2144
2145pub fn run(
2147 settings: &crate::config::Settings,
2148 root: &str,
2149 argv: &[String],
2150 extra: &[String],
2151) -> bool {
2152 let Some((program, rest)) = argv.split_first() else {
2153 return true;
2154 };
2155 let mut cmd = Command::new(program);
2156 cmd.args(rest)
2157 .args(extra)
2158 .current_dir(root)
2159 .stdin(Stdio::null());
2160 strip_git_env(&mut cmd);
2161 bounded_success(settings, &mut cmd, program)
2162}
2163
2164pub fn run_quiet(
2170 settings: &crate::config::Settings,
2171 root: &str,
2172 argv: &[String],
2173 extra: &[String],
2174) -> bool {
2175 let Some((program, rest)) = argv.split_first() else {
2176 return true;
2177 };
2178 let mut cmd = Command::new(program);
2179 cmd.args(rest)
2180 .args(extra)
2181 .current_dir(root)
2182 .stdin(Stdio::null());
2183 strip_git_env(&mut cmd);
2184 match run_observed(settings, &mut cmd, |_| {}, None) {
2189 Ok(Ran::Status(s)) => s.success(),
2190 Ok(Ran::TimedOut(b)) => {
2191 say_timed_out(program, b);
2192 false
2193 }
2194 Err(_) => false,
2195 }
2196}
2197
2198pub fn fixing_enabled(settings: &crate::config::Settings) -> bool {
2206 !not_the_index() && fixing_requested(settings)
2208}
2209
2210pub fn fixing_requested(settings: &crate::config::Settings) -> bool {
2216 *settings
2217 .fixing
2218 .get_or_init(|| crate::config::boolean_or(settings, "greengate.fix", false))
2219}
2220
2221#[derive(Debug, Clone, PartialEq, Eq)]
2232pub enum Restaged {
2233 Nothing,
2235 Staged,
2237 Failed(Vec<String>),
2242}
2243
2244static INDEX_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
2253
2254pub fn restage(paths: &[String]) -> Restaged {
2261 if not_the_index() {
2264 return Restaged::Nothing;
2265 }
2266 let changed: Vec<String> = paths
2267 .iter()
2268 .filter(|p| !git::succeeds(&["diff", "--quiet", "--", p]))
2269 .cloned()
2270 .collect();
2271 if changed.is_empty() {
2272 return Restaged::Nothing;
2273 }
2274 let mut args = vec!["add", "--"];
2275 args.extend(changed.iter().map(String::as_str));
2276
2277 let _serialised = INDEX_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2278 const BACKOFF_MS: [u64; 3] = [50, 150, 400];
2284 if git::succeeds(&args) {
2285 return Restaged::Staged;
2286 }
2287 for wait in BACKOFF_MS {
2288 std::thread::sleep(std::time::Duration::from_millis(wait));
2289 if git::succeeds(&args) {
2290 return Restaged::Staged;
2291 }
2292 }
2293 Restaged::Failed(changed)
2294}
2295
2296pub fn ok(settings: &crate::config::Settings, msg: &str) {
2299 if crate::live::quiet(settings) {
2300 return;
2301 }
2302 crate::live::say(&format!("{} {msg}", valid_sign()));
2303}
2304pub fn fail(msg: &str) {
2305 if crate::host_slots::deferred_here() {
2309 return;
2310 }
2311 crate::live::say(&format!("{} {msg}", error_sign()));
2312}
2313pub fn warn(msg: &str) {
2314 if crate::host_slots::deferred_here() {
2318 return;
2319 }
2320 crate::live::say(&format!("{} {msg}", warning_sign()));
2321}
2322pub fn say(msg: &str) {
2325 crate::live::say(msg);
2326}
2327
2328pub fn hl(s: &str) -> String {
2330 crate::ui::highlight(s)
2331}
2332
2333#[cfg(test)]
2334mod tests {
2335
2336 #[cfg(unix)]
2340 #[test]
2341 fn capture_stdout_within_keeps_the_streams_apart() {
2342 let settings = crate::config::Settings::default();
2343 let mut cmd = std::process::Command::new(super::program("sh"));
2344 cmd.args([
2345 "-c",
2346 "printf '{\"a\":1}'; printf 'npm warn x\\n' >&2; exit 3",
2347 ]);
2348 let captured = super::capture_stdout_within(&settings, &mut cmd).expect("sh runs");
2349 assert_eq!(captured.stdout, "{\"a\":1}", "stdout alone");
2350 assert_eq!(captured.stderr, "npm warn x\n", "stderr alone");
2351 match captured.ran {
2352 super::Ran::Status(s) => assert_eq!(s.code(), Some(3), "the real exit status"),
2353 super::Ran::TimedOut(_) => panic!("a one-line child timed out"),
2354 }
2355 }
2356
2357 #[cfg(unix)]
2360 #[test]
2361 fn stderr_only_output_leaves_stdout_empty() {
2362 let settings = crate::config::Settings::default();
2363 let mut cmd = std::process::Command::new(super::program("sh"));
2364 cmd.args(["-c", "printf 'only a warning\\n' >&2"]);
2365 let captured = super::capture_stdout_within(&settings, &mut cmd).expect("sh runs");
2366 assert!(
2367 captured.stdout.is_empty(),
2368 "stdout must be empty, got {:?}",
2369 captured.stdout
2370 );
2371 assert_eq!(captured.stderr, "only a warning\n");
2372 assert!(matches!(captured.ran, super::Ran::Status(s) if s.success()));
2373 }
2374
2375 #[test]
2377 fn only_the_one_newline_git_prints_is_stripped() {
2378 assert_eq!(super::strip_one_newline(b"/r/.git\n".to_vec()), b"/r/.git");
2379 assert_eq!(super::strip_one_newline(b"/r/x\r\n".to_vec()), b"/r/x\r");
2380 assert_eq!(super::strip_one_newline(b"/r/x".to_vec()), b"/r/x");
2381 }
2382
2383 #[test]
2386 fn a_git_path_becomes_the_same_path() {
2387 assert_eq!(
2388 super::path_from_bytes(b"/r/.git/index".to_vec()),
2389 std::path::PathBuf::from("/r/.git/index")
2390 );
2391 }
2392
2393 #[test]
2394 fn a_lookup_error_says_git_s_reason() {
2395 let e = super::IndexLookupError::Git {
2396 args: "rev-parse --git-path index".into(),
2397 why: "fatal: not a git repository".into(),
2398 };
2399 assert_eq!(
2400 e.to_string(),
2401 "git rev-parse --git-path index failed: fatal: not a git repository"
2402 );
2403 }
2404
2405 fn window(
2409 start: std::time::Instant,
2410 end: std::time::Instant,
2411 milli: u64,
2412 ) -> crate::proctree::Observation {
2413 let wall = u64::try_from(end.duration_since(start).as_nanos())
2414 .unwrap_or(u64::MAX)
2415 .max(1);
2416 let gain = wall * milli / 1000;
2417 crate::proctree::Observation::Window(crate::proctree::Window {
2418 start,
2419 end,
2420 gain_ns: gain,
2421 gapped: false,
2422 })
2423 }
2424
2425 #[test]
2429 fn a_gapped_window_is_never_claimed_as_measured_idle() {
2430 use super::{Activity, CpuVerdict};
2431 use crate::proctree::{Observation, Window};
2432 let s = std::time::Duration::from_secs;
2433 let every = s(10);
2434 let a = Activity::new();
2435 a.enable_cpu();
2436 let t0 = std::time::Instant::now() - s(30);
2437 a.record(Observation::Baseline, t0, every);
2438 a.record(Observation::Skipped, t0 + s(10), every);
2439 let gap_end = std::time::Instant::now();
2440 a.record(
2441 Observation::Window(Window {
2442 start: t0,
2443 end: gap_end,
2444 gain_ns: 0,
2445 gapped: true,
2446 }),
2447 gap_end,
2448 every,
2449 );
2450 assert_eq!(a.verdict(), CpuVerdict::MeasuredIdle(0));
2452 assert_eq!(a.gate(), super::CpuGate::Measured);
2453
2454 let busy = Activity::new();
2455 busy.enable_cpu();
2456 busy.record(Observation::Baseline, t0, every);
2457 busy.record(Observation::Skipped, t0 + s(10), every);
2458 let now = std::time::Instant::now();
2459 busy.record(window_gapped(t0, now, 3000), now, every);
2460 assert_eq!(busy.verdict(), CpuVerdict::BusyAtKill(3000));
2461 assert!(busy.still_for() < s(1));
2462 }
2463
2464 fn window_gapped(
2465 start: std::time::Instant,
2466 end: std::time::Instant,
2467 milli: u64,
2468 ) -> crate::proctree::Observation {
2469 match window(start, end, milli) {
2470 crate::proctree::Observation::Window(w) => {
2471 crate::proctree::Observation::Window(crate::proctree::Window { gapped: true, ..w })
2472 }
2473 o => o,
2474 }
2475 }
2476
2477 #[test]
2480 fn the_sampling_schedule_follows_the_budget_within_floors() {
2481 use super::sampling_schedule;
2482 let ms = std::time::Duration::from_millis;
2483 let third = |secs: u64| std::time::Duration::from_secs(secs) / 3;
2484 assert_eq!(sampling_schedule(1), (third(1), ms(250)));
2485 assert_eq!(sampling_schedule(2), (third(2), ms(500)));
2486 assert_eq!(sampling_schedule(120), (ms(30_000), ms(10_000)));
2487 assert_eq!(sampling_schedule(0), (ms(250), ms(250)));
2488 }
2489
2490 #[test]
2493 fn busy_work_resets_the_still_time_but_not_the_output_silence() {
2494 use super::Activity;
2495 let a = Activity::new();
2496 a.touch();
2497 std::thread::sleep(std::time::Duration::from_millis(60));
2498 let quiet = a.quiet_for();
2499 assert!(a.still_for() >= quiet.saturating_sub(std::time::Duration::from_millis(5)));
2500 a.enable_cpu();
2501 let now = std::time::Instant::now();
2502 a.record(
2503 window(now - std::time::Duration::from_millis(10), now, 2000),
2504 now,
2505 std::time::Duration::from_secs(1),
2506 );
2507 assert!(a.still_for() < std::time::Duration::from_millis(40));
2508 assert!(a.quiet_for() >= std::time::Duration::from_millis(60));
2509 }
2510
2511 #[test]
2515 fn the_cpu_verdict_claims_only_what_was_measured() {
2516 use super::{Activity, CpuVerdict};
2517 use crate::proctree::Observation;
2518 let s = std::time::Duration::from_secs;
2519 let every = s(10);
2520
2521 let off = Activity::new();
2522 assert_eq!(off.verdict(), CpuVerdict::NotSampled);
2523
2524 let waiting = Activity::new();
2525 waiting.enable_cpu();
2526 assert_eq!(waiting.verdict(), CpuVerdict::Unmeasured);
2527
2528 let now = std::time::Instant::now();
2529 let before = now - s(1);
2530 let idle = Activity::new();
2532 idle.enable_cpu();
2533 let t0 = std::time::Instant::now();
2534 idle.record(Observation::Baseline, t0, every);
2535 std::thread::sleep(std::time::Duration::from_millis(1050));
2536 let t1 = std::time::Instant::now();
2537 idle.record(window(t0, t1, 20), t1, every);
2538 assert_eq!(idle.verdict(), CpuVerdict::MeasuredIdle(1));
2539
2540 let busy = Activity::new();
2541 busy.enable_cpu();
2542 busy.record(Observation::Baseline, before, every);
2543 busy.record(window(before, now, 3900), now, every);
2544 assert_eq!(busy.verdict(), CpuVerdict::BusyAtKill(3900));
2545
2546 let broken = Activity::new();
2547 broken.enable_cpu();
2548 broken.record(Observation::Baseline, before, every);
2549 broken.record(window(before, now, 20), now, every);
2550 broken.record(Observation::Unmeasured, now, every);
2551 assert_eq!(broken.verdict(), CpuVerdict::Unmeasured);
2552 assert_eq!(broken.gate(), super::CpuGate::Unmeasured);
2553 assert_eq!(off.gate(), super::CpuGate::NotSampled);
2554 assert_eq!(idle.gate(), super::CpuGate::Measured);
2555 assert_eq!(busy.gate(), super::CpuGate::Measured);
2556 }
2557
2558 #[test]
2561 fn a_stale_rate_expires() {
2562 use super::{Activity, CpuVerdict};
2563 use crate::proctree::Observation;
2564 let a = Activity::new();
2565 a.enable_cpu();
2566 let then = std::time::Instant::now();
2567 let tick = std::time::Duration::from_millis(5);
2568 let earlier = then - std::time::Duration::from_secs(1);
2569 a.record(Observation::Baseline, earlier, tick);
2570 a.record(window(earlier, then, 3000), then, tick);
2571 std::thread::sleep(std::time::Duration::from_millis(40));
2572 assert_eq!(a.fresh_rate(), None);
2573 assert_eq!(a.verdict(), CpuVerdict::Unmeasured);
2574 }
2575
2576 #[test]
2577 fn cores_read_as_one_decimal() {
2578 assert_eq!(super::cores(3900), "~3.9 cores");
2579 assert_eq!(super::cores(420), "~0.4 cores");
2580 assert_eq!(super::cores(100), "~0.1 cores");
2581 }
2582
2583 #[test]
2587 fn the_clocks_judge_silence_and_ceiling_separately() {
2588 use super::{judge, CpuGate, Why};
2589 use std::time::Duration as D;
2590 let s = D::from_secs;
2591 let c = |ceiling: Option<u64>, silence: Option<u64>| super::Clocks {
2592 ceiling,
2593 silence,
2594 lock_wait: super::LockWait::Secs(600),
2595 extended: silence,
2596 scale: 1,
2597 };
2598 assert_eq!(
2600 judge(
2601 s(900),
2602 Some(s(0)),
2603 None,
2604 CpuGate::NotSampled,
2605 &c(Some(3600), Some(5))
2606 ),
2607 None
2608 );
2609 assert_eq!(
2610 judge(
2611 s(900),
2612 Some(s(4)),
2613 None,
2614 CpuGate::NotSampled,
2615 &c(Some(3600), Some(5))
2616 ),
2617 None
2618 );
2619 assert_eq!(
2621 judge(
2622 s(30),
2623 Some(s(5)),
2624 None,
2625 CpuGate::NotSampled,
2626 &c(Some(3600), Some(5))
2627 ),
2628 Some(Why::Silence(5))
2629 );
2630 assert_eq!(
2632 judge(
2633 s(900),
2634 None,
2635 None,
2636 CpuGate::NotSampled,
2637 &c(Some(3600), Some(5))
2638 ),
2639 None
2640 );
2641 assert_eq!(
2643 judge(
2644 s(3600),
2645 Some(s(0)),
2646 None,
2647 CpuGate::NotSampled,
2648 &c(Some(3600), Some(120))
2649 ),
2650 Some(Why::Ceiling(3600))
2651 );
2652 assert_eq!(
2654 judge(
2655 s(3600),
2656 Some(s(600)),
2657 None,
2658 CpuGate::NotSampled,
2659 &c(Some(3600), Some(120))
2660 ),
2661 Some(Why::Ceiling(3600))
2662 );
2663 assert_eq!(
2665 judge(
2666 s(86_400),
2667 Some(s(86_400)),
2668 None,
2669 CpuGate::NotSampled,
2670 &c(None, None)
2671 ),
2672 None
2673 );
2674 assert_eq!(
2676 judge(
2677 s(86_400),
2678 Some(s(1)),
2679 None,
2680 CpuGate::NotSampled,
2681 &c(None, Some(120))
2682 ),
2683 None
2684 );
2685 }
2686
2687 #[test]
2691 fn a_declared_wait_answers_to_its_own_budget() {
2692 use super::{judge, Clocks, CpuGate, LockWait, Why};
2693 use crate::hooks::wait::{CargoLockWhat, WaitKind};
2694 use std::time::Duration as D;
2695 let s = D::from_secs;
2696 let kind = WaitKind::CargoLock(CargoLockWhat::BuildDirectory);
2697 let clocks = Clocks {
2698 ceiling: Some(3600),
2699 silence: Some(120),
2700 lock_wait: LockWait::Secs(600),
2701 extended: Some(480),
2702 scale: 4,
2703 };
2704 assert_eq!(
2706 judge(
2707 s(1300),
2708 Some(s(0)),
2709 Some((kind, s(599))),
2710 CpuGate::Measured,
2711 &clocks
2712 ),
2713 None
2714 );
2715 assert_eq!(
2717 judge(
2718 s(1300),
2719 Some(s(0)),
2720 Some((kind, s(600))),
2721 CpuGate::Measured,
2722 &clocks
2723 ),
2724 Some(Why::Waited(kind, 600))
2725 );
2726 assert_eq!(
2728 judge(
2729 s(3600),
2730 Some(s(0)),
2731 Some((kind, s(3000))),
2732 CpuGate::Measured,
2733 &clocks
2734 ),
2735 Some(Why::Ceiling(3600))
2736 );
2737 let until = Clocks {
2739 lock_wait: LockWait::UntilCeiling,
2740 ..clocks
2741 };
2742 assert_eq!(
2743 judge(
2744 s(3000),
2745 Some(s(0)),
2746 Some((kind, s(2900))),
2747 CpuGate::Measured,
2748 &until
2749 ),
2750 None
2751 );
2752 let open = Clocks {
2754 ceiling: None,
2755 ..until
2756 };
2757 assert_eq!(
2758 judge(
2759 s(3000),
2760 Some(s(0)),
2761 Some((kind, s(479))),
2762 CpuGate::Measured,
2763 &open
2764 ),
2765 None
2766 );
2767 assert_eq!(
2768 judge(
2769 s(3000),
2770 Some(s(0)),
2771 Some((kind, s(480))),
2772 CpuGate::Measured,
2773 &open
2774 ),
2775 Some(Why::Waited(kind, 480))
2776 );
2777 }
2778
2779 #[test]
2783 fn a_wait_like_silence_kill_earns_one_retry_under_the_remaining_ceiling() {
2784 use super::{retry_budget, CpuVerdict, Killed, Retry, Why};
2785 use crate::hooks::wait::{CargoLockWhat, WaitKind};
2786 let k = |why: Why, line: &str, ran: u64| Killed {
2787 why,
2788 ran_secs: ran,
2789 quiet_secs: Some(ran),
2790 cpu: CpuVerdict::MeasuredIdle(1),
2791 idle_secs: 120,
2792 waiting: None,
2793 last_line: Some(line.to_string()),
2794 load: None,
2795 };
2796 let wait = "waiting for lock on x";
2797 assert_eq!(
2798 retry_budget(Retry::Once, &k(Why::Silence(120), wait, 120), 3600),
2799 Some(Some(3480))
2800 );
2801 assert_eq!(
2802 retry_budget(Retry::Once, &k(Why::Silence(120), wait, 120), 0),
2803 Some(None)
2804 );
2805 assert_eq!(
2806 retry_budget(Retry::Never, &k(Why::Silence(120), wait, 120), 3600),
2807 None
2808 );
2809 assert_eq!(
2810 retry_budget(
2811 Retry::Once,
2812 &k(Why::Silence(120), "test_lock.py::x", 120),
2813 3600
2814 ),
2815 None
2816 );
2817 assert_eq!(
2818 retry_budget(Retry::Once, &k(Why::Ceiling(3600), wait, 3600), 3600),
2819 None
2820 );
2821 let waited = Why::Waited(WaitKind::CargoLock(CargoLockWhat::BuildDirectory), 600);
2822 assert_eq!(retry_budget(Retry::Once, &k(waited, wait, 700), 3600), None);
2823 assert_eq!(
2825 retry_budget(Retry::Once, &k(Why::Silence(120), wait, 3500), 3600),
2826 None
2827 );
2828 }
2829
2830 #[test]
2834 fn an_unmeasured_cpu_answers_to_the_extended_budget() {
2835 use super::{judge, Clocks, CpuGate, LockWait, Why};
2836 use std::time::Duration as D;
2837 let s = D::from_secs;
2838 let clocks = Clocks {
2839 ceiling: None,
2840 silence: Some(120),
2841 lock_wait: LockWait::Secs(600),
2842 extended: Some(480),
2843 scale: 4,
2844 };
2845 assert_eq!(
2846 judge(s(500), Some(s(300)), None, CpuGate::Unmeasured, &clocks),
2847 None
2848 );
2849 assert_eq!(
2850 judge(s(500), Some(s(479)), None, CpuGate::Unmeasured, &clocks),
2851 None
2852 );
2853 assert_eq!(
2854 judge(s(500), Some(s(480)), None, CpuGate::Unmeasured, &clocks),
2855 Some(Why::Silence(480))
2856 );
2857 assert_eq!(
2858 judge(s(500), Some(s(120)), None, CpuGate::Measured, &clocks),
2859 Some(Why::Silence(120))
2860 );
2861 assert_eq!(
2862 judge(s(500), Some(s(120)), None, CpuGate::NotSampled, &clocks),
2863 Some(Why::Silence(120))
2864 );
2865 let off = Clocks {
2867 silence: None,
2868 extended: None,
2869 ..clocks
2870 };
2871 assert_eq!(
2872 judge(s(86_400), Some(s(86_400)), None, CpuGate::Unmeasured, &off),
2873 None
2874 );
2875 }
2876
2877 #[test]
2881 fn a_marker_line_pauses_the_silence_clock_until_another_line() {
2882 use super::Activity;
2883 use crate::hooks::wait::{CargoLockWhat, WaitKind};
2884 let a = Activity::new();
2885 a.touch();
2886 assert_eq!(a.waiting(), None);
2887 a.stderr_line(" Blocking waiting for file lock on package cache");
2888 std::thread::sleep(std::time::Duration::from_millis(30));
2889 let (kind, waited) = a.waiting().expect("a wait is in progress");
2890 assert_eq!(kind, WaitKind::CargoLock(CargoLockWhat::PackageCache));
2891 assert!(waited >= std::time::Duration::from_millis(30));
2892 assert_eq!(a.silence_for(), std::time::Duration::ZERO);
2893 assert_eq!(a.still_for(), std::time::Duration::ZERO);
2894 assert!(a.quiet_for() >= std::time::Duration::from_millis(30));
2895 a.stderr_line("\u{1b}[1m Blocking\u{1b}[0m waiting for file lock on build directory");
2897 let (kind, again) = a.waiting().expect("still waiting");
2898 assert_eq!(kind, WaitKind::CargoLock(CargoLockWhat::BuildDirectory));
2899 assert!(again >= waited);
2900 a.touch();
2903 a.stderr_line(" Checking foo v0.1.0");
2904 assert_eq!(a.waiting(), None);
2905 assert!(a.waited_total() >= std::time::Duration::from_millis(30));
2906 assert_eq!(a.last_wait_kind(), Some(kind));
2907 assert_eq!(a.last_line().as_deref(), Some("Checking foo v0.1.0"));
2908 assert!(a.silence_for() < std::time::Duration::from_millis(20));
2909 a.stderr_line("Waiting to acquire write lock for `x`");
2911 assert!(a.waiting().is_some());
2912 a.end_wait();
2913 assert_eq!(a.waiting(), None);
2914 }
2915
2916 #[cfg(unix)]
2918 #[test]
2919 fn the_deadline_kills_a_sleeper_and_spares_a_finisher() {
2920 let started = std::time::Instant::now();
2921 let mut slow = Command::new(program("sleep"));
2922 slow.arg("300").stdin(Stdio::null());
2923 match status_within_secs(&mut slow, 1) {
2924 Ok(Ran::TimedOut(Killed {
2925 why: Why::Ceiling(1),
2926 quiet_secs: None,
2927 ..
2928 })) => {}
2929 other => panic!("expected TimedOut(1), got {:?}", other.map(|_| "ran")),
2930 }
2931 assert!(
2932 started.elapsed() < std::time::Duration::from_secs(60),
2933 "the kill did not happen at the deadline"
2934 );
2935
2936 let mut quick = Command::new(program("true"));
2937 quick.stdin(Stdio::null());
2938 match status_within_secs(&mut quick, 60) {
2939 Ok(Ran::Status(s)) => assert!(s.success()),
2940 other => panic!("expected a clean exit, got {:?}", other.map(|_| "?")),
2941 }
2942 }
2943
2944 use super::*;
2945
2946 #[test]
2947 fn which_finds_a_real_binary_and_not_a_fake_one() {
2948 assert!(which("git").is_some());
2949 assert!(which("definitely-not-a-real-binary-xyz").is_none());
2950 }
2951
2952 #[test]
2956 #[cfg(windows)]
2957 fn windows_prefers_an_executable_extension_over_a_bare_file() {
2958 let dir = std::env::temp_dir().join("greengate-which-order");
2959 let _ = std::fs::create_dir_all(&dir);
2960 std::fs::write(dir.join("faketool"), "#!/bin/sh\n").unwrap();
2961 std::fs::write(dir.join("faketool.cmd"), "@echo off\n").unwrap();
2962 let found = which_on(dir.as_os_str(), "faketool").unwrap();
2966 assert!(found.ends_with(".cmd"), "got {found}");
2967 let _ = std::fs::remove_dir_all(&dir);
2968 }
2969
2970 #[test]
2983 fn restage_distinguishes_nothing_from_failure() {
2984 let _cwd = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
2990 let outside = std::env::temp_dir()
2991 .join("greengate-restage-outside-any-repo")
2992 .to_string_lossy()
2993 .into_owned();
2994 assert_eq!(
2995 restage(std::slice::from_ref(&outside)),
2996 Restaged::Failed(vec![outside]),
2997 "a `git add` git refuses must report Failed, never Nothing"
2998 );
2999 assert_eq!(
3000 restage(&[]),
3001 Restaged::Nothing,
3002 "no paths is nothing to do, and nothing wrong"
3003 );
3004 }
3005
3006 #[test]
3022 fn no_hook_spawns_a_bare_program_name() {
3023 let needle = concat!("Command", "::new(");
3024 let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/src/hooks");
3025 let mut scanned = 0usize;
3026 for entry in std::fs::read_dir(dir).expect("hooks dir").flatten() {
3027 let path = entry.path();
3028 if path.extension().and_then(|e| e.to_str()) != Some("rs") {
3029 continue;
3030 }
3031 scanned += 1;
3032 let src = std::fs::read_to_string(&path).expect("read a hook module");
3033 for (n, line) in src.lines().enumerate() {
3034 if line.trim_start().starts_with("//") {
3035 continue;
3036 }
3037 let Some(after) = line.split_once(needle) else {
3038 continue;
3039 };
3040 assert!(
3041 !after.1.starts_with('"'),
3042 "{}:{} spawns a bare name — route it through `program()` or \
3043 the path `which()` already resolved: {}",
3044 path.display(),
3045 n + 1,
3046 line.trim()
3047 );
3048 }
3049 }
3050 assert!(
3051 scanned > 10,
3052 "the scan found almost nothing: {scanned} files"
3053 );
3054 }
3055
3056 #[test]
3057 fn first_existing_picks_the_earliest_present_name() {
3058 let dir = std::env::temp_dir().join("greengate-first-existing-test");
3059 let _ = std::fs::create_dir_all(&dir);
3060 let root = dir.to_string_lossy().into_owned();
3061 let _ = std::fs::write(dir.join("second"), "x");
3062 assert_eq!(
3063 first_existing(&root, &["first", "second", "third"]).as_deref(),
3064 Some("second")
3065 );
3066 assert_eq!(first_existing(&root, &["nope"]), None);
3067 let _ = std::fs::remove_dir_all(&dir);
3068 }
3069}
3070
3071#[cfg(test)]
3072mod js_tool_tests {
3073 use super::{package_json_declares, version_in};
3074
3075 #[test]
3076 fn package_json_declares_a_dev_dependency() {
3077 assert!(package_json_declares(
3078 r#"{"devDependencies":{"prettier":"3.9.10"}}"#,
3079 "prettier"
3080 ));
3081 assert!(package_json_declares(
3082 "{\n \"name\": \"x\",\n \"dependencies\": { \"eslint\": \"9.1.0\" }\n}\n",
3083 "eslint"
3084 ));
3085 assert!(package_json_declares(
3087 "\u{feff}{\"devDependencies\":{\"prettier\":\"3.9.10\"}}",
3088 "prettier"
3089 ));
3090 }
3091
3092 #[test]
3094 fn package_json_declares_gives_up_on_deep_nesting() {
3095 let deep = format!(
3096 "{{\"x\":{}{},\"devDependencies\":{{\"prettier\":\"3\"}}}}",
3097 "[".repeat(100_000),
3098 "]".repeat(100_000)
3099 );
3100 assert!(!package_json_declares(&deep, "prettier"));
3101 let fine = format!(
3102 "{{\"x\":{}{},\"devDependencies\":{{\"prettier\":\"3\"}}}}",
3103 "[".repeat(50),
3104 "]".repeat(50)
3105 );
3106 assert!(package_json_declares(&fine, "prettier"));
3107 }
3108
3109 #[test]
3110 fn package_json_declares_nothing_else() {
3111 let not = |text: &str| assert!(!package_json_declares(text, "prettier"), "{text}");
3112 not(r#"{"prettier":{"semi":false}}"#);
3114 not(r#"{"devDependencies":{"prettier-plugin-x":"1.0.0"}}"#);
3116 not(r#"{"peerDependencies":{"prettier":"3"}}"#);
3118 not(r#"{"optionalDependencies":{"prettier":"3"}}"#);
3119 not(r#"{"pnpm":{"overrides":{"prettier":"3"}}}"#);
3120 not(r#"{"scripts":{"prettier":"prettier --check ."}}"#);
3121 not(r#"{"metadata":{"devDependencies":{"prettier":"3"}}}"#);
3123 not(r#"{"list":[{"dependencies":{"prettier":"3"}}]}"#);
3124 not(r#"{"description":"say \"devDependencies\": {\"prettier\": 1}"}"#);
3126 not(r#"{"devDependencies":{"prettier":"3.9.10""#);
3128 not(r#"{"devDependencies":{"prettier":"3.9.10"}} trailing"#);
3129 not("");
3130 }
3131
3132 #[test]
3133 fn package_json_declares_past_escapes_and_nesting() {
3134 assert!(package_json_declares(
3135 r#"{"description":"a \"quoted\" {brace}","x":[1,{"y":null}],"devDependencies":{"a":"1","prettier":"^3"}}"#,
3136 "prettier"
3137 ));
3138 }
3139
3140 #[test]
3141 fn version_in_skips_warnings_and_strips_v() {
3142 assert_eq!(version_in("3.9.10\n").as_deref(), Some("3.9.10"));
3143 assert_eq!(version_in("v9.14.0").as_deref(), Some("9.14.0"));
3144 assert_eq!(
3145 version_in("npm warn exec The following package was not found\n3.9.10").as_deref(),
3146 Some("3.9.10")
3147 );
3148 assert_eq!(
3149 version_in("(node:1) Warning: x\n3.0.0-beta.1").as_deref(),
3150 Some("3.0.0-beta.1")
3151 );
3152 assert_eq!(version_in("3.9.10\u{1b}[2J").as_deref(), Some("3.9.10"));
3153 assert_eq!(version_in("no version here\n1.2"), None);
3154 assert_eq!(version_in(""), None);
3155 }
3156}