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)]
53pub enum Reason {
54 DirUnsafe(String),
56 Unsupported,
58 Io(String),
62 Ended(greenharness_slots::LineEnd),
65}
66
67impl Reason {
68 fn ended(&self) -> Option<&greenharness_slots::LineEnd> {
71 match self {
72 Reason::Ended(end) => Some(end),
73 Reason::DirUnsafe(_) | Reason::Unsupported | Reason::Io(_) => None,
74 }
75 }
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum DeferredBy {
83 SlotWait,
84 LineEnded,
85}
86
87static DEFERRED_BY_SLOT_WAIT: AtomicBool = AtomicBool::new(false);
89
90pub fn deferred_by() -> DeferredBy {
92 if DEFERRED_BY_SLOT_WAIT.load(Ordering::SeqCst) {
93 DeferredBy::SlotWait
94 } else {
95 DeferredBy::LineEnded
96 }
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101enum HostSeen {
102 Busy,
103 NotYet,
104}
105
106static BUSY_SEEN: AtomicBool = AtomicBool::new(false);
110
111pub fn host_sizing(settings: &crate::config::Settings) -> greenharness_slots::host::HostSizing {
116 let rows = crate::config::host_rows(settings);
117 let mut sizing = greenharness_slots::host::resolve(
118 |name| std::env::var(name).ok(),
119 rows.unwrap_or(&[]),
120 greenharness_slots::detect_cores(),
121 );
122 if rows.is_none() {
123 sizing
124 .warnings
125 .push(greenharness_slots::host::NO_SCOPES_WARNING.to_string());
126 }
127 for warning in &sizing.warnings {
128 say_once(warning);
129 }
130 sizing
131}
132
133fn say_once(warning: &str) {
136 use std::collections::BTreeSet;
137 use std::sync::{Mutex, OnceLock};
138 static SAID: OnceLock<Mutex<BTreeSet<String>>> = OnceLock::new();
139 let said = SAID.get_or_init(|| Mutex::new(BTreeSet::new()));
140 let fresh = match said.lock() {
141 Ok(mut set) => set.insert(warning.to_string()),
142 Err(_) => true,
143 };
144 if fresh {
145 eprintln!("{}: warning: {warning}", crate::names::BIN);
146 }
147}
148
149pub fn sizing_and_machine(
153 settings: &crate::config::Settings,
154) -> (
155 Option<greenharness_slots::Sizing>,
156 greenharness_slots::Machine,
157) {
158 let host = host_sizing(settings);
159 (
160 host.slots.value,
161 greenharness_slots::Machine {
162 cores: host.cores.value.max(1),
163 },
164 )
165}
166
167pub fn promote_switch(
171 settings: &crate::config::Settings,
172) -> Option<greenharness_slots::host::OffBy> {
173 let rows = crate::config::host_rows(settings);
174 let (off, warnings) =
175 greenharness_slots::host::resolve_promote(|name| std::env::var(name).ok(), rows);
176 for warning in &warnings {
177 say_once(warning);
178 }
179 off
180}
181
182pub fn sizing(settings: &crate::config::Settings) -> Option<greenharness_slots::Sizing> {
185 sizing_and_machine(settings).0
186}
187
188pub const ON_BUSY_ENV: &str = "GREENGATE_ON_BUSY";
191
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
195pub enum BusyPolicy {
196 Wait,
199 Defer { slot_wait: Duration },
201 Now,
205}
206
207pub fn busy_policy(settings: &crate::config::Settings) -> BusyPolicy {
211 resolve_busy(std::env::var(ON_BUSY_ENV).ok().as_deref(), settings)
212}
213
214fn resolve_busy(from_env: Option<&str>, settings: &crate::config::Settings) -> BusyPolicy {
217 let from_env = from_env.filter(|v| !v.is_empty());
218 let mode = match from_env.map(str::to_ascii_lowercase).as_deref() {
219 Some("wait") => "wait",
220 Some("defer") => "defer",
221 Some("now") => return BusyPolicy::Now,
222 Some(other) => {
223 crate::config::complain(
224 ON_BUSY_ENV,
225 &format!("{other:?} is not one of wait, defer, now"),
226 "greengate.onBusy",
227 );
228 crate::config::enumerated_or(settings, "greengate.onBusy", &["wait", "defer"], "wait")
229 }
230 None => {
231 crate::config::enumerated_or(settings, "greengate.onBusy", &["wait", "defer"], "wait")
232 }
233 };
234 if mode == "defer" {
235 let secs = crate::config::integer_or(settings, "greengate.slotWait", 60, 1..=3600) as u64;
236 BusyPolicy::Defer {
237 slot_wait: Duration::from_secs(secs),
238 }
239 } else {
240 BusyPolicy::Wait
241 }
242}
243
244#[derive(Default)]
246struct Current {
247 name: String,
249 heavy: bool,
250 settled: bool,
253 held: Option<greenharness_slots::Lease>,
254 queued: Duration,
255 deferred: Option<Duration>,
261 deferred_cause: String,
263 jobs: Option<u32>,
267 sized: Option<(u32, u32)>,
270 slot_wait: SlotWait,
272}
273
274#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
276enum SlotWait {
277 #[default]
279 Policy,
280 NeverWaits,
286 BoundedForWarn,
290}
291
292struct Parked {
295 lease: greenharness_slots::Lease,
296 jobs: Option<u32>,
297 sized: Option<(u32, u32)>,
298}
299
300static PARKED: Mutex<Option<Parked>> = Mutex::new(None);
304
305static PARK_SCOPE_DEPTH: AtomicUsize = AtomicUsize::new(0);
308
309fn parked() -> std::sync::MutexGuard<'static, Option<Parked>> {
310 PARKED
311 .lock()
312 .unwrap_or_else(|poisoned| poisoned.into_inner())
313}
314
315fn parking() -> bool {
319 PARK_SCOPE_DEPTH.load(Ordering::SeqCst) > 0 && crate::rehearsal::in_snapshot()
320}
321
322#[must_use = "the scope releases the parked slot when dropped"]
326pub struct ParkScope {
327 _private: (),
328}
329
330impl ParkScope {
331 #[must_use = "the scope releases the parked slot when dropped"]
332 pub fn begin() -> ParkScope {
333 PARK_SCOPE_DEPTH.fetch_add(1, Ordering::SeqCst);
334 ParkScope { _private: () }
335 }
336}
337
338impl Drop for ParkScope {
339 fn drop(&mut self) {
340 if PARK_SCOPE_DEPTH.fetch_sub(1, Ordering::SeqCst) == 1 {
341 release_parked();
342 }
343 }
344}
345
346pub fn release_parked() {
351 let leftover = parked().take();
352 drop(leftover);
353}
354
355fn between_gates() -> greenharness_slots::Holder {
357 holder_for("pre-push, between checks")
358}
359
360fn holder_for(command: &str) -> greenharness_slots::Holder {
365 let mut holder = greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, command);
366 if let Some(src) = crate::rehearsal::source_worktree() {
367 holder.repo = src.display().to_string();
368 }
369 holder
370}
371
372thread_local! {
373 static CURRENT: RefCell<Current> = RefCell::new(Current::default());
374}
375
376pub struct CheckGuard;
379
380impl CheckGuard {
381 pub fn queued(&self) -> Duration {
383 CURRENT.with(|c| c.borrow().queued)
384 }
385
386 pub fn deferred(&self) -> Option<Duration> {
389 CURRENT.with(|c| c.borrow().deferred)
390 }
391}
392
393pub fn deferred_here() -> bool {
396 CURRENT.with(|c| c.borrow().deferred.is_some())
397}
398
399fn refusal() -> std::io::Error {
403 let cause = CURRENT.with(|c| c.borrow().deferred_cause.clone());
404 std::io::Error::other(if cause.is_empty() {
405 "deferred to CI: the host is busy".to_string()
406 } else {
407 cause
408 })
409}
410
411fn defer_cause(
413 end: &greenharness_slots::LineEnd,
414 policy: BusyPolicy,
415 slot_wait: SlotWait,
416) -> String {
417 use greenharness_slots::LineEnd;
418 let human = |d: Duration| crate::hooks::common::human_secs(d.as_secs());
419 match end {
420 LineEnd::Stalled { window, position } => format!(
423 "deferred to CI: the host slot line made no progress for {} (position {})",
424 human(*window),
425 position + 1
426 ),
427 LineEnd::PollFailed { error } => {
428 format!("deferred to CI: the host slot files failed: {error}")
429 }
430 LineEnd::Ceiling { waited } => match policy {
431 BusyPolicy::Defer { .. } => format!(
432 "deferred to CI: no host slot freed in {} (greengate.onBusy defer)",
433 human(*waited)
434 ),
435 BusyPolicy::Wait | BusyPolicy::Now => {
436 let setting = match slot_wait {
439 SlotWait::BoundedForWarn => "greengate.warnSlotWait",
440 SlotWait::Policy | SlotWait::NeverWaits => "greengate.timeout",
441 };
442 format!(
443 "deferred to CI: no host slot within {} ({setting})",
444 human(*waited)
445 )
446 }
447 },
448 }
449}
450
451#[derive(Debug, Clone, Copy, PartialEq, Eq)]
454enum WaitPlan {
455 Now,
456 Queue(greenharness_slots::WaitBounds),
457}
458
459pub(crate) fn wait_ceiling_secs(timeout: u64) -> u64 {
463 match timeout {
464 0 => 3600,
465 secs => secs,
466 }
467}
468
469fn wait_plan(
476 slot_wait: SlotWait,
477 policy: BusyPolicy,
478 ceiling: Duration,
479 warn_wait: Duration,
480 seen: HostSeen,
481) -> WaitPlan {
482 let queue =
483 |window, ceiling| WaitPlan::Queue(greenharness_slots::WaitBounds { window, ceiling });
484 match (slot_wait, policy) {
485 (_, BusyPolicy::Now) => WaitPlan::Now,
486 (SlotWait::NeverWaits, _) => queue(None, Duration::ZERO),
487 (SlotWait::BoundedForWarn, _) => queue(None, warn_wait.min(ceiling)),
488 (SlotWait::Policy, BusyPolicy::Wait) => queue(None, ceiling),
489 (SlotWait::Policy, BusyPolicy::Defer { slot_wait }) => match seen {
490 HostSeen::Busy => queue(None, Duration::ZERO),
492 HostSeen::NotYet => queue(None, slot_wait),
493 },
494 }
495}
496
497fn sibling_bounds(
504 slot_wait: SlotWait,
505 held_in_process: usize,
506 ceiling: Duration,
507 elapsed: Duration,
508) -> greenharness_slots::WaitBounds {
509 let waits_on_sibling = held_in_process > 0 && !matches!(slot_wait, SlotWait::NeverWaits);
510 if waits_on_sibling {
511 greenharness_slots::WaitBounds {
512 window: None,
513 ceiling: ceiling.saturating_sub(elapsed),
514 }
515 } else {
516 greenharness_slots::WaitBounds {
517 window: None,
518 ceiling: Duration::ZERO,
519 }
520 }
521}
522
523impl Drop for CheckGuard {
524 fn drop(&mut self) {
525 let finished = CURRENT.with(RefCell::take);
526 if let Some(lease) = finished.held {
527 if parking() {
528 park(lease, finished.jobs, finished.sized);
529 }
530 }
531 }
532}
533
534fn park(lease: greenharness_slots::Lease, jobs: Option<u32>, sized: Option<(u32, u32)>) {
537 if let Err(error) = lease.rename(&between_gates()) {
538 crate::hooks::common::say(&format!(
539 " host slot kept, but `{BIN} slots` may still name the previous check: {error}"
540 ));
541 }
542 let earlier = parked().replace(Parked { lease, jobs, sized });
543 drop(earlier);
544}
545
546pub fn enter_check(name: &str, weight: Weight) -> CheckGuard {
550 CURRENT.with(|c| {
551 *c.borrow_mut() = Current {
552 name: name.to_string(),
553 heavy: weight == Weight::Heavy,
554 ..Current::default()
555 }
556 });
557 CheckGuard
558}
559
560pub fn never_waits() {
568 CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::NeverWaits);
569}
570
571pub fn wait_bounded_for_warn() {
576 CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::BoundedForWarn);
577}
578
579fn warn_slot_wait(settings: &crate::config::Settings) -> Duration {
582 Duration::from_secs(
583 crate::config::integer_or(settings, "greengate.warnSlotWait", 600, 1..=3600) as u64,
584 )
585}
586
587pub fn current_check() -> Option<String> {
590 CURRENT.with(|c| {
591 let c = c.borrow();
592 (!c.name.is_empty()).then(|| crate::short_name(&c.name).to_string())
593 })
594}
595
596fn marker(settings: &crate::config::Settings) -> &greenharness_slots::Marker {
600 settings.marker.get_or_init(greenharness_slots::held_marker)
601}
602
603pub(crate) fn nested(settings: &crate::config::Settings) -> bool {
609 let marker = marker(settings);
610 if matches!(marker, greenharness_slots::Marker::Held { bare: true }) {
611 settings.marker_log.record(
612 &greenharness_slots::dir(),
613 crate::names::SLOT_HOLDER,
614 marker,
615 );
616 }
617 marker.is_held()
618}
619
620pub(crate) fn marker_refused_note(settings: &crate::config::Settings) -> Option<String> {
623 let marker = marker(settings);
624 settings
625 .marker_log
626 .record(
627 &greenharness_slots::dir(),
628 crate::names::SLOT_HOLDER,
629 marker,
630 )
631 .then(|| greenharness_slots::refused_line(BIN, marker))
632 .flatten()
633}
634
635fn say_refusal(line: &str) {
639 if crate::live::current_sink().is_some() {
640 crate::hooks::common::say(line);
641 } else {
642 eprintln!("{line}");
643 }
644}
645
646pub fn before_spawn(settings: &crate::config::Settings) -> std::io::Result<Option<String>> {
654 let (pending, deferred, name, slot_wait) = CURRENT.with(|current| {
655 let current = current.borrow();
656 (
657 current.heavy && !current.settled,
658 current.deferred.is_some(),
659 current.name.clone(),
660 current.slot_wait,
661 )
662 });
663 if deferred {
666 return Err(refusal());
667 }
668 if pending {
669 if let Some(handed) = parking().then(|| parked().take()).flatten() {
670 return Ok(Some(take_handed(handed, &name)));
671 }
672 let (sizing, machine) = if nested(settings) {
676 (None, greenharness_slots::Machine::detect())
677 } else {
678 sizing_and_machine(settings)
679 };
680 let Some(sizing) = sizing else {
681 CURRENT.with(|c| c.borrow_mut().settled = true);
682 return Ok(None);
683 };
684 if !greenharness_slots::SUPPORTED {
685 CURRENT.with(|c| c.borrow_mut().settled = true);
686 return Ok(None);
687 }
688 let policy = match slot_wait {
689 SlotWait::NeverWaits => BusyPolicy::Defer {
690 slot_wait: Duration::ZERO,
691 },
692 SlotWait::BoundedForWarn => BusyPolicy::Wait,
693 SlotWait::Policy => busy_policy(settings),
694 };
695 let ceiling = Duration::from_secs(wait_ceiling_secs(crate::hooks::common::check_timeout(
696 settings,
697 )));
698 let seen = if BUSY_SEEN.load(Ordering::SeqCst) {
699 HostSeen::Busy
700 } else {
701 HostSeen::NotYet
702 };
703 let plan = wait_plan(slot_wait, policy, ceiling, warn_slot_wait(settings), seen);
704 let slot_cap = sizing.cap_for(machine.cores);
705 let cap = u64::from(slot_cap);
706 let jobs = greenharness_slots::parallelism(1, machine.cores, slot_cap);
709 let bounds = match plan {
710 WaitPlan::Queue(bounds) => bounds,
711 WaitPlan::Now => {
712 crate::hooks::common::say(&format!(
715 " running unqueued: {}=now skips the host slot queue",
716 crate::ui::highlight(ON_BUSY_ENV)
717 ));
718 record_acquisition(
719 &name,
720 Some(jobs),
721 Some((slot_cap, machine.cores)),
722 Duration::ZERO,
723 "now",
724 None,
725 );
726 CURRENT.with(|c| {
727 let mut c = c.borrow_mut();
728 c.settled = true;
729 c.jobs = Some(jobs);
730 c.sized = Some((slot_cap, machine.cores));
731 });
732 return Ok(None);
733 }
734 };
735 if let Some(line) = marker_refused_note(settings) {
737 say_refusal(&line);
738 }
739 let sink = crate::live::current_sink();
740 if let Some((stage, idx)) = &sink {
741 stage.queue(*idx, Some((Instant::now(), cap)));
742 }
743 let started = Instant::now();
744 let holder = holder_for(&name);
745 let mut got = wait_for_slot(sizing, machine, holder.clone(), bounds);
746 if let (
747 BusyPolicy::Defer { .. },
748 Err(Reason::Ended(greenharness_slots::LineEnd::Ceiling { .. })),
749 ) = (policy, &got)
750 {
751 let more = sibling_bounds(
752 slot_wait,
753 greenharness_slots::held_in_process(),
754 ceiling,
755 started.elapsed(),
756 );
757 got = wait_for_slot(sizing, machine, holder, more);
758 }
759 if let Some((stage, idx)) = &sink {
760 stage.queue(*idx, None);
761 }
762 let waited = started.elapsed();
763 CURRENT.with(|c| c.borrow_mut().queued += waited);
764 if got.is_ok() && waited >= Duration::from_secs(1) {
767 crate::hooks::common::say(&format!(
768 " (waited {} for a host slot, {} {cap})",
769 crate::hooks::common::human_secs(waited.as_secs()),
770 crate::ui::highlight("greengate.hostSlots")
771 ));
772 }
773 let ended = got.as_ref().err().and_then(Reason::ended);
776 let defer = ended.is_some();
777 let end = ended.map(greenharness_slots::LineEnd::end);
778 let cause = ended.map_or(String::new(), |end| defer_cause(end, policy, slot_wait));
779 let by_slot_wait = matches!(
780 (policy, ended),
781 (
782 BusyPolicy::Defer { .. },
783 Some(greenharness_slots::LineEnd::Ceiling { .. })
784 )
785 );
786 let outcome = match (&got, defer) {
787 (Ok(_), _) => "admitted",
788 (Err(_), true) => "deferred",
789 (Err(_), false) => "unqueued",
790 };
791 record_acquisition(
792 &name,
793 Some(jobs),
794 Some((slot_cap, machine.cores)),
795 waited,
796 outcome,
797 end,
798 );
799 let held = match got {
800 Ok(lease) => Some(lease),
801 Err(Reason::Ended(_)) => None,
803 Err(reason) => {
804 note(&reason);
805 None
806 }
807 };
808 if defer {
809 BUSY_SEEN.store(true, Ordering::SeqCst);
810 if by_slot_wait {
811 DEFERRED_BY_SLOT_WAIT.store(true, Ordering::SeqCst);
812 }
813 }
814 CURRENT.with(|c| {
815 let mut c = c.borrow_mut();
816 c.held = held;
817 c.settled = true;
818 c.jobs = Some(jobs);
819 c.sized = Some((slot_cap, machine.cores));
820 if defer {
821 c.deferred = Some(waited);
822 c.deferred_cause = cause;
823 }
824 });
825 if defer {
826 return Err(refusal());
827 }
828 }
829 let own = CURRENT.with(|c| {
833 c.borrow()
834 .held
835 .as_ref()
836 .map(greenharness_slots::Lease::marker)
837 });
838 Ok(own.or_else(|| {
839 if parking() {
840 parked().as_ref().map(|p| p.lease.marker())
841 } else {
842 None
843 }
844 }))
845}
846
847fn take_handed(handed: Parked, name: &str) -> String {
851 let Parked { lease, jobs, sized } = handed;
852 if let Err(error) = lease.rename(&holder_for(name)) {
853 crate::hooks::common::say(&format!(
854 " host slot kept, but `{BIN} slots` may still name the previous check: {error}"
855 ));
856 }
857 record_acquisition(name, jobs, sized, Duration::ZERO, "handed", None);
858 let marker = lease.marker();
859 CURRENT.with(|current| {
860 let mut current = current.borrow_mut();
861 current.held = Some(lease);
862 current.settled = true;
863 current.jobs = jobs;
864 current.sized = sized;
865 });
866 marker
867}
868
869fn record_acquisition(
872 name: &str,
873 jobs: Option<u32>,
874 sized: Option<(u32, u32)>,
875 waited: Duration,
876 outcome: &str,
877 end: Option<greenharness_slots::WaitEnd>,
878) {
879 let short = crate::short_name(name);
880 greenharness_slots::record_wait_named(
881 &greenharness_slots::dir(),
882 crate::names::SLOT_HOLDER,
883 greenharness_slots::WaitContext {
884 name: Some(short),
885 place: if crate::rehearsal::in_prestage() {
886 greenharness_slots::WaitPlace::Prestage
887 } else if crate::rehearsal::in_snapshot() {
888 greenharness_slots::WaitPlace::Rehearsal
889 } else {
890 greenharness_slots::WaitPlace::Push
891 },
892 cap: sized.map(|(cap, _)| cap),
893 cores: sized.map(|(_, cores)| cores),
894 end,
895 },
896 1,
897 jobs,
898 waited.as_millis(),
899 outcome,
900 );
901}
902
903pub fn bound(cmd: &mut std::process::Command) {
907 let own = CURRENT.with(|c| c.borrow().jobs);
908 if let Some(jobs) = own.or_else(|| {
910 parking()
911 .then(|| parked().as_ref().and_then(|p| p.jobs))
912 .flatten()
913 }) {
914 greenharness_slots::bound_width(cmd, jobs);
915 }
916}
917
918fn wait_for_slot(
922 sizing: greenharness_slots::Sizing,
923 machine: greenharness_slots::Machine,
924 holder: greenharness_slots::Holder,
925 bounds: greenharness_slots::WaitBounds,
926) -> Result<greenharness_slots::Lease, Reason> {
927 let waiter = match greenharness_slots::Waiter::new_in_on(
928 &greenharness_slots::dir(),
929 sizing,
930 1,
931 holder,
932 machine,
933 ) {
934 Ok(w) => w,
935 Err(e) if e.kind() == std::io::ErrorKind::Other => {
936 return Err(Reason::DirUnsafe(e.to_string()))
937 }
938 Err(e) => return Err(Reason::Io(e.to_string())),
939 };
940 let mut said = false;
941 greenharness_slots::wait_in_line(waiter, bounds, |queue| {
942 if !said && (!queue.holders.is_empty() || queue.unknown > 0) {
943 said = true;
944 crate::hooks::common::say(&format!(" {}", behind(queue)));
945 crate::hooks::common::say(&format!(" see: {BIN} slots"));
946 }
947 })
948 .map_err(Reason::Ended)
949}
950
951pub fn behind(queue: &greenharness_slots::Queue) -> String {
953 let now = greenharness_slots::now_ms();
954 let mut who: Vec<String> = queue.holders.iter().map(|h| h.describe(now)).collect();
955 if queue.unknown > 0 {
956 who.push(format!("{} unknown (old client)", queue.unknown));
957 }
958 let reason = queue
959 .reason
960 .map_or(String::new(), |r| format!(" ({})", r.describe()));
961 format!(
962 "queued behind {}{reason} · {} waiting",
963 who.join(", "),
964 queue.waiting.max(1)
965 )
966}
967
968fn note(reason: &Reason) {
972 match reason {
973 Reason::DirUnsafe(why) => crate::hooks::common::warn(&format!(
974 "host slots are off for this check: {why}. Remove it, or set {} to a directory \
975 only you own",
976 crate::ui::highlight(DIR_ENV)
977 )),
978 Reason::Io(why) => {
979 crate::hooks::common::warn(&format!("host slots are off for this check: {why}"))
980 }
981 Reason::Ended(_) | Reason::Unsupported => {}
982 }
983}
984
985#[cfg(all(test, unix))]
986mod tests {
987 use super::*;
988
989 fn settings_from(conf: &str) -> crate::config::Settings {
990 let lines = crate::manifest::parse_lines(conf);
991 let (policy, _) = crate::policy::Policy::from_lines(&lines);
992 crate::config::Settings::new(policy)
993 }
994
995 #[test]
998 fn the_busy_policy_is_env_then_file_then_wait() {
999 let none = settings_from("");
1000 let defer = settings_from("set onBusy defer\nset slotWait 5\n");
1001 assert_eq!(resolve_busy(None, &none), BusyPolicy::Wait);
1002 assert_eq!(
1003 resolve_busy(None, &defer),
1004 BusyPolicy::Defer {
1005 slot_wait: Duration::from_secs(5)
1006 }
1007 );
1008 assert_eq!(resolve_busy(Some("wait"), &defer), BusyPolicy::Wait);
1009 assert_eq!(
1010 resolve_busy(Some("DEFER"), &none),
1011 BusyPolicy::Defer {
1012 slot_wait: Duration::from_secs(60)
1013 }
1014 );
1015 assert_eq!(
1016 resolve_busy(Some("later"), &defer),
1017 BusyPolicy::Defer {
1018 slot_wait: Duration::from_secs(5)
1019 }
1020 );
1021 assert_eq!(resolve_busy(Some(""), &none), BusyPolicy::Wait);
1022 assert_eq!(resolve_busy(Some("now"), &defer), BusyPolicy::Now);
1025 let committed = settings_from("set onBusy now\n");
1026 assert_eq!(resolve_busy(None, &committed), BusyPolicy::Wait);
1027 }
1028
1029 #[test]
1032 fn each_caller_waits_by_its_row_of_the_table() {
1033 use greenharness_slots::WaitBounds;
1034 let s = |n| Duration::from_secs(n);
1035 let (ceiling, warn) = (s(3600), s(600));
1036 let defer = BusyPolicy::Defer { slot_wait: s(60) };
1037 let queue = |window, ceiling| WaitPlan::Queue(WaitBounds { window, ceiling });
1038 let row =
1039 |slot_wait, policy, ceiling, seen| wait_plan(slot_wait, policy, ceiling, warn, seen);
1040 assert_eq!(
1043 row(
1044 SlotWait::Policy,
1045 BusyPolicy::Wait,
1046 ceiling,
1047 HostSeen::NotYet
1048 ),
1049 queue(None, ceiling)
1050 );
1051 assert_eq!(
1054 row(
1055 SlotWait::BoundedForWarn,
1056 BusyPolicy::Wait,
1057 ceiling,
1058 HostSeen::NotYet
1059 ),
1060 queue(None, warn)
1061 );
1062 assert_eq!(
1063 row(
1064 SlotWait::BoundedForWarn,
1065 BusyPolicy::Wait,
1066 s(100),
1067 HostSeen::NotYet
1068 ),
1069 queue(None, s(100))
1070 );
1071 assert_eq!(
1074 row(SlotWait::Policy, defer, ceiling, HostSeen::NotYet),
1075 queue(None, s(60))
1076 );
1077 assert_eq!(
1078 row(SlotWait::Policy, defer, ceiling, HostSeen::Busy),
1079 queue(None, Duration::ZERO)
1080 );
1081 assert_eq!(
1083 row(
1084 SlotWait::NeverWaits,
1085 BusyPolicy::Wait,
1086 ceiling,
1087 HostSeen::NotYet
1088 ),
1089 queue(None, Duration::ZERO)
1090 );
1091 assert_eq!(
1093 row(SlotWait::Policy, BusyPolicy::Now, ceiling, HostSeen::NotYet),
1094 WaitPlan::Now
1095 );
1096 }
1097
1098 #[test]
1102 fn the_sibling_extension_waits_to_the_ceiling() {
1103 let s = |n| Duration::from_secs(n);
1104 let with_sibling = sibling_bounds(SlotWait::Policy, 1, s(3600), s(60));
1105 assert_eq!(
1106 with_sibling.window, None,
1107 "no stall window on the hook path"
1108 );
1109 assert_eq!(with_sibling.ceiling, s(3540));
1110 let alone = sibling_bounds(SlotWait::Policy, 0, s(3600), s(60));
1111 assert_eq!((alone.window, alone.ceiling), (None, Duration::ZERO));
1112 let never = sibling_bounds(SlotWait::NeverWaits, 1, s(3600), s(60));
1113 assert_eq!((never.window, never.ceiling), (None, Duration::ZERO));
1114 }
1115
1116 #[test]
1120 fn a_deferral_names_its_cause() {
1121 use greenharness_slots::LineEnd;
1122 let stalled = LineEnd::Stalled {
1123 window: Duration::from_secs(300),
1124 position: 1,
1125 };
1126 let cause = defer_cause(
1127 &stalled,
1128 BusyPolicy::Defer {
1129 slot_wait: Duration::from_secs(60),
1130 },
1131 SlotWait::Policy,
1132 );
1133 assert!(cause.contains("made no progress for 5m00s"), "{cause}");
1134 assert!(cause.contains("(position 2)"), "{cause}");
1135 let slot_wait = defer_cause(
1136 &LineEnd::Ceiling {
1137 waited: Duration::from_secs(60),
1138 },
1139 BusyPolicy::Defer {
1140 slot_wait: Duration::from_secs(60),
1141 },
1142 SlotWait::Policy,
1143 );
1144 assert!(
1145 slot_wait.ends_with("(greengate.onBusy defer)"),
1146 "{slot_wait}"
1147 );
1148 let ceiling = defer_cause(
1149 &LineEnd::Ceiling {
1150 waited: Duration::from_secs(3600),
1151 },
1152 BusyPolicy::Wait,
1153 SlotWait::Policy,
1154 );
1155 assert!(ceiling.contains("no host slot within 1h00m"), "{ceiling}");
1156 assert!(ceiling.ends_with("(greengate.timeout)"), "{ceiling}");
1157 let warn = defer_cause(
1158 &LineEnd::Ceiling {
1159 waited: Duration::from_secs(600),
1160 },
1161 BusyPolicy::Wait,
1162 SlotWait::BoundedForWarn,
1163 );
1164 assert!(warn.ends_with("(greengate.warnSlotWait)"), "{warn}");
1165 let failed = defer_cause(
1166 &LineEnd::PollFailed {
1167 error: std::io::Error::other("busy disk"),
1168 },
1169 BusyPolicy::Wait,
1170 SlotWait::Policy,
1171 );
1172 assert!(failed.contains("busy disk"), "{failed}");
1173 }
1174
1175 #[test]
1178 fn every_end_of_a_wait_in_line_defers() {
1179 let ended = Reason::Ended(greenharness_slots::LineEnd::Ceiling {
1180 waited: Duration::from_secs(1),
1181 });
1182 assert!(ended.ended().is_some());
1183 for reason in [
1184 Reason::Io("x".into()),
1185 Reason::DirUnsafe("x".into()),
1186 Reason::Unsupported,
1187 ] {
1188 assert!(reason.ended().is_none(), "{reason:?}");
1189 }
1190 }
1191
1192 #[test]
1193 fn heavy_is_the_list() {
1194 assert_eq!(weight_of("pre-commit-clippy"), Weight::Heavy);
1195 assert_eq!(weight_of("pre-commit-cargo-fmt"), Weight::Light);
1196 }
1197
1198 #[test]
1201 fn every_heavy_name_is_a_builtin() {
1202 for name in HEAVY {
1203 assert!(
1204 crate::registry::CHECKS.iter().any(|c| c.name == *name),
1205 "{name} is not a built-in check"
1206 );
1207 }
1208 }
1209
1210 #[test]
1216 fn cargo_pins_the_host_knobs_for_tests() {
1217 assert_eq!(std::env::var(HELD_ENV).as_deref(), Ok(""));
1218 assert_eq!(
1219 std::env::var(greenharness_slots::host::SLOTS_ENV).as_deref(),
1220 Ok("0")
1221 );
1222 assert_eq!(
1223 std::env::var("GREENGATE_IDLE_LOAD_SCALE").as_deref(),
1224 Ok("1")
1225 );
1226 assert_eq!(
1227 std::env::var(greenharness_slots::host::PROMOTE_ENV).as_deref(),
1228 Ok("1")
1229 );
1230 }
1231
1232 #[test]
1236 fn a_light_check_never_takes_a_slot() {
1237 let settings = crate::config::Settings::default();
1238 let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1239 assert!(before_spawn(&settings).unwrap().is_none());
1240 }
1241
1242 #[test]
1243 fn a_heavy_check_with_slots_off_settles_without_a_slot() {
1244 let settings = crate::config::Settings::default();
1245 let _g = enter_check("pre-commit-clippy", weight_of("pre-commit-clippy"));
1246 assert_eq!(current_check().as_deref(), Some("clippy"));
1247 assert!(before_spawn(&settings).unwrap().is_none());
1248 assert!(CURRENT.with(|c| c.borrow().settled));
1249 let mut cmd = std::process::Command::new("true");
1251 bound(&mut cmd);
1252 assert_eq!(cmd.get_envs().count(), 0);
1253 }
1254
1255 #[test]
1258 fn a_park_scope_dropped_early_releases_the_parked_slot() {
1259 let dir = std::env::temp_dir().join(format!("greengate-park-{}", std::process::id()));
1260 let _ = std::fs::remove_dir_all(&dir); let early = || {
1262 let _scope = ParkScope::begin();
1263 let mut waiter = greenharness_slots::Waiter::new_in(
1264 &dir,
1265 greenharness_slots::Sizing::Fixed(1),
1266 1,
1267 greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, "gate"),
1268 )
1269 .unwrap();
1270 let greenharness_slots::Poll::Granted(lease) = waiter.poll().unwrap() else {
1271 panic!("the empty directory grants the slot");
1272 };
1273 assert!(dir.join("holders/slot-0.who").exists());
1274 park(lease, Some(2), Some((3, 6)));
1275 assert!(dir.join("holders/slot-0.who").exists());
1276 };
1277 early();
1278 assert!(!dir.join("holders/slot-0.who").exists());
1279 let _ = std::fs::remove_dir_all(&dir); }
1281
1282 #[test]
1283 fn a_light_check_sets_no_width() {
1284 let settings = crate::config::Settings::default();
1285 let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1286 before_spawn(&settings).unwrap();
1287 let mut cmd = std::process::Command::new("true");
1288 bound(&mut cmd);
1289 assert_eq!(cmd.get_envs().count(), 0);
1290 }
1291}