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 fn human_secs(secs: u64) -> String {
854 match secs {
855 s if s < 60 => format!("{s}s"),
856 s if s < 3600 => format!("{}m{:02}s", s / 60, s % 60),
857 s => format!("{}h{:02}m", s / 3600, (s % 3600) / 60),
858 }
859}
860
861pub const LAST_LINE_CHARS: usize = 200;
863
864pub const BUSY_MILLI_CORES: u32 = 100;
868
869#[derive(Debug, Clone, Copy, PartialEq, Eq)]
871pub enum CpuState {
872 Off = 0,
875 Waiting = 1,
878 Measuring = 2,
880 Unavailable = 3,
882}
883
884pub struct Activity {
894 base: std::time::Instant,
895 last_out: std::sync::atomic::AtomicU64,
896 last_busy: std::sync::atomic::AtomicU64,
897 measured_since: std::sync::atomic::AtomicU64,
900 last_measured: std::sync::atomic::AtomicU64,
902 rate_milli: std::sync::atomic::AtomicU32,
903 interval_ms: std::sync::atomic::AtomicU32,
904 cpu: std::sync::atomic::AtomicU8,
905 wait_since: std::sync::atomic::AtomicU64,
908 wait_kind: std::sync::atomic::AtomicU8,
910 waited_ns: std::sync::atomic::AtomicU64,
913 last_wait_kind: std::sync::atomic::AtomicU8,
916 budget_secs: std::sync::atomic::AtomicU32,
920 load_avg_milli: std::sync::atomic::AtomicU32,
922 load_cores: std::sync::atomic::AtomicU32,
923 load_factor_milli: std::sync::atomic::AtomicU32,
924 last_line: std::sync::Mutex<String>,
927}
928
929impl Activity {
930 pub fn new() -> std::sync::Arc<Activity> {
931 std::sync::Arc::new(Activity {
932 base: std::time::Instant::now(),
933 last_out: Default::default(),
934 last_busy: Default::default(),
935 measured_since: Default::default(),
936 last_measured: Default::default(),
937 rate_milli: Default::default(),
938 interval_ms: Default::default(),
939 cpu: std::sync::atomic::AtomicU8::new(CpuState::Off as u8),
940 wait_since: Default::default(),
941 wait_kind: Default::default(),
942 waited_ns: Default::default(),
943 last_wait_kind: Default::default(),
944 budget_secs: Default::default(),
945 load_avg_milli: Default::default(),
946 load_cores: Default::default(),
947 load_factor_milli: Default::default(),
948 last_line: std::sync::Mutex::new(String::new()),
949 })
950 }
951
952 pub fn last_wait_kind(&self) -> Option<crate::hooks::wait::WaitKind> {
954 crate::hooks::wait::WaitKind::from_code(
955 self.last_wait_kind
956 .load(std::sync::atomic::Ordering::Relaxed),
957 )
958 }
959
960 pub fn stderr_line(&self, raw: &str) {
965 use std::sync::atomic::Ordering::Relaxed;
966 let line = crate::hooks::wait::strip_csi(raw);
967 if !line.trim().is_empty() {
968 let mut keep = self.last_line.lock().unwrap_or_else(|p| p.into_inner());
969 keep.clear();
970 keep.extend(line.trim().chars().take(LAST_LINE_CHARS));
971 }
972 match crate::hooks::wait::marker(&line) {
973 Some(kind) => {
974 self.wait_kind.store(kind.code(), Relaxed);
975 self.last_wait_kind.store(kind.code(), Relaxed);
976 let _ = self
979 .wait_since
980 .compare_exchange(0, self.now() + 1, Relaxed, Relaxed);
981 }
982 None => self.end_wait(),
983 }
984 }
985
986 pub fn end_wait(&self) {
989 use std::sync::atomic::Ordering::Relaxed;
990 let since = self.wait_since.swap(0, Relaxed);
991 if since != 0 {
992 let spent = self.now().saturating_sub(since - 1);
993 self.waited_ns.fetch_add(spent, Relaxed);
994 }
995 self.wait_kind.store(0, Relaxed);
996 }
997
998 pub fn waiting(&self) -> Option<(crate::hooks::wait::WaitKind, std::time::Duration)> {
1000 use std::sync::atomic::Ordering::Relaxed;
1001 let since = self.wait_since.load(Relaxed);
1002 if since == 0 {
1003 return None;
1004 }
1005 let kind = crate::hooks::wait::WaitKind::from_code(self.wait_kind.load(Relaxed))?;
1006 Some((kind, self.since(since - 1)))
1007 }
1008
1009 pub fn waited_total(&self) -> std::time::Duration {
1012 use std::sync::atomic::Ordering::Relaxed;
1013 let banked = std::time::Duration::from_nanos(self.waited_ns.load(Relaxed));
1014 banked + self.waiting().map_or(std::time::Duration::ZERO, |(_, d)| d)
1015 }
1016
1017 pub fn last_line(&self) -> Option<String> {
1019 let keep = self.last_line.lock().unwrap_or_else(|p| p.into_inner());
1020 (!keep.is_empty()).then(|| keep.clone())
1021 }
1022
1023 pub fn set_load(&self, budget_secs: u64, load: crate::load::Load, factor_milli: u32) {
1025 use std::sync::atomic::Ordering::Relaxed;
1026 self.budget_secs
1027 .store(u32::try_from(budget_secs).unwrap_or(u32::MAX), Relaxed);
1028 self.load_avg_milli.store(load.avg1_milli, Relaxed);
1029 self.load_cores.store(load.cores, Relaxed);
1030 self.load_factor_milli.store(factor_milli, Relaxed);
1031 }
1032
1033 pub fn load_scale(&self) -> Option<(u64, crate::load::Load, u32)> {
1036 use std::sync::atomic::Ordering::Relaxed;
1037 let factor = self.load_factor_milli.load(Relaxed);
1038 if factor <= 1000 {
1039 return None;
1040 }
1041 Some((
1042 u64::from(self.budget_secs.load(Relaxed)),
1043 crate::load::Load {
1044 avg1_milli: self.load_avg_milli.load(Relaxed),
1045 cores: self.load_cores.load(Relaxed),
1046 },
1047 factor,
1048 ))
1049 }
1050 fn offset(&self, at: std::time::Instant) -> u64 {
1051 u64::try_from(at.saturating_duration_since(self.base).as_nanos()).unwrap_or(u64::MAX)
1052 }
1053 fn now(&self) -> u64 {
1054 self.offset(std::time::Instant::now())
1055 }
1056 fn since(&self, offset: u64) -> std::time::Duration {
1057 std::time::Duration::from_nanos(self.now().saturating_sub(offset))
1058 }
1059 pub fn touch(&self) {
1061 self.last_out
1062 .fetch_max(self.now(), std::sync::atomic::Ordering::Relaxed);
1063 }
1064 pub fn quiet_for(&self) -> std::time::Duration {
1067 self.since(self.last_out.load(std::sync::atomic::Ordering::Relaxed))
1068 }
1069 pub fn silence_for(&self) -> std::time::Duration {
1074 if self.waiting().is_some() {
1075 std::time::Duration::ZERO
1076 } else {
1077 self.quiet_for()
1078 }
1079 }
1080 pub fn still_for(&self) -> std::time::Duration {
1084 let busy = self.last_busy.load(std::sync::atomic::Ordering::Relaxed);
1085 self.silence_for().min(self.since(busy))
1086 }
1087 pub fn cpu_state(&self) -> CpuState {
1088 match self.cpu.load(std::sync::atomic::Ordering::Relaxed) {
1089 1 => CpuState::Waiting,
1090 2 => CpuState::Measuring,
1091 3 => CpuState::Unavailable,
1092 _ => CpuState::Off,
1093 }
1094 }
1095 fn set_cpu_state(&self, s: CpuState) {
1096 self.cpu
1097 .store(s as u8, std::sync::atomic::Ordering::Relaxed);
1098 }
1099 pub fn fresh_rate(&self) -> Option<u32> {
1103 if self.cpu_state() != CpuState::Measuring {
1104 return None;
1105 }
1106 let end = self
1107 .last_measured
1108 .load(std::sync::atomic::Ordering::Relaxed);
1109 if end == 0 {
1110 return None;
1111 }
1112 let every = u64::from(self.interval_ms.load(std::sync::atomic::Ordering::Relaxed));
1113 let stale = std::time::Duration::from_millis(2 * every.max(1));
1114 (self.since(end - 1) <= stale)
1115 .then(|| self.rate_milli.load(std::sync::atomic::Ordering::Relaxed))
1116 }
1117 pub fn verdict(&self) -> CpuVerdict {
1122 match self.cpu_state() {
1123 CpuState::Off => return CpuVerdict::NotSampled,
1124 CpuState::Waiting | CpuState::Unavailable => return CpuVerdict::Unmeasured,
1125 CpuState::Measuring => {}
1126 }
1127 if let Some(rate) = self.fresh_rate().filter(|r| *r >= BUSY_MILLI_CORES) {
1128 return CpuVerdict::BusyAtKill(rate);
1129 }
1130 let since = self
1131 .measured_since
1132 .load(std::sync::atomic::Ordering::Relaxed);
1133 match (since, self.fresh_rate()) {
1134 (s, Some(_)) if s != 0 => CpuVerdict::MeasuredIdle(self.since(s - 1).as_secs()),
1135 _ => CpuVerdict::Unmeasured,
1136 }
1137 }
1138 pub fn record(
1141 &self,
1142 obs: crate::proctree::Observation,
1143 at: std::time::Instant,
1144 interval: std::time::Duration,
1145 ) {
1146 use std::sync::atomic::Ordering::Relaxed;
1147 self.interval_ms.store(
1148 u32::try_from(interval.as_millis()).unwrap_or(u32::MAX),
1149 Relaxed,
1150 );
1151 match obs {
1152 crate::proctree::Observation::Baseline => {
1153 self.measured_since.store(self.offset(at) + 1, Relaxed);
1154 self.set_cpu_state(CpuState::Waiting);
1155 }
1156 crate::proctree::Observation::Window(w) => {
1157 let milli = w.milli_cores();
1158 self.rate_milli.store(milli, Relaxed);
1159 self.last_measured.store(self.offset(w.end) + 1, Relaxed);
1160 if milli >= BUSY_MILLI_CORES {
1161 self.last_busy.fetch_max(self.offset(w.start), Relaxed);
1164 }
1165 if w.gapped {
1166 self.measured_since.store(self.offset(w.end) + 1, Relaxed);
1170 }
1171 self.set_cpu_state(CpuState::Measuring);
1172 }
1173 crate::proctree::Observation::Skipped => {}
1176 crate::proctree::Observation::Unmeasured => {
1177 self.measured_since.store(0, Relaxed);
1178 self.set_cpu_state(CpuState::Unavailable);
1179 }
1180 }
1181 }
1182 pub fn enable_cpu(&self) {
1184 self.set_cpu_state(CpuState::Waiting);
1185 }
1186 pub fn gate(&self) -> CpuGate {
1189 match self.verdict() {
1190 CpuVerdict::NotSampled => CpuGate::NotSampled,
1191 CpuVerdict::MeasuredIdle(_) | CpuVerdict::BusyAtKill(_) => CpuGate::Measured,
1192 CpuVerdict::Unmeasured => CpuGate::Unmeasured,
1193 }
1194 }
1195}
1196
1197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1205pub enum CpuGate {
1206 NotSampled,
1207 Measured,
1208 Unmeasured,
1209}
1210
1211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1213pub enum CpuVerdict {
1214 NotSampled,
1216 MeasuredIdle(u64),
1219 Unmeasured,
1221 BusyAtKill(u32),
1224}
1225
1226pub fn cores(milli: u32) -> String {
1228 format!("~{}.{} cores", milli / 1000, (milli % 1000) / 100)
1229}
1230
1231pub fn network_probe_budget(settings: &crate::config::Settings) -> u64 {
1239 match check_timeout(settings) {
1240 0 => 0,
1241 t => t.min(30),
1242 }
1243}
1244
1245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1247pub enum Why {
1248 Ceiling(u64),
1250 Silence(u64),
1252 Waited(crate::hooks::wait::WaitKind, u64),
1255}
1256
1257#[derive(Debug, Clone)]
1260pub struct Killed {
1261 pub why: Why,
1262 pub ran_secs: u64,
1264 pub quiet_secs: Option<u64>,
1267 pub cpu: CpuVerdict,
1269 pub idle_secs: u64,
1273 pub waiting: Option<(crate::hooks::wait::WaitKind, u64)>,
1275 pub last_line: Option<String>,
1279 pub load: Option<(crate::load::Load, u32)>,
1282}
1283
1284#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1287pub struct Clocks {
1288 pub ceiling: Option<u64>,
1290 pub silence: Option<u64>,
1293 pub lock_wait: LockWait,
1295 pub extended: Option<u64>,
1299 pub scale: u64,
1302}
1303
1304impl Clocks {
1305 pub fn ceiling_only(wall_secs: u64) -> Clocks {
1307 Clocks {
1308 ceiling: (wall_secs > 0).then_some(wall_secs),
1309 silence: None,
1310 lock_wait: LockWait::UntilCeiling,
1311 extended: None,
1312 scale: 1,
1313 }
1314 }
1315
1316 pub fn from_settings(settings: &crate::config::Settings, idle_secs: u64) -> Clocks {
1319 let wall = check_timeout(settings);
1320 let scale = idle_load_scale(settings);
1321 Clocks {
1322 ceiling: (wall > 0).then_some(wall),
1323 silence: (idle_secs > 0).then_some(idle_secs),
1324 lock_wait: lock_wait(settings),
1325 extended: (idle_secs > 0).then(|| idle_secs.saturating_mul(scale)),
1326 scale,
1327 }
1328 }
1329}
1330
1331const LOAD_EVERY: std::time::Duration = std::time::Duration::from_secs(5);
1333
1334pub fn idle_load_scale(settings: &crate::config::Settings) -> u64 {
1341 *settings.idle_load_scale.get_or_init(|| {
1342 crate::config::host_integer_or(settings, "greengate.idleLoadScale", 4, 1..=16) as u64
1343 })
1344}
1345
1346pub enum Ran {
1348 Status(std::process::ExitStatus),
1349 TimedOut(Killed),
1351}
1352
1353pub fn status_within(
1366 settings: &crate::config::Settings,
1367 cmd: &mut Command,
1368) -> std::io::Result<Ran> {
1369 if crate::host_slots::before_spawn(settings)? {
1372 cmd.env(crate::host_slots::HELD_ENV, "held");
1373 }
1374 crate::host_slots::bound(cmd);
1375 status_within_secs(cmd, check_timeout(settings))
1376}
1377
1378pub fn status_within_secs(cmd: &mut Command, budget_secs: u64) -> std::io::Result<Ran> {
1382 if budget_secs == 0 {
1383 return cmd.status().map(Ran::Status);
1384 }
1385 let mut child = cmd.spawn()?;
1386 wait_within(&mut child, Clocks::ceiling_only(budget_secs), None)
1387}
1388
1389fn run_observed(
1394 settings: &crate::config::Settings,
1395 cmd: &mut Command,
1396 on_output: impl Fn(&[u8]) + Send + Sync + 'static,
1397 ceiling_left: Option<u64>,
1398) -> std::io::Result<Ran> {
1399 let shared = std::sync::Arc::new(on_output);
1400 let for_stdout = std::sync::Arc::clone(&shared);
1401 run_observed_split(
1402 settings,
1403 cmd,
1404 move |bytes| for_stdout(bytes),
1405 move |bytes| shared(bytes),
1406 ceiling_left,
1407 )
1408}
1409
1410type OnBytes = std::sync::Arc<dyn Fn(&[u8]) + Send + Sync>;
1411
1412fn run_observed_split(
1414 settings: &crate::config::Settings,
1415 cmd: &mut Command,
1416 on_stdout: impl Fn(&[u8]) + Send + Sync + 'static,
1417 on_stderr: impl Fn(&[u8]) + Send + Sync + 'static,
1418 ceiling_left: Option<u64>,
1419) -> std::io::Result<Ran> {
1420 if crate::host_slots::before_spawn(settings)? {
1423 cmd.env(crate::host_slots::HELD_ENV, "held");
1424 }
1425 crate::host_slots::bound(cmd);
1426 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
1427 let activity = Activity::new();
1428 let on_stdout: OnBytes = std::sync::Arc::new(on_stdout);
1429 let on_stderr: OnBytes = std::sync::Arc::new(on_stderr);
1430 let mut child = cmd.spawn()?;
1431 activity.touch();
1435 let mut readers = Vec::new();
1436 let pipes = [
1441 (
1442 child
1443 .stdout
1444 .take()
1445 .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
1446 false,
1447 on_stdout,
1448 ),
1449 (
1450 child
1451 .stderr
1452 .take()
1453 .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
1454 true,
1455 on_stderr,
1456 ),
1457 ];
1458 for (pipe, is_stderr, on_output) in pipes {
1459 let Some(pipe) = pipe else { continue };
1460 let activity = std::sync::Arc::clone(&activity);
1461 readers.push(std::thread::spawn(move || {
1462 let mut pipe = pipe;
1463 let mut chunk = [0u8; 4096];
1464 let mut framer = crate::hooks::wait::LineFramer::default();
1465 let mut pending: Vec<u8> = Vec::new();
1471 loop {
1472 match std::io::Read::read(&mut pipe, &mut chunk) {
1473 Ok(0) | Err(_) => break,
1474 Ok(n) => {
1475 activity.touch();
1476 if is_stderr {
1477 for line in framer.feed(&chunk[..n]) {
1478 activity.stderr_line(&line);
1479 }
1480 } else {
1481 activity.end_wait();
1482 }
1483 pending.extend_from_slice(&chunk[..n]);
1484 if let Some(end) = whole_lines(&pending) {
1485 on_output(&pending[..end]);
1486 pending.drain(..end);
1487 }
1488 }
1489 }
1490 }
1491 if !pending.is_empty() {
1492 on_output(&pending);
1493 }
1494 }));
1495 }
1496 let _attached = crate::live::current_sink()
1498 .map(|(stage, idx)| stage.attach(idx, std::sync::Arc::clone(&activity)));
1499 let idle = idle_timeout(settings);
1500 let sampler = (idle > 0 && idle_cpu_credit(settings) && crate::proctree::SUPPORTED)
1501 .then(|| CpuSampler::start(child.id(), std::sync::Arc::clone(&activity), idle));
1502 let mut clocks = Clocks::from_settings(settings, idle);
1503 if let Some(left) = ceiling_left {
1504 clocks.ceiling = Some(left.max(1));
1507 }
1508 let ran = wait_within(&mut child, clocks, Some(&activity));
1509 if let Some(s) = sampler {
1510 s.stop();
1511 }
1512 for r in readers {
1513 let _ = r.join();
1515 }
1516 if let Ok(Ran::Status(_)) = &ran {
1520 let waited = activity.waited_total();
1521 if waited >= std::time::Duration::from_secs(1) {
1522 let what = activity
1523 .last_wait_kind()
1524 .map_or("a lock", crate::hooks::wait::WaitKind::describe);
1525 say(&format!(
1526 " (waited {} for {what})",
1527 human_secs(waited.as_secs())
1528 ));
1529 }
1530 }
1531 ran
1532}
1533
1534struct CpuSampler {
1540 stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
1541 handle: std::thread::JoinHandle<()>,
1542}
1543
1544impl CpuSampler {
1545 fn start(pid: u32, activity: std::sync::Arc<Activity>, idle_secs: u64) -> CpuSampler {
1546 activity.enable_cpu();
1547 let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1548 let flag = std::sync::Arc::clone(&stop);
1549 let handle = std::thread::Builder::new()
1550 .name("greengate-cpu".into())
1551 .spawn(move || sample_loop(pid, &activity, idle_secs, &flag))
1552 .expect("spawn the CPU sampler thread");
1553 CpuSampler { stop, handle }
1554 }
1555
1556 fn stop(self) {
1560 self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
1561 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1);
1562 while !self.handle.is_finished() && std::time::Instant::now() < deadline {
1563 std::thread::sleep(std::time::Duration::from_millis(10));
1564 }
1565 if self.handle.is_finished() {
1566 let _ = self.handle.join();
1567 }
1568 }
1569}
1570
1571pub fn sampling_schedule(idle_secs: u64) -> (std::time::Duration, std::time::Duration) {
1576 let ms = std::time::Duration::from_millis;
1577 let budget = std::time::Duration::from_secs(idle_secs);
1578 let first = (budget / 3)
1579 .min(std::time::Duration::from_secs(30))
1580 .max(ms(250));
1581 let every = (budget / 4).clamp(ms(250), std::time::Duration::from_secs(10));
1582 (first, every)
1583}
1584
1585fn sample_loop(
1586 pid: u32,
1587 activity: &Activity,
1588 idle_secs: u64,
1589 stop: &std::sync::atomic::AtomicBool,
1590) {
1591 use std::sync::atomic::Ordering::Relaxed;
1592 let (first, every) = sampling_schedule(idle_secs);
1593 let mut limits = crate::proctree::Limits::default();
1594 if let Some(n) = std::env::var("GREENGATE_CPU_MAX_PROCS")
1597 .ok()
1598 .and_then(|v| v.trim().parse::<usize>().ok())
1599 {
1600 limits.max_procs = n;
1601 }
1602 let trace = std::env::var_os("GREENGATE_CPU_TRACE");
1603 let mut tracker = crate::proctree::Tracker::default();
1604 let nap = |d: std::time::Duration| {
1605 let until = std::time::Instant::now() + d;
1606 while !stop.load(Relaxed) && std::time::Instant::now() < until {
1607 std::thread::sleep(std::time::Duration::from_millis(50));
1608 }
1609 };
1610 while !stop.load(Relaxed) {
1611 if activity.silence_for() < first {
1614 tracker = crate::proctree::Tracker::default();
1617 nap(std::time::Duration::from_millis(100));
1618 continue;
1619 }
1620 let snap = crate::proctree::snapshot(pid, &tracker.seen(), &limits);
1621 let at = std::time::Instant::now();
1622 let traced = trace.as_ref().map(|_| match &snap {
1623 crate::proctree::Snapshot::Complete(procs) => procs.clone(),
1624 _ => Vec::new(),
1625 });
1626 let obs = tracker.observe(at, snap);
1627 if let (Some(path), Some(procs)) = (&trace, traced) {
1628 trace_sample(path, pid, &procs, &obs);
1629 }
1630 activity.record(obs, at, every);
1631 nap(every);
1632 }
1633}
1634
1635fn trace_sample(
1641 path: &std::ffi::OsStr,
1642 root: u32,
1643 procs: &[crate::proctree::Proc],
1644 obs: &crate::proctree::Observation,
1645) {
1646 use std::io::Write;
1647 let Ok(mut f) = std::fs::OpenOptions::new()
1648 .create(true)
1649 .append(true)
1650 .open(path)
1651 else {
1652 return;
1653 };
1654 let mut text = String::new();
1655 for p in procs {
1656 text.push_str(&format!(
1657 "{} {} {} {}\n",
1658 p.id.pid, p.id.start, p.ppid, p.cpu_ns
1659 ));
1660 }
1661 let obs = match obs {
1662 crate::proctree::Observation::Window(w) => {
1663 format!("window {} milli-cores", w.milli_cores())
1664 }
1665 other => format!("{other:?}").to_lowercase(),
1666 };
1667 text.push_str(&format!("# root {root} {obs}\n"));
1668 let _ = f.write_all(text.as_bytes());
1669}
1670
1671pub fn status_streamed(
1683 settings: &crate::config::Settings,
1684 cmd: &mut Command,
1685 retry: Retry,
1686) -> std::io::Result<Ran> {
1687 let Some((stage, idx)) = crate::live::current_sink() else {
1688 return status_within(settings, cmd);
1689 };
1690 if crate::live::watching() {
1691 cmd.env("FORCE_COLOR", "1")
1694 .env("CLICOLOR_FORCE", "1")
1695 .env("CARGO_TERM_COLOR", "always");
1696 }
1697 let first = run_observed(
1698 settings,
1699 cmd,
1700 {
1701 let stage = std::sync::Arc::clone(&stage);
1702 move |bytes| stage.append_raw(idx, bytes)
1703 },
1704 None,
1705 );
1706 stage.runner_exit(idx, exit_of(&first));
1707 let Ok(Ran::TimedOut(k)) = &first else {
1708 return first;
1709 };
1710 let Some(left) = retry_budget(retry, k, check_timeout(settings)) else {
1711 return first;
1712 };
1713 let what = crate::host_slots::current_check()
1716 .unwrap_or_else(|| cmd.get_program().to_string_lossy().into_owned());
1717 say(&format!(
1718 "{} was killed while it looked like it was waiting ({}); retrying once{}.",
1719 hl(&what),
1720 k.last_line.as_deref().unwrap_or(""),
1721 match left {
1722 Some(s) => format!(" with {} left", human_secs(s)),
1723 None => String::new(),
1724 }
1725 ));
1726 let second = run_observed(
1727 settings,
1728 cmd,
1729 {
1730 let stage = std::sync::Arc::clone(&stage);
1731 move |bytes| stage.append_raw(idx, bytes)
1732 },
1733 left,
1734 );
1735 stage.runner_exit(idx, exit_of(&second));
1736 second
1737}
1738
1739fn whole_lines(pending: &[u8]) -> Option<usize> {
1743 match pending.iter().rposition(|&b| b == b'\n') {
1744 Some(i) => Some(i + 1),
1745 None if pending.len() >= LINE_HOLD => Some(pending.len()),
1746 None => None,
1747 }
1748}
1749
1750const LINE_HOLD: usize = 64 * 1024;
1751
1752fn exit_of(ran: &std::io::Result<Ran>) -> Option<i32> {
1755 match ran {
1756 Ok(Ran::Status(s)) => s.code(),
1757 _ => None,
1758 }
1759}
1760
1761#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1763pub enum Retry {
1764 Once,
1766 Never,
1768}
1769
1770pub fn retry_budget(retry: Retry, k: &Killed, ceiling: u64) -> Option<Option<u64>> {
1776 if retry == Retry::Never || !matches!(k.why, Why::Silence(_)) {
1777 return None;
1778 }
1779 if !k
1780 .last_line
1781 .as_deref()
1782 .is_some_and(crate::hooks::wait::looks_like_wait)
1783 {
1784 return None;
1785 }
1786 if ceiling == 0 {
1787 return Some(None);
1788 }
1789 let left = ceiling.saturating_sub(k.ran_secs);
1790 (left >= k.idle_secs.max(1)).then_some(Some(left))
1791}
1792
1793pub fn capture_within(
1799 settings: &crate::config::Settings,
1800 cmd: &mut Command,
1801) -> Option<(Ran, String)> {
1802 let text = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
1803 let sink = std::sync::Arc::clone(&text);
1804 let ran = run_observed(
1805 settings,
1806 cmd,
1807 move |bytes| {
1808 sink.lock()
1809 .unwrap_or_else(|p| p.into_inner())
1810 .push_str(&String::from_utf8_lossy(bytes));
1811 },
1812 None,
1813 )
1814 .ok()?;
1815 let text = std::sync::Arc::try_unwrap(text)
1816 .map(|m| m.into_inner().unwrap_or_else(|p| p.into_inner()))
1817 .unwrap_or_default();
1818 Some((ran, text))
1819}
1820
1821pub struct CapturedOutput {
1823 pub ran: Ran,
1824 pub stdout: String,
1825 pub stderr: String,
1826}
1827
1828pub fn capture_stdout_within(
1834 settings: &crate::config::Settings,
1835 cmd: &mut Command,
1836) -> std::io::Result<CapturedOutput> {
1837 let out = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
1838 let err = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
1839 let (out_sink, err_sink) = (std::sync::Arc::clone(&out), std::sync::Arc::clone(&err));
1840 let ran = run_observed_split(
1841 settings,
1842 cmd,
1843 move |bytes| {
1844 out_sink
1845 .lock()
1846 .unwrap_or_else(|p| p.into_inner())
1847 .extend_from_slice(bytes);
1848 },
1849 move |bytes| {
1850 err_sink
1851 .lock()
1852 .unwrap_or_else(|p| p.into_inner())
1853 .extend_from_slice(bytes);
1854 },
1855 None,
1856 )?;
1857 let take = |sink: std::sync::Arc<std::sync::Mutex<Vec<u8>>>| {
1858 let bytes = std::mem::take(&mut *sink.lock().unwrap_or_else(|p| p.into_inner()));
1859 String::from_utf8_lossy(&bytes).into_owned()
1860 };
1861 Ok(CapturedOutput {
1862 ran,
1863 stdout: take(out),
1864 stderr: take(err),
1865 })
1866}
1867
1868pub(crate) fn wait_within(
1873 child: &mut std::process::Child,
1874 clocks: Clocks,
1875 activity: Option<&Activity>,
1876) -> std::io::Result<Ran> {
1877 let started = std::time::Instant::now();
1878 let clocks = match activity {
1879 Some(_) => clocks,
1880 None => Clocks {
1881 silence: None,
1882 extended: None,
1883 ..clocks
1884 },
1885 };
1886 if clocks.ceiling.is_none() && clocks.silence.is_none() {
1887 return child.wait().map(Ran::Status);
1888 }
1889 let mut live = clocks;
1893 let mut load: Option<(crate::load::Load, u32)> = None;
1894 let mut next_load = started;
1895 loop {
1896 if let Some(status) = child.try_wait()? {
1897 return Ok(Ran::Status(status));
1898 }
1899 let now = std::time::Instant::now();
1900 if let (Some(idle), Some(a)) = (clocks.silence, activity) {
1901 if clocks.scale > 1 && now >= next_load {
1902 next_load = now + LOAD_EVERY;
1903 if let Some(l) = crate::load::read() {
1904 let factor = l.factor_milli(clocks.scale);
1905 let applied = crate::load::scaled_budget(idle, l, clocks.scale, clocks.ceiling);
1906 live.silence = Some(applied);
1907 a.set_load(applied, l, factor);
1908 load = (factor > 1000).then_some((l, factor));
1909 }
1910 }
1911 }
1912 let quiet = activity.map(|a| a.still_for());
1915 let waiting = activity.and_then(Activity::waiting);
1916 let gate = activity.map_or(CpuGate::NotSampled, Activity::gate);
1917 let why = judge(now.duration_since(started), quiet, waiting, gate, &live);
1918 if let Some(why) = why {
1919 let _ = child.kill();
1920 let _ = child.wait();
1921 return Ok(Ran::TimedOut(Killed {
1922 why,
1923 ran_secs: now.duration_since(started).as_secs(),
1924 quiet_secs: activity.map(|a| a.quiet_for().as_secs()),
1927 cpu: activity.map_or(CpuVerdict::NotSampled, Activity::verdict),
1928 idle_secs: clocks.silence.unwrap_or(0),
1929 waiting: waiting.map(|(k, d)| (k, d.as_secs())),
1930 last_line: activity.and_then(Activity::last_line),
1931 load,
1932 }));
1933 }
1934 std::thread::sleep(std::time::Duration::from_millis(25));
1935 }
1936}
1937
1938pub fn judge(
1953 ran: std::time::Duration,
1954 quiet: Option<std::time::Duration>,
1955 waiting: Option<(crate::hooks::wait::WaitKind, std::time::Duration)>,
1956 cpu: CpuGate,
1957 clocks: &Clocks,
1958) -> Option<Why> {
1959 if let Some(wall) = clocks.ceiling {
1960 if ran >= std::time::Duration::from_secs(wall) {
1961 return Some(Why::Ceiling(wall));
1962 }
1963 }
1964 if let Some((kind, waited)) = waiting {
1965 let budget = match clocks.lock_wait {
1966 LockWait::Secs(s) => Some(s),
1967 LockWait::UntilCeiling if clocks.ceiling.is_some() => None,
1968 LockWait::UntilCeiling => clocks.extended,
1969 };
1970 return match budget {
1971 Some(b) if waited >= std::time::Duration::from_secs(b) => Some(Why::Waited(kind, b)),
1972 _ => None,
1973 };
1974 }
1975 let budget = match cpu {
1976 CpuGate::NotSampled | CpuGate::Measured => clocks.silence,
1977 CpuGate::Unmeasured => clocks.extended.or(clocks.silence),
1978 };
1979 if let (Some(idle), Some(q)) = (budget, quiet) {
1980 if q >= std::time::Duration::from_secs(idle) {
1981 return Some(Why::Silence(idle));
1982 }
1983 }
1984 None
1985}
1986
1987pub fn say_timed_out(what: &str, k: Killed) {
1993 match k.why {
1994 Why::Silence(budget) => {
1995 let stretched = match (k.cpu, k.load) {
1999 _ if budget == k.idle_secs => String::new(),
2000 (CpuVerdict::Unmeasured, _) => format!(
2001 " (the extended budget, {} × {}: its CPU could not be measured)",
2002 human_secs(k.idle_secs),
2003 hl("greengate.idleLoadScale")
2004 ),
2005 (_, Some((load, factor))) => format!(
2006 " ({} stretched {} by a load average of {} on {} cores — {})",
2007 human_secs(k.idle_secs),
2008 crate::load::factor_text(factor),
2009 load.avg1_text(),
2010 load.cores,
2011 hl("greengate.idleLoadScale")
2012 ),
2013 _ => String::new(),
2014 };
2015 fail(&match k.cpu {
2016 CpuVerdict::MeasuredIdle(covered) => format!(
2017 "{} printed nothing for {}{stretched} and did no measurable CPU work \
2018 (< 0.1 core) in the last {} of it; killed after {} — a tool this idle \
2019 is stuck, not slow. {} raises the silence budget (0 disables)",
2020 hl(what),
2021 human_secs(budget),
2022 human_secs(covered.max(1)),
2023 human_secs(k.ran_secs),
2024 hl("git config greengate.idleTimeout <secs>")
2025 ),
2026 _ => format!(
2027 "{} printed nothing for {}{stretched}{} and was killed after {} — a tool \
2028 this quiet is usually stuck, not slow. {} raises the silence budget (0 \
2029 disables)",
2030 hl(what),
2031 human_secs(budget),
2032 if k.cpu == CpuVerdict::Unmeasured && stretched.is_empty() {
2033 " (CPU not measured)"
2034 } else {
2035 ""
2036 },
2037 human_secs(k.ran_secs),
2038 hl("git config greengate.idleTimeout <secs>")
2039 ),
2040 })
2041 }
2042 Why::Waited(kind, budget) => fail(&format!(
2043 "{} waited {} for {} and was killed after {} — {}. {} raises the wait budget \
2044 (0: until the ceiling)",
2045 hl(what),
2046 human_secs(budget),
2047 kind.describe(),
2048 human_secs(k.ran_secs),
2049 kind.holders(),
2050 hl("git config greengate.lockWait <secs>")
2051 )),
2052 Why::Ceiling(budget) => {
2053 let verdict = match (k.quiet_secs, k.cpu) {
2054 (_, _) if k.waiting.is_some() => {
2055 let (kind, w) = k.waiting.expect("checked");
2056 format!(
2057 " It was waiting for {} for the last {} — {}.",
2058 kind.describe(),
2059 human_secs(w),
2060 kind.holders()
2061 )
2062 }
2063 (Some(q), CpuVerdict::BusyAtKill(m)) if k.idle_secs > 0 && q >= k.idle_secs => {
2064 format!(
2065 " It printed nothing for the last {} but kept its CPU busy ({}), so the \
2066 silence budget did not stop it: a busy loop, or a tool that prints only \
2067 at the end (give it a per-file reporter). {} kills quiet runs at the \
2068 silence budget whatever their CPU.",
2069 human_secs(q),
2070 cores(m),
2071 hl("git config greengate.idleCpuCredit false")
2072 )
2073 }
2074 (Some(q), CpuVerdict::Unmeasured) if k.idle_secs > 0 && q >= k.idle_secs => {
2075 format!(
2076 " It printed nothing for the last {} and its CPU could not be measured, \
2077 so only the extended silence budget applied. {} kills quiet runs at \
2078 the silence budget whatever their CPU.",
2079 human_secs(q),
2080 hl("git config greengate.idleCpuCredit false")
2081 )
2082 }
2083 (Some(q), _) if q < 30 => format!(
2084 " It was still printing ({} since its last line): slow, not stuck.",
2085 human_secs(q)
2086 ),
2087 (Some(q), _) => format!(" Its last output was {} ago.", human_secs(q)),
2088 (None, _) => String::new(),
2089 };
2090 fail(&format!(
2091 "{} timed out: ran for {} and was killed at the ceiling. {} raises it \
2092 (0 disables).{verdict}",
2093 hl(what),
2094 human_secs(budget),
2095 hl("git config greengate.timeout <secs>")
2096 ))
2097 }
2098 }
2099}
2100
2101pub fn bounded_success(settings: &crate::config::Settings, cmd: &mut Command, what: &str) -> bool {
2104 match status_streamed(settings, cmd, Retry::Once) {
2105 Ok(Ran::Status(s)) => s.success(),
2106 Ok(Ran::TimedOut(b)) => {
2107 say_timed_out(what, b);
2108 false
2109 }
2110 Err(_) => false,
2111 }
2112}
2113
2114pub fn run(
2116 settings: &crate::config::Settings,
2117 root: &str,
2118 argv: &[String],
2119 extra: &[String],
2120) -> bool {
2121 let Some((program, rest)) = argv.split_first() else {
2122 return true;
2123 };
2124 let mut cmd = Command::new(program);
2125 cmd.args(rest)
2126 .args(extra)
2127 .current_dir(root)
2128 .stdin(Stdio::null());
2129 strip_git_env(&mut cmd);
2130 bounded_success(settings, &mut cmd, program)
2131}
2132
2133pub fn run_quiet(
2139 settings: &crate::config::Settings,
2140 root: &str,
2141 argv: &[String],
2142 extra: &[String],
2143) -> bool {
2144 let Some((program, rest)) = argv.split_first() else {
2145 return true;
2146 };
2147 let mut cmd = Command::new(program);
2148 cmd.args(rest)
2149 .args(extra)
2150 .current_dir(root)
2151 .stdin(Stdio::null());
2152 strip_git_env(&mut cmd);
2153 match run_observed(settings, &mut cmd, |_| {}, None) {
2158 Ok(Ran::Status(s)) => s.success(),
2159 Ok(Ran::TimedOut(b)) => {
2160 say_timed_out(program, b);
2161 false
2162 }
2163 Err(_) => false,
2164 }
2165}
2166
2167pub fn fixing_enabled(settings: &crate::config::Settings) -> bool {
2175 !not_the_index() && fixing_requested(settings)
2177}
2178
2179pub fn fixing_requested(settings: &crate::config::Settings) -> bool {
2185 *settings
2186 .fixing
2187 .get_or_init(|| crate::config::boolean_or(settings, "greengate.fix", false))
2188}
2189
2190#[derive(Debug, Clone, PartialEq, Eq)]
2201pub enum Restaged {
2202 Nothing,
2204 Staged,
2206 Failed(Vec<String>),
2211}
2212
2213static INDEX_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
2222
2223pub fn restage(paths: &[String]) -> Restaged {
2230 if not_the_index() {
2233 return Restaged::Nothing;
2234 }
2235 let changed: Vec<String> = paths
2236 .iter()
2237 .filter(|p| !git::succeeds(&["diff", "--quiet", "--", p]))
2238 .cloned()
2239 .collect();
2240 if changed.is_empty() {
2241 return Restaged::Nothing;
2242 }
2243 let mut args = vec!["add", "--"];
2244 args.extend(changed.iter().map(String::as_str));
2245
2246 let _serialised = INDEX_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2247 const BACKOFF_MS: [u64; 3] = [50, 150, 400];
2253 if git::succeeds(&args) {
2254 return Restaged::Staged;
2255 }
2256 for wait in BACKOFF_MS {
2257 std::thread::sleep(std::time::Duration::from_millis(wait));
2258 if git::succeeds(&args) {
2259 return Restaged::Staged;
2260 }
2261 }
2262 Restaged::Failed(changed)
2263}
2264
2265pub fn ok(settings: &crate::config::Settings, msg: &str) {
2268 if crate::live::quiet(settings) {
2269 return;
2270 }
2271 crate::live::say(&format!("{} {msg}", valid_sign()));
2272}
2273pub fn fail(msg: &str) {
2274 if crate::host_slots::deferred_here() {
2278 return;
2279 }
2280 crate::live::say(&format!("{} {msg}", error_sign()));
2281}
2282pub fn warn(msg: &str) {
2283 if crate::host_slots::deferred_here() {
2287 return;
2288 }
2289 crate::live::say(&format!("{} {msg}", warning_sign()));
2290}
2291pub fn say(msg: &str) {
2294 crate::live::say(msg);
2295}
2296
2297pub fn hl(s: &str) -> String {
2299 crate::ui::highlight(s)
2300}
2301
2302#[cfg(test)]
2303mod tests {
2304
2305 #[cfg(unix)]
2309 #[test]
2310 fn capture_stdout_within_keeps_the_streams_apart() {
2311 let settings = crate::config::Settings::default();
2312 let mut cmd = std::process::Command::new(super::program("sh"));
2313 cmd.args([
2314 "-c",
2315 "printf '{\"a\":1}'; printf 'npm warn x\\n' >&2; exit 3",
2316 ]);
2317 let captured = super::capture_stdout_within(&settings, &mut cmd).expect("sh runs");
2318 assert_eq!(captured.stdout, "{\"a\":1}", "stdout alone");
2319 assert_eq!(captured.stderr, "npm warn x\n", "stderr alone");
2320 match captured.ran {
2321 super::Ran::Status(s) => assert_eq!(s.code(), Some(3), "the real exit status"),
2322 super::Ran::TimedOut(_) => panic!("a one-line child timed out"),
2323 }
2324 }
2325
2326 #[cfg(unix)]
2329 #[test]
2330 fn stderr_only_output_leaves_stdout_empty() {
2331 let settings = crate::config::Settings::default();
2332 let mut cmd = std::process::Command::new(super::program("sh"));
2333 cmd.args(["-c", "printf 'only a warning\\n' >&2"]);
2334 let captured = super::capture_stdout_within(&settings, &mut cmd).expect("sh runs");
2335 assert!(
2336 captured.stdout.is_empty(),
2337 "stdout must be empty, got {:?}",
2338 captured.stdout
2339 );
2340 assert_eq!(captured.stderr, "only a warning\n");
2341 assert!(matches!(captured.ran, super::Ran::Status(s) if s.success()));
2342 }
2343
2344 #[test]
2346 fn only_the_one_newline_git_prints_is_stripped() {
2347 assert_eq!(super::strip_one_newline(b"/r/.git\n".to_vec()), b"/r/.git");
2348 assert_eq!(super::strip_one_newline(b"/r/x\r\n".to_vec()), b"/r/x\r");
2349 assert_eq!(super::strip_one_newline(b"/r/x".to_vec()), b"/r/x");
2350 }
2351
2352 #[test]
2355 fn a_git_path_becomes_the_same_path() {
2356 assert_eq!(
2357 super::path_from_bytes(b"/r/.git/index".to_vec()),
2358 std::path::PathBuf::from("/r/.git/index")
2359 );
2360 }
2361
2362 #[test]
2363 fn a_lookup_error_says_git_s_reason() {
2364 let e = super::IndexLookupError::Git {
2365 args: "rev-parse --git-path index".into(),
2366 why: "fatal: not a git repository".into(),
2367 };
2368 assert_eq!(
2369 e.to_string(),
2370 "git rev-parse --git-path index failed: fatal: not a git repository"
2371 );
2372 }
2373
2374 fn window(
2378 start: std::time::Instant,
2379 end: std::time::Instant,
2380 milli: u64,
2381 ) -> crate::proctree::Observation {
2382 let wall = u64::try_from(end.duration_since(start).as_nanos())
2383 .unwrap_or(u64::MAX)
2384 .max(1);
2385 let gain = wall * milli / 1000;
2386 crate::proctree::Observation::Window(crate::proctree::Window {
2387 start,
2388 end,
2389 gain_ns: gain,
2390 gapped: false,
2391 })
2392 }
2393
2394 #[test]
2398 fn a_gapped_window_is_never_claimed_as_measured_idle() {
2399 use super::{Activity, CpuVerdict};
2400 use crate::proctree::{Observation, Window};
2401 let s = std::time::Duration::from_secs;
2402 let every = s(10);
2403 let a = Activity::new();
2404 a.enable_cpu();
2405 let t0 = std::time::Instant::now() - s(30);
2406 a.record(Observation::Baseline, t0, every);
2407 a.record(Observation::Skipped, t0 + s(10), every);
2408 let gap_end = std::time::Instant::now();
2409 a.record(
2410 Observation::Window(Window {
2411 start: t0,
2412 end: gap_end,
2413 gain_ns: 0,
2414 gapped: true,
2415 }),
2416 gap_end,
2417 every,
2418 );
2419 assert_eq!(a.verdict(), CpuVerdict::MeasuredIdle(0));
2421 assert_eq!(a.gate(), super::CpuGate::Measured);
2422
2423 let busy = Activity::new();
2424 busy.enable_cpu();
2425 busy.record(Observation::Baseline, t0, every);
2426 busy.record(Observation::Skipped, t0 + s(10), every);
2427 let now = std::time::Instant::now();
2428 busy.record(window_gapped(t0, now, 3000), now, every);
2429 assert_eq!(busy.verdict(), CpuVerdict::BusyAtKill(3000));
2430 assert!(busy.still_for() < s(1));
2431 }
2432
2433 fn window_gapped(
2434 start: std::time::Instant,
2435 end: std::time::Instant,
2436 milli: u64,
2437 ) -> crate::proctree::Observation {
2438 match window(start, end, milli) {
2439 crate::proctree::Observation::Window(w) => {
2440 crate::proctree::Observation::Window(crate::proctree::Window { gapped: true, ..w })
2441 }
2442 o => o,
2443 }
2444 }
2445
2446 #[test]
2449 fn the_sampling_schedule_follows_the_budget_within_floors() {
2450 use super::sampling_schedule;
2451 let ms = std::time::Duration::from_millis;
2452 let third = |secs: u64| std::time::Duration::from_secs(secs) / 3;
2453 assert_eq!(sampling_schedule(1), (third(1), ms(250)));
2454 assert_eq!(sampling_schedule(2), (third(2), ms(500)));
2455 assert_eq!(sampling_schedule(120), (ms(30_000), ms(10_000)));
2456 assert_eq!(sampling_schedule(0), (ms(250), ms(250)));
2457 }
2458
2459 #[test]
2462 fn busy_work_resets_the_still_time_but_not_the_output_silence() {
2463 use super::Activity;
2464 let a = Activity::new();
2465 a.touch();
2466 std::thread::sleep(std::time::Duration::from_millis(60));
2467 let quiet = a.quiet_for();
2468 assert!(a.still_for() >= quiet.saturating_sub(std::time::Duration::from_millis(5)));
2469 a.enable_cpu();
2470 let now = std::time::Instant::now();
2471 a.record(
2472 window(now - std::time::Duration::from_millis(10), now, 2000),
2473 now,
2474 std::time::Duration::from_secs(1),
2475 );
2476 assert!(a.still_for() < std::time::Duration::from_millis(40));
2477 assert!(a.quiet_for() >= std::time::Duration::from_millis(60));
2478 }
2479
2480 #[test]
2484 fn the_cpu_verdict_claims_only_what_was_measured() {
2485 use super::{Activity, CpuVerdict};
2486 use crate::proctree::Observation;
2487 let s = std::time::Duration::from_secs;
2488 let every = s(10);
2489
2490 let off = Activity::new();
2491 assert_eq!(off.verdict(), CpuVerdict::NotSampled);
2492
2493 let waiting = Activity::new();
2494 waiting.enable_cpu();
2495 assert_eq!(waiting.verdict(), CpuVerdict::Unmeasured);
2496
2497 let now = std::time::Instant::now();
2498 let before = now - s(1);
2499 let idle = Activity::new();
2501 idle.enable_cpu();
2502 let t0 = std::time::Instant::now();
2503 idle.record(Observation::Baseline, t0, every);
2504 std::thread::sleep(std::time::Duration::from_millis(1050));
2505 let t1 = std::time::Instant::now();
2506 idle.record(window(t0, t1, 20), t1, every);
2507 assert_eq!(idle.verdict(), CpuVerdict::MeasuredIdle(1));
2508
2509 let busy = Activity::new();
2510 busy.enable_cpu();
2511 busy.record(Observation::Baseline, before, every);
2512 busy.record(window(before, now, 3900), now, every);
2513 assert_eq!(busy.verdict(), CpuVerdict::BusyAtKill(3900));
2514
2515 let broken = Activity::new();
2516 broken.enable_cpu();
2517 broken.record(Observation::Baseline, before, every);
2518 broken.record(window(before, now, 20), now, every);
2519 broken.record(Observation::Unmeasured, now, every);
2520 assert_eq!(broken.verdict(), CpuVerdict::Unmeasured);
2521 assert_eq!(broken.gate(), super::CpuGate::Unmeasured);
2522 assert_eq!(off.gate(), super::CpuGate::NotSampled);
2523 assert_eq!(idle.gate(), super::CpuGate::Measured);
2524 assert_eq!(busy.gate(), super::CpuGate::Measured);
2525 }
2526
2527 #[test]
2530 fn a_stale_rate_expires() {
2531 use super::{Activity, CpuVerdict};
2532 use crate::proctree::Observation;
2533 let a = Activity::new();
2534 a.enable_cpu();
2535 let then = std::time::Instant::now();
2536 let tick = std::time::Duration::from_millis(5);
2537 let earlier = then - std::time::Duration::from_secs(1);
2538 a.record(Observation::Baseline, earlier, tick);
2539 a.record(window(earlier, then, 3000), then, tick);
2540 std::thread::sleep(std::time::Duration::from_millis(40));
2541 assert_eq!(a.fresh_rate(), None);
2542 assert_eq!(a.verdict(), CpuVerdict::Unmeasured);
2543 }
2544
2545 #[test]
2546 fn cores_read_as_one_decimal() {
2547 assert_eq!(super::cores(3900), "~3.9 cores");
2548 assert_eq!(super::cores(420), "~0.4 cores");
2549 assert_eq!(super::cores(100), "~0.1 cores");
2550 }
2551
2552 #[test]
2556 fn the_clocks_judge_silence_and_ceiling_separately() {
2557 use super::{judge, CpuGate, Why};
2558 use std::time::Duration as D;
2559 let s = D::from_secs;
2560 let c = |ceiling: Option<u64>, silence: Option<u64>| super::Clocks {
2561 ceiling,
2562 silence,
2563 lock_wait: super::LockWait::Secs(600),
2564 extended: silence,
2565 scale: 1,
2566 };
2567 assert_eq!(
2569 judge(
2570 s(900),
2571 Some(s(0)),
2572 None,
2573 CpuGate::NotSampled,
2574 &c(Some(3600), Some(5))
2575 ),
2576 None
2577 );
2578 assert_eq!(
2579 judge(
2580 s(900),
2581 Some(s(4)),
2582 None,
2583 CpuGate::NotSampled,
2584 &c(Some(3600), Some(5))
2585 ),
2586 None
2587 );
2588 assert_eq!(
2590 judge(
2591 s(30),
2592 Some(s(5)),
2593 None,
2594 CpuGate::NotSampled,
2595 &c(Some(3600), Some(5))
2596 ),
2597 Some(Why::Silence(5))
2598 );
2599 assert_eq!(
2601 judge(
2602 s(900),
2603 None,
2604 None,
2605 CpuGate::NotSampled,
2606 &c(Some(3600), Some(5))
2607 ),
2608 None
2609 );
2610 assert_eq!(
2612 judge(
2613 s(3600),
2614 Some(s(0)),
2615 None,
2616 CpuGate::NotSampled,
2617 &c(Some(3600), Some(120))
2618 ),
2619 Some(Why::Ceiling(3600))
2620 );
2621 assert_eq!(
2623 judge(
2624 s(3600),
2625 Some(s(600)),
2626 None,
2627 CpuGate::NotSampled,
2628 &c(Some(3600), Some(120))
2629 ),
2630 Some(Why::Ceiling(3600))
2631 );
2632 assert_eq!(
2634 judge(
2635 s(86_400),
2636 Some(s(86_400)),
2637 None,
2638 CpuGate::NotSampled,
2639 &c(None, None)
2640 ),
2641 None
2642 );
2643 assert_eq!(
2645 judge(
2646 s(86_400),
2647 Some(s(1)),
2648 None,
2649 CpuGate::NotSampled,
2650 &c(None, Some(120))
2651 ),
2652 None
2653 );
2654 }
2655
2656 #[test]
2660 fn a_declared_wait_answers_to_its_own_budget() {
2661 use super::{judge, Clocks, CpuGate, LockWait, Why};
2662 use crate::hooks::wait::{CargoLockWhat, WaitKind};
2663 use std::time::Duration as D;
2664 let s = D::from_secs;
2665 let kind = WaitKind::CargoLock(CargoLockWhat::BuildDirectory);
2666 let clocks = Clocks {
2667 ceiling: Some(3600),
2668 silence: Some(120),
2669 lock_wait: LockWait::Secs(600),
2670 extended: Some(480),
2671 scale: 4,
2672 };
2673 assert_eq!(
2675 judge(
2676 s(1300),
2677 Some(s(0)),
2678 Some((kind, s(599))),
2679 CpuGate::Measured,
2680 &clocks
2681 ),
2682 None
2683 );
2684 assert_eq!(
2686 judge(
2687 s(1300),
2688 Some(s(0)),
2689 Some((kind, s(600))),
2690 CpuGate::Measured,
2691 &clocks
2692 ),
2693 Some(Why::Waited(kind, 600))
2694 );
2695 assert_eq!(
2697 judge(
2698 s(3600),
2699 Some(s(0)),
2700 Some((kind, s(3000))),
2701 CpuGate::Measured,
2702 &clocks
2703 ),
2704 Some(Why::Ceiling(3600))
2705 );
2706 let until = Clocks {
2708 lock_wait: LockWait::UntilCeiling,
2709 ..clocks
2710 };
2711 assert_eq!(
2712 judge(
2713 s(3000),
2714 Some(s(0)),
2715 Some((kind, s(2900))),
2716 CpuGate::Measured,
2717 &until
2718 ),
2719 None
2720 );
2721 let open = Clocks {
2723 ceiling: None,
2724 ..until
2725 };
2726 assert_eq!(
2727 judge(
2728 s(3000),
2729 Some(s(0)),
2730 Some((kind, s(479))),
2731 CpuGate::Measured,
2732 &open
2733 ),
2734 None
2735 );
2736 assert_eq!(
2737 judge(
2738 s(3000),
2739 Some(s(0)),
2740 Some((kind, s(480))),
2741 CpuGate::Measured,
2742 &open
2743 ),
2744 Some(Why::Waited(kind, 480))
2745 );
2746 }
2747
2748 #[test]
2752 fn a_wait_like_silence_kill_earns_one_retry_under_the_remaining_ceiling() {
2753 use super::{retry_budget, CpuVerdict, Killed, Retry, Why};
2754 use crate::hooks::wait::{CargoLockWhat, WaitKind};
2755 let k = |why: Why, line: &str, ran: u64| Killed {
2756 why,
2757 ran_secs: ran,
2758 quiet_secs: Some(ran),
2759 cpu: CpuVerdict::MeasuredIdle(1),
2760 idle_secs: 120,
2761 waiting: None,
2762 last_line: Some(line.to_string()),
2763 load: None,
2764 };
2765 let wait = "waiting for lock on x";
2766 assert_eq!(
2767 retry_budget(Retry::Once, &k(Why::Silence(120), wait, 120), 3600),
2768 Some(Some(3480))
2769 );
2770 assert_eq!(
2771 retry_budget(Retry::Once, &k(Why::Silence(120), wait, 120), 0),
2772 Some(None)
2773 );
2774 assert_eq!(
2775 retry_budget(Retry::Never, &k(Why::Silence(120), wait, 120), 3600),
2776 None
2777 );
2778 assert_eq!(
2779 retry_budget(
2780 Retry::Once,
2781 &k(Why::Silence(120), "test_lock.py::x", 120),
2782 3600
2783 ),
2784 None
2785 );
2786 assert_eq!(
2787 retry_budget(Retry::Once, &k(Why::Ceiling(3600), wait, 3600), 3600),
2788 None
2789 );
2790 let waited = Why::Waited(WaitKind::CargoLock(CargoLockWhat::BuildDirectory), 600);
2791 assert_eq!(retry_budget(Retry::Once, &k(waited, wait, 700), 3600), None);
2792 assert_eq!(
2794 retry_budget(Retry::Once, &k(Why::Silence(120), wait, 3500), 3600),
2795 None
2796 );
2797 }
2798
2799 #[test]
2803 fn an_unmeasured_cpu_answers_to_the_extended_budget() {
2804 use super::{judge, Clocks, CpuGate, LockWait, Why};
2805 use std::time::Duration as D;
2806 let s = D::from_secs;
2807 let clocks = Clocks {
2808 ceiling: None,
2809 silence: Some(120),
2810 lock_wait: LockWait::Secs(600),
2811 extended: Some(480),
2812 scale: 4,
2813 };
2814 assert_eq!(
2815 judge(s(500), Some(s(300)), None, CpuGate::Unmeasured, &clocks),
2816 None
2817 );
2818 assert_eq!(
2819 judge(s(500), Some(s(479)), None, CpuGate::Unmeasured, &clocks),
2820 None
2821 );
2822 assert_eq!(
2823 judge(s(500), Some(s(480)), None, CpuGate::Unmeasured, &clocks),
2824 Some(Why::Silence(480))
2825 );
2826 assert_eq!(
2827 judge(s(500), Some(s(120)), None, CpuGate::Measured, &clocks),
2828 Some(Why::Silence(120))
2829 );
2830 assert_eq!(
2831 judge(s(500), Some(s(120)), None, CpuGate::NotSampled, &clocks),
2832 Some(Why::Silence(120))
2833 );
2834 let off = Clocks {
2836 silence: None,
2837 extended: None,
2838 ..clocks
2839 };
2840 assert_eq!(
2841 judge(s(86_400), Some(s(86_400)), None, CpuGate::Unmeasured, &off),
2842 None
2843 );
2844 }
2845
2846 #[test]
2850 fn a_marker_line_pauses_the_silence_clock_until_another_line() {
2851 use super::Activity;
2852 use crate::hooks::wait::{CargoLockWhat, WaitKind};
2853 let a = Activity::new();
2854 a.touch();
2855 assert_eq!(a.waiting(), None);
2856 a.stderr_line(" Blocking waiting for file lock on package cache");
2857 std::thread::sleep(std::time::Duration::from_millis(30));
2858 let (kind, waited) = a.waiting().expect("a wait is in progress");
2859 assert_eq!(kind, WaitKind::CargoLock(CargoLockWhat::PackageCache));
2860 assert!(waited >= std::time::Duration::from_millis(30));
2861 assert_eq!(a.silence_for(), std::time::Duration::ZERO);
2862 assert_eq!(a.still_for(), std::time::Duration::ZERO);
2863 assert!(a.quiet_for() >= std::time::Duration::from_millis(30));
2864 a.stderr_line("\u{1b}[1m Blocking\u{1b}[0m waiting for file lock on build directory");
2866 let (kind, again) = a.waiting().expect("still waiting");
2867 assert_eq!(kind, WaitKind::CargoLock(CargoLockWhat::BuildDirectory));
2868 assert!(again >= waited);
2869 a.touch();
2872 a.stderr_line(" Checking foo v0.1.0");
2873 assert_eq!(a.waiting(), None);
2874 assert!(a.waited_total() >= std::time::Duration::from_millis(30));
2875 assert_eq!(a.last_wait_kind(), Some(kind));
2876 assert_eq!(a.last_line().as_deref(), Some("Checking foo v0.1.0"));
2877 assert!(a.silence_for() < std::time::Duration::from_millis(20));
2878 a.stderr_line("Waiting to acquire write lock for `x`");
2880 assert!(a.waiting().is_some());
2881 a.end_wait();
2882 assert_eq!(a.waiting(), None);
2883 }
2884
2885 #[cfg(unix)]
2887 #[test]
2888 fn the_deadline_kills_a_sleeper_and_spares_a_finisher() {
2889 let started = std::time::Instant::now();
2890 let mut slow = Command::new(program("sleep"));
2891 slow.arg("300").stdin(Stdio::null());
2892 match status_within_secs(&mut slow, 1) {
2893 Ok(Ran::TimedOut(Killed {
2894 why: Why::Ceiling(1),
2895 quiet_secs: None,
2896 ..
2897 })) => {}
2898 other => panic!("expected TimedOut(1), got {:?}", other.map(|_| "ran")),
2899 }
2900 assert!(
2901 started.elapsed() < std::time::Duration::from_secs(60),
2902 "the kill did not happen at the deadline"
2903 );
2904
2905 let mut quick = Command::new(program("true"));
2906 quick.stdin(Stdio::null());
2907 match status_within_secs(&mut quick, 60) {
2908 Ok(Ran::Status(s)) => assert!(s.success()),
2909 other => panic!("expected a clean exit, got {:?}", other.map(|_| "?")),
2910 }
2911 }
2912
2913 use super::*;
2914
2915 #[test]
2916 fn which_finds_a_real_binary_and_not_a_fake_one() {
2917 assert!(which("git").is_some());
2918 assert!(which("definitely-not-a-real-binary-xyz").is_none());
2919 }
2920
2921 #[test]
2925 #[cfg(windows)]
2926 fn windows_prefers_an_executable_extension_over_a_bare_file() {
2927 let dir = std::env::temp_dir().join("greengate-which-order");
2928 let _ = std::fs::create_dir_all(&dir);
2929 std::fs::write(dir.join("faketool"), "#!/bin/sh\n").unwrap();
2930 std::fs::write(dir.join("faketool.cmd"), "@echo off\n").unwrap();
2931 let found = which_on(dir.as_os_str(), "faketool").unwrap();
2935 assert!(found.ends_with(".cmd"), "got {found}");
2936 let _ = std::fs::remove_dir_all(&dir);
2937 }
2938
2939 #[test]
2952 fn restage_distinguishes_nothing_from_failure() {
2953 let _cwd = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
2959 let outside = std::env::temp_dir()
2960 .join("greengate-restage-outside-any-repo")
2961 .to_string_lossy()
2962 .into_owned();
2963 assert_eq!(
2964 restage(std::slice::from_ref(&outside)),
2965 Restaged::Failed(vec![outside]),
2966 "a `git add` git refuses must report Failed, never Nothing"
2967 );
2968 assert_eq!(
2969 restage(&[]),
2970 Restaged::Nothing,
2971 "no paths is nothing to do, and nothing wrong"
2972 );
2973 }
2974
2975 #[test]
2991 fn no_hook_spawns_a_bare_program_name() {
2992 let needle = concat!("Command", "::new(");
2993 let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/src/hooks");
2994 let mut scanned = 0usize;
2995 for entry in std::fs::read_dir(dir).expect("hooks dir").flatten() {
2996 let path = entry.path();
2997 if path.extension().and_then(|e| e.to_str()) != Some("rs") {
2998 continue;
2999 }
3000 scanned += 1;
3001 let src = std::fs::read_to_string(&path).expect("read a hook module");
3002 for (n, line) in src.lines().enumerate() {
3003 if line.trim_start().starts_with("//") {
3004 continue;
3005 }
3006 let Some(after) = line.split_once(needle) else {
3007 continue;
3008 };
3009 assert!(
3010 !after.1.starts_with('"'),
3011 "{}:{} spawns a bare name — route it through `program()` or \
3012 the path `which()` already resolved: {}",
3013 path.display(),
3014 n + 1,
3015 line.trim()
3016 );
3017 }
3018 }
3019 assert!(
3020 scanned > 10,
3021 "the scan found almost nothing: {scanned} files"
3022 );
3023 }
3024
3025 #[test]
3026 fn first_existing_picks_the_earliest_present_name() {
3027 let dir = std::env::temp_dir().join("greengate-first-existing-test");
3028 let _ = std::fs::create_dir_all(&dir);
3029 let root = dir.to_string_lossy().into_owned();
3030 let _ = std::fs::write(dir.join("second"), "x");
3031 assert_eq!(
3032 first_existing(&root, &["first", "second", "third"]).as_deref(),
3033 Some("second")
3034 );
3035 assert_eq!(first_existing(&root, &["nope"]), None);
3036 let _ = std::fs::remove_dir_all(&dir);
3037 }
3038}
3039
3040#[cfg(test)]
3041mod js_tool_tests {
3042 use super::{package_json_declares, version_in};
3043
3044 #[test]
3045 fn package_json_declares_a_dev_dependency() {
3046 assert!(package_json_declares(
3047 r#"{"devDependencies":{"prettier":"3.9.10"}}"#,
3048 "prettier"
3049 ));
3050 assert!(package_json_declares(
3051 "{\n \"name\": \"x\",\n \"dependencies\": { \"eslint\": \"9.1.0\" }\n}\n",
3052 "eslint"
3053 ));
3054 assert!(package_json_declares(
3056 "\u{feff}{\"devDependencies\":{\"prettier\":\"3.9.10\"}}",
3057 "prettier"
3058 ));
3059 }
3060
3061 #[test]
3063 fn package_json_declares_gives_up_on_deep_nesting() {
3064 let deep = format!(
3065 "{{\"x\":{}{},\"devDependencies\":{{\"prettier\":\"3\"}}}}",
3066 "[".repeat(100_000),
3067 "]".repeat(100_000)
3068 );
3069 assert!(!package_json_declares(&deep, "prettier"));
3070 let fine = format!(
3071 "{{\"x\":{}{},\"devDependencies\":{{\"prettier\":\"3\"}}}}",
3072 "[".repeat(50),
3073 "]".repeat(50)
3074 );
3075 assert!(package_json_declares(&fine, "prettier"));
3076 }
3077
3078 #[test]
3079 fn package_json_declares_nothing_else() {
3080 let not = |text: &str| assert!(!package_json_declares(text, "prettier"), "{text}");
3081 not(r#"{"prettier":{"semi":false}}"#);
3083 not(r#"{"devDependencies":{"prettier-plugin-x":"1.0.0"}}"#);
3085 not(r#"{"peerDependencies":{"prettier":"3"}}"#);
3087 not(r#"{"optionalDependencies":{"prettier":"3"}}"#);
3088 not(r#"{"pnpm":{"overrides":{"prettier":"3"}}}"#);
3089 not(r#"{"scripts":{"prettier":"prettier --check ."}}"#);
3090 not(r#"{"metadata":{"devDependencies":{"prettier":"3"}}}"#);
3092 not(r#"{"list":[{"dependencies":{"prettier":"3"}}]}"#);
3093 not(r#"{"description":"say \"devDependencies\": {\"prettier\": 1}"}"#);
3095 not(r#"{"devDependencies":{"prettier":"3.9.10""#);
3097 not(r#"{"devDependencies":{"prettier":"3.9.10"}} trailing"#);
3098 not("");
3099 }
3100
3101 #[test]
3102 fn package_json_declares_past_escapes_and_nesting() {
3103 assert!(package_json_declares(
3104 r#"{"description":"a \"quoted\" {brace}","x":[1,{"y":null}],"devDependencies":{"a":"1","prettier":"^3"}}"#,
3105 "prettier"
3106 ));
3107 }
3108
3109 #[test]
3110 fn version_in_skips_warnings_and_strips_v() {
3111 assert_eq!(version_in("3.9.10\n").as_deref(), Some("3.9.10"));
3112 assert_eq!(version_in("v9.14.0").as_deref(), Some("9.14.0"));
3113 assert_eq!(
3114 version_in("npm warn exec The following package was not found\n3.9.10").as_deref(),
3115 Some("3.9.10")
3116 );
3117 assert_eq!(
3118 version_in("(node:1) Warning: x\n3.0.0-beta.1").as_deref(),
3119 Some("3.0.0-beta.1")
3120 );
3121 assert_eq!(version_in("3.9.10\u{1b}[2J").as_deref(), Some("3.9.10"));
3122 assert_eq!(version_in("no version here\n1.2"), None);
3123 assert_eq!(version_in(""), None);
3124 }
3125}