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 {
647 let marker = marker(settings);
648 if matches!(marker, greenharness_slots::Marker::Held { bare: true }) {
649 settings.marker_log.record(
650 &greenharness_slots::dir(),
651 crate::names::SLOT_HOLDER,
652 marker,
653 );
654 }
655 marker.is_held()
656}
657
658pub(crate) fn marker_refused_note(settings: &crate::config::Settings) -> Option<String> {
661 let marker = marker(settings);
662 settings
663 .marker_log
664 .record(
665 &greenharness_slots::dir(),
666 crate::names::SLOT_HOLDER,
667 marker,
668 )
669 .then(|| greenharness_slots::refused_line(BIN, marker))
670 .flatten()
671}
672
673fn say_refusal(line: &str) {
677 if crate::live::current_sink().is_some() {
678 crate::hooks::common::say(line);
679 } else {
680 eprintln!("{line}");
681 }
682}
683
684pub fn before_spawn(settings: &crate::config::Settings) -> std::io::Result<Option<String>> {
692 let (pending, deferred, name, slot_wait) = CURRENT.with(|current| {
693 let current = current.borrow();
694 (
695 current.heavy && !current.settled,
696 current.deferred.is_some(),
697 current.name.clone(),
698 current.slot_wait,
699 )
700 });
701 if deferred {
704 return Err(refusal());
705 }
706 if pending {
707 if let Some(handed) = parking().then(|| parked().take()).flatten() {
708 return Ok(Some(take_handed(handed, &name)));
709 }
710 let (sizing, machine) = if nested(settings) {
714 (None, greenharness_slots::Machine::detect())
715 } else {
716 sizing_and_machine(settings)
717 };
718 let Some(sizing) = sizing else {
719 CURRENT.with(|c| c.borrow_mut().settled = true);
720 return Ok(None);
721 };
722 if !greenharness_slots::SUPPORTED {
723 CURRENT.with(|c| c.borrow_mut().settled = true);
724 return Ok(None);
725 }
726 let policy = match slot_wait {
727 SlotWait::NeverWaits => BusyPolicy::Defer {
728 slot_wait: Duration::ZERO,
729 },
730 SlotWait::BoundedForWarn | SlotWait::Waits => BusyPolicy::Wait,
731 SlotWait::Policy => busy_policy(settings),
732 };
733 let ceiling = Duration::from_secs(wait_ceiling_secs(crate::hooks::common::check_timeout(
734 settings,
735 )));
736 let seen = if BUSY_SEEN.load(Ordering::SeqCst) {
737 HostSeen::Busy
738 } else {
739 HostSeen::NotYet
740 };
741 let plan = wait_plan(slot_wait, policy, ceiling, warn_slot_wait(settings), seen);
742 let slot_cap = sizing.cap_for(machine.cores);
743 let cap = u64::from(slot_cap);
744 let jobs = greenharness_slots::parallelism(1, machine.cores, slot_cap);
747 let bounds = match plan {
748 WaitPlan::Queue(bounds) => bounds,
749 WaitPlan::Now => {
750 crate::hooks::common::say(&format!(
753 " running unqueued: {}=now skips the host slot queue",
754 crate::ui::highlight(ON_BUSY_ENV)
755 ));
756 record_acquisition(
757 &name,
758 Some(jobs),
759 Some((slot_cap, machine.cores)),
760 Duration::ZERO,
761 "now",
762 None,
763 );
764 CURRENT.with(|c| {
765 let mut c = c.borrow_mut();
766 c.settled = true;
767 c.jobs = Some(jobs);
768 c.sized = Some((slot_cap, machine.cores));
769 });
770 return Ok(None);
771 }
772 };
773 if let Some(line) = marker_refused_note(settings) {
775 say_refusal(&line);
776 }
777 let sink = crate::live::current_sink();
778 if let Some((stage, idx)) = &sink {
779 stage.queue(*idx, Some((Instant::now(), cap)));
780 }
781 let started = Instant::now();
782 let holder = holder_for(&name);
783 let mut got = wait_for_slot(sizing, machine, holder.clone(), bounds);
784 if let (
785 BusyPolicy::Defer { .. },
786 Err(Reason::Ended(greenharness_slots::LineEnd::Ceiling { .. })),
787 ) = (policy, &got)
788 {
789 let more = sibling_bounds(
790 slot_wait,
791 greenharness_slots::held_in_process(),
792 ceiling,
793 started.elapsed(),
794 );
795 got = wait_for_slot(sizing, machine, holder, more);
796 }
797 if let Some((stage, idx)) = &sink {
798 stage.queue(*idx, None);
799 }
800 let waited = started.elapsed();
801 CURRENT.with(|c| c.borrow_mut().queued += waited);
802 if got.is_ok() && waited >= Duration::from_secs(1) {
805 crate::hooks::common::say(&format!(
806 " (waited {} for a host slot, {} {cap})",
807 crate::hooks::common::human_secs(waited.as_secs()),
808 crate::ui::highlight("greengate.hostSlots")
809 ));
810 }
811 let ended = got.as_ref().err().and_then(Reason::ended);
814 let defer = ended.is_some();
815 let end = ended.map(greenharness_slots::LineEnd::end);
816 let cause = ended.map_or(String::new(), |end| defer_cause(end, policy, slot_wait));
817 let by_slot_wait = matches!(
818 (policy, ended),
819 (
820 BusyPolicy::Defer { .. },
821 Some(greenharness_slots::LineEnd::Ceiling { .. })
822 )
823 );
824 let outcome = match (&got, defer) {
825 (Ok(_), _) => "admitted",
826 (Err(_), true) => "deferred",
827 (Err(_), false) => "unqueued",
828 };
829 record_acquisition(
830 &name,
831 Some(jobs),
832 Some((slot_cap, machine.cores)),
833 waited,
834 outcome,
835 end,
836 );
837 let held = match got {
838 Ok(lease) => Some(lease),
839 Err(Reason::Ended(_)) => None,
841 Err(reason) => {
842 note(&reason);
843 None
844 }
845 };
846 if defer {
847 BUSY_SEEN.store(true, Ordering::SeqCst);
848 if by_slot_wait {
849 DEFERRED_BY_SLOT_WAIT.store(true, Ordering::SeqCst);
850 }
851 }
852 CURRENT.with(|c| {
853 let mut c = c.borrow_mut();
854 c.held = held;
855 c.settled = true;
856 c.jobs = Some(jobs);
857 c.sized = Some((slot_cap, machine.cores));
858 if defer {
859 c.deferred = Some(waited);
860 c.deferred_cause = cause;
861 c.deferred_end = end;
862 }
863 });
864 if defer {
865 return Err(refusal());
866 }
867 }
868 let own = CURRENT.with(|c| {
872 c.borrow()
873 .held
874 .as_ref()
875 .map(greenharness_slots::Lease::marker)
876 });
877 Ok(own.or_else(|| {
878 if parking() {
879 parked().as_ref().map(|p| p.lease.marker())
880 } else {
881 None
882 }
883 }))
884}
885
886fn take_handed(handed: Parked, name: &str) -> String {
890 let Parked { lease, jobs, sized } = handed;
891 if let Err(error) = lease.rename(&holder_for(name)) {
892 crate::hooks::common::say(&format!(
893 " host slot kept, but `{BIN} slots` may still name the previous check: {error}"
894 ));
895 }
896 record_acquisition(name, jobs, sized, Duration::ZERO, "handed", None);
897 let marker = lease.marker();
898 CURRENT.with(|current| {
899 let mut current = current.borrow_mut();
900 current.held = Some(lease);
901 current.settled = true;
902 current.jobs = jobs;
903 current.sized = sized;
904 });
905 marker
906}
907
908fn record_acquisition(
911 name: &str,
912 jobs: Option<u32>,
913 sized: Option<(u32, u32)>,
914 waited: Duration,
915 outcome: &str,
916 end: Option<greenharness_slots::WaitEnd>,
917) {
918 let short = crate::short_name(name);
919 let own_place = CURRENT.with(|c| c.borrow().place);
920 greenharness_slots::record_wait_named(
921 &greenharness_slots::dir(),
922 crate::names::SLOT_HOLDER,
923 greenharness_slots::WaitContext {
924 name: Some(short),
925 place: if let Some(place) = own_place {
926 place
927 } else if crate::rehearsal::in_prestage() {
928 greenharness_slots::WaitPlace::Prestage
929 } else if crate::rehearsal::in_snapshot() {
930 greenharness_slots::WaitPlace::Rehearsal
931 } else {
932 greenharness_slots::WaitPlace::Push
933 },
934 cap: sized.map(|(cap, _)| cap),
935 cores: sized.map(|(_, cores)| cores),
936 end,
937 },
938 1,
939 jobs,
940 waited.as_millis(),
941 outcome,
942 );
943}
944
945pub fn bound(cmd: &mut std::process::Command) {
949 let own = CURRENT.with(|c| c.borrow().jobs);
950 if let Some(jobs) = own.or_else(|| {
952 parking()
953 .then(|| parked().as_ref().and_then(|p| p.jobs))
954 .flatten()
955 }) {
956 greenharness_slots::bound_width(cmd, jobs);
957 }
958}
959
960fn wait_for_slot(
964 sizing: greenharness_slots::Sizing,
965 machine: greenharness_slots::Machine,
966 holder: greenharness_slots::Holder,
967 bounds: greenharness_slots::WaitBounds,
968) -> Result<greenharness_slots::Lease, Reason> {
969 let waiter = match greenharness_slots::Waiter::new_in_on(
970 &greenharness_slots::dir(),
971 sizing,
972 1,
973 holder,
974 machine,
975 ) {
976 Ok(w) => w,
977 Err(e) if e.kind() == std::io::ErrorKind::Other => {
978 return Err(Reason::DirUnsafe(e.to_string()))
979 }
980 Err(e) => return Err(Reason::Io(e.to_string())),
981 };
982 let mut said = false;
983 greenharness_slots::wait_in_line(waiter, bounds, |queue| {
984 if !said && (!queue.holders.is_empty() || queue.unknown > 0) {
985 said = true;
986 crate::hooks::common::say(&format!(" {}", behind(queue)));
987 crate::hooks::common::say(&format!(" see: {BIN} slots"));
988 }
989 })
990 .map_err(Reason::Ended)
991}
992
993pub fn behind(queue: &greenharness_slots::Queue) -> String {
995 let now = greenharness_slots::now_ms();
996 let mut who: Vec<String> = queue.holders.iter().map(|h| h.describe(now)).collect();
997 if queue.unknown > 0 {
998 who.push(format!("{} unknown (old client)", queue.unknown));
999 }
1000 let reason = queue
1001 .reason
1002 .map_or(String::new(), |r| format!(" ({})", r.describe()));
1003 format!(
1004 "queued behind {}{reason} · {} waiting",
1005 who.join(", "),
1006 queue.waiting.max(1)
1007 )
1008}
1009
1010fn note(reason: &Reason) {
1014 match reason {
1015 Reason::DirUnsafe(why) => crate::hooks::common::warn(&format!(
1016 "host slots are off for this check: {why}. Remove it, or set {} to a directory \
1017 only you own",
1018 crate::ui::highlight(DIR_ENV)
1019 )),
1020 Reason::Io(why) => {
1021 crate::hooks::common::warn(&format!("host slots are off for this check: {why}"))
1022 }
1023 Reason::Ended(_) | Reason::Unsupported => {}
1024 }
1025}
1026
1027#[cfg(all(test, unix))]
1028mod tests {
1029 use super::*;
1030
1031 fn settings_from(conf: &str) -> crate::config::Settings {
1032 let lines = crate::manifest::parse_lines(conf);
1033 let (policy, _) = crate::policy::Policy::from_lines(&lines);
1034 crate::config::Settings::new(policy)
1035 }
1036
1037 #[test]
1040 fn the_busy_policy_is_env_then_file_then_wait() {
1041 let none = settings_from("");
1042 let defer = settings_from("set onBusy defer\nset slotWait 5\n");
1043 assert_eq!(resolve_busy(None, &none), BusyPolicy::Wait);
1044 assert_eq!(
1045 resolve_busy(None, &defer),
1046 BusyPolicy::Defer {
1047 slot_wait: Duration::from_secs(5)
1048 }
1049 );
1050 assert_eq!(resolve_busy(Some("wait"), &defer), BusyPolicy::Wait);
1051 assert_eq!(
1052 resolve_busy(Some("DEFER"), &none),
1053 BusyPolicy::Defer {
1054 slot_wait: Duration::from_secs(60)
1055 }
1056 );
1057 assert_eq!(
1058 resolve_busy(Some("later"), &defer),
1059 BusyPolicy::Defer {
1060 slot_wait: Duration::from_secs(5)
1061 }
1062 );
1063 assert_eq!(resolve_busy(Some(""), &none), BusyPolicy::Wait);
1064 assert_eq!(resolve_busy(Some("now"), &defer), BusyPolicy::Now);
1067 let committed = settings_from("set onBusy now\n");
1068 assert_eq!(resolve_busy(None, &committed), BusyPolicy::Wait);
1069 }
1070
1071 #[test]
1074 fn each_caller_waits_by_its_row_of_the_table() {
1075 use greenharness_slots::WaitBounds;
1076 let s = |n| Duration::from_secs(n);
1077 let (ceiling, warn) = (s(3600), s(600));
1078 let defer = BusyPolicy::Defer { slot_wait: s(60) };
1079 let queue = |window, ceiling| WaitPlan::Queue(WaitBounds { window, ceiling });
1080 let row =
1081 |slot_wait, policy, ceiling, seen| wait_plan(slot_wait, policy, ceiling, warn, seen);
1082 assert_eq!(
1085 row(
1086 SlotWait::Policy,
1087 BusyPolicy::Wait,
1088 ceiling,
1089 HostSeen::NotYet
1090 ),
1091 queue(None, ceiling)
1092 );
1093 assert_eq!(
1096 row(
1097 SlotWait::BoundedForWarn,
1098 BusyPolicy::Wait,
1099 ceiling,
1100 HostSeen::NotYet
1101 ),
1102 queue(None, warn)
1103 );
1104 assert_eq!(
1105 row(
1106 SlotWait::BoundedForWarn,
1107 BusyPolicy::Wait,
1108 s(100),
1109 HostSeen::NotYet
1110 ),
1111 queue(None, s(100))
1112 );
1113 assert_eq!(
1116 row(SlotWait::Policy, defer, ceiling, HostSeen::NotYet),
1117 queue(None, s(60))
1118 );
1119 assert_eq!(
1120 row(SlotWait::Policy, defer, ceiling, HostSeen::Busy),
1121 queue(None, Duration::ZERO)
1122 );
1123 assert_eq!(
1125 row(
1126 SlotWait::NeverWaits,
1127 BusyPolicy::Wait,
1128 ceiling,
1129 HostSeen::NotYet
1130 ),
1131 queue(None, Duration::ZERO)
1132 );
1133 assert_eq!(
1135 row(SlotWait::Policy, BusyPolicy::Now, ceiling, HostSeen::NotYet),
1136 WaitPlan::Now
1137 );
1138 for policy in [BusyPolicy::Wait, defer, BusyPolicy::Now] {
1141 assert_eq!(
1142 row(SlotWait::Waits, policy, ceiling, HostSeen::Busy),
1143 queue(None, ceiling)
1144 );
1145 }
1146 }
1147
1148 #[test]
1151 fn rehearsal_place_sets_the_wait_mode_and_the_place() {
1152 let _g = enter_check("snapshot-prepare", Weight::Heavy);
1153 rehearsal_place(greenharness_slots::WaitPlace::Prestage);
1154 CURRENT.with(|c| {
1155 let c = c.borrow();
1156 assert!(c.heavy);
1157 assert_eq!(c.slot_wait, SlotWait::Waits);
1158 assert_eq!(c.place, Some(greenharness_slots::WaitPlace::Prestage));
1159 });
1160 rehearsal_place(greenharness_slots::WaitPlace::Rehearsal);
1161 CURRENT.with(|c| {
1162 assert_eq!(
1163 c.borrow().place,
1164 Some(greenharness_slots::WaitPlace::Rehearsal)
1165 );
1166 });
1167 }
1168
1169 #[test]
1173 fn the_sibling_extension_waits_to_the_ceiling() {
1174 let s = |n| Duration::from_secs(n);
1175 let with_sibling = sibling_bounds(SlotWait::Policy, 1, s(3600), s(60));
1176 assert_eq!(
1177 with_sibling.window, None,
1178 "no stall window on the hook path"
1179 );
1180 assert_eq!(with_sibling.ceiling, s(3540));
1181 let alone = sibling_bounds(SlotWait::Policy, 0, s(3600), s(60));
1182 assert_eq!((alone.window, alone.ceiling), (None, Duration::ZERO));
1183 let never = sibling_bounds(SlotWait::NeverWaits, 1, s(3600), s(60));
1184 assert_eq!((never.window, never.ceiling), (None, Duration::ZERO));
1185 }
1186
1187 #[test]
1191 fn a_deferral_names_its_cause() {
1192 use greenharness_slots::LineEnd;
1193 let stalled = LineEnd::Stalled {
1194 window: Duration::from_secs(300),
1195 position: 1,
1196 };
1197 let cause = defer_cause(
1198 &stalled,
1199 BusyPolicy::Defer {
1200 slot_wait: Duration::from_secs(60),
1201 },
1202 SlotWait::Policy,
1203 );
1204 assert!(cause.contains("made no progress for 5m00s"), "{cause}");
1205 assert!(cause.contains("(position 2)"), "{cause}");
1206 let slot_wait = defer_cause(
1207 &LineEnd::Ceiling {
1208 waited: Duration::from_secs(60),
1209 },
1210 BusyPolicy::Defer {
1211 slot_wait: Duration::from_secs(60),
1212 },
1213 SlotWait::Policy,
1214 );
1215 assert!(
1216 slot_wait.ends_with("(greengate.onBusy defer)"),
1217 "{slot_wait}"
1218 );
1219 let ceiling = defer_cause(
1220 &LineEnd::Ceiling {
1221 waited: Duration::from_secs(3600),
1222 },
1223 BusyPolicy::Wait,
1224 SlotWait::Policy,
1225 );
1226 assert!(ceiling.contains("no host slot within 1h00m"), "{ceiling}");
1227 assert!(ceiling.ends_with("(greengate.timeout)"), "{ceiling}");
1228 let warn = defer_cause(
1229 &LineEnd::Ceiling {
1230 waited: Duration::from_secs(600),
1231 },
1232 BusyPolicy::Wait,
1233 SlotWait::BoundedForWarn,
1234 );
1235 assert!(warn.ends_with("(greengate.warnSlotWait)"), "{warn}");
1236 let failed = defer_cause(
1237 &LineEnd::PollFailed {
1238 error: std::io::Error::other("busy disk"),
1239 },
1240 BusyPolicy::Wait,
1241 SlotWait::Policy,
1242 );
1243 assert!(failed.contains("busy disk"), "{failed}");
1244 for cause in [&cause, &slot_wait, &ceiling, &warn, &failed] {
1246 assert!(!cause.contains("deferred to CI"), "{cause}");
1247 }
1248 }
1249
1250 #[test]
1253 fn every_end_of_a_wait_in_line_defers() {
1254 let ended = Reason::Ended(greenharness_slots::LineEnd::Ceiling {
1255 waited: Duration::from_secs(1),
1256 });
1257 assert!(ended.ended().is_some());
1258 for reason in [
1259 Reason::Io("x".into()),
1260 Reason::DirUnsafe("x".into()),
1261 Reason::Unsupported,
1262 ] {
1263 assert!(reason.ended().is_none(), "{reason:?}");
1264 }
1265 }
1266
1267 #[test]
1268 fn heavy_is_the_list() {
1269 assert_eq!(weight_of("pre-commit-clippy"), Weight::Heavy);
1270 assert_eq!(weight_of("pre-commit-cargo-fmt"), Weight::Light);
1271 }
1272
1273 #[test]
1276 fn every_heavy_name_is_a_builtin() {
1277 for name in HEAVY {
1278 assert!(
1279 crate::registry::CHECKS.iter().any(|c| c.name == *name),
1280 "{name} is not a built-in check"
1281 );
1282 }
1283 }
1284
1285 #[test]
1291 fn cargo_pins_the_host_knobs_for_tests() {
1292 assert_eq!(std::env::var(HELD_ENV).as_deref(), Ok(""));
1293 assert_eq!(
1294 std::env::var(greenharness_slots::host::SLOTS_ENV).as_deref(),
1295 Ok("0")
1296 );
1297 assert_eq!(
1298 std::env::var("GREENGATE_IDLE_LOAD_SCALE").as_deref(),
1299 Ok("1")
1300 );
1301 assert_eq!(
1302 std::env::var(greenharness_slots::host::PROMOTE_ENV).as_deref(),
1303 Ok("1")
1304 );
1305 }
1306
1307 #[test]
1311 fn a_light_check_never_takes_a_slot() {
1312 let settings = crate::config::Settings::default();
1313 let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1314 assert!(before_spawn(&settings).unwrap().is_none());
1315 }
1316
1317 #[test]
1318 fn a_heavy_check_with_slots_off_settles_without_a_slot() {
1319 let settings = crate::config::Settings::default();
1320 let _g = enter_check("pre-commit-clippy", weight_of("pre-commit-clippy"));
1321 assert_eq!(current_check().as_deref(), Some("clippy"));
1322 assert!(before_spawn(&settings).unwrap().is_none());
1323 assert!(CURRENT.with(|c| c.borrow().settled));
1324 let mut cmd = std::process::Command::new("true");
1326 bound(&mut cmd);
1327 assert_eq!(cmd.get_envs().count(), 0);
1328 }
1329
1330 #[test]
1333 fn a_park_scope_dropped_early_releases_the_parked_slot() {
1334 let dir = std::env::temp_dir().join(format!("greengate-park-{}", std::process::id()));
1335 let _ = std::fs::remove_dir_all(&dir); let early = || {
1337 let _scope = ParkScope::begin();
1338 let mut waiter = greenharness_slots::Waiter::new_in(
1339 &dir,
1340 greenharness_slots::Sizing::Fixed(1),
1341 1,
1342 greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, "gate"),
1343 )
1344 .unwrap();
1345 let greenharness_slots::Poll::Granted(lease) = waiter.poll().unwrap() else {
1346 panic!("the empty directory grants the slot");
1347 };
1348 assert!(dir.join("holders/slot-0.who").exists());
1349 park(lease, Some(2), Some((3, 6)));
1350 assert!(dir.join("holders/slot-0.who").exists());
1351 };
1352 early();
1353 assert!(!dir.join("holders/slot-0.who").exists());
1354 let _ = std::fs::remove_dir_all(&dir); }
1356
1357 #[test]
1358 fn a_light_check_sets_no_width() {
1359 let settings = crate::config::Settings::default();
1360 let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1361 before_spawn(&settings).unwrap();
1362 let mut cmd = std::process::Command::new("true");
1363 bound(&mut cmd);
1364 assert_eq!(cmd.get_envs().count(), 0);
1365 }
1366}