use crate::names::BIN;
use std::cell::RefCell;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Mutex;
use std::time::{Duration, Instant};
pub use greenharness_slots::{DIR_ENV, HELD_ENV};
pub const HEAVY: &[&str] = &[
"pre-commit-clippy",
"pre-commit-go-vet",
"pre-commit-pyright",
"pre-push-run-tests-js",
"pre-push-cargo-test",
"pre-push-go-test",
"pre-push-pytest",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Weight {
Light,
Heavy,
}
pub fn weight_of(name: &str) -> Weight {
if HEAVY.contains(&name) {
Weight::Heavy
} else {
Weight::Light
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Reason {
DirUnsafe(String),
Unsupported,
TimedOut(Duration),
Io(String),
}
static BUSY_SEEN: AtomicBool = AtomicBool::new(false);
pub fn host_sizing(settings: &crate::config::Settings) -> greenharness_slots::host::HostSizing {
let rows = crate::config::host_rows(settings);
let mut sizing = greenharness_slots::host::resolve(
|name| std::env::var(name).ok(),
rows.unwrap_or(&[]),
greenharness_slots::detect_cores(),
);
if rows.is_none() {
sizing
.warnings
.push(greenharness_slots::host::NO_SCOPES_WARNING.to_string());
}
for warning in &sizing.warnings {
say_once(warning);
}
sizing
}
fn say_once(warning: &str) {
use std::collections::BTreeSet;
use std::sync::{Mutex, OnceLock};
static SAID: OnceLock<Mutex<BTreeSet<String>>> = OnceLock::new();
let said = SAID.get_or_init(|| Mutex::new(BTreeSet::new()));
let fresh = match said.lock() {
Ok(mut set) => set.insert(warning.to_string()),
Err(_) => true,
};
if fresh {
eprintln!("{}: warning: {warning}", crate::names::BIN);
}
}
pub fn sizing_and_machine(
settings: &crate::config::Settings,
) -> (
Option<greenharness_slots::Sizing>,
greenharness_slots::Machine,
) {
let host = host_sizing(settings);
(
host.slots.value,
greenharness_slots::Machine {
cores: host.cores.value.max(1),
},
)
}
pub fn sizing(settings: &crate::config::Settings) -> Option<greenharness_slots::Sizing> {
sizing_and_machine(settings).0
}
pub const ON_BUSY_ENV: &str = "GREENGATE_ON_BUSY";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BusyPolicy {
Wait,
Defer { slot_wait: Duration },
}
pub fn busy_policy(settings: &crate::config::Settings) -> BusyPolicy {
resolve_busy(std::env::var(ON_BUSY_ENV).ok().as_deref(), settings)
}
fn resolve_busy(from_env: Option<&str>, settings: &crate::config::Settings) -> BusyPolicy {
let from_env = from_env.filter(|v| !v.is_empty());
let mode = match from_env.map(str::to_ascii_lowercase).as_deref() {
Some("wait") => "wait",
Some("defer") => "defer",
Some(other) => {
crate::config::complain(
ON_BUSY_ENV,
&format!("{other:?} is not one of wait, defer"),
"greengate.onBusy",
);
crate::config::enumerated_or(settings, "greengate.onBusy", &["wait", "defer"], "wait")
}
None => {
crate::config::enumerated_or(settings, "greengate.onBusy", &["wait", "defer"], "wait")
}
};
if mode == "defer" {
let secs = crate::config::integer_or(settings, "greengate.slotWait", 60, 1..=3600) as u64;
BusyPolicy::Defer {
slot_wait: Duration::from_secs(secs),
}
} else {
BusyPolicy::Wait
}
}
#[derive(Default)]
struct Current {
name: String,
heavy: bool,
settled: bool,
held: Option<greenharness_slots::Lease>,
queued: Duration,
deferred: Option<Duration>,
jobs: Option<u32>,
sized: Option<(u32, u32)>,
slot_wait: SlotWait,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum SlotWait {
#[default]
Policy,
NeverWaits,
BoundedForWarn,
}
struct Parked {
lease: greenharness_slots::Lease,
jobs: Option<u32>,
sized: Option<(u32, u32)>,
}
static PARKED: Mutex<Option<Parked>> = Mutex::new(None);
static PARK_SCOPE_DEPTH: AtomicUsize = AtomicUsize::new(0);
fn parked() -> std::sync::MutexGuard<'static, Option<Parked>> {
PARKED
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn parking() -> bool {
PARK_SCOPE_DEPTH.load(Ordering::SeqCst) > 0 && crate::rehearsal::in_snapshot()
}
#[must_use = "the scope releases the parked slot when dropped"]
pub struct ParkScope {
_private: (),
}
impl ParkScope {
#[must_use = "the scope releases the parked slot when dropped"]
pub fn begin() -> ParkScope {
PARK_SCOPE_DEPTH.fetch_add(1, Ordering::SeqCst);
ParkScope { _private: () }
}
}
impl Drop for ParkScope {
fn drop(&mut self) {
if PARK_SCOPE_DEPTH.fetch_sub(1, Ordering::SeqCst) == 1 {
release_parked();
}
}
}
pub fn release_parked() {
let leftover = parked().take();
drop(leftover);
}
fn between_gates() -> greenharness_slots::Holder {
holder_for("pre-push, between checks")
}
fn holder_for(command: &str) -> greenharness_slots::Holder {
let mut holder = greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, command);
if let Some(src) = crate::rehearsal::source_worktree() {
holder.repo = src.display().to_string();
}
holder
}
thread_local! {
static CURRENT: RefCell<Current> = RefCell::new(Current::default());
}
pub struct CheckGuard;
impl CheckGuard {
pub fn queued(&self) -> Duration {
CURRENT.with(|c| c.borrow().queued)
}
pub fn deferred(&self) -> Option<Duration> {
CURRENT.with(|c| c.borrow().deferred)
}
}
pub fn deferred_here() -> bool {
CURRENT.with(|c| c.borrow().deferred.is_some())
}
fn refusal() -> std::io::Error {
std::io::Error::other("deferred to CI: no host slot freed (greengate.onBusy defer)")
}
impl Drop for CheckGuard {
fn drop(&mut self) {
let finished = CURRENT.with(RefCell::take);
if let Some(lease) = finished.held {
if parking() {
park(lease, finished.jobs, finished.sized);
}
}
}
}
fn park(lease: greenharness_slots::Lease, jobs: Option<u32>, sized: Option<(u32, u32)>) {
if let Err(error) = lease.rename(&between_gates()) {
crate::hooks::common::say(&format!(
" host slot kept, but `{BIN} slots` may still name the previous check: {error}"
));
}
let earlier = parked().replace(Parked { lease, jobs, sized });
drop(earlier);
}
pub fn enter_check(name: &str, weight: Weight) -> CheckGuard {
CURRENT.with(|c| {
*c.borrow_mut() = Current {
name: name.to_string(),
heavy: weight == Weight::Heavy,
..Current::default()
}
});
CheckGuard
}
pub fn never_waits() {
CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::NeverWaits);
}
pub fn wait_bounded_for_warn() {
CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::BoundedForWarn);
}
fn warn_slot_wait(settings: &crate::config::Settings) -> Duration {
Duration::from_secs(
crate::config::integer_or(settings, "greengate.warnSlotWait", 600, 1..=3600) as u64,
)
}
pub fn current_check() -> Option<String> {
CURRENT.with(|c| {
let c = c.borrow();
(!c.name.is_empty()).then(|| crate::short_name(&c.name).to_string())
})
}
fn nested() -> bool {
std::env::var_os(HELD_ENV).is_some_and(|v| !v.is_empty())
}
pub fn before_spawn(settings: &crate::config::Settings) -> std::io::Result<bool> {
let (pending, deferred, name, slot_wait) = CURRENT.with(|current| {
let current = current.borrow();
(
current.heavy && !current.settled,
current.deferred.is_some(),
current.name.clone(),
current.slot_wait,
)
});
if deferred {
return Err(refusal());
}
if pending {
if let Some(handed) = parking().then(|| parked().take()).flatten() {
return Ok(take_handed(handed, &name));
}
let (sizing, machine) = if nested() {
(None, greenharness_slots::Machine::detect())
} else {
sizing_and_machine(settings)
};
let Some(sizing) = sizing else {
CURRENT.with(|c| c.borrow_mut().settled = true);
return Ok(false);
};
if !greenharness_slots::SUPPORTED {
CURRENT.with(|c| c.borrow_mut().settled = true);
return Ok(false);
}
let policy = match slot_wait {
SlotWait::NeverWaits => BusyPolicy::Defer {
slot_wait: Duration::ZERO,
},
SlotWait::BoundedForWarn => BusyPolicy::Wait,
SlotWait::Policy => busy_policy(settings),
};
let ceiling = Duration::from_secs(match crate::hooks::common::check_timeout(settings) {
0 => 3600,
s => s,
});
let warn_wait = warn_slot_wait(settings);
let cut_by_warn_wait =
matches!(slot_wait, SlotWait::BoundedForWarn) && warn_wait <= ceiling;
let budget = match policy {
BusyPolicy::Wait if matches!(slot_wait, SlotWait::BoundedForWarn) => {
warn_wait.min(ceiling)
}
BusyPolicy::Wait => ceiling,
BusyPolicy::Defer { .. } if BUSY_SEEN.load(Ordering::SeqCst) => Duration::ZERO,
BusyPolicy::Defer { slot_wait } => slot_wait,
};
let slot_cap = sizing.cap_for(machine.cores);
let cap = u64::from(slot_cap);
let jobs = greenharness_slots::parallelism(1, machine.cores, slot_cap);
let sink = crate::live::current_sink();
if let Some((stage, idx)) = &sink {
stage.queue(*idx, Some((Instant::now(), cap)));
}
let started = Instant::now();
let holder = holder_for(&name);
let mut got = wait_for_slot(sizing, machine, holder.clone(), budget);
if let (BusyPolicy::Defer { .. }, Err(Reason::TimedOut(_))) = (policy, &got) {
let rest = if greenharness_slots::held_in_process() > 0
&& !matches!(slot_wait, SlotWait::NeverWaits)
{
ceiling.saturating_sub(started.elapsed())
} else {
Duration::ZERO
};
got = wait_for_slot(sizing, machine, holder, rest);
}
if let Some((stage, idx)) = &sink {
stage.queue(*idx, None);
}
let waited = started.elapsed();
CURRENT.with(|c| c.borrow_mut().queued += waited);
if got.is_ok() && waited >= Duration::from_secs(1) {
crate::hooks::common::say(&format!(
" (waited {} for a host slot, {} {cap})",
crate::hooks::common::human_secs(waited.as_secs()),
crate::ui::highlight("greengate.hostSlots")
));
}
let defer =
matches!(policy, BusyPolicy::Defer { .. }) && matches!(got, Err(Reason::TimedOut(_)));
let outcome = match (&got, defer) {
(Ok(_), _) => "admitted",
(Err(_), true) => "deferred",
(Err(_), false) => "unqueued",
};
record_acquisition(
&name,
Some(jobs),
Some((slot_cap, machine.cores)),
waited,
outcome,
);
let held = match got {
Ok(lease) => Some(lease),
Err(_) if defer => None,
Err(reason) => {
note(&reason, cap, cut_by_warn_wait.then_some(warn_wait));
None
}
};
if defer {
BUSY_SEEN.store(true, Ordering::SeqCst);
}
CURRENT.with(|c| {
let mut c = c.borrow_mut();
c.held = held;
c.settled = true;
c.jobs = Some(jobs);
c.sized = Some((slot_cap, machine.cores));
if defer {
c.deferred = Some(waited);
}
});
if defer {
return Err(refusal());
}
}
Ok(CURRENT.with(|c| c.borrow().held.is_some()) || (parking() && parked().is_some()))
}
fn take_handed(handed: Parked, name: &str) -> bool {
let Parked { lease, jobs, sized } = handed;
if let Err(error) = lease.rename(&holder_for(name)) {
crate::hooks::common::say(&format!(
" host slot kept, but `{BIN} slots` may still name the previous check: {error}"
));
}
record_acquisition(name, jobs, sized, Duration::ZERO, "handed");
CURRENT.with(|current| {
let mut current = current.borrow_mut();
current.held = Some(lease);
current.settled = true;
current.jobs = jobs;
current.sized = sized;
});
true
}
fn record_acquisition(
name: &str,
jobs: Option<u32>,
sized: Option<(u32, u32)>,
waited: Duration,
outcome: &str,
) {
let short = crate::short_name(name);
greenharness_slots::record_wait_named(
&greenharness_slots::dir(),
crate::names::SLOT_HOLDER,
greenharness_slots::WaitContext {
name: Some(short),
place: if crate::rehearsal::in_prestage() {
greenharness_slots::WaitPlace::Prestage
} else if crate::rehearsal::in_snapshot() {
greenharness_slots::WaitPlace::Rehearsal
} else {
greenharness_slots::WaitPlace::Push
},
cap: sized.map(|(cap, _)| cap),
cores: sized.map(|(_, cores)| cores),
},
1,
jobs,
waited.as_millis(),
outcome,
);
}
pub fn bound(cmd: &mut std::process::Command) {
let own = CURRENT.with(|c| c.borrow().jobs);
if let Some(jobs) = own.or_else(|| {
parking()
.then(|| parked().as_ref().and_then(|p| p.jobs))
.flatten()
}) {
greenharness_slots::bound_width(cmd, jobs);
}
}
fn wait_for_slot(
sizing: greenharness_slots::Sizing,
machine: greenharness_slots::Machine,
holder: greenharness_slots::Holder,
budget: Duration,
) -> Result<greenharness_slots::Lease, Reason> {
let started = Instant::now();
let mut waiter = match greenharness_slots::Waiter::new_in_on(
&greenharness_slots::dir(),
sizing,
1,
holder,
machine,
) {
Ok(w) => w,
Err(e) if e.kind() == std::io::ErrorKind::Other => {
return Err(Reason::DirUnsafe(e.to_string()))
}
Err(e) => return Err(Reason::Io(e.to_string())),
};
let mut said = false;
loop {
match waiter.poll() {
Ok(greenharness_slots::Poll::Granted(lease)) => return Ok(lease),
Ok(greenharness_slots::Poll::Waiting(queue)) => {
if !said && (!queue.holders.is_empty() || queue.unknown > 0) {
said = true;
crate::hooks::common::say(&format!(" {}", behind(&queue)));
crate::hooks::common::say(&format!(" see: {BIN} slots"));
}
}
Err(e) => return Err(Reason::Io(e.to_string())),
}
if started.elapsed() >= budget {
return Err(Reason::TimedOut(started.elapsed()));
}
std::thread::sleep(Duration::from_millis(200));
}
}
pub fn behind(queue: &greenharness_slots::Queue) -> String {
let now = greenharness_slots::now_ms();
let mut who: Vec<String> = queue.holders.iter().map(|h| h.describe(now)).collect();
if queue.unknown > 0 {
who.push(format!("{} unknown (old client)", queue.unknown));
}
let reason = queue
.reason
.map_or(String::new(), |r| format!(" ({})", r.describe()));
format!(
"queued behind {}{reason} · {} waiting",
who.join(", "),
queue.waiting.max(1)
)
}
fn note(reason: &Reason, cap: u64, warn_wait: Option<Duration>) {
match reason {
Reason::DirUnsafe(why) => crate::hooks::common::warn(&format!(
"host slots are off for this check: {why}. Remove it, or set {} to a directory \
only you own",
crate::ui::highlight(DIR_ENV)
)),
Reason::TimedOut(waited) if warn_wait.is_some() => crate::hooks::common::warn(&format!(
"no host slot in {} (land: {}={}s); running it anyway",
crate::hooks::common::human_secs(waited.as_secs()),
crate::ui::highlight("greengate.warnSlotWait"),
warn_wait.map_or(0, |limit| limit.as_secs())
)),
Reason::TimedOut(waited) => crate::hooks::common::warn(&format!(
"no host slot freed in {} ({} {cap}); running it anyway",
crate::hooks::common::human_secs(waited.as_secs()),
crate::ui::highlight("greengate.hostSlots")
)),
Reason::Io(why) => {
crate::hooks::common::warn(&format!("host slots are off for this check: {why}"))
}
Reason::Unsupported => {}
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
fn settings_from(conf: &str) -> crate::config::Settings {
let lines = crate::manifest::parse_lines(conf);
let (policy, _) = crate::policy::Policy::from_lines(&lines);
crate::config::Settings::new(policy)
}
#[test]
fn the_busy_policy_is_env_then_file_then_wait() {
let none = settings_from("");
let defer = settings_from("set onBusy defer\nset slotWait 5\n");
assert_eq!(resolve_busy(None, &none), BusyPolicy::Wait);
assert_eq!(
resolve_busy(None, &defer),
BusyPolicy::Defer {
slot_wait: Duration::from_secs(5)
}
);
assert_eq!(resolve_busy(Some("wait"), &defer), BusyPolicy::Wait);
assert_eq!(
resolve_busy(Some("DEFER"), &none),
BusyPolicy::Defer {
slot_wait: Duration::from_secs(60)
}
);
assert_eq!(
resolve_busy(Some("later"), &defer),
BusyPolicy::Defer {
slot_wait: Duration::from_secs(5)
}
);
assert_eq!(resolve_busy(Some(""), &none), BusyPolicy::Wait);
}
#[test]
fn heavy_is_the_list() {
assert_eq!(weight_of("pre-commit-clippy"), Weight::Heavy);
assert_eq!(weight_of("pre-commit-cargo-fmt"), Weight::Light);
}
#[test]
fn every_heavy_name_is_a_builtin() {
for name in HEAVY {
assert!(
crate::registry::CHECKS.iter().any(|c| c.name == *name),
"{name} is not a built-in check"
);
}
}
#[test]
fn cargo_pins_the_host_knobs_for_tests() {
assert_eq!(std::env::var(HELD_ENV).as_deref(), Ok("held"));
assert_eq!(
std::env::var("GREENGATE_IDLE_LOAD_SCALE").as_deref(),
Ok("1")
);
}
#[test]
fn a_light_check_never_takes_a_slot() {
let settings = crate::config::Settings::default();
let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
assert!(!before_spawn(&settings).unwrap());
}
#[test]
fn a_nested_heavy_check_settles_without_a_slot() {
let settings = crate::config::Settings::default();
let _g = enter_check("pre-commit-clippy", weight_of("pre-commit-clippy"));
assert_eq!(current_check().as_deref(), Some("clippy"));
assert!(!before_spawn(&settings).unwrap());
assert!(CURRENT.with(|c| c.borrow().settled));
let mut cmd = std::process::Command::new("true");
bound(&mut cmd);
assert_eq!(cmd.get_envs().count(), 0);
}
#[test]
fn a_park_scope_dropped_early_releases_the_parked_slot() {
let dir = std::env::temp_dir().join(format!("greengate-park-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir); let early = || {
let _scope = ParkScope::begin();
let mut waiter = greenharness_slots::Waiter::new_in(
&dir,
greenharness_slots::Sizing::Fixed(1),
1,
greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, "gate"),
)
.unwrap();
let greenharness_slots::Poll::Granted(lease) = waiter.poll().unwrap() else {
panic!("the empty directory grants the slot");
};
assert!(dir.join("holders/slot-0.who").exists());
park(lease, Some(2), Some((3, 6)));
assert!(dir.join("holders/slot-0.who").exists());
};
early();
assert!(!dir.join("holders/slot-0.who").exists());
let _ = std::fs::remove_dir_all(&dir); }
#[test]
fn a_light_check_sets_no_width() {
let settings = crate::config::Settings::default();
let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
before_spawn(&settings).unwrap();
let mut cmd = std::process::Command::new("true");
bound(&mut cmd);
assert_eq!(cmd.get_envs().count(), 0);
}
}