use std::sync::{Mutex, OnceLock, PoisonError};
use std::thread;
use std::time::Duration;
use openmoat_hosts::{HookEvent, Host};
#[cfg(debug_assertions)]
const DEADLINE_ENV: &str = "MOAT_TEST_GUARD_DEADLINE_MS";
pub(super) fn of(host: Host) -> Duration {
#[cfg(debug_assertions)]
if let Some(ms) = std::env::var(DEADLINE_ENV)
.ok()
.and_then(|v| v.parse::<u64>().ok())
{
return Duration::from_millis(ms);
}
Duration::from_secs(host.spec().guard_deadline_s())
}
pub(super) struct Gate(Mutex<bool>);
impl Gate {
pub(super) const fn new() -> Self {
Self(Mutex::new(false))
}
pub(super) fn once<T>(&self, write: impl FnOnce() -> T) -> Option<T> {
let mut written = self.0.lock().unwrap_or_else(PoisonError::into_inner);
if *written {
return None;
}
*written = true;
Some(write())
}
}
static SEEN: OnceLock<(Host, HookEvent)> = OnceLock::new();
pub(super) fn saw(host: Host, event: &HookEvent) {
let _ = SEEN.set((host, event.clone()));
}
pub(super) fn seen(installed_for: Host) -> (Host, HookEvent) {
SEEN.get()
.cloned()
.unwrap_or_else(|| (installed_for, HookEvent::default()))
}
pub(super) fn arm(after: Duration, fire: impl FnOnce() + Send + 'static) -> std::io::Result<()> {
thread::Builder::new()
.name("openmoat-deadline".to_owned())
.spawn(move || {
thread::sleep(after);
fire();
})
.map(drop)
}
#[cfg(test)]
mod tests {
use std::io::Write as _;
use std::sync::{Arc, mpsc};
use std::time::{Duration, Instant};
use super::{Gate, arm};
#[test]
fn a_stuck_decision_is_answered_by_the_deadline_once() {
let gate = Arc::new(Gate::new());
let out = Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
let deadline = Duration::from_millis(100);
let started = Instant::now();
let (fired, at) = mpsc::channel();
let (g, o) = (Arc::clone(&gate), Arc::clone(&out));
arm(deadline, move || {
let wrote = g.once(|| writeln!(o.lock().unwrap(), "{{\"deny\":true}}").unwrap());
fired.send((wrote.is_some(), started.elapsed())).unwrap();
})
.unwrap();
let (wrote, elapsed) = at.recv_timeout(Duration::from_secs(5)).unwrap();
let late = gate.once(|| out.lock().unwrap().extend_from_slice(b"{\"allow\":true}\n"));
assert!(wrote, "the deadline's deny was not written");
assert!(
elapsed >= deadline && elapsed < deadline + Duration::from_secs(2),
"{elapsed:?}"
);
assert!(late.is_none(), "the late decision was written too");
assert_eq!(*out.lock().unwrap(), b"{\"deny\":true}\n");
}
#[test]
fn a_decision_in_time_leaves_the_deadline_nothing_to_write() {
let gate = Arc::new(Gate::new());
let (fired, at) = mpsc::channel();
let g = Arc::clone(&gate);
arm(Duration::from_millis(50), move || {
fired.send(g.once(|| ()).is_some()).unwrap();
})
.unwrap();
assert!(gate.once(|| ()).is_some());
assert!(!at.recv_timeout(Duration::from_secs(5)).unwrap());
}
#[test]
fn a_race_writes_one_whole_answer() {
for _ in 0..50 {
let gate = Arc::new(Gate::new());
let out = Arc::new(std::sync::Mutex::new(String::new()));
let (done, wait) = mpsc::channel();
let (g, o) = (Arc::clone(&gate), Arc::clone(&out));
arm(Duration::ZERO, move || {
g.once(|| o.lock().unwrap().push_str("deny\n"));
done.send(()).unwrap();
})
.unwrap();
gate.once(|| out.lock().unwrap().push_str("allow\n"));
wait.recv_timeout(Duration::from_secs(5)).unwrap();
let written = out.lock().unwrap().clone();
assert!(written == "deny\n" || written == "allow\n", "{written:?}");
}
}
}