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(
398 end: &greenharness_slots::LineEnd,
399 policy: BusyPolicy,
400 slot_wait: SlotWait,
401) -> String {
402 use greenharness_slots::LineEnd;
403 let human = |d: Duration| crate::hooks::common::human_secs(d.as_secs());
404 match end {
405 LineEnd::Stalled { window, position } => format!(
408 "deferred to CI: the host slot line made no progress for {} (position {})",
409 human(*window),
410 position + 1
411 ),
412 LineEnd::PollFailed { error } => {
413 format!("deferred to CI: the host slot files failed: {error}")
414 }
415 LineEnd::Ceiling { waited } => match policy {
416 BusyPolicy::Defer { .. } => format!(
417 "deferred to CI: no host slot freed in {} (greengate.onBusy defer)",
418 human(*waited)
419 ),
420 BusyPolicy::Wait | BusyPolicy::Now => {
421 let setting = match slot_wait {
424 SlotWait::BoundedForWarn => "greengate.warnSlotWait",
425 SlotWait::Policy | SlotWait::NeverWaits => "greengate.timeout",
426 };
427 format!(
428 "deferred to CI: no host slot within {} ({setting})",
429 human(*waited)
430 )
431 }
432 },
433 }
434}
435
436#[derive(Debug, Clone, Copy, PartialEq, Eq)]
439enum WaitPlan {
440 Now,
441 Queue(greenharness_slots::WaitBounds),
442}
443
444fn wait_plan(
451 slot_wait: SlotWait,
452 policy: BusyPolicy,
453 ceiling: Duration,
454 warn_wait: Duration,
455 seen: HostSeen,
456) -> WaitPlan {
457 let queue =
458 |window, ceiling| WaitPlan::Queue(greenharness_slots::WaitBounds { window, ceiling });
459 match (slot_wait, policy) {
460 (_, BusyPolicy::Now) => WaitPlan::Now,
461 (SlotWait::NeverWaits, _) => queue(None, Duration::ZERO),
462 (SlotWait::BoundedForWarn, _) => queue(None, warn_wait.min(ceiling)),
463 (SlotWait::Policy, BusyPolicy::Wait) => queue(None, ceiling),
464 (SlotWait::Policy, BusyPolicy::Defer { slot_wait }) => match seen {
465 HostSeen::Busy => queue(None, Duration::ZERO),
467 HostSeen::NotYet => queue(None, slot_wait),
468 },
469 }
470}
471
472fn sibling_bounds(
479 slot_wait: SlotWait,
480 held_in_process: usize,
481 ceiling: Duration,
482 elapsed: Duration,
483) -> greenharness_slots::WaitBounds {
484 let waits_on_sibling = held_in_process > 0 && !matches!(slot_wait, SlotWait::NeverWaits);
485 if waits_on_sibling {
486 greenharness_slots::WaitBounds {
487 window: None,
488 ceiling: ceiling.saturating_sub(elapsed),
489 }
490 } else {
491 greenharness_slots::WaitBounds {
492 window: None,
493 ceiling: Duration::ZERO,
494 }
495 }
496}
497
498impl Drop for CheckGuard {
499 fn drop(&mut self) {
500 let finished = CURRENT.with(RefCell::take);
501 if let Some(lease) = finished.held {
502 if parking() {
503 park(lease, finished.jobs, finished.sized);
504 }
505 }
506 }
507}
508
509fn park(lease: greenharness_slots::Lease, jobs: Option<u32>, sized: Option<(u32, u32)>) {
512 if let Err(error) = lease.rename(&between_gates()) {
513 crate::hooks::common::say(&format!(
514 " host slot kept, but `{BIN} slots` may still name the previous check: {error}"
515 ));
516 }
517 let earlier = parked().replace(Parked { lease, jobs, sized });
518 drop(earlier);
519}
520
521pub fn enter_check(name: &str, weight: Weight) -> CheckGuard {
525 CURRENT.with(|c| {
526 *c.borrow_mut() = Current {
527 name: name.to_string(),
528 heavy: weight == Weight::Heavy,
529 ..Current::default()
530 }
531 });
532 CheckGuard
533}
534
535pub fn never_waits() {
543 CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::NeverWaits);
544}
545
546pub fn wait_bounded_for_warn() {
551 CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::BoundedForWarn);
552}
553
554fn warn_slot_wait(settings: &crate::config::Settings) -> Duration {
557 Duration::from_secs(
558 crate::config::integer_or(settings, "greengate.warnSlotWait", 600, 1..=3600) as u64,
559 )
560}
561
562pub fn current_check() -> Option<String> {
565 CURRENT.with(|c| {
566 let c = c.borrow();
567 (!c.name.is_empty()).then(|| crate::short_name(&c.name).to_string())
568 })
569}
570
571fn marker(settings: &crate::config::Settings) -> &greenharness_slots::Marker {
575 settings.marker.get_or_init(greenharness_slots::held_marker)
576}
577
578pub(crate) fn nested(settings: &crate::config::Settings) -> bool {
581 marker(settings).is_held()
582}
583
584pub(crate) fn marker_refused_note(settings: &crate::config::Settings) -> Option<String> {
587 let marker = marker(settings);
588 settings
589 .marker_log
590 .record(
591 &greenharness_slots::dir(),
592 crate::names::SLOT_HOLDER,
593 marker,
594 )
595 .then(|| greenharness_slots::refused_line(BIN, marker))
596 .flatten()
597}
598
599fn say_refusal(line: &str) {
603 if crate::live::current_sink().is_some() {
604 crate::hooks::common::say(line);
605 } else {
606 eprintln!("{line}");
607 }
608}
609
610pub fn before_spawn(settings: &crate::config::Settings) -> std::io::Result<bool> {
615 let (pending, deferred, name, slot_wait) = CURRENT.with(|current| {
616 let current = current.borrow();
617 (
618 current.heavy && !current.settled,
619 current.deferred.is_some(),
620 current.name.clone(),
621 current.slot_wait,
622 )
623 });
624 if deferred {
627 return Err(refusal());
628 }
629 if pending {
630 if let Some(handed) = parking().then(|| parked().take()).flatten() {
631 return Ok(take_handed(handed, &name));
632 }
633 let (sizing, machine) = if nested(settings) {
637 (None, greenharness_slots::Machine::detect())
638 } else {
639 sizing_and_machine(settings)
640 };
641 let Some(sizing) = sizing else {
642 CURRENT.with(|c| c.borrow_mut().settled = true);
643 return Ok(false);
644 };
645 if !greenharness_slots::SUPPORTED {
646 CURRENT.with(|c| c.borrow_mut().settled = true);
647 return Ok(false);
648 }
649 let policy = match slot_wait {
650 SlotWait::NeverWaits => BusyPolicy::Defer {
651 slot_wait: Duration::ZERO,
652 },
653 SlotWait::BoundedForWarn => BusyPolicy::Wait,
654 SlotWait::Policy => busy_policy(settings),
655 };
656 let ceiling = Duration::from_secs(match crate::hooks::common::check_timeout(settings) {
657 0 => 3600,
658 s => s,
659 });
660 let seen = if BUSY_SEEN.load(Ordering::SeqCst) {
661 HostSeen::Busy
662 } else {
663 HostSeen::NotYet
664 };
665 let plan = wait_plan(slot_wait, policy, ceiling, warn_slot_wait(settings), seen);
666 let slot_cap = sizing.cap_for(machine.cores);
667 let cap = u64::from(slot_cap);
668 let jobs = greenharness_slots::parallelism(1, machine.cores, slot_cap);
671 let bounds = match plan {
672 WaitPlan::Queue(bounds) => bounds,
673 WaitPlan::Now => {
674 crate::hooks::common::say(&format!(
677 " running unqueued: {}=now skips the host slot queue",
678 crate::ui::highlight(ON_BUSY_ENV)
679 ));
680 record_acquisition(
681 &name,
682 Some(jobs),
683 Some((slot_cap, machine.cores)),
684 Duration::ZERO,
685 "now",
686 None,
687 );
688 CURRENT.with(|c| {
689 let mut c = c.borrow_mut();
690 c.settled = true;
691 c.jobs = Some(jobs);
692 c.sized = Some((slot_cap, machine.cores));
693 });
694 return Ok(false);
695 }
696 };
697 if let Some(line) = marker_refused_note(settings) {
699 say_refusal(&line);
700 }
701 let sink = crate::live::current_sink();
702 if let Some((stage, idx)) = &sink {
703 stage.queue(*idx, Some((Instant::now(), cap)));
704 }
705 let started = Instant::now();
706 let holder = holder_for(&name);
707 let mut got = wait_for_slot(sizing, machine, holder.clone(), bounds);
708 if let (
709 BusyPolicy::Defer { .. },
710 Err(Reason::Ended(greenharness_slots::LineEnd::Ceiling { .. })),
711 ) = (policy, &got)
712 {
713 let more = sibling_bounds(
714 slot_wait,
715 greenharness_slots::held_in_process(),
716 ceiling,
717 started.elapsed(),
718 );
719 got = wait_for_slot(sizing, machine, holder, more);
720 }
721 if let Some((stage, idx)) = &sink {
722 stage.queue(*idx, None);
723 }
724 let waited = started.elapsed();
725 CURRENT.with(|c| c.borrow_mut().queued += waited);
726 if got.is_ok() && waited >= Duration::from_secs(1) {
729 crate::hooks::common::say(&format!(
730 " (waited {} for a host slot, {} {cap})",
731 crate::hooks::common::human_secs(waited.as_secs()),
732 crate::ui::highlight("greengate.hostSlots")
733 ));
734 }
735 let ended = got.as_ref().err().and_then(Reason::ended);
738 let defer = ended.is_some();
739 let end = ended.map(greenharness_slots::LineEnd::end);
740 let cause = ended.map_or(String::new(), |end| defer_cause(end, policy, slot_wait));
741 let by_slot_wait = matches!(
742 (policy, ended),
743 (
744 BusyPolicy::Defer { .. },
745 Some(greenharness_slots::LineEnd::Ceiling { .. })
746 )
747 );
748 let outcome = match (&got, defer) {
749 (Ok(_), _) => "admitted",
750 (Err(_), true) => "deferred",
751 (Err(_), false) => "unqueued",
752 };
753 record_acquisition(
754 &name,
755 Some(jobs),
756 Some((slot_cap, machine.cores)),
757 waited,
758 outcome,
759 end,
760 );
761 let held = match got {
762 Ok(lease) => Some(lease),
763 Err(Reason::Ended(_)) => None,
765 Err(reason) => {
766 note(&reason);
767 None
768 }
769 };
770 if defer {
771 BUSY_SEEN.store(true, Ordering::SeqCst);
772 if by_slot_wait {
773 DEFERRED_BY_SLOT_WAIT.store(true, Ordering::SeqCst);
774 }
775 }
776 CURRENT.with(|c| {
777 let mut c = c.borrow_mut();
778 c.held = held;
779 c.settled = true;
780 c.jobs = Some(jobs);
781 c.sized = Some((slot_cap, machine.cores));
782 if defer {
783 c.deferred = Some(waited);
784 c.deferred_cause = cause;
785 }
786 });
787 if defer {
788 return Err(refusal());
789 }
790 }
791 Ok(CURRENT.with(|c| c.borrow().held.is_some()) || (parking() && parked().is_some()))
795}
796
797fn take_handed(handed: Parked, name: &str) -> bool {
800 let Parked { lease, jobs, sized } = handed;
801 if let Err(error) = lease.rename(&holder_for(name)) {
802 crate::hooks::common::say(&format!(
803 " host slot kept, but `{BIN} slots` may still name the previous check: {error}"
804 ));
805 }
806 record_acquisition(name, jobs, sized, Duration::ZERO, "handed", None);
807 CURRENT.with(|current| {
808 let mut current = current.borrow_mut();
809 current.held = Some(lease);
810 current.settled = true;
811 current.jobs = jobs;
812 current.sized = sized;
813 });
814 true
815}
816
817fn record_acquisition(
820 name: &str,
821 jobs: Option<u32>,
822 sized: Option<(u32, u32)>,
823 waited: Duration,
824 outcome: &str,
825 end: Option<greenharness_slots::WaitEnd>,
826) {
827 let short = crate::short_name(name);
828 greenharness_slots::record_wait_named(
829 &greenharness_slots::dir(),
830 crate::names::SLOT_HOLDER,
831 greenharness_slots::WaitContext {
832 name: Some(short),
833 place: if crate::rehearsal::in_prestage() {
834 greenharness_slots::WaitPlace::Prestage
835 } else if crate::rehearsal::in_snapshot() {
836 greenharness_slots::WaitPlace::Rehearsal
837 } else {
838 greenharness_slots::WaitPlace::Push
839 },
840 cap: sized.map(|(cap, _)| cap),
841 cores: sized.map(|(_, cores)| cores),
842 end,
843 },
844 1,
845 jobs,
846 waited.as_millis(),
847 outcome,
848 );
849}
850
851pub fn bound(cmd: &mut std::process::Command) {
855 let own = CURRENT.with(|c| c.borrow().jobs);
856 if let Some(jobs) = own.or_else(|| {
858 parking()
859 .then(|| parked().as_ref().and_then(|p| p.jobs))
860 .flatten()
861 }) {
862 greenharness_slots::bound_width(cmd, jobs);
863 }
864}
865
866fn wait_for_slot(
870 sizing: greenharness_slots::Sizing,
871 machine: greenharness_slots::Machine,
872 holder: greenharness_slots::Holder,
873 bounds: greenharness_slots::WaitBounds,
874) -> Result<greenharness_slots::Lease, Reason> {
875 let waiter = match greenharness_slots::Waiter::new_in_on(
876 &greenharness_slots::dir(),
877 sizing,
878 1,
879 holder,
880 machine,
881 ) {
882 Ok(w) => w,
883 Err(e) if e.kind() == std::io::ErrorKind::Other => {
884 return Err(Reason::DirUnsafe(e.to_string()))
885 }
886 Err(e) => return Err(Reason::Io(e.to_string())),
887 };
888 let mut said = false;
889 greenharness_slots::wait_in_line(waiter, bounds, |queue| {
890 if !said && (!queue.holders.is_empty() || queue.unknown > 0) {
891 said = true;
892 crate::hooks::common::say(&format!(" {}", behind(queue)));
893 crate::hooks::common::say(&format!(" see: {BIN} slots"));
894 }
895 })
896 .map_err(Reason::Ended)
897}
898
899pub fn behind(queue: &greenharness_slots::Queue) -> String {
901 let now = greenharness_slots::now_ms();
902 let mut who: Vec<String> = queue.holders.iter().map(|h| h.describe(now)).collect();
903 if queue.unknown > 0 {
904 who.push(format!("{} unknown (old client)", queue.unknown));
905 }
906 let reason = queue
907 .reason
908 .map_or(String::new(), |r| format!(" ({})", r.describe()));
909 format!(
910 "queued behind {}{reason} · {} waiting",
911 who.join(", "),
912 queue.waiting.max(1)
913 )
914}
915
916fn note(reason: &Reason) {
920 match reason {
921 Reason::DirUnsafe(why) => crate::hooks::common::warn(&format!(
922 "host slots are off for this check: {why}. Remove it, or set {} to a directory \
923 only you own",
924 crate::ui::highlight(DIR_ENV)
925 )),
926 Reason::Io(why) => {
927 crate::hooks::common::warn(&format!("host slots are off for this check: {why}"))
928 }
929 Reason::Ended(_) | Reason::Unsupported => {}
930 }
931}
932
933#[cfg(all(test, unix))]
934mod tests {
935 use super::*;
936
937 fn settings_from(conf: &str) -> crate::config::Settings {
938 let lines = crate::manifest::parse_lines(conf);
939 let (policy, _) = crate::policy::Policy::from_lines(&lines);
940 crate::config::Settings::new(policy)
941 }
942
943 #[test]
946 fn the_busy_policy_is_env_then_file_then_wait() {
947 let none = settings_from("");
948 let defer = settings_from("set onBusy defer\nset slotWait 5\n");
949 assert_eq!(resolve_busy(None, &none), BusyPolicy::Wait);
950 assert_eq!(
951 resolve_busy(None, &defer),
952 BusyPolicy::Defer {
953 slot_wait: Duration::from_secs(5)
954 }
955 );
956 assert_eq!(resolve_busy(Some("wait"), &defer), BusyPolicy::Wait);
957 assert_eq!(
958 resolve_busy(Some("DEFER"), &none),
959 BusyPolicy::Defer {
960 slot_wait: Duration::from_secs(60)
961 }
962 );
963 assert_eq!(
964 resolve_busy(Some("later"), &defer),
965 BusyPolicy::Defer {
966 slot_wait: Duration::from_secs(5)
967 }
968 );
969 assert_eq!(resolve_busy(Some(""), &none), BusyPolicy::Wait);
970 assert_eq!(resolve_busy(Some("now"), &defer), BusyPolicy::Now);
973 let committed = settings_from("set onBusy now\n");
974 assert_eq!(resolve_busy(None, &committed), BusyPolicy::Wait);
975 }
976
977 #[test]
980 fn each_caller_waits_by_its_row_of_the_table() {
981 use greenharness_slots::WaitBounds;
982 let s = |n| Duration::from_secs(n);
983 let (ceiling, warn) = (s(3600), s(600));
984 let defer = BusyPolicy::Defer { slot_wait: s(60) };
985 let queue = |window, ceiling| WaitPlan::Queue(WaitBounds { window, ceiling });
986 let row =
987 |slot_wait, policy, ceiling, seen| wait_plan(slot_wait, policy, ceiling, warn, seen);
988 assert_eq!(
991 row(
992 SlotWait::Policy,
993 BusyPolicy::Wait,
994 ceiling,
995 HostSeen::NotYet
996 ),
997 queue(None, ceiling)
998 );
999 assert_eq!(
1002 row(
1003 SlotWait::BoundedForWarn,
1004 BusyPolicy::Wait,
1005 ceiling,
1006 HostSeen::NotYet
1007 ),
1008 queue(None, warn)
1009 );
1010 assert_eq!(
1011 row(
1012 SlotWait::BoundedForWarn,
1013 BusyPolicy::Wait,
1014 s(100),
1015 HostSeen::NotYet
1016 ),
1017 queue(None, s(100))
1018 );
1019 assert_eq!(
1022 row(SlotWait::Policy, defer, ceiling, HostSeen::NotYet),
1023 queue(None, s(60))
1024 );
1025 assert_eq!(
1026 row(SlotWait::Policy, defer, ceiling, HostSeen::Busy),
1027 queue(None, Duration::ZERO)
1028 );
1029 assert_eq!(
1031 row(
1032 SlotWait::NeverWaits,
1033 BusyPolicy::Wait,
1034 ceiling,
1035 HostSeen::NotYet
1036 ),
1037 queue(None, Duration::ZERO)
1038 );
1039 assert_eq!(
1041 row(SlotWait::Policy, BusyPolicy::Now, ceiling, HostSeen::NotYet),
1042 WaitPlan::Now
1043 );
1044 }
1045
1046 #[test]
1050 fn the_sibling_extension_waits_to_the_ceiling() {
1051 let s = |n| Duration::from_secs(n);
1052 let with_sibling = sibling_bounds(SlotWait::Policy, 1, s(3600), s(60));
1053 assert_eq!(
1054 with_sibling.window, None,
1055 "no stall window on the hook path"
1056 );
1057 assert_eq!(with_sibling.ceiling, s(3540));
1058 let alone = sibling_bounds(SlotWait::Policy, 0, s(3600), s(60));
1059 assert_eq!((alone.window, alone.ceiling), (None, Duration::ZERO));
1060 let never = sibling_bounds(SlotWait::NeverWaits, 1, s(3600), s(60));
1061 assert_eq!((never.window, never.ceiling), (None, Duration::ZERO));
1062 }
1063
1064 #[test]
1068 fn a_deferral_names_its_cause() {
1069 use greenharness_slots::LineEnd;
1070 let stalled = LineEnd::Stalled {
1071 window: Duration::from_secs(300),
1072 position: 1,
1073 };
1074 let cause = defer_cause(
1075 &stalled,
1076 BusyPolicy::Defer {
1077 slot_wait: Duration::from_secs(60),
1078 },
1079 SlotWait::Policy,
1080 );
1081 assert!(cause.contains("made no progress for 5m00s"), "{cause}");
1082 assert!(cause.contains("(position 2)"), "{cause}");
1083 let slot_wait = defer_cause(
1084 &LineEnd::Ceiling {
1085 waited: Duration::from_secs(60),
1086 },
1087 BusyPolicy::Defer {
1088 slot_wait: Duration::from_secs(60),
1089 },
1090 SlotWait::Policy,
1091 );
1092 assert!(
1093 slot_wait.ends_with("(greengate.onBusy defer)"),
1094 "{slot_wait}"
1095 );
1096 let ceiling = defer_cause(
1097 &LineEnd::Ceiling {
1098 waited: Duration::from_secs(3600),
1099 },
1100 BusyPolicy::Wait,
1101 SlotWait::Policy,
1102 );
1103 assert!(ceiling.contains("no host slot within 1h00m"), "{ceiling}");
1104 assert!(ceiling.ends_with("(greengate.timeout)"), "{ceiling}");
1105 let warn = defer_cause(
1106 &LineEnd::Ceiling {
1107 waited: Duration::from_secs(600),
1108 },
1109 BusyPolicy::Wait,
1110 SlotWait::BoundedForWarn,
1111 );
1112 assert!(warn.ends_with("(greengate.warnSlotWait)"), "{warn}");
1113 let failed = defer_cause(
1114 &LineEnd::PollFailed {
1115 error: std::io::Error::other("busy disk"),
1116 },
1117 BusyPolicy::Wait,
1118 SlotWait::Policy,
1119 );
1120 assert!(failed.contains("busy disk"), "{failed}");
1121 }
1122
1123 #[test]
1126 fn every_end_of_a_wait_in_line_defers() {
1127 let ended = Reason::Ended(greenharness_slots::LineEnd::Ceiling {
1128 waited: Duration::from_secs(1),
1129 });
1130 assert!(ended.ended().is_some());
1131 for reason in [
1132 Reason::Io("x".into()),
1133 Reason::DirUnsafe("x".into()),
1134 Reason::Unsupported,
1135 ] {
1136 assert!(reason.ended().is_none(), "{reason:?}");
1137 }
1138 }
1139
1140 #[test]
1141 fn heavy_is_the_list() {
1142 assert_eq!(weight_of("pre-commit-clippy"), Weight::Heavy);
1143 assert_eq!(weight_of("pre-commit-cargo-fmt"), Weight::Light);
1144 }
1145
1146 #[test]
1149 fn every_heavy_name_is_a_builtin() {
1150 for name in HEAVY {
1151 assert!(
1152 crate::registry::CHECKS.iter().any(|c| c.name == *name),
1153 "{name} is not a built-in check"
1154 );
1155 }
1156 }
1157
1158 #[test]
1164 fn cargo_pins_the_host_knobs_for_tests() {
1165 assert_eq!(std::env::var(HELD_ENV).as_deref(), Ok(""));
1166 assert_eq!(
1167 std::env::var(greenharness_slots::host::SLOTS_ENV).as_deref(),
1168 Ok("0")
1169 );
1170 assert_eq!(
1171 std::env::var("GREENGATE_IDLE_LOAD_SCALE").as_deref(),
1172 Ok("1")
1173 );
1174 }
1175
1176 #[test]
1180 fn a_light_check_never_takes_a_slot() {
1181 let settings = crate::config::Settings::default();
1182 let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1183 assert!(!before_spawn(&settings).unwrap());
1184 }
1185
1186 #[test]
1187 fn a_heavy_check_with_slots_off_settles_without_a_slot() {
1188 let settings = crate::config::Settings::default();
1189 let _g = enter_check("pre-commit-clippy", weight_of("pre-commit-clippy"));
1190 assert_eq!(current_check().as_deref(), Some("clippy"));
1191 assert!(!before_spawn(&settings).unwrap());
1192 assert!(CURRENT.with(|c| c.borrow().settled));
1193 let mut cmd = std::process::Command::new("true");
1195 bound(&mut cmd);
1196 assert_eq!(cmd.get_envs().count(), 0);
1197 }
1198
1199 #[test]
1202 fn a_park_scope_dropped_early_releases_the_parked_slot() {
1203 let dir = std::env::temp_dir().join(format!("greengate-park-{}", std::process::id()));
1204 let _ = std::fs::remove_dir_all(&dir); let early = || {
1206 let _scope = ParkScope::begin();
1207 let mut waiter = greenharness_slots::Waiter::new_in(
1208 &dir,
1209 greenharness_slots::Sizing::Fixed(1),
1210 1,
1211 greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, "gate"),
1212 )
1213 .unwrap();
1214 let greenharness_slots::Poll::Granted(lease) = waiter.poll().unwrap() else {
1215 panic!("the empty directory grants the slot");
1216 };
1217 assert!(dir.join("holders/slot-0.who").exists());
1218 park(lease, Some(2), Some((3, 6)));
1219 assert!(dir.join("holders/slot-0.who").exists());
1220 };
1221 early();
1222 assert!(!dir.join("holders/slot-0.who").exists());
1223 let _ = std::fs::remove_dir_all(&dir); }
1225
1226 #[test]
1227 fn a_light_check_sets_no_width() {
1228 let settings = crate::config::Settings::default();
1229 let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1230 before_spawn(&settings).unwrap();
1231 let mut cmd = std::process::Command::new("true");
1232 bound(&mut cmd);
1233 assert_eq!(cmd.get_envs().count(), 0);
1234 }
1235}