1use crate::names::BIN;
17use std::cell::RefCell;
18use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
19use std::sync::Mutex;
20use std::time::{Duration, Instant};
21
22pub use greenharness_slots::{DIR_ENV, HELD_ENV};
23
24pub const HEAVY: &[&str] = &[
27 "pre-commit-clippy",
28 "pre-commit-go-vet",
29 "pre-commit-pyright",
30 "pre-push-run-tests-js",
31 "pre-push-cargo-test",
32 "pre-push-go-test",
33 "pre-push-pytest",
34];
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum Weight {
39 Light,
40 Heavy,
41}
42
43pub fn weight_of(name: &str) -> Weight {
44 if HEAVY.contains(&name) {
45 Weight::Heavy
46 } else {
47 Weight::Light
48 }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum Reason {
54 DirUnsafe(String),
56 Unsupported,
58 TimedOut(Duration),
60 Io(String),
63}
64
65static BUSY_SEEN: AtomicBool = AtomicBool::new(false);
69
70pub fn host_sizing(settings: &crate::config::Settings) -> greenharness_slots::host::HostSizing {
75 let rows = crate::config::host_rows(settings);
76 let mut sizing = greenharness_slots::host::resolve(
77 |name| std::env::var(name).ok(),
78 rows.unwrap_or(&[]),
79 greenharness_slots::detect_cores(),
80 );
81 if rows.is_none() {
82 sizing
83 .warnings
84 .push(greenharness_slots::host::NO_SCOPES_WARNING.to_string());
85 }
86 for warning in &sizing.warnings {
87 say_once(warning);
88 }
89 sizing
90}
91
92fn say_once(warning: &str) {
95 use std::collections::BTreeSet;
96 use std::sync::{Mutex, OnceLock};
97 static SAID: OnceLock<Mutex<BTreeSet<String>>> = OnceLock::new();
98 let said = SAID.get_or_init(|| Mutex::new(BTreeSet::new()));
99 let fresh = match said.lock() {
100 Ok(mut set) => set.insert(warning.to_string()),
101 Err(_) => true,
102 };
103 if fresh {
104 eprintln!("{}: warning: {warning}", crate::names::BIN);
105 }
106}
107
108pub fn sizing_and_machine(
112 settings: &crate::config::Settings,
113) -> (
114 Option<greenharness_slots::Sizing>,
115 greenharness_slots::Machine,
116) {
117 let host = host_sizing(settings);
118 (
119 host.slots.value,
120 greenharness_slots::Machine {
121 cores: host.cores.value.max(1),
122 },
123 )
124}
125
126pub fn sizing(settings: &crate::config::Settings) -> Option<greenharness_slots::Sizing> {
129 sizing_and_machine(settings).0
130}
131
132pub const ON_BUSY_ENV: &str = "GREENGATE_ON_BUSY";
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub enum BusyPolicy {
140 Wait,
143 Defer { slot_wait: Duration },
145}
146
147pub fn busy_policy(settings: &crate::config::Settings) -> BusyPolicy {
150 resolve_busy(std::env::var(ON_BUSY_ENV).ok().as_deref(), settings)
151}
152
153fn resolve_busy(from_env: Option<&str>, settings: &crate::config::Settings) -> BusyPolicy {
156 let from_env = from_env.filter(|v| !v.is_empty());
157 let mode = match from_env.map(str::to_ascii_lowercase).as_deref() {
158 Some("wait") => "wait",
159 Some("defer") => "defer",
160 Some(other) => {
161 crate::config::complain(
162 ON_BUSY_ENV,
163 &format!("{other:?} is not one of wait, defer"),
164 "greengate.onBusy",
165 );
166 crate::config::enumerated_or(settings, "greengate.onBusy", &["wait", "defer"], "wait")
167 }
168 None => {
169 crate::config::enumerated_or(settings, "greengate.onBusy", &["wait", "defer"], "wait")
170 }
171 };
172 if mode == "defer" {
173 let secs = crate::config::integer_or(settings, "greengate.slotWait", 60, 1..=3600) as u64;
174 BusyPolicy::Defer {
175 slot_wait: Duration::from_secs(secs),
176 }
177 } else {
178 BusyPolicy::Wait
179 }
180}
181
182#[derive(Default)]
184struct Current {
185 name: String,
187 heavy: bool,
188 settled: bool,
191 held: Option<greenharness_slots::Lease>,
192 queued: Duration,
193 deferred: Option<Duration>,
199 jobs: Option<u32>,
203 sized: Option<(u32, u32)>,
206 slot_wait: SlotWait,
208}
209
210#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
212enum SlotWait {
213 #[default]
215 Policy,
216 NeverWaits,
222 BoundedForWarn,
226}
227
228struct Parked {
231 lease: greenharness_slots::Lease,
232 jobs: Option<u32>,
233 sized: Option<(u32, u32)>,
234}
235
236static PARKED: Mutex<Option<Parked>> = Mutex::new(None);
240
241static PARK_SCOPE_DEPTH: AtomicUsize = AtomicUsize::new(0);
244
245fn parked() -> std::sync::MutexGuard<'static, Option<Parked>> {
246 PARKED
247 .lock()
248 .unwrap_or_else(|poisoned| poisoned.into_inner())
249}
250
251fn parking() -> bool {
255 PARK_SCOPE_DEPTH.load(Ordering::SeqCst) > 0 && crate::rehearsal::in_snapshot()
256}
257
258#[must_use = "the scope releases the parked slot when dropped"]
262pub struct ParkScope {
263 _private: (),
264}
265
266impl ParkScope {
267 #[must_use = "the scope releases the parked slot when dropped"]
268 pub fn begin() -> ParkScope {
269 PARK_SCOPE_DEPTH.fetch_add(1, Ordering::SeqCst);
270 ParkScope { _private: () }
271 }
272}
273
274impl Drop for ParkScope {
275 fn drop(&mut self) {
276 if PARK_SCOPE_DEPTH.fetch_sub(1, Ordering::SeqCst) == 1 {
277 release_parked();
278 }
279 }
280}
281
282pub fn release_parked() {
287 let leftover = parked().take();
288 drop(leftover);
289}
290
291fn between_gates() -> greenharness_slots::Holder {
293 holder_for("pre-push, between checks")
294}
295
296fn holder_for(command: &str) -> greenharness_slots::Holder {
301 let mut holder = greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, command);
302 if let Some(src) = crate::rehearsal::source_worktree() {
303 holder.repo = src.display().to_string();
304 }
305 holder
306}
307
308thread_local! {
309 static CURRENT: RefCell<Current> = RefCell::new(Current::default());
310}
311
312pub struct CheckGuard;
315
316impl CheckGuard {
317 pub fn queued(&self) -> Duration {
319 CURRENT.with(|c| c.borrow().queued)
320 }
321
322 pub fn deferred(&self) -> Option<Duration> {
325 CURRENT.with(|c| c.borrow().deferred)
326 }
327}
328
329pub fn deferred_here() -> bool {
332 CURRENT.with(|c| c.borrow().deferred.is_some())
333}
334
335fn refusal() -> std::io::Error {
338 std::io::Error::other("deferred to CI: no host slot freed (greengate.onBusy defer)")
339}
340
341impl Drop for CheckGuard {
342 fn drop(&mut self) {
343 let finished = CURRENT.with(RefCell::take);
344 if let Some(lease) = finished.held {
345 if parking() {
346 park(lease, finished.jobs, finished.sized);
347 }
348 }
349 }
350}
351
352fn park(lease: greenharness_slots::Lease, jobs: Option<u32>, sized: Option<(u32, u32)>) {
355 if let Err(error) = lease.rename(&between_gates()) {
356 crate::hooks::common::say(&format!(
357 " host slot kept, but `{BIN} slots` may still name the previous check: {error}"
358 ));
359 }
360 let earlier = parked().replace(Parked { lease, jobs, sized });
361 drop(earlier);
362}
363
364pub fn enter_check(name: &str, weight: Weight) -> CheckGuard {
368 CURRENT.with(|c| {
369 *c.borrow_mut() = Current {
370 name: name.to_string(),
371 heavy: weight == Weight::Heavy,
372 ..Current::default()
373 }
374 });
375 CheckGuard
376}
377
378pub fn never_waits() {
386 CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::NeverWaits);
387}
388
389pub fn wait_bounded_for_warn() {
394 CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::BoundedForWarn);
395}
396
397fn warn_slot_wait(settings: &crate::config::Settings) -> Duration {
400 Duration::from_secs(
401 crate::config::integer_or(settings, "greengate.warnSlotWait", 600, 1..=3600) as u64,
402 )
403}
404
405pub fn current_check() -> Option<String> {
408 CURRENT.with(|c| {
409 let c = c.borrow();
410 (!c.name.is_empty()).then(|| crate::short_name(&c.name).to_string())
411 })
412}
413
414fn nested() -> bool {
416 std::env::var_os(HELD_ENV).is_some_and(|v| !v.is_empty())
417}
418
419pub fn before_spawn(settings: &crate::config::Settings) -> std::io::Result<bool> {
424 let (pending, deferred, name, slot_wait) = CURRENT.with(|current| {
425 let current = current.borrow();
426 (
427 current.heavy && !current.settled,
428 current.deferred.is_some(),
429 current.name.clone(),
430 current.slot_wait,
431 )
432 });
433 if deferred {
436 return Err(refusal());
437 }
438 if pending {
439 if let Some(handed) = parking().then(|| parked().take()).flatten() {
440 return Ok(take_handed(handed, &name));
441 }
442 let (sizing, machine) = if nested() {
446 (None, greenharness_slots::Machine::detect())
447 } else {
448 sizing_and_machine(settings)
449 };
450 let Some(sizing) = sizing else {
451 CURRENT.with(|c| c.borrow_mut().settled = true);
452 return Ok(false);
453 };
454 if !greenharness_slots::SUPPORTED {
455 CURRENT.with(|c| c.borrow_mut().settled = true);
456 return Ok(false);
457 }
458 let policy = match slot_wait {
459 SlotWait::NeverWaits => BusyPolicy::Defer {
460 slot_wait: Duration::ZERO,
461 },
462 SlotWait::BoundedForWarn => BusyPolicy::Wait,
463 SlotWait::Policy => busy_policy(settings),
464 };
465 let ceiling = Duration::from_secs(match crate::hooks::common::check_timeout(settings) {
466 0 => 3600,
467 s => s,
468 });
469 let warn_wait = warn_slot_wait(settings);
470 let cut_by_warn_wait =
471 matches!(slot_wait, SlotWait::BoundedForWarn) && warn_wait <= ceiling;
472 let budget = match policy {
473 BusyPolicy::Wait if matches!(slot_wait, SlotWait::BoundedForWarn) => {
474 warn_wait.min(ceiling)
475 }
476 BusyPolicy::Wait => ceiling,
477 BusyPolicy::Defer { .. } if BUSY_SEEN.load(Ordering::SeqCst) => Duration::ZERO,
479 BusyPolicy::Defer { slot_wait } => slot_wait,
480 };
481 let slot_cap = sizing.cap_for(machine.cores);
482 let cap = u64::from(slot_cap);
483 let jobs = greenharness_slots::parallelism(1, machine.cores, slot_cap);
486 let sink = crate::live::current_sink();
487 if let Some((stage, idx)) = &sink {
488 stage.queue(*idx, Some((Instant::now(), cap)));
489 }
490 let started = Instant::now();
491 let holder = holder_for(&name);
492 let mut got = wait_for_slot(sizing, machine, holder.clone(), budget);
493 if let (BusyPolicy::Defer { .. }, Err(Reason::TimedOut(_))) = (policy, &got) {
494 let rest = if greenharness_slots::held_in_process() > 0
499 && !matches!(slot_wait, SlotWait::NeverWaits)
500 {
501 ceiling.saturating_sub(started.elapsed())
502 } else {
503 Duration::ZERO
504 };
505 got = wait_for_slot(sizing, machine, holder, rest);
506 }
507 if let Some((stage, idx)) = &sink {
508 stage.queue(*idx, None);
509 }
510 let waited = started.elapsed();
511 CURRENT.with(|c| c.borrow_mut().queued += waited);
512 if got.is_ok() && waited >= Duration::from_secs(1) {
515 crate::hooks::common::say(&format!(
516 " (waited {} for a host slot, {} {cap})",
517 crate::hooks::common::human_secs(waited.as_secs()),
518 crate::ui::highlight("greengate.hostSlots")
519 ));
520 }
521 let defer =
522 matches!(policy, BusyPolicy::Defer { .. }) && matches!(got, Err(Reason::TimedOut(_)));
523 let outcome = match (&got, defer) {
524 (Ok(_), _) => "admitted",
525 (Err(_), true) => "deferred",
526 (Err(_), false) => "unqueued",
527 };
528 record_acquisition(
529 &name,
530 Some(jobs),
531 Some((slot_cap, machine.cores)),
532 waited,
533 outcome,
534 );
535 let held = match got {
536 Ok(lease) => Some(lease),
537 Err(_) if defer => None,
539 Err(reason) => {
540 note(&reason, cap, cut_by_warn_wait.then_some(warn_wait));
541 None
542 }
543 };
544 if defer {
545 BUSY_SEEN.store(true, Ordering::SeqCst);
546 }
547 CURRENT.with(|c| {
548 let mut c = c.borrow_mut();
549 c.held = held;
550 c.settled = true;
551 c.jobs = Some(jobs);
552 c.sized = Some((slot_cap, machine.cores));
553 if defer {
554 c.deferred = Some(waited);
555 }
556 });
557 if defer {
558 return Err(refusal());
559 }
560 }
561 Ok(CURRENT.with(|c| c.borrow().held.is_some()) || (parking() && parked().is_some()))
565}
566
567fn take_handed(handed: Parked, name: &str) -> bool {
570 let Parked { lease, jobs, sized } = handed;
571 if let Err(error) = lease.rename(&holder_for(name)) {
572 crate::hooks::common::say(&format!(
573 " host slot kept, but `{BIN} slots` may still name the previous check: {error}"
574 ));
575 }
576 record_acquisition(name, jobs, sized, Duration::ZERO, "handed");
577 CURRENT.with(|current| {
578 let mut current = current.borrow_mut();
579 current.held = Some(lease);
580 current.settled = true;
581 current.jobs = jobs;
582 current.sized = sized;
583 });
584 true
585}
586
587fn record_acquisition(
590 name: &str,
591 jobs: Option<u32>,
592 sized: Option<(u32, u32)>,
593 waited: Duration,
594 outcome: &str,
595) {
596 let short = crate::short_name(name);
597 greenharness_slots::record_wait_named(
598 &greenharness_slots::dir(),
599 crate::names::SLOT_HOLDER,
600 greenharness_slots::WaitContext {
601 name: Some(short),
602 place: if crate::rehearsal::in_prestage() {
603 greenharness_slots::WaitPlace::Prestage
604 } else if crate::rehearsal::in_snapshot() {
605 greenharness_slots::WaitPlace::Rehearsal
606 } else {
607 greenharness_slots::WaitPlace::Push
608 },
609 cap: sized.map(|(cap, _)| cap),
610 cores: sized.map(|(_, cores)| cores),
611 },
612 1,
613 jobs,
614 waited.as_millis(),
615 outcome,
616 );
617}
618
619pub fn bound(cmd: &mut std::process::Command) {
623 let own = CURRENT.with(|c| c.borrow().jobs);
624 if let Some(jobs) = own.or_else(|| {
626 parking()
627 .then(|| parked().as_ref().and_then(|p| p.jobs))
628 .flatten()
629 }) {
630 greenharness_slots::bound_width(cmd, jobs);
631 }
632}
633
634fn wait_for_slot(
637 sizing: greenharness_slots::Sizing,
638 machine: greenharness_slots::Machine,
639 holder: greenharness_slots::Holder,
640 budget: Duration,
641) -> Result<greenharness_slots::Lease, Reason> {
642 let started = Instant::now();
643 let mut waiter = match greenharness_slots::Waiter::new_in_on(
644 &greenharness_slots::dir(),
645 sizing,
646 1,
647 holder,
648 machine,
649 ) {
650 Ok(w) => w,
651 Err(e) if e.kind() == std::io::ErrorKind::Other => {
652 return Err(Reason::DirUnsafe(e.to_string()))
653 }
654 Err(e) => return Err(Reason::Io(e.to_string())),
655 };
656 let mut said = false;
657 loop {
658 match waiter.poll() {
659 Ok(greenharness_slots::Poll::Granted(lease)) => return Ok(lease),
660 Ok(greenharness_slots::Poll::Waiting(queue)) => {
661 if !said && (!queue.holders.is_empty() || queue.unknown > 0) {
662 said = true;
663 crate::hooks::common::say(&format!(" {}", behind(&queue)));
664 crate::hooks::common::say(&format!(" see: {BIN} slots"));
665 }
666 }
667 Err(e) => return Err(Reason::Io(e.to_string())),
668 }
669 if started.elapsed() >= budget {
670 return Err(Reason::TimedOut(started.elapsed()));
671 }
672 std::thread::sleep(Duration::from_millis(200));
673 }
674}
675
676pub fn behind(queue: &greenharness_slots::Queue) -> String {
678 let now = greenharness_slots::now_ms();
679 let mut who: Vec<String> = queue.holders.iter().map(|h| h.describe(now)).collect();
680 if queue.unknown > 0 {
681 who.push(format!("{} unknown (old client)", queue.unknown));
682 }
683 let reason = queue
684 .reason
685 .map_or(String::new(), |r| format!(" ({})", r.describe()));
686 format!(
687 "queued behind {}{reason} · {} waiting",
688 who.join(", "),
689 queue.waiting.max(1)
690 )
691}
692
693fn note(reason: &Reason, cap: u64, warn_wait: Option<Duration>) {
699 match reason {
700 Reason::DirUnsafe(why) => crate::hooks::common::warn(&format!(
701 "host slots are off for this check: {why}. Remove it, or set {} to a directory \
702 only you own",
703 crate::ui::highlight(DIR_ENV)
704 )),
705 Reason::TimedOut(waited) if warn_wait.is_some() => crate::hooks::common::warn(&format!(
706 "no host slot in {} (land: {}={}s); running it anyway",
707 crate::hooks::common::human_secs(waited.as_secs()),
708 crate::ui::highlight("greengate.warnSlotWait"),
709 warn_wait.map_or(0, |limit| limit.as_secs())
710 )),
711 Reason::TimedOut(waited) => crate::hooks::common::warn(&format!(
712 "no host slot freed in {} ({} {cap}); running it anyway",
713 crate::hooks::common::human_secs(waited.as_secs()),
714 crate::ui::highlight("greengate.hostSlots")
715 )),
716 Reason::Io(why) => {
717 crate::hooks::common::warn(&format!("host slots are off for this check: {why}"))
718 }
719 Reason::Unsupported => {}
720 }
721}
722
723#[cfg(all(test, unix))]
724mod tests {
725 use super::*;
726
727 fn settings_from(conf: &str) -> crate::config::Settings {
728 let lines = crate::manifest::parse_lines(conf);
729 let (policy, _) = crate::policy::Policy::from_lines(&lines);
730 crate::config::Settings::new(policy)
731 }
732
733 #[test]
736 fn the_busy_policy_is_env_then_file_then_wait() {
737 let none = settings_from("");
738 let defer = settings_from("set onBusy defer\nset slotWait 5\n");
739 assert_eq!(resolve_busy(None, &none), BusyPolicy::Wait);
740 assert_eq!(
741 resolve_busy(None, &defer),
742 BusyPolicy::Defer {
743 slot_wait: Duration::from_secs(5)
744 }
745 );
746 assert_eq!(resolve_busy(Some("wait"), &defer), BusyPolicy::Wait);
747 assert_eq!(
748 resolve_busy(Some("DEFER"), &none),
749 BusyPolicy::Defer {
750 slot_wait: Duration::from_secs(60)
751 }
752 );
753 assert_eq!(
754 resolve_busy(Some("later"), &defer),
755 BusyPolicy::Defer {
756 slot_wait: Duration::from_secs(5)
757 }
758 );
759 assert_eq!(resolve_busy(Some(""), &none), BusyPolicy::Wait);
760 }
761
762 #[test]
763 fn heavy_is_the_list() {
764 assert_eq!(weight_of("pre-commit-clippy"), Weight::Heavy);
765 assert_eq!(weight_of("pre-commit-cargo-fmt"), Weight::Light);
766 }
767
768 #[test]
771 fn every_heavy_name_is_a_builtin() {
772 for name in HEAVY {
773 assert!(
774 crate::registry::CHECKS.iter().any(|c| c.name == *name),
775 "{name} is not a built-in check"
776 );
777 }
778 }
779
780 #[test]
783 fn cargo_pins_the_host_knobs_for_tests() {
784 assert_eq!(std::env::var(HELD_ENV).as_deref(), Ok("held"));
785 assert_eq!(
786 std::env::var("GREENGATE_IDLE_LOAD_SCALE").as_deref(),
787 Ok("1")
788 );
789 }
790
791 #[test]
795 fn a_light_check_never_takes_a_slot() {
796 let settings = crate::config::Settings::default();
797 let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
798 assert!(!before_spawn(&settings).unwrap());
799 }
800
801 #[test]
802 fn a_nested_heavy_check_settles_without_a_slot() {
803 let settings = crate::config::Settings::default();
804 let _g = enter_check("pre-commit-clippy", weight_of("pre-commit-clippy"));
805 assert_eq!(current_check().as_deref(), Some("clippy"));
806 assert!(!before_spawn(&settings).unwrap());
807 assert!(CURRENT.with(|c| c.borrow().settled));
808 let mut cmd = std::process::Command::new("true");
810 bound(&mut cmd);
811 assert_eq!(cmd.get_envs().count(), 0);
812 }
813
814 #[test]
817 fn a_park_scope_dropped_early_releases_the_parked_slot() {
818 let dir = std::env::temp_dir().join(format!("greengate-park-{}", std::process::id()));
819 let _ = std::fs::remove_dir_all(&dir); let early = || {
821 let _scope = ParkScope::begin();
822 let mut waiter = greenharness_slots::Waiter::new_in(
823 &dir,
824 greenharness_slots::Sizing::Fixed(1),
825 1,
826 greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, "gate"),
827 )
828 .unwrap();
829 let greenharness_slots::Poll::Granted(lease) = waiter.poll().unwrap() else {
830 panic!("the empty directory grants the slot");
831 };
832 assert!(dir.join("holders/slot-0.who").exists());
833 park(lease, Some(2), Some((3, 6)));
834 assert!(dir.join("holders/slot-0.who").exists());
835 };
836 early();
837 assert!(!dir.join("holders/slot-0.who").exists());
838 let _ = std::fs::remove_dir_all(&dir); }
840
841 #[test]
842 fn a_light_check_sets_no_width() {
843 let settings = crate::config::Settings::default();
844 let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
845 before_spawn(&settings).unwrap();
846 let mut cmd = std::process::Command::new("true");
847 bound(&mut cmd);
848 assert_eq!(cmd.get_envs().count(), 0);
849 }
850}