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,
264 deferred_end: Option<greenharness_slots::WaitEnd>,
266 jobs: Option<u32>,
270 sized: Option<(u32, u32)>,
273 slot_wait: SlotWait,
275 place: Option<greenharness_slots::WaitPlace>,
279}
280
281#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
283enum SlotWait {
284 #[default]
286 Policy,
287 NeverWaits,
293 BoundedForWarn,
297 Waits,
302}
303
304struct Parked {
307 lease: greenharness_slots::Lease,
308 jobs: Option<u32>,
309 sized: Option<(u32, u32)>,
310}
311
312static PARKED: Mutex<Option<Parked>> = Mutex::new(None);
316
317static PARK_SCOPE_DEPTH: AtomicUsize = AtomicUsize::new(0);
320
321fn parked() -> std::sync::MutexGuard<'static, Option<Parked>> {
322 PARKED
323 .lock()
324 .unwrap_or_else(|poisoned| poisoned.into_inner())
325}
326
327fn parking() -> bool {
331 PARK_SCOPE_DEPTH.load(Ordering::SeqCst) > 0 && crate::rehearsal::in_snapshot()
332}
333
334#[must_use = "the scope releases the parked slot when dropped"]
338pub struct ParkScope {
339 _private: (),
340}
341
342impl ParkScope {
343 #[must_use = "the scope releases the parked slot when dropped"]
344 pub fn begin() -> ParkScope {
345 PARK_SCOPE_DEPTH.fetch_add(1, Ordering::SeqCst);
346 ParkScope { _private: () }
347 }
348}
349
350impl Drop for ParkScope {
351 fn drop(&mut self) {
352 if PARK_SCOPE_DEPTH.fetch_sub(1, Ordering::SeqCst) == 1 {
353 release_parked();
354 }
355 }
356}
357
358pub fn release_parked() {
363 let leftover = parked().take();
364 drop(leftover);
365}
366
367fn between_gates() -> greenharness_slots::Holder {
369 holder_for("pre-push, between checks")
370}
371
372fn holder_for(command: &str) -> greenharness_slots::Holder {
377 let mut holder = greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, command);
378 if let Some(src) = crate::rehearsal::source_worktree() {
379 holder.repo = src.display().to_string();
380 }
381 holder
382}
383
384thread_local! {
385 static CURRENT: RefCell<Current> = RefCell::new(Current::default());
386}
387
388pub struct CheckGuard;
391
392impl CheckGuard {
393 pub fn queued(&self) -> Duration {
395 CURRENT.with(|c| c.borrow().queued)
396 }
397
398 pub fn deferred(&self) -> Option<Duration> {
401 CURRENT.with(|c| c.borrow().deferred)
402 }
403
404 pub fn deferred_end(&self) -> Option<(greenharness_slots::WaitEnd, String)> {
408 CURRENT.with(|c| {
409 let c = c.borrow();
410 c.deferred_end.map(|end| (end, c.deferred_cause.clone()))
411 })
412 }
413}
414
415pub fn deferred_here() -> bool {
418 CURRENT.with(|c| c.borrow().deferred.is_some())
419}
420
421fn refusal() -> std::io::Error {
425 let cause = CURRENT.with(|c| c.borrow().deferred_cause.clone());
426 std::io::Error::other(if cause.is_empty() {
427 "deferred to CI: the host is busy".to_string()
428 } else {
429 format!("deferred to CI: {cause}")
430 })
431}
432
433fn defer_cause(
436 end: &greenharness_slots::LineEnd,
437 policy: BusyPolicy,
438 slot_wait: SlotWait,
439) -> String {
440 use greenharness_slots::LineEnd;
441 let human = |d: Duration| crate::hooks::common::human_secs(d.as_secs());
442 match end {
443 LineEnd::Stalled { window, position } => format!(
446 "the host slot line made no progress for {} (position {})",
447 human(*window),
448 position + 1
449 ),
450 LineEnd::PollFailed { error } => {
451 format!("the host slot files failed: {error}")
452 }
453 LineEnd::Ceiling { waited } => match policy {
454 BusyPolicy::Defer { .. } => format!(
455 "no host slot freed in {} (greengate.onBusy defer)",
456 human(*waited)
457 ),
458 BusyPolicy::Wait | BusyPolicy::Now => {
459 let setting = match slot_wait {
462 SlotWait::BoundedForWarn => "greengate.warnSlotWait",
463 SlotWait::Policy | SlotWait::NeverWaits | SlotWait::Waits => {
464 "greengate.timeout"
465 }
466 };
467 format!("no host slot within {} ({setting})", human(*waited))
468 }
469 },
470 }
471}
472
473#[derive(Debug, Clone, Copy, PartialEq, Eq)]
476enum WaitPlan {
477 Now,
478 Queue(greenharness_slots::WaitBounds),
479}
480
481pub(crate) fn wait_ceiling_secs(timeout: u64) -> u64 {
485 match timeout {
486 0 => 3600,
487 secs => secs,
488 }
489}
490
491fn wait_plan(
498 slot_wait: SlotWait,
499 policy: BusyPolicy,
500 ceiling: Duration,
501 warn_wait: Duration,
502 seen: HostSeen,
503) -> WaitPlan {
504 let queue =
505 |window, ceiling| WaitPlan::Queue(greenharness_slots::WaitBounds { window, ceiling });
506 match (slot_wait, policy) {
507 (SlotWait::Waits, _) => queue(None, ceiling),
510 (_, BusyPolicy::Now) => WaitPlan::Now,
511 (SlotWait::NeverWaits, _) => queue(None, Duration::ZERO),
512 (SlotWait::BoundedForWarn, _) => queue(None, warn_wait.min(ceiling)),
513 (SlotWait::Policy, BusyPolicy::Wait) => queue(None, ceiling),
514 (SlotWait::Policy, BusyPolicy::Defer { slot_wait }) => match seen {
515 HostSeen::Busy => queue(None, Duration::ZERO),
517 HostSeen::NotYet => queue(None, slot_wait),
518 },
519 }
520}
521
522fn sibling_bounds(
529 slot_wait: SlotWait,
530 held_in_process: usize,
531 ceiling: Duration,
532 elapsed: Duration,
533) -> greenharness_slots::WaitBounds {
534 let waits_on_sibling = held_in_process > 0 && !matches!(slot_wait, SlotWait::NeverWaits);
535 if waits_on_sibling {
536 greenharness_slots::WaitBounds {
537 window: None,
538 ceiling: ceiling.saturating_sub(elapsed),
539 }
540 } else {
541 greenharness_slots::WaitBounds {
542 window: None,
543 ceiling: Duration::ZERO,
544 }
545 }
546}
547
548impl Drop for CheckGuard {
549 fn drop(&mut self) {
550 let finished = CURRENT.with(RefCell::take);
551 if let Some(lease) = finished.held {
552 if parking() {
553 park(lease, finished.jobs, finished.sized);
554 }
555 }
556 }
557}
558
559fn park(lease: greenharness_slots::Lease, jobs: Option<u32>, sized: Option<(u32, u32)>) {
562 if let Err(error) = lease.rename(&between_gates()) {
563 crate::hooks::common::say(&format!(
564 " host slot kept, but `{BIN} slots` may still name the previous check: {error}"
565 ));
566 }
567 let earlier = parked().replace(Parked { lease, jobs, sized });
568 drop(earlier);
569}
570
571pub fn enter_check(name: &str, weight: Weight) -> CheckGuard {
575 CURRENT.with(|c| {
576 *c.borrow_mut() = Current {
577 name: name.to_string(),
578 heavy: weight == Weight::Heavy,
579 ..Current::default()
580 }
581 });
582 CheckGuard
583}
584
585pub fn never_waits() {
593 CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::NeverWaits);
594}
595
596pub fn wait_bounded_for_warn() {
601 CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::BoundedForWarn);
602}
603
604pub fn rehearsal_place(place: greenharness_slots::WaitPlace) {
610 CURRENT.with(|current| {
611 let mut current = current.borrow_mut();
612 current.slot_wait = SlotWait::Waits;
613 current.place = Some(place);
614 });
615}
616
617fn warn_slot_wait(settings: &crate::config::Settings) -> Duration {
620 Duration::from_secs(
621 crate::config::integer_or(settings, "greengate.warnSlotWait", 600, 1..=3600) as u64,
622 )
623}
624
625pub fn current_check() -> Option<String> {
628 CURRENT.with(|c| {
629 let c = c.borrow();
630 (!c.name.is_empty()).then(|| crate::short_name(&c.name).to_string())
631 })
632}
633
634fn marker(settings: &crate::config::Settings) -> &greenharness_slots::Marker {
638 settings.marker.get_or_init(greenharness_slots::held_marker)
639}
640
641pub(crate) fn nested(settings: &crate::config::Settings) -> bool {
645 marker(settings).is_held()
646}
647
648pub(crate) fn marker_refused_note(settings: &crate::config::Settings) -> Option<String> {
651 let marker = marker(settings);
652 settings
653 .marker_log
654 .record(
655 &greenharness_slots::dir(),
656 crate::names::SLOT_HOLDER,
657 marker,
658 )
659 .then(|| greenharness_slots::refused_line(BIN, marker))
660 .flatten()
661}
662
663fn say_refusal(line: &str) {
667 if crate::live::current_sink().is_some() {
668 crate::hooks::common::say(line);
669 } else {
670 eprintln!("{line}");
671 }
672}
673
674pub fn before_spawn(settings: &crate::config::Settings) -> std::io::Result<Option<String>> {
682 let (pending, deferred, name, slot_wait) = CURRENT.with(|current| {
683 let current = current.borrow();
684 (
685 current.heavy && !current.settled,
686 current.deferred.is_some(),
687 current.name.clone(),
688 current.slot_wait,
689 )
690 });
691 if deferred {
694 return Err(refusal());
695 }
696 if pending {
697 if let Some(handed) = parking().then(|| parked().take()).flatten() {
698 return Ok(Some(take_handed(handed, &name)));
699 }
700 let (sizing, machine) = if nested(settings) {
704 (None, greenharness_slots::Machine::detect())
705 } else {
706 sizing_and_machine(settings)
707 };
708 let Some(sizing) = sizing else {
709 CURRENT.with(|c| c.borrow_mut().settled = true);
710 return Ok(None);
711 };
712 if !greenharness_slots::SUPPORTED {
713 CURRENT.with(|c| c.borrow_mut().settled = true);
714 return Ok(None);
715 }
716 let policy = match slot_wait {
717 SlotWait::NeverWaits => BusyPolicy::Defer {
718 slot_wait: Duration::ZERO,
719 },
720 SlotWait::BoundedForWarn | SlotWait::Waits => BusyPolicy::Wait,
721 SlotWait::Policy => busy_policy(settings),
722 };
723 let ceiling = Duration::from_secs(wait_ceiling_secs(crate::hooks::common::check_timeout(
724 settings,
725 )));
726 let seen = if BUSY_SEEN.load(Ordering::SeqCst) {
727 HostSeen::Busy
728 } else {
729 HostSeen::NotYet
730 };
731 let plan = wait_plan(slot_wait, policy, ceiling, warn_slot_wait(settings), seen);
732 let slot_cap = sizing.cap_for(machine.cores);
733 let cap = u64::from(slot_cap);
734 let jobs = greenharness_slots::parallelism(1, machine.cores, slot_cap);
737 let bounds = match plan {
738 WaitPlan::Queue(bounds) => bounds,
739 WaitPlan::Now => {
740 crate::hooks::common::say(&format!(
743 " running unqueued: {}=now skips the host slot queue",
744 crate::ui::highlight(ON_BUSY_ENV)
745 ));
746 record_acquisition(
747 &name,
748 Some(jobs),
749 Some((slot_cap, machine.cores)),
750 Duration::ZERO,
751 "now",
752 None,
753 );
754 CURRENT.with(|c| {
755 let mut c = c.borrow_mut();
756 c.settled = true;
757 c.jobs = Some(jobs);
758 c.sized = Some((slot_cap, machine.cores));
759 });
760 return Ok(None);
761 }
762 };
763 if let Some(line) = marker_refused_note(settings) {
765 say_refusal(&line);
766 }
767 let sink = crate::live::current_sink();
768 if let Some((stage, idx)) = &sink {
769 stage.queue(*idx, Some((Instant::now(), cap)));
770 }
771 let started = Instant::now();
772 let holder = holder_for(&name);
773 let mut got = wait_for_slot(sizing, machine, holder.clone(), bounds);
774 if let (
775 BusyPolicy::Defer { .. },
776 Err(Reason::Ended(greenharness_slots::LineEnd::Ceiling { .. })),
777 ) = (policy, &got)
778 {
779 let more = sibling_bounds(
780 slot_wait,
781 greenharness_slots::held_in_process(),
782 ceiling,
783 started.elapsed(),
784 );
785 got = wait_for_slot(sizing, machine, holder, more);
786 }
787 if let Some((stage, idx)) = &sink {
788 stage.queue(*idx, None);
789 }
790 let waited = started.elapsed();
791 CURRENT.with(|c| c.borrow_mut().queued += waited);
792 if got.is_ok() && waited >= Duration::from_secs(1) {
795 crate::hooks::common::say(&format!(
796 " (waited {} for a host slot, {} {cap})",
797 crate::hooks::common::human_secs(waited.as_secs()),
798 crate::ui::highlight("greengate.hostSlots")
799 ));
800 }
801 let ended = got.as_ref().err().and_then(Reason::ended);
804 let defer = ended.is_some();
805 let end = ended.map(greenharness_slots::LineEnd::end);
806 let cause = ended.map_or(String::new(), |end| defer_cause(end, policy, slot_wait));
807 let by_slot_wait = matches!(
808 (policy, ended),
809 (
810 BusyPolicy::Defer { .. },
811 Some(greenharness_slots::LineEnd::Ceiling { .. })
812 )
813 );
814 let outcome = match (&got, defer) {
815 (Ok(_), _) => "admitted",
816 (Err(_), true) => "deferred",
817 (Err(_), false) => "unqueued",
818 };
819 record_acquisition(
820 &name,
821 Some(jobs),
822 Some((slot_cap, machine.cores)),
823 waited,
824 outcome,
825 end,
826 );
827 let held = match got {
828 Ok(lease) => Some(lease),
829 Err(Reason::Ended(_)) => None,
831 Err(reason) => {
832 note(&reason);
833 None
834 }
835 };
836 if defer {
837 BUSY_SEEN.store(true, Ordering::SeqCst);
838 if by_slot_wait {
839 DEFERRED_BY_SLOT_WAIT.store(true, Ordering::SeqCst);
840 }
841 }
842 CURRENT.with(|c| {
843 let mut c = c.borrow_mut();
844 c.held = held;
845 c.settled = true;
846 c.jobs = Some(jobs);
847 c.sized = Some((slot_cap, machine.cores));
848 if defer {
849 c.deferred = Some(waited);
850 c.deferred_cause = cause;
851 c.deferred_end = end;
852 }
853 });
854 if defer {
855 return Err(refusal());
856 }
857 }
858 let own = CURRENT.with(|c| {
862 c.borrow()
863 .held
864 .as_ref()
865 .map(greenharness_slots::Lease::marker)
866 });
867 Ok(own.or_else(|| {
868 if parking() {
869 parked().as_ref().map(|p| p.lease.marker())
870 } else {
871 None
872 }
873 }))
874}
875
876fn take_handed(handed: Parked, name: &str) -> String {
880 let Parked { lease, jobs, sized } = handed;
881 if let Err(error) = lease.rename(&holder_for(name)) {
882 crate::hooks::common::say(&format!(
883 " host slot kept, but `{BIN} slots` may still name the previous check: {error}"
884 ));
885 }
886 record_acquisition(name, jobs, sized, Duration::ZERO, "handed", None);
887 let marker = lease.marker();
888 CURRENT.with(|current| {
889 let mut current = current.borrow_mut();
890 current.held = Some(lease);
891 current.settled = true;
892 current.jobs = jobs;
893 current.sized = sized;
894 });
895 marker
896}
897
898fn record_acquisition(
901 name: &str,
902 jobs: Option<u32>,
903 sized: Option<(u32, u32)>,
904 waited: Duration,
905 outcome: &str,
906 end: Option<greenharness_slots::WaitEnd>,
907) {
908 let short = crate::short_name(name);
909 let own_place = CURRENT.with(|c| c.borrow().place);
910 greenharness_slots::record_wait_named(
911 &greenharness_slots::dir(),
912 crate::names::SLOT_HOLDER,
913 greenharness_slots::WaitContext {
914 name: Some(short),
915 place: if let Some(place) = own_place {
916 place
917 } else if crate::rehearsal::in_prestage() {
918 greenharness_slots::WaitPlace::Prestage
919 } else if crate::rehearsal::in_snapshot() {
920 greenharness_slots::WaitPlace::Rehearsal
921 } else {
922 greenharness_slots::WaitPlace::Push
923 },
924 cap: sized.map(|(cap, _)| cap),
925 cores: sized.map(|(_, cores)| cores),
926 end,
927 },
928 1,
929 jobs,
930 waited.as_millis(),
931 outcome,
932 );
933}
934
935pub fn bound(cmd: &mut std::process::Command) {
939 let own = CURRENT.with(|c| c.borrow().jobs);
940 if let Some(jobs) = own.or_else(|| {
942 parking()
943 .then(|| parked().as_ref().and_then(|p| p.jobs))
944 .flatten()
945 }) {
946 greenharness_slots::bound_width(cmd, jobs);
947 }
948}
949
950fn wait_for_slot(
954 sizing: greenharness_slots::Sizing,
955 machine: greenharness_slots::Machine,
956 holder: greenharness_slots::Holder,
957 bounds: greenharness_slots::WaitBounds,
958) -> Result<greenharness_slots::Lease, Reason> {
959 let waiter = match greenharness_slots::Waiter::new_in_on(
960 &greenharness_slots::dir(),
961 sizing,
962 1,
963 holder,
964 machine,
965 ) {
966 Ok(w) => w,
967 Err(e) if e.kind() == std::io::ErrorKind::Other => {
968 return Err(Reason::DirUnsafe(e.to_string()))
969 }
970 Err(e) => return Err(Reason::Io(e.to_string())),
971 };
972 let mut said = false;
973 greenharness_slots::wait_in_line(waiter, bounds, |queue| {
974 if !said && (!queue.holders.is_empty() || queue.unknown > 0) {
975 said = true;
976 crate::hooks::common::say(&format!(" {}", behind(queue)));
977 crate::hooks::common::say(&format!(" see: {BIN} slots"));
978 }
979 })
980 .map_err(Reason::Ended)
981}
982
983pub fn behind(queue: &greenharness_slots::Queue) -> String {
985 let now = greenharness_slots::now_ms();
986 let mut who: Vec<String> = queue.holders.iter().map(|h| h.describe(now)).collect();
987 if queue.unknown > 0 {
988 who.push(format!("{} unknown (old client)", queue.unknown));
989 }
990 let reason = queue
991 .reason
992 .map_or(String::new(), |r| format!(" ({})", r.describe()));
993 format!(
994 "queued behind {}{reason} · {} waiting",
995 who.join(", "),
996 queue.waiting.max(1)
997 )
998}
999
1000fn note(reason: &Reason) {
1004 match reason {
1005 Reason::DirUnsafe(why) => crate::hooks::common::warn(&format!(
1006 "host slots are off for this check: {why}. Remove it, or set {} to a directory \
1007 only you own",
1008 crate::ui::highlight(DIR_ENV)
1009 )),
1010 Reason::Io(why) => {
1011 crate::hooks::common::warn(&format!("host slots are off for this check: {why}"))
1012 }
1013 Reason::Ended(_) | Reason::Unsupported => {}
1014 }
1015}
1016
1017#[cfg(all(test, unix))]
1018mod tests {
1019 use super::*;
1020
1021 fn settings_from(conf: &str) -> crate::config::Settings {
1022 let lines = crate::manifest::parse_lines(conf);
1023 let (policy, _) = crate::policy::Policy::from_lines(&lines);
1024 crate::config::Settings::new(policy)
1025 }
1026
1027 #[test]
1030 fn the_busy_policy_is_env_then_file_then_wait() {
1031 let none = settings_from("");
1032 let defer = settings_from("set onBusy defer\nset slotWait 5\n");
1033 assert_eq!(resolve_busy(None, &none), BusyPolicy::Wait);
1034 assert_eq!(
1035 resolve_busy(None, &defer),
1036 BusyPolicy::Defer {
1037 slot_wait: Duration::from_secs(5)
1038 }
1039 );
1040 assert_eq!(resolve_busy(Some("wait"), &defer), BusyPolicy::Wait);
1041 assert_eq!(
1042 resolve_busy(Some("DEFER"), &none),
1043 BusyPolicy::Defer {
1044 slot_wait: Duration::from_secs(60)
1045 }
1046 );
1047 assert_eq!(
1048 resolve_busy(Some("later"), &defer),
1049 BusyPolicy::Defer {
1050 slot_wait: Duration::from_secs(5)
1051 }
1052 );
1053 assert_eq!(resolve_busy(Some(""), &none), BusyPolicy::Wait);
1054 assert_eq!(resolve_busy(Some("now"), &defer), BusyPolicy::Now);
1057 let committed = settings_from("set onBusy now\n");
1058 assert_eq!(resolve_busy(None, &committed), BusyPolicy::Wait);
1059 }
1060
1061 #[test]
1064 fn each_caller_waits_by_its_row_of_the_table() {
1065 use greenharness_slots::WaitBounds;
1066 let s = |n| Duration::from_secs(n);
1067 let (ceiling, warn) = (s(3600), s(600));
1068 let defer = BusyPolicy::Defer { slot_wait: s(60) };
1069 let queue = |window, ceiling| WaitPlan::Queue(WaitBounds { window, ceiling });
1070 let row =
1071 |slot_wait, policy, ceiling, seen| wait_plan(slot_wait, policy, ceiling, warn, seen);
1072 assert_eq!(
1075 row(
1076 SlotWait::Policy,
1077 BusyPolicy::Wait,
1078 ceiling,
1079 HostSeen::NotYet
1080 ),
1081 queue(None, ceiling)
1082 );
1083 assert_eq!(
1086 row(
1087 SlotWait::BoundedForWarn,
1088 BusyPolicy::Wait,
1089 ceiling,
1090 HostSeen::NotYet
1091 ),
1092 queue(None, warn)
1093 );
1094 assert_eq!(
1095 row(
1096 SlotWait::BoundedForWarn,
1097 BusyPolicy::Wait,
1098 s(100),
1099 HostSeen::NotYet
1100 ),
1101 queue(None, s(100))
1102 );
1103 assert_eq!(
1106 row(SlotWait::Policy, defer, ceiling, HostSeen::NotYet),
1107 queue(None, s(60))
1108 );
1109 assert_eq!(
1110 row(SlotWait::Policy, defer, ceiling, HostSeen::Busy),
1111 queue(None, Duration::ZERO)
1112 );
1113 assert_eq!(
1115 row(
1116 SlotWait::NeverWaits,
1117 BusyPolicy::Wait,
1118 ceiling,
1119 HostSeen::NotYet
1120 ),
1121 queue(None, Duration::ZERO)
1122 );
1123 assert_eq!(
1125 row(SlotWait::Policy, BusyPolicy::Now, ceiling, HostSeen::NotYet),
1126 WaitPlan::Now
1127 );
1128 for policy in [BusyPolicy::Wait, defer, BusyPolicy::Now] {
1131 assert_eq!(
1132 row(SlotWait::Waits, policy, ceiling, HostSeen::Busy),
1133 queue(None, ceiling)
1134 );
1135 }
1136 }
1137
1138 #[test]
1141 fn rehearsal_place_sets_the_wait_mode_and_the_place() {
1142 let _g = enter_check("snapshot-prepare", Weight::Heavy);
1143 rehearsal_place(greenharness_slots::WaitPlace::Prestage);
1144 CURRENT.with(|c| {
1145 let c = c.borrow();
1146 assert!(c.heavy);
1147 assert_eq!(c.slot_wait, SlotWait::Waits);
1148 assert_eq!(c.place, Some(greenharness_slots::WaitPlace::Prestage));
1149 });
1150 rehearsal_place(greenharness_slots::WaitPlace::Rehearsal);
1151 CURRENT.with(|c| {
1152 assert_eq!(
1153 c.borrow().place,
1154 Some(greenharness_slots::WaitPlace::Rehearsal)
1155 );
1156 });
1157 }
1158
1159 #[test]
1163 fn the_sibling_extension_waits_to_the_ceiling() {
1164 let s = |n| Duration::from_secs(n);
1165 let with_sibling = sibling_bounds(SlotWait::Policy, 1, s(3600), s(60));
1166 assert_eq!(
1167 with_sibling.window, None,
1168 "no stall window on the hook path"
1169 );
1170 assert_eq!(with_sibling.ceiling, s(3540));
1171 let alone = sibling_bounds(SlotWait::Policy, 0, s(3600), s(60));
1172 assert_eq!((alone.window, alone.ceiling), (None, Duration::ZERO));
1173 let never = sibling_bounds(SlotWait::NeverWaits, 1, s(3600), s(60));
1174 assert_eq!((never.window, never.ceiling), (None, Duration::ZERO));
1175 }
1176
1177 #[test]
1181 fn a_deferral_names_its_cause() {
1182 use greenharness_slots::LineEnd;
1183 let stalled = LineEnd::Stalled {
1184 window: Duration::from_secs(300),
1185 position: 1,
1186 };
1187 let cause = defer_cause(
1188 &stalled,
1189 BusyPolicy::Defer {
1190 slot_wait: Duration::from_secs(60),
1191 },
1192 SlotWait::Policy,
1193 );
1194 assert!(cause.contains("made no progress for 5m00s"), "{cause}");
1195 assert!(cause.contains("(position 2)"), "{cause}");
1196 let slot_wait = defer_cause(
1197 &LineEnd::Ceiling {
1198 waited: Duration::from_secs(60),
1199 },
1200 BusyPolicy::Defer {
1201 slot_wait: Duration::from_secs(60),
1202 },
1203 SlotWait::Policy,
1204 );
1205 assert!(
1206 slot_wait.ends_with("(greengate.onBusy defer)"),
1207 "{slot_wait}"
1208 );
1209 let ceiling = defer_cause(
1210 &LineEnd::Ceiling {
1211 waited: Duration::from_secs(3600),
1212 },
1213 BusyPolicy::Wait,
1214 SlotWait::Policy,
1215 );
1216 assert!(ceiling.contains("no host slot within 1h00m"), "{ceiling}");
1217 assert!(ceiling.ends_with("(greengate.timeout)"), "{ceiling}");
1218 let warn = defer_cause(
1219 &LineEnd::Ceiling {
1220 waited: Duration::from_secs(600),
1221 },
1222 BusyPolicy::Wait,
1223 SlotWait::BoundedForWarn,
1224 );
1225 assert!(warn.ends_with("(greengate.warnSlotWait)"), "{warn}");
1226 let failed = defer_cause(
1227 &LineEnd::PollFailed {
1228 error: std::io::Error::other("busy disk"),
1229 },
1230 BusyPolicy::Wait,
1231 SlotWait::Policy,
1232 );
1233 assert!(failed.contains("busy disk"), "{failed}");
1234 for cause in [&cause, &slot_wait, &ceiling, &warn, &failed] {
1236 assert!(!cause.contains("deferred to CI"), "{cause}");
1237 }
1238 }
1239
1240 #[test]
1243 fn every_end_of_a_wait_in_line_defers() {
1244 let ended = Reason::Ended(greenharness_slots::LineEnd::Ceiling {
1245 waited: Duration::from_secs(1),
1246 });
1247 assert!(ended.ended().is_some());
1248 for reason in [
1249 Reason::Io("x".into()),
1250 Reason::DirUnsafe("x".into()),
1251 Reason::Unsupported,
1252 ] {
1253 assert!(reason.ended().is_none(), "{reason:?}");
1254 }
1255 }
1256
1257 #[test]
1258 fn heavy_is_the_list() {
1259 assert_eq!(weight_of("pre-commit-clippy"), Weight::Heavy);
1260 assert_eq!(weight_of("pre-commit-cargo-fmt"), Weight::Light);
1261 }
1262
1263 #[test]
1266 fn every_heavy_name_is_a_builtin() {
1267 for name in HEAVY {
1268 assert!(
1269 crate::registry::CHECKS.iter().any(|c| c.name == *name),
1270 "{name} is not a built-in check"
1271 );
1272 }
1273 }
1274
1275 #[test]
1281 fn cargo_pins_the_host_knobs_for_tests() {
1282 assert_eq!(std::env::var(HELD_ENV).as_deref(), Ok(""));
1283 assert_eq!(
1284 std::env::var(greenharness_slots::host::SLOTS_ENV).as_deref(),
1285 Ok("0")
1286 );
1287 assert_eq!(
1288 std::env::var("GREENGATE_IDLE_LOAD_SCALE").as_deref(),
1289 Ok("1")
1290 );
1291 assert_eq!(
1292 std::env::var(greenharness_slots::host::PROMOTE_ENV).as_deref(),
1293 Ok("1")
1294 );
1295 }
1296
1297 #[test]
1301 fn a_light_check_never_takes_a_slot() {
1302 let settings = crate::config::Settings::default();
1303 let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1304 assert!(before_spawn(&settings).unwrap().is_none());
1305 }
1306
1307 #[test]
1308 fn a_heavy_check_with_slots_off_settles_without_a_slot() {
1309 let settings = crate::config::Settings::default();
1310 let _g = enter_check("pre-commit-clippy", weight_of("pre-commit-clippy"));
1311 assert_eq!(current_check().as_deref(), Some("clippy"));
1312 assert!(before_spawn(&settings).unwrap().is_none());
1313 assert!(CURRENT.with(|c| c.borrow().settled));
1314 let mut cmd = std::process::Command::new("true");
1316 bound(&mut cmd);
1317 assert_eq!(cmd.get_envs().count(), 0);
1318 }
1319
1320 #[test]
1323 fn a_park_scope_dropped_early_releases_the_parked_slot() {
1324 let dir = std::env::temp_dir().join(format!("greengate-park-{}", std::process::id()));
1325 let _ = std::fs::remove_dir_all(&dir); let early = || {
1327 let _scope = ParkScope::begin();
1328 let mut waiter = greenharness_slots::Waiter::new_in(
1329 &dir,
1330 greenharness_slots::Sizing::Fixed(1),
1331 1,
1332 greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, "gate"),
1333 )
1334 .unwrap();
1335 let greenharness_slots::Poll::Granted(lease) = waiter.poll().unwrap() else {
1336 panic!("the empty directory grants the slot");
1337 };
1338 assert!(dir.join("holders/slot-0.who").exists());
1339 park(lease, Some(2), Some((3, 6)));
1340 assert!(dir.join("holders/slot-0.who").exists());
1341 };
1342 early();
1343 assert!(!dir.join("holders/slot-0.who").exists());
1344 let _ = std::fs::remove_dir_all(&dir); }
1346
1347 #[test]
1348 fn a_light_check_sets_no_width() {
1349 let settings = crate::config::Settings::default();
1350 let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1351 before_spawn(&settings).unwrap();
1352 let mut cmd = std::process::Command::new("true");
1353 bound(&mut cmd);
1354 assert_eq!(cmd.get_envs().count(), 0);
1355 }
1356}