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, Clone, PartialEq, Eq)]
53pub enum Reason {
54 DirUnsafe(String),
56 Unsupported,
58 TimedOut(Duration),
60 Io(String),
63}
64
65static BUSY_SEEN: AtomicBool = AtomicBool::new(false);
69
70pub fn sizing(settings: &crate::config::Settings) -> Option<greenharness_slots::Sizing> {
73 match crate::config::host_integer_or(settings, "amont.hostSlots", -1, 0..=64) {
74 0 => None,
75 n if n < 0 => Some(greenharness_slots::Sizing::Auto),
76 n => Some(greenharness_slots::Sizing::Fixed(n as u32)),
77 }
78}
79
80pub const ON_BUSY_ENV: &str = "AMONT_ON_BUSY";
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum BusyPolicy {
88 Wait,
91 Defer { slot_wait: Duration },
93}
94
95pub fn busy_policy(settings: &crate::config::Settings) -> BusyPolicy {
98 resolve_busy(std::env::var(ON_BUSY_ENV).ok().as_deref(), settings)
99}
100
101fn resolve_busy(from_env: Option<&str>, settings: &crate::config::Settings) -> BusyPolicy {
104 let from_env = from_env.filter(|v| !v.is_empty());
105 let mode = match from_env.map(str::to_ascii_lowercase).as_deref() {
106 Some("wait") => "wait",
107 Some("defer") => "defer",
108 Some(other) => {
109 crate::config::complain(
110 ON_BUSY_ENV,
111 &format!("{other:?} is not one of wait, defer"),
112 "amont.onBusy",
113 );
114 crate::config::enumerated_or(settings, "amont.onBusy", &["wait", "defer"], "wait")
115 }
116 None => crate::config::enumerated_or(settings, "amont.onBusy", &["wait", "defer"], "wait"),
117 };
118 if mode == "defer" {
119 let secs = crate::config::integer_or(settings, "amont.slotWait", 60, 1..=3600) as u64;
120 BusyPolicy::Defer {
121 slot_wait: Duration::from_secs(secs),
122 }
123 } else {
124 BusyPolicy::Wait
125 }
126}
127
128#[derive(Default)]
130struct Current {
131 name: String,
133 heavy: bool,
134 settled: bool,
137 held: Option<greenharness_slots::Lease>,
138 queued: Duration,
139 deferred: Option<Duration>,
145 jobs: Option<u32>,
149 slot_wait: SlotWait,
151}
152
153#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
155enum SlotWait {
156 #[default]
158 Policy,
159 NeverWaits,
165 BoundedForWarn,
169}
170
171struct Parked {
174 lease: greenharness_slots::Lease,
175 jobs: Option<u32>,
176}
177
178static PARKED: Mutex<Option<Parked>> = Mutex::new(None);
182
183static PARK_SCOPE_DEPTH: AtomicUsize = AtomicUsize::new(0);
186
187fn parked() -> std::sync::MutexGuard<'static, Option<Parked>> {
188 PARKED
189 .lock()
190 .unwrap_or_else(|poisoned| poisoned.into_inner())
191}
192
193fn parking() -> bool {
197 PARK_SCOPE_DEPTH.load(Ordering::SeqCst) > 0 && crate::rehearsal::in_snapshot()
198}
199
200#[must_use = "the scope releases the parked slot when dropped"]
204pub struct ParkScope {
205 _private: (),
206}
207
208impl ParkScope {
209 #[must_use = "the scope releases the parked slot when dropped"]
210 pub fn begin() -> ParkScope {
211 PARK_SCOPE_DEPTH.fetch_add(1, Ordering::SeqCst);
212 ParkScope { _private: () }
213 }
214}
215
216impl Drop for ParkScope {
217 fn drop(&mut self) {
218 if PARK_SCOPE_DEPTH.fetch_sub(1, Ordering::SeqCst) == 1 {
219 release_parked();
220 }
221 }
222}
223
224pub fn release_parked() {
229 let leftover = parked().take();
230 drop(leftover);
231}
232
233fn between_gates() -> greenharness_slots::Holder {
235 holder_for("pre-push, between checks")
236}
237
238fn holder_for(command: &str) -> greenharness_slots::Holder {
243 let mut holder = greenharness_slots::Holder::here("amont", command);
244 if let Some(src) = crate::rehearsal::source_worktree() {
245 holder.repo = src.display().to_string();
246 }
247 holder
248}
249
250thread_local! {
251 static CURRENT: RefCell<Current> = RefCell::new(Current::default());
252}
253
254pub struct CheckGuard;
257
258impl CheckGuard {
259 pub fn queued(&self) -> Duration {
261 CURRENT.with(|c| c.borrow().queued)
262 }
263
264 pub fn deferred(&self) -> Option<Duration> {
267 CURRENT.with(|c| c.borrow().deferred)
268 }
269}
270
271pub fn deferred_here() -> bool {
274 CURRENT.with(|c| c.borrow().deferred.is_some())
275}
276
277fn refusal() -> std::io::Error {
280 std::io::Error::other("deferred to CI: no host slot freed (amont.onBusy defer)")
281}
282
283impl Drop for CheckGuard {
284 fn drop(&mut self) {
285 let finished = CURRENT.with(RefCell::take);
286 if let Some(lease) = finished.held {
287 if parking() {
288 park(lease, finished.jobs);
289 }
290 }
291 }
292}
293
294fn park(lease: greenharness_slots::Lease, jobs: Option<u32>) {
297 if let Err(error) = lease.rename(&between_gates()) {
298 crate::hooks::common::say(&format!(
299 " host slot kept, but `{BIN} slots` may still name the previous check: {error}"
300 ));
301 }
302 let earlier = parked().replace(Parked { lease, jobs });
303 drop(earlier);
304}
305
306pub fn enter_check(name: &str, weight: Weight) -> CheckGuard {
310 CURRENT.with(|c| {
311 *c.borrow_mut() = Current {
312 name: name.to_string(),
313 heavy: weight == Weight::Heavy,
314 ..Current::default()
315 }
316 });
317 CheckGuard
318}
319
320pub fn never_waits() {
328 CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::NeverWaits);
329}
330
331pub fn wait_bounded_for_warn() {
336 CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::BoundedForWarn);
337}
338
339fn warn_slot_wait(settings: &crate::config::Settings) -> Duration {
342 Duration::from_secs(
343 crate::config::integer_or(settings, "amont.warnSlotWait", 600, 1..=3600) as u64,
344 )
345}
346
347pub fn current_check() -> Option<String> {
350 CURRENT.with(|c| {
351 let c = c.borrow();
352 (!c.name.is_empty()).then(|| crate::short_name(&c.name).to_string())
353 })
354}
355
356fn nested() -> bool {
358 std::env::var_os(HELD_ENV).is_some_and(|v| !v.is_empty())
359}
360
361pub fn before_spawn(settings: &crate::config::Settings) -> std::io::Result<bool> {
366 let (pending, deferred, name, slot_wait) = CURRENT.with(|current| {
367 let current = current.borrow();
368 (
369 current.heavy && !current.settled,
370 current.deferred.is_some(),
371 current.name.clone(),
372 current.slot_wait,
373 )
374 });
375 if deferred {
378 return Err(refusal());
379 }
380 if pending {
381 if let Some(handed) = parking().then(|| parked().take()).flatten() {
382 return Ok(take_handed(handed, &name));
383 }
384 let sizing = if nested() { None } else { sizing(settings) };
388 let Some(sizing) = sizing else {
389 CURRENT.with(|c| c.borrow_mut().settled = true);
390 return Ok(false);
391 };
392 if !greenharness_slots::SUPPORTED {
393 CURRENT.with(|c| c.borrow_mut().settled = true);
394 return Ok(false);
395 }
396 let policy = match slot_wait {
397 SlotWait::NeverWaits => BusyPolicy::Defer {
398 slot_wait: Duration::ZERO,
399 },
400 SlotWait::BoundedForWarn => BusyPolicy::Wait,
401 SlotWait::Policy => busy_policy(settings),
402 };
403 let ceiling = Duration::from_secs(match crate::hooks::common::check_timeout(settings) {
404 0 => 3600,
405 s => s,
406 });
407 let warn_wait = warn_slot_wait(settings);
408 let cut_by_warn_wait =
409 matches!(slot_wait, SlotWait::BoundedForWarn) && warn_wait <= ceiling;
410 let budget = match policy {
411 BusyPolicy::Wait if matches!(slot_wait, SlotWait::BoundedForWarn) => {
412 warn_wait.min(ceiling)
413 }
414 BusyPolicy::Wait => ceiling,
415 BusyPolicy::Defer { .. } if BUSY_SEEN.load(Ordering::SeqCst) => Duration::ZERO,
417 BusyPolicy::Defer { slot_wait } => slot_wait,
418 };
419 let cap = u64::from(sizing.cap());
420 let jobs = greenharness_slots::parallelism(1, greenharness_slots::cores(), sizing.cap());
423 let sink = crate::live::current_sink();
424 if let Some((stage, idx)) = &sink {
425 stage.queue(*idx, Some((Instant::now(), cap)));
426 }
427 let started = Instant::now();
428 let holder = holder_for(&name);
429 let mut got = wait_for_slot(sizing, holder.clone(), budget);
430 if let (BusyPolicy::Defer { .. }, Err(Reason::TimedOut(_))) = (policy, &got) {
431 let rest = if greenharness_slots::held_in_process() > 0
436 && !matches!(slot_wait, SlotWait::NeverWaits)
437 {
438 ceiling.saturating_sub(started.elapsed())
439 } else {
440 Duration::ZERO
441 };
442 got = wait_for_slot(sizing, holder, rest);
443 }
444 if let Some((stage, idx)) = &sink {
445 stage.queue(*idx, None);
446 }
447 let waited = started.elapsed();
448 CURRENT.with(|c| c.borrow_mut().queued += waited);
449 if got.is_ok() && waited >= Duration::from_secs(1) {
452 crate::hooks::common::say(&format!(
453 " (waited {} for a host slot, {} {cap})",
454 crate::hooks::common::human_secs(waited.as_secs()),
455 crate::ui::highlight("amont.hostSlots")
456 ));
457 }
458 let defer =
459 matches!(policy, BusyPolicy::Defer { .. }) && matches!(got, Err(Reason::TimedOut(_)));
460 let outcome = match (&got, defer) {
461 (Ok(_), _) => "admitted",
462 (Err(_), true) => "deferred",
463 (Err(_), false) => "unqueued",
464 };
465 record_acquisition(&name, Some(jobs), waited, outcome);
466 let held = match got {
467 Ok(lease) => Some(lease),
468 Err(_) if defer => None,
470 Err(reason) => {
471 note(&reason, cap, cut_by_warn_wait.then_some(warn_wait));
472 None
473 }
474 };
475 if defer {
476 BUSY_SEEN.store(true, Ordering::SeqCst);
477 }
478 CURRENT.with(|c| {
479 let mut c = c.borrow_mut();
480 c.held = held;
481 c.settled = true;
482 c.jobs = Some(jobs);
483 if defer {
484 c.deferred = Some(waited);
485 }
486 });
487 if defer {
488 return Err(refusal());
489 }
490 }
491 Ok(CURRENT.with(|c| c.borrow().held.is_some()) || (parking() && parked().is_some()))
495}
496
497fn take_handed(handed: Parked, name: &str) -> bool {
500 let Parked { lease, jobs } = handed;
501 if let Err(error) = lease.rename(&holder_for(name)) {
502 crate::hooks::common::say(&format!(
503 " host slot kept, but `{BIN} slots` may still name the previous check: {error}"
504 ));
505 }
506 record_acquisition(name, jobs, Duration::ZERO, "handed");
507 CURRENT.with(|current| {
508 let mut current = current.borrow_mut();
509 current.held = Some(lease);
510 current.settled = true;
511 current.jobs = jobs;
512 });
513 true
514}
515
516fn record_acquisition(name: &str, jobs: Option<u32>, waited: Duration, outcome: &str) {
518 let short = crate::short_name(name);
519 greenharness_slots::record_wait_named(
520 &greenharness_slots::dir(),
521 "amont",
522 greenharness_slots::WaitContext {
523 name: Some(short),
524 place: if crate::rehearsal::in_prestage() {
525 greenharness_slots::WaitPlace::Prestage
526 } else if crate::rehearsal::in_snapshot() {
527 greenharness_slots::WaitPlace::Rehearsal
528 } else {
529 greenharness_slots::WaitPlace::Push
530 },
531 },
532 1,
533 jobs,
534 waited.as_millis(),
535 outcome,
536 );
537}
538
539pub fn bound(cmd: &mut std::process::Command) {
543 let own = CURRENT.with(|c| c.borrow().jobs);
544 if let Some(jobs) = own.or_else(|| {
546 parking()
547 .then(|| parked().as_ref().and_then(|p| p.jobs))
548 .flatten()
549 }) {
550 greenharness_slots::bound_width(cmd, jobs);
551 }
552}
553
554fn wait_for_slot(
557 sizing: greenharness_slots::Sizing,
558 holder: greenharness_slots::Holder,
559 budget: Duration,
560) -> Result<greenharness_slots::Lease, Reason> {
561 let started = Instant::now();
562 let mut waiter = match greenharness_slots::Waiter::new(sizing, 1, holder) {
563 Ok(w) => w,
564 Err(e) if e.kind() == std::io::ErrorKind::Other => {
565 return Err(Reason::DirUnsafe(e.to_string()))
566 }
567 Err(e) => return Err(Reason::Io(e.to_string())),
568 };
569 let mut said = false;
570 loop {
571 match waiter.poll() {
572 Ok(greenharness_slots::Poll::Granted(lease)) => return Ok(lease),
573 Ok(greenharness_slots::Poll::Waiting(queue)) => {
574 if !said && (!queue.holders.is_empty() || queue.unknown > 0) {
575 said = true;
576 crate::hooks::common::say(&format!(" {}", behind(&queue)));
577 }
578 }
579 Err(e) => return Err(Reason::Io(e.to_string())),
580 }
581 if started.elapsed() >= budget {
582 return Err(Reason::TimedOut(started.elapsed()));
583 }
584 std::thread::sleep(Duration::from_millis(200));
585 }
586}
587
588pub fn behind(queue: &greenharness_slots::Queue) -> String {
590 let now = greenharness_slots::now_ms();
591 let mut who: Vec<String> = queue.holders.iter().map(|h| h.describe(now)).collect();
592 if queue.unknown > 0 {
593 who.push(format!("{} unknown (old client)", queue.unknown));
594 }
595 format!(
596 "queued behind {} · {} waiting",
597 who.join(", "),
598 queue.waiting.max(1)
599 )
600}
601
602fn note(reason: &Reason, cap: u64, warn_wait: Option<Duration>) {
608 match reason {
609 Reason::DirUnsafe(why) => crate::hooks::common::warn(&format!(
610 "host slots are off for this check: {why}. Remove it, or set {} to a directory \
611 only you own",
612 crate::ui::highlight(DIR_ENV)
613 )),
614 Reason::TimedOut(waited) if warn_wait.is_some() => crate::hooks::common::warn(&format!(
615 "no host slot in {} (land: {}={}s); running it anyway",
616 crate::hooks::common::human_secs(waited.as_secs()),
617 crate::ui::highlight("amont.warnSlotWait"),
618 warn_wait.map_or(0, |limit| limit.as_secs())
619 )),
620 Reason::TimedOut(waited) => crate::hooks::common::warn(&format!(
621 "no host slot freed in {} ({} {cap}); running it anyway",
622 crate::hooks::common::human_secs(waited.as_secs()),
623 crate::ui::highlight("amont.hostSlots")
624 )),
625 Reason::Io(why) => {
626 crate::hooks::common::warn(&format!("host slots are off for this check: {why}"))
627 }
628 Reason::Unsupported => {}
629 }
630}
631
632#[cfg(all(test, unix))]
633mod tests {
634 use super::*;
635
636 fn settings_from(conf: &str) -> crate::config::Settings {
637 let lines = crate::manifest::parse_lines(conf);
638 let (policy, _) = crate::policy::Policy::from_lines(&lines);
639 crate::config::Settings::new(policy)
640 }
641
642 #[test]
645 fn the_busy_policy_is_env_then_file_then_wait() {
646 let none = settings_from("");
647 let defer = settings_from("set onBusy defer\nset slotWait 5\n");
648 assert_eq!(resolve_busy(None, &none), BusyPolicy::Wait);
649 assert_eq!(
650 resolve_busy(None, &defer),
651 BusyPolicy::Defer {
652 slot_wait: Duration::from_secs(5)
653 }
654 );
655 assert_eq!(resolve_busy(Some("wait"), &defer), BusyPolicy::Wait);
656 assert_eq!(
657 resolve_busy(Some("DEFER"), &none),
658 BusyPolicy::Defer {
659 slot_wait: Duration::from_secs(60)
660 }
661 );
662 assert_eq!(
663 resolve_busy(Some("later"), &defer),
664 BusyPolicy::Defer {
665 slot_wait: Duration::from_secs(5)
666 }
667 );
668 assert_eq!(resolve_busy(Some(""), &none), BusyPolicy::Wait);
669 }
670
671 #[test]
672 fn heavy_is_the_list() {
673 assert_eq!(weight_of("pre-commit-clippy"), Weight::Heavy);
674 assert_eq!(weight_of("pre-commit-cargo-fmt"), Weight::Light);
675 }
676
677 #[test]
680 fn every_heavy_name_is_a_builtin() {
681 for name in HEAVY {
682 assert!(
683 crate::registry::CHECKS.iter().any(|c| c.name == *name),
684 "{name} is not a built-in check"
685 );
686 }
687 }
688
689 #[test]
692 fn cargo_pins_the_host_knobs_for_tests() {
693 assert_eq!(std::env::var(HELD_ENV).as_deref(), Ok("held"));
694 assert_eq!(std::env::var("AMONT_IDLE_LOAD_SCALE").as_deref(), Ok("1"));
695 }
696
697 #[test]
701 fn a_light_check_never_takes_a_slot() {
702 let settings = crate::config::Settings::default();
703 let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
704 assert!(!before_spawn(&settings).unwrap());
705 }
706
707 #[test]
708 fn a_nested_heavy_check_settles_without_a_slot() {
709 let settings = crate::config::Settings::default();
710 let _g = enter_check("pre-commit-clippy", weight_of("pre-commit-clippy"));
711 assert_eq!(current_check().as_deref(), Some("clippy"));
712 assert!(!before_spawn(&settings).unwrap());
713 assert!(CURRENT.with(|c| c.borrow().settled));
714 let mut cmd = std::process::Command::new("true");
716 bound(&mut cmd);
717 assert_eq!(cmd.get_envs().count(), 0);
718 }
719
720 #[test]
723 fn a_park_scope_dropped_early_releases_the_parked_slot() {
724 let dir = std::env::temp_dir().join(format!("amont-park-{}", std::process::id()));
725 let _ = std::fs::remove_dir_all(&dir); let early = || {
727 let _scope = ParkScope::begin();
728 let mut waiter = greenharness_slots::Waiter::new_in(
729 &dir,
730 greenharness_slots::Sizing::Fixed(1),
731 1,
732 greenharness_slots::Holder::here("amont", "gate"),
733 )
734 .unwrap();
735 let greenharness_slots::Poll::Granted(lease) = waiter.poll().unwrap() else {
736 panic!("the empty directory grants the slot");
737 };
738 assert!(dir.join("holders/slot-0.who").exists());
739 park(lease, Some(2));
740 assert!(dir.join("holders/slot-0.who").exists());
741 };
742 early();
743 assert!(!dir.join("holders/slot-0.who").exists());
744 let _ = std::fs::remove_dir_all(&dir); }
746
747 #[test]
748 fn a_light_check_sets_no_width() {
749 let settings = crate::config::Settings::default();
750 let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
751 before_spawn(&settings).unwrap();
752 let mut cmd = std::process::Command::new("true");
753 bound(&mut cmd);
754 assert_eq!(cmd.get_envs().count(), 0);
755 }
756}