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 sizing(settings: &crate::config::Settings) -> Option<greenharness_slots::Sizing> {
170 sizing_and_machine(settings).0
171}
172
173pub const ON_BUSY_ENV: &str = "GREENGATE_ON_BUSY";
176
177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub enum BusyPolicy {
181 Wait,
184 Defer { slot_wait: Duration },
186 Now,
190}
191
192pub fn busy_policy(settings: &crate::config::Settings) -> BusyPolicy {
196 resolve_busy(std::env::var(ON_BUSY_ENV).ok().as_deref(), settings)
197}
198
199fn resolve_busy(from_env: Option<&str>, settings: &crate::config::Settings) -> BusyPolicy {
202 let from_env = from_env.filter(|v| !v.is_empty());
203 let mode = match from_env.map(str::to_ascii_lowercase).as_deref() {
204 Some("wait") => "wait",
205 Some("defer") => "defer",
206 Some("now") => return BusyPolicy::Now,
207 Some(other) => {
208 crate::config::complain(
209 ON_BUSY_ENV,
210 &format!("{other:?} is not one of wait, defer, now"),
211 "greengate.onBusy",
212 );
213 crate::config::enumerated_or(settings, "greengate.onBusy", &["wait", "defer"], "wait")
214 }
215 None => {
216 crate::config::enumerated_or(settings, "greengate.onBusy", &["wait", "defer"], "wait")
217 }
218 };
219 if mode == "defer" {
220 let secs = crate::config::integer_or(settings, "greengate.slotWait", 60, 1..=3600) as u64;
221 BusyPolicy::Defer {
222 slot_wait: Duration::from_secs(secs),
223 }
224 } else {
225 BusyPolicy::Wait
226 }
227}
228
229#[derive(Default)]
231struct Current {
232 name: String,
234 heavy: bool,
235 settled: bool,
238 held: Option<greenharness_slots::Lease>,
239 queued: Duration,
240 deferred: Option<Duration>,
246 deferred_cause: String,
248 jobs: Option<u32>,
252 sized: Option<(u32, u32)>,
255 slot_wait: SlotWait,
257}
258
259#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
261enum SlotWait {
262 #[default]
264 Policy,
265 NeverWaits,
271 BoundedForWarn,
275}
276
277struct Parked {
280 lease: greenharness_slots::Lease,
281 jobs: Option<u32>,
282 sized: Option<(u32, u32)>,
283}
284
285static PARKED: Mutex<Option<Parked>> = Mutex::new(None);
289
290static PARK_SCOPE_DEPTH: AtomicUsize = AtomicUsize::new(0);
293
294fn parked() -> std::sync::MutexGuard<'static, Option<Parked>> {
295 PARKED
296 .lock()
297 .unwrap_or_else(|poisoned| poisoned.into_inner())
298}
299
300fn parking() -> bool {
304 PARK_SCOPE_DEPTH.load(Ordering::SeqCst) > 0 && crate::rehearsal::in_snapshot()
305}
306
307#[must_use = "the scope releases the parked slot when dropped"]
311pub struct ParkScope {
312 _private: (),
313}
314
315impl ParkScope {
316 #[must_use = "the scope releases the parked slot when dropped"]
317 pub fn begin() -> ParkScope {
318 PARK_SCOPE_DEPTH.fetch_add(1, Ordering::SeqCst);
319 ParkScope { _private: () }
320 }
321}
322
323impl Drop for ParkScope {
324 fn drop(&mut self) {
325 if PARK_SCOPE_DEPTH.fetch_sub(1, Ordering::SeqCst) == 1 {
326 release_parked();
327 }
328 }
329}
330
331pub fn release_parked() {
336 let leftover = parked().take();
337 drop(leftover);
338}
339
340fn between_gates() -> greenharness_slots::Holder {
342 holder_for("pre-push, between checks")
343}
344
345fn holder_for(command: &str) -> greenharness_slots::Holder {
350 let mut holder = greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, command);
351 if let Some(src) = crate::rehearsal::source_worktree() {
352 holder.repo = src.display().to_string();
353 }
354 holder
355}
356
357thread_local! {
358 static CURRENT: RefCell<Current> = RefCell::new(Current::default());
359}
360
361pub struct CheckGuard;
364
365impl CheckGuard {
366 pub fn queued(&self) -> Duration {
368 CURRENT.with(|c| c.borrow().queued)
369 }
370
371 pub fn deferred(&self) -> Option<Duration> {
374 CURRENT.with(|c| c.borrow().deferred)
375 }
376}
377
378pub fn deferred_here() -> bool {
381 CURRENT.with(|c| c.borrow().deferred.is_some())
382}
383
384fn refusal() -> std::io::Error {
388 let cause = CURRENT.with(|c| c.borrow().deferred_cause.clone());
389 std::io::Error::other(if cause.is_empty() {
390 "deferred to CI: the host is busy".to_string()
391 } else {
392 cause
393 })
394}
395
396fn defer_cause(end: &greenharness_slots::LineEnd, policy: BusyPolicy) -> String {
398 use greenharness_slots::LineEnd;
399 let human = |d: Duration| crate::hooks::common::human_secs(d.as_secs());
400 match end {
401 LineEnd::Stalled { window, position } => format!(
402 "deferred to CI: the host slot line made no progress for {} (position {})",
403 human(*window),
404 position + 1
405 ),
406 LineEnd::PollFailed { error } => {
407 format!("deferred to CI: the host slot files failed: {error}")
408 }
409 LineEnd::Ceiling { waited } => match policy {
410 BusyPolicy::Defer { .. } => format!(
411 "deferred to CI: no host slot freed in {} (greengate.onBusy defer)",
412 human(*waited)
413 ),
414 BusyPolicy::Wait | BusyPolicy::Now => {
415 format!("deferred to CI: no host slot within {}", human(*waited))
416 }
417 },
418 }
419}
420
421#[derive(Debug, Clone, Copy, PartialEq, Eq)]
424enum WaitPlan {
425 Now,
426 Queue(greenharness_slots::WaitBounds),
427}
428
429fn wait_plan(
433 slot_wait: SlotWait,
434 policy: BusyPolicy,
435 ceiling: Duration,
436 warn_wait: Duration,
437 stall: Duration,
438 seen: HostSeen,
439) -> WaitPlan {
440 let queue =
441 |window, ceiling| WaitPlan::Queue(greenharness_slots::WaitBounds { window, ceiling });
442 match (slot_wait, policy) {
443 (_, BusyPolicy::Now) => WaitPlan::Now,
444 (SlotWait::NeverWaits, _) => queue(None, Duration::ZERO),
445 (SlotWait::BoundedForWarn, _) => queue(Some(stall), warn_wait.min(ceiling)),
446 (SlotWait::Policy, BusyPolicy::Wait) => queue(Some(stall), ceiling),
447 (SlotWait::Policy, BusyPolicy::Defer { slot_wait }) => match seen {
448 HostSeen::Busy => queue(None, Duration::ZERO),
450 HostSeen::NotYet => queue(None, slot_wait),
451 },
452 }
453}
454
455fn sibling_bounds(
462 slot_wait: SlotWait,
463 held_in_process: usize,
464 ceiling: Duration,
465 elapsed: Duration,
466 stall: Duration,
467) -> greenharness_slots::WaitBounds {
468 let waits_on_sibling = held_in_process > 0 && !matches!(slot_wait, SlotWait::NeverWaits);
469 if waits_on_sibling {
470 greenharness_slots::WaitBounds {
471 window: Some(stall),
472 ceiling: ceiling.saturating_sub(elapsed),
473 }
474 } else {
475 greenharness_slots::WaitBounds {
476 window: None,
477 ceiling: Duration::ZERO,
478 }
479 }
480}
481
482fn stall_window() -> Duration {
485 let setting = std::env::var(greenharness_slots::STALL_ENV).ok();
486 let (window, warning) = greenharness_slots::Stall::window_from(setting.as_deref());
487 if let Some(warning) = warning {
488 say_once(&warning);
489 }
490 window
491}
492
493impl Drop for CheckGuard {
494 fn drop(&mut self) {
495 let finished = CURRENT.with(RefCell::take);
496 if let Some(lease) = finished.held {
497 if parking() {
498 park(lease, finished.jobs, finished.sized);
499 }
500 }
501 }
502}
503
504fn park(lease: greenharness_slots::Lease, jobs: Option<u32>, sized: Option<(u32, u32)>) {
507 if let Err(error) = lease.rename(&between_gates()) {
508 crate::hooks::common::say(&format!(
509 " host slot kept, but `{BIN} slots` may still name the previous check: {error}"
510 ));
511 }
512 let earlier = parked().replace(Parked { lease, jobs, sized });
513 drop(earlier);
514}
515
516pub fn enter_check(name: &str, weight: Weight) -> CheckGuard {
520 CURRENT.with(|c| {
521 *c.borrow_mut() = Current {
522 name: name.to_string(),
523 heavy: weight == Weight::Heavy,
524 ..Current::default()
525 }
526 });
527 CheckGuard
528}
529
530pub fn never_waits() {
538 CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::NeverWaits);
539}
540
541pub fn wait_bounded_for_warn() {
546 CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::BoundedForWarn);
547}
548
549fn warn_slot_wait(settings: &crate::config::Settings) -> Duration {
552 Duration::from_secs(
553 crate::config::integer_or(settings, "greengate.warnSlotWait", 600, 1..=3600) as u64,
554 )
555}
556
557pub fn current_check() -> Option<String> {
560 CURRENT.with(|c| {
561 let c = c.borrow();
562 (!c.name.is_empty()).then(|| crate::short_name(&c.name).to_string())
563 })
564}
565
566fn nested() -> bool {
568 std::env::var_os(HELD_ENV).is_some_and(|v| !v.is_empty())
569}
570
571pub fn before_spawn(settings: &crate::config::Settings) -> std::io::Result<bool> {
576 let (pending, deferred, name, slot_wait) = CURRENT.with(|current| {
577 let current = current.borrow();
578 (
579 current.heavy && !current.settled,
580 current.deferred.is_some(),
581 current.name.clone(),
582 current.slot_wait,
583 )
584 });
585 if deferred {
588 return Err(refusal());
589 }
590 if pending {
591 if let Some(handed) = parking().then(|| parked().take()).flatten() {
592 return Ok(take_handed(handed, &name));
593 }
594 let (sizing, machine) = if nested() {
598 (None, greenharness_slots::Machine::detect())
599 } else {
600 sizing_and_machine(settings)
601 };
602 let Some(sizing) = sizing else {
603 CURRENT.with(|c| c.borrow_mut().settled = true);
604 return Ok(false);
605 };
606 if !greenharness_slots::SUPPORTED {
607 CURRENT.with(|c| c.borrow_mut().settled = true);
608 return Ok(false);
609 }
610 let policy = match slot_wait {
611 SlotWait::NeverWaits => BusyPolicy::Defer {
612 slot_wait: Duration::ZERO,
613 },
614 SlotWait::BoundedForWarn => BusyPolicy::Wait,
615 SlotWait::Policy => busy_policy(settings),
616 };
617 let ceiling = Duration::from_secs(match crate::hooks::common::check_timeout(settings) {
618 0 => 3600,
619 s => s,
620 });
621 let seen = if BUSY_SEEN.load(Ordering::SeqCst) {
622 HostSeen::Busy
623 } else {
624 HostSeen::NotYet
625 };
626 let plan = wait_plan(
627 slot_wait,
628 policy,
629 ceiling,
630 warn_slot_wait(settings),
631 stall_window(),
632 seen,
633 );
634 let slot_cap = sizing.cap_for(machine.cores);
635 let cap = u64::from(slot_cap);
636 let jobs = greenharness_slots::parallelism(1, machine.cores, slot_cap);
639 let bounds = match plan {
640 WaitPlan::Queue(bounds) => bounds,
641 WaitPlan::Now => {
642 crate::hooks::common::say(&format!(
645 " running unqueued: {}=now skips the host slot queue",
646 crate::ui::highlight(ON_BUSY_ENV)
647 ));
648 record_acquisition(
649 &name,
650 Some(jobs),
651 Some((slot_cap, machine.cores)),
652 Duration::ZERO,
653 "now",
654 None,
655 );
656 CURRENT.with(|c| {
657 let mut c = c.borrow_mut();
658 c.settled = true;
659 c.jobs = Some(jobs);
660 c.sized = Some((slot_cap, machine.cores));
661 });
662 return Ok(false);
663 }
664 };
665 let sink = crate::live::current_sink();
666 if let Some((stage, idx)) = &sink {
667 stage.queue(*idx, Some((Instant::now(), cap)));
668 }
669 let started = Instant::now();
670 let holder = holder_for(&name);
671 let mut got = wait_for_slot(sizing, machine, holder.clone(), bounds);
672 if let (
673 BusyPolicy::Defer { .. },
674 Err(Reason::Ended(greenharness_slots::LineEnd::Ceiling { .. })),
675 ) = (policy, &got)
676 {
677 let more = sibling_bounds(
678 slot_wait,
679 greenharness_slots::held_in_process(),
680 ceiling,
681 started.elapsed(),
682 stall_window(),
683 );
684 got = wait_for_slot(sizing, machine, holder, more);
685 }
686 if let Some((stage, idx)) = &sink {
687 stage.queue(*idx, None);
688 }
689 let waited = started.elapsed();
690 CURRENT.with(|c| c.borrow_mut().queued += waited);
691 if got.is_ok() && waited >= Duration::from_secs(1) {
694 crate::hooks::common::say(&format!(
695 " (waited {} for a host slot, {} {cap})",
696 crate::hooks::common::human_secs(waited.as_secs()),
697 crate::ui::highlight("greengate.hostSlots")
698 ));
699 }
700 let ended = got.as_ref().err().and_then(Reason::ended);
703 let defer = ended.is_some();
704 let end = ended.map(greenharness_slots::LineEnd::end);
705 let cause = ended.map_or(String::new(), |end| defer_cause(end, policy));
706 let by_slot_wait = matches!(
707 (policy, ended),
708 (
709 BusyPolicy::Defer { .. },
710 Some(greenharness_slots::LineEnd::Ceiling { .. })
711 )
712 );
713 let outcome = match (&got, defer) {
714 (Ok(_), _) => "admitted",
715 (Err(_), true) => "deferred",
716 (Err(_), false) => "unqueued",
717 };
718 record_acquisition(
719 &name,
720 Some(jobs),
721 Some((slot_cap, machine.cores)),
722 waited,
723 outcome,
724 end,
725 );
726 let held = match got {
727 Ok(lease) => Some(lease),
728 Err(Reason::Ended(_)) => None,
730 Err(reason) => {
731 note(&reason);
732 None
733 }
734 };
735 if defer {
736 BUSY_SEEN.store(true, Ordering::SeqCst);
737 if by_slot_wait {
738 DEFERRED_BY_SLOT_WAIT.store(true, Ordering::SeqCst);
739 }
740 }
741 CURRENT.with(|c| {
742 let mut c = c.borrow_mut();
743 c.held = held;
744 c.settled = true;
745 c.jobs = Some(jobs);
746 c.sized = Some((slot_cap, machine.cores));
747 if defer {
748 c.deferred = Some(waited);
749 c.deferred_cause = cause;
750 }
751 });
752 if defer {
753 return Err(refusal());
754 }
755 }
756 Ok(CURRENT.with(|c| c.borrow().held.is_some()) || (parking() && parked().is_some()))
760}
761
762fn take_handed(handed: Parked, name: &str) -> bool {
765 let Parked { lease, jobs, sized } = handed;
766 if let Err(error) = lease.rename(&holder_for(name)) {
767 crate::hooks::common::say(&format!(
768 " host slot kept, but `{BIN} slots` may still name the previous check: {error}"
769 ));
770 }
771 record_acquisition(name, jobs, sized, Duration::ZERO, "handed", None);
772 CURRENT.with(|current| {
773 let mut current = current.borrow_mut();
774 current.held = Some(lease);
775 current.settled = true;
776 current.jobs = jobs;
777 current.sized = sized;
778 });
779 true
780}
781
782fn record_acquisition(
785 name: &str,
786 jobs: Option<u32>,
787 sized: Option<(u32, u32)>,
788 waited: Duration,
789 outcome: &str,
790 end: Option<greenharness_slots::WaitEnd>,
791) {
792 let short = crate::short_name(name);
793 greenharness_slots::record_wait_named(
794 &greenharness_slots::dir(),
795 crate::names::SLOT_HOLDER,
796 greenharness_slots::WaitContext {
797 name: Some(short),
798 place: if crate::rehearsal::in_prestage() {
799 greenharness_slots::WaitPlace::Prestage
800 } else if crate::rehearsal::in_snapshot() {
801 greenharness_slots::WaitPlace::Rehearsal
802 } else {
803 greenharness_slots::WaitPlace::Push
804 },
805 cap: sized.map(|(cap, _)| cap),
806 cores: sized.map(|(_, cores)| cores),
807 end,
808 },
809 1,
810 jobs,
811 waited.as_millis(),
812 outcome,
813 );
814}
815
816pub fn bound(cmd: &mut std::process::Command) {
820 let own = CURRENT.with(|c| c.borrow().jobs);
821 if let Some(jobs) = own.or_else(|| {
823 parking()
824 .then(|| parked().as_ref().and_then(|p| p.jobs))
825 .flatten()
826 }) {
827 greenharness_slots::bound_width(cmd, jobs);
828 }
829}
830
831fn wait_for_slot(
835 sizing: greenharness_slots::Sizing,
836 machine: greenharness_slots::Machine,
837 holder: greenharness_slots::Holder,
838 bounds: greenharness_slots::WaitBounds,
839) -> Result<greenharness_slots::Lease, Reason> {
840 let waiter = match greenharness_slots::Waiter::new_in_on(
841 &greenharness_slots::dir(),
842 sizing,
843 1,
844 holder,
845 machine,
846 ) {
847 Ok(w) => w,
848 Err(e) if e.kind() == std::io::ErrorKind::Other => {
849 return Err(Reason::DirUnsafe(e.to_string()))
850 }
851 Err(e) => return Err(Reason::Io(e.to_string())),
852 };
853 let mut said = false;
854 greenharness_slots::wait_in_line(waiter, bounds, |queue| {
855 if !said && (!queue.holders.is_empty() || queue.unknown > 0) {
856 said = true;
857 crate::hooks::common::say(&format!(" {}", behind(queue)));
858 crate::hooks::common::say(&format!(" see: {BIN} slots"));
859 }
860 })
861 .map_err(Reason::Ended)
862}
863
864pub fn behind(queue: &greenharness_slots::Queue) -> String {
866 let now = greenharness_slots::now_ms();
867 let mut who: Vec<String> = queue.holders.iter().map(|h| h.describe(now)).collect();
868 if queue.unknown > 0 {
869 who.push(format!("{} unknown (old client)", queue.unknown));
870 }
871 let reason = queue
872 .reason
873 .map_or(String::new(), |r| format!(" ({})", r.describe()));
874 format!(
875 "queued behind {}{reason} · {} waiting",
876 who.join(", "),
877 queue.waiting.max(1)
878 )
879}
880
881fn note(reason: &Reason) {
885 match reason {
886 Reason::DirUnsafe(why) => crate::hooks::common::warn(&format!(
887 "host slots are off for this check: {why}. Remove it, or set {} to a directory \
888 only you own",
889 crate::ui::highlight(DIR_ENV)
890 )),
891 Reason::Io(why) => {
892 crate::hooks::common::warn(&format!("host slots are off for this check: {why}"))
893 }
894 Reason::Ended(_) | Reason::Unsupported => {}
895 }
896}
897
898#[cfg(all(test, unix))]
899mod tests {
900 use super::*;
901
902 fn settings_from(conf: &str) -> crate::config::Settings {
903 let lines = crate::manifest::parse_lines(conf);
904 let (policy, _) = crate::policy::Policy::from_lines(&lines);
905 crate::config::Settings::new(policy)
906 }
907
908 #[test]
911 fn the_busy_policy_is_env_then_file_then_wait() {
912 let none = settings_from("");
913 let defer = settings_from("set onBusy defer\nset slotWait 5\n");
914 assert_eq!(resolve_busy(None, &none), BusyPolicy::Wait);
915 assert_eq!(
916 resolve_busy(None, &defer),
917 BusyPolicy::Defer {
918 slot_wait: Duration::from_secs(5)
919 }
920 );
921 assert_eq!(resolve_busy(Some("wait"), &defer), BusyPolicy::Wait);
922 assert_eq!(
923 resolve_busy(Some("DEFER"), &none),
924 BusyPolicy::Defer {
925 slot_wait: Duration::from_secs(60)
926 }
927 );
928 assert_eq!(
929 resolve_busy(Some("later"), &defer),
930 BusyPolicy::Defer {
931 slot_wait: Duration::from_secs(5)
932 }
933 );
934 assert_eq!(resolve_busy(Some(""), &none), BusyPolicy::Wait);
935 assert_eq!(resolve_busy(Some("now"), &defer), BusyPolicy::Now);
938 let committed = settings_from("set onBusy now\n");
939 assert_eq!(resolve_busy(None, &committed), BusyPolicy::Wait);
940 }
941
942 #[test]
945 fn each_caller_waits_by_its_row_of_the_table() {
946 use greenharness_slots::WaitBounds;
947 let s = |n| Duration::from_secs(n);
948 let (ceiling, warn, stall) = (s(3600), s(600), s(300));
949 let defer = BusyPolicy::Defer { slot_wait: s(60) };
950 let queue = |window, ceiling| WaitPlan::Queue(WaitBounds { window, ceiling });
951 let row = |slot_wait, policy, ceiling, seen| {
952 wait_plan(slot_wait, policy, ceiling, warn, stall, seen)
953 };
954 assert_eq!(
956 row(
957 SlotWait::Policy,
958 BusyPolicy::Wait,
959 ceiling,
960 HostSeen::NotYet
961 ),
962 queue(Some(stall), ceiling)
963 );
964 assert_eq!(
967 row(
968 SlotWait::BoundedForWarn,
969 BusyPolicy::Wait,
970 ceiling,
971 HostSeen::NotYet
972 ),
973 queue(Some(stall), warn)
974 );
975 assert_eq!(
976 row(
977 SlotWait::BoundedForWarn,
978 BusyPolicy::Wait,
979 s(100),
980 HostSeen::NotYet
981 ),
982 queue(Some(stall), s(100))
983 );
984 assert_eq!(
987 row(SlotWait::Policy, defer, ceiling, HostSeen::NotYet),
988 queue(None, s(60))
989 );
990 assert_eq!(
991 row(SlotWait::Policy, defer, ceiling, HostSeen::Busy),
992 queue(None, Duration::ZERO)
993 );
994 assert_eq!(
996 row(
997 SlotWait::NeverWaits,
998 BusyPolicy::Wait,
999 ceiling,
1000 HostSeen::NotYet
1001 ),
1002 queue(None, Duration::ZERO)
1003 );
1004 assert_eq!(
1006 row(SlotWait::Policy, BusyPolicy::Now, ceiling, HostSeen::NotYet),
1007 WaitPlan::Now
1008 );
1009 }
1010
1011 #[test]
1015 fn the_sibling_extension_waits_while_the_line_moves() {
1016 let s = |n| Duration::from_secs(n);
1017 let with_sibling = sibling_bounds(SlotWait::Policy, 1, s(3600), s(60), s(300));
1018 assert_eq!(with_sibling.window, Some(s(300)));
1019 assert_eq!(with_sibling.ceiling, s(3540));
1020 let alone = sibling_bounds(SlotWait::Policy, 0, s(3600), s(60), s(300));
1021 assert_eq!((alone.window, alone.ceiling), (None, Duration::ZERO));
1022 let never = sibling_bounds(SlotWait::NeverWaits, 1, s(3600), s(60), s(300));
1023 assert_eq!((never.window, never.ceiling), (None, Duration::ZERO));
1024 }
1025
1026 #[test]
1030 fn a_deferral_names_its_cause() {
1031 use greenharness_slots::LineEnd;
1032 let stalled = LineEnd::Stalled {
1033 window: Duration::from_secs(300),
1034 position: 1,
1035 };
1036 let cause = defer_cause(
1037 &stalled,
1038 BusyPolicy::Defer {
1039 slot_wait: Duration::from_secs(60),
1040 },
1041 );
1042 assert!(cause.contains("made no progress for 5m00s"), "{cause}");
1043 assert!(cause.contains("(position 2)"), "{cause}");
1044 let slot_wait = defer_cause(
1045 &LineEnd::Ceiling {
1046 waited: Duration::from_secs(60),
1047 },
1048 BusyPolicy::Defer {
1049 slot_wait: Duration::from_secs(60),
1050 },
1051 );
1052 assert!(
1053 slot_wait.ends_with("(greengate.onBusy defer)"),
1054 "{slot_wait}"
1055 );
1056 let ceiling = defer_cause(
1057 &LineEnd::Ceiling {
1058 waited: Duration::from_secs(3600),
1059 },
1060 BusyPolicy::Wait,
1061 );
1062 assert!(ceiling.contains("no host slot within 1h00m"), "{ceiling}");
1063 let failed = defer_cause(
1064 &LineEnd::PollFailed {
1065 error: std::io::Error::other("busy disk"),
1066 },
1067 BusyPolicy::Wait,
1068 );
1069 assert!(failed.contains("busy disk"), "{failed}");
1070 }
1071
1072 #[test]
1075 fn every_end_of_a_wait_in_line_defers() {
1076 let ended = Reason::Ended(greenharness_slots::LineEnd::Ceiling {
1077 waited: Duration::from_secs(1),
1078 });
1079 assert!(ended.ended().is_some());
1080 for reason in [
1081 Reason::Io("x".into()),
1082 Reason::DirUnsafe("x".into()),
1083 Reason::Unsupported,
1084 ] {
1085 assert!(reason.ended().is_none(), "{reason:?}");
1086 }
1087 }
1088
1089 #[test]
1090 fn heavy_is_the_list() {
1091 assert_eq!(weight_of("pre-commit-clippy"), Weight::Heavy);
1092 assert_eq!(weight_of("pre-commit-cargo-fmt"), Weight::Light);
1093 }
1094
1095 #[test]
1098 fn every_heavy_name_is_a_builtin() {
1099 for name in HEAVY {
1100 assert!(
1101 crate::registry::CHECKS.iter().any(|c| c.name == *name),
1102 "{name} is not a built-in check"
1103 );
1104 }
1105 }
1106
1107 #[test]
1110 fn cargo_pins_the_host_knobs_for_tests() {
1111 assert_eq!(std::env::var(HELD_ENV).as_deref(), Ok("held"));
1112 assert_eq!(
1113 std::env::var("GREENGATE_IDLE_LOAD_SCALE").as_deref(),
1114 Ok("1")
1115 );
1116 }
1117
1118 #[test]
1122 fn a_light_check_never_takes_a_slot() {
1123 let settings = crate::config::Settings::default();
1124 let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1125 assert!(!before_spawn(&settings).unwrap());
1126 }
1127
1128 #[test]
1129 fn a_nested_heavy_check_settles_without_a_slot() {
1130 let settings = crate::config::Settings::default();
1131 let _g = enter_check("pre-commit-clippy", weight_of("pre-commit-clippy"));
1132 assert_eq!(current_check().as_deref(), Some("clippy"));
1133 assert!(!before_spawn(&settings).unwrap());
1134 assert!(CURRENT.with(|c| c.borrow().settled));
1135 let mut cmd = std::process::Command::new("true");
1137 bound(&mut cmd);
1138 assert_eq!(cmd.get_envs().count(), 0);
1139 }
1140
1141 #[test]
1144 fn a_park_scope_dropped_early_releases_the_parked_slot() {
1145 let dir = std::env::temp_dir().join(format!("greengate-park-{}", std::process::id()));
1146 let _ = std::fs::remove_dir_all(&dir); let early = || {
1148 let _scope = ParkScope::begin();
1149 let mut waiter = greenharness_slots::Waiter::new_in(
1150 &dir,
1151 greenharness_slots::Sizing::Fixed(1),
1152 1,
1153 greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, "gate"),
1154 )
1155 .unwrap();
1156 let greenharness_slots::Poll::Granted(lease) = waiter.poll().unwrap() else {
1157 panic!("the empty directory grants the slot");
1158 };
1159 assert!(dir.join("holders/slot-0.who").exists());
1160 park(lease, Some(2), Some((3, 6)));
1161 assert!(dir.join("holders/slot-0.who").exists());
1162 };
1163 early();
1164 assert!(!dir.join("holders/slot-0.who").exists());
1165 let _ = std::fs::remove_dir_all(&dir); }
1167
1168 #[test]
1169 fn a_light_check_sets_no_width() {
1170 let settings = crate::config::Settings::default();
1171 let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1172 before_spawn(&settings).unwrap();
1173 let mut cmd = std::process::Command::new("true");
1174 bound(&mut cmd);
1175 assert_eq!(cmd.get_envs().count(), 0);
1176 }
1177}