diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/http/mod.rs | 8 | ||||
| -rw-r--r-- | src/http/sse.rs | 2 | ||||
| -rw-r--r-- | src/pipeline/dispatch.rs | 14 | ||||
| -rw-r--r-- | src/sandbox/agent.rs | 6 | ||||
| -rw-r--r-- | src/sandbox/remote.rs | 6 | ||||
| -rw-r--r-- | src/time.rs | 149 | ||||
| -rw-r--r-- | src/watch/scheduler.rs | 14 |
7 files changed, 176 insertions, 23 deletions
diff --git a/src/http/mod.rs b/src/http/mod.rs index 7beeff4..0d78a00 100644 --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -97,19 +97,19 @@ pub fn spawn(cfg: Config, db: Db) -> std::io::Result<Server> { eprintln!("aur-build listening on http://{addr}"); let handle = std::thread::Builder::new() .name("http-accept".into()) - .spawn(move || { + .spawn(crate::time::inherit(move || { for request in server.incoming_requests() { let state = state.clone(); std::thread::Builder::new() .name("http-conn".into()) - .spawn(move || { + .spawn(crate::time::inherit(move || { if let Err(e) = serve(state, request) { eprintln!("http: {e}"); } - }) + })) .ok(); } - })?; + }))?; Ok(Server { handle, addr }) } diff --git a/src/http/sse.rs b/src/http/sse.rs index e4a5e6a..39266be 100644 --- a/src/http/sse.rs +++ b/src/http/sse.rs @@ -91,7 +91,7 @@ impl Read for LogTail { self.finish(); continue; } - std::thread::sleep(POLL); + crate::time::sleep(POLL); self.since_keepalive += POLL; if self.since_keepalive >= KEEPALIVE { self.since_keepalive = Duration::ZERO; diff --git a/src/pipeline/dispatch.rs b/src/pipeline/dispatch.rs index 88f300e..89a8788 100644 --- a/src/pipeline/dispatch.rs +++ b/src/pipeline/dispatch.rs @@ -28,7 +28,7 @@ impl Pool { handles.push( std::thread::Builder::new() .name(format!("worker-{n}")) - .spawn(move || worker(cfg, db, rx, stop)) + .spawn(crate::time::inherit(move || worker(cfg, db, rx, stop))) .expect("spawn worker"), ); } @@ -40,7 +40,7 @@ impl Pool { handles.push( std::thread::Builder::new() .name("dispatcher".into()) - .spawn(move || dispatcher(cfg2, db2, stop2, tx)) + .spawn(crate::time::inherit(move || dispatcher(cfg2, db2, stop2, tx))) .expect("spawn dispatcher"), ); @@ -58,10 +58,12 @@ impl Pool { fn dispatcher(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>, tx: Sender<String>) { while !stop.load(Ordering::SeqCst) { dispatch_once(&cfg, &db, &tx); - let mut slept = 0u64; - while slept < cfg.dispatch_tick_secs && !stop.load(Ordering::SeqCst) { - std::thread::sleep(std::time::Duration::from_millis(200)); - slept += 1; + if !crate::time::wait( + std::time::Duration::from_secs(cfg.dispatch_tick_secs), + std::time::Duration::from_millis(200), + &stop, + ) { + break; } } } diff --git a/src/sandbox/agent.rs b/src/sandbox/agent.rs index e9626f6..3eaa799 100644 --- a/src/sandbox/agent.rs +++ b/src/sandbox/agent.rs @@ -52,8 +52,8 @@ pub fn serve(opts: &AgentOptions) -> Result<()> { { let (last, child, alive, ttl) = (last_inbound.clone(), child.clone(), alive.clone(), ttl); - std::thread::spawn(move || loop { - std::thread::sleep(Duration::from_millis(1000)); + std::thread::spawn(crate::time::inherit(move || loop { + crate::time::sleep(Duration::from_secs(1)); let quiet = last.lock().unwrap().elapsed(); if quiet > ttl { eprintln!("agent: hub silent for {quiet:?} past the TTL; dying"); @@ -67,7 +67,7 @@ pub fn serve(opts: &AgentOptions) -> Result<()> { if !alive.load(Ordering::Relaxed) { return; } - }); + })); } let mut outcome = Ok(()); diff --git a/src/sandbox/remote.rs b/src/sandbox/remote.rs index ba70155..51ec047 100644 --- a/src/sandbox/remote.rs +++ b/src/sandbox/remote.rs @@ -140,9 +140,9 @@ impl Sandbox for RemoteSandbox { let mut writer = self.writer.lock().unwrap().try_clone()?; { let (stop, interval) = (stop.clone(), self.ttl / 3); - std::thread::spawn(move || { + std::thread::spawn(crate::time::inherit(move || { while !stop.load(Ordering::SeqCst) { - std::thread::sleep(interval.max(std::time::Duration::from_millis(50))); + crate::time::sleep(interval.max(std::time::Duration::from_millis(50))); if stop.load(Ordering::SeqCst) { break; } @@ -150,7 +150,7 @@ impl Sandbox for RemoteSandbox { break; } } - }); + })); } let mut stdout = Vec::new(); let mut stderr = Vec::new(); diff --git a/src/time.rs b/src/time.rs index 8460f20..1ffc116 100644 --- a/src/time.rs +++ b/src/time.rs @@ -1,6 +1,13 @@ +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + use chrono::{DateTime, SecondsFormat, TimeZone, Utc}; pub fn now() -> String { + #[cfg(feature = "test-support")] + if let Some(t) = clock::now() { + return fmt(t); + } match pinned() { Some(pinned) => pinned, None => fmt(Utc::now()), @@ -8,6 +15,10 @@ pub fn now() -> String { } fn base() -> DateTime<Utc> { + #[cfg(feature = "test-support")] + if let Some(t) = clock::now() { + return t; + } match pinned().and_then(|p| parse(&p)) { Some(t) => t, None => Utc::now(), @@ -59,3 +70,141 @@ pub fn secs_ago(secs: i64) -> String { pub fn secs_ahead(secs: i64) -> String { fmt(base() + chrono::Duration::seconds(secs)) } + +// ---- waiting ---- + +/// Wait for `d`, checking `stop` every `slice`. Returns false if `stop` was set +/// before the wait finished, so a control loop can leave instead of doing one +/// more pass. +pub fn wait(d: Duration, slice: Duration, stop: &AtomicBool) -> bool { + if clock::advance(d) { + return !stop.load(Ordering::SeqCst); + } + let mut left = d; + while !left.is_zero() { + if stop.load(Ordering::SeqCst) { + return false; + } + let step = slice.min(left); + std::thread::sleep(step); + left -= step; + } + true +} + +pub fn sleep(d: Duration) { + if clock::advance(d) { + return; + } + std::thread::sleep(d); +} + +/// Wrap a closure about to be spawned so the child thread inherits this one's +/// clock setting. Without it a control loop spawned by a test runs on wall time +/// while the test itself runs on the virtual clock, and the two disagree. +pub fn inherit<F, T>(f: F) -> impl FnOnce() -> T +where + F: FnOnce() -> T + Send + 'static, + T: Send + 'static, +{ + clock::wrap(f) +} + +#[cfg(feature = "test-support")] +pub fn virtualize() -> clock::VirtualClock { + clock::virtualize() +} + +#[cfg(feature = "test-support")] +pub fn virtual_now() -> Option<DateTime<Utc>> { + clock::now() +} + +#[cfg(feature = "test-support")] +mod clock { + use super::*; + use std::cell::Cell; + use std::sync::{Mutex, MutexGuard}; + + thread_local! { + static ON: Cell<bool> = const { Cell::new(false) }; + } + + static AT: Mutex<Option<DateTime<Utc>>> = Mutex::new(None); + static OWNER: Mutex<()> = Mutex::new(()); + + pub struct VirtualClock { + _owner: MutexGuard<'static, ()>, + } + + pub fn virtualize() -> VirtualClock { + let owner = OWNER.lock().unwrap_or_else(|e| e.into_inner()); + *lock(&AT) = Some(Utc::now()); + ON.set(true); + VirtualClock { _owner: owner } + } + + impl Drop for VirtualClock { + fn drop(&mut self) { + ON.set(false); + *lock(&AT) = None; + } + } + + fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) + } + + pub fn now() -> Option<DateTime<Utc>> { + if !ON.get() { + return None; + } + *lock(&AT) + } + + /// Returns true when the wait was virtual: the clock moved, no wall time did. + pub fn advance(d: Duration) -> bool { + if !ON.get() { + return false; + } + let mut at = lock(&AT); + if let Some(t) = *at { + let step = chrono::TimeDelta::from_std(d).unwrap_or_else(|_| chrono::TimeDelta::zero()); + *at = Some(t + step); + } + // A control loop that never blocks still needs to let its caller run. + std::thread::yield_now(); + true + } + + pub fn wrap<F, T>(f: F) -> impl FnOnce() -> T + where + F: FnOnce() -> T + Send + 'static, + T: Send + 'static, + { + let on = ON.get(); + move || { + ON.set(on); + f() + } + } +} + +#[cfg(not(feature = "test-support"))] +mod clock { + use super::*; + + #[inline(always)] + pub fn advance(_d: Duration) -> bool { + false + } + + #[inline(always)] + pub fn wrap<F, T>(f: F) -> F + where + F: FnOnce() -> T + Send + 'static, + T: Send + 'static, + { + f + } +} diff --git a/src/watch/scheduler.rs b/src/watch/scheduler.rs index eb79db0..4508a03 100644 --- a/src/watch/scheduler.rs +++ b/src/watch/scheduler.rs @@ -9,17 +9,19 @@ use crate::watch::detect::check_pkgbase; pub fn spawn_scheduler(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>) -> JoinHandle<()> { std::thread::Builder::new() .name("watcher".into()) - .spawn(move || { + .spawn(crate::time::inherit(move || { while !stop.load(Ordering::SeqCst) { let tick = crate::db::setting_i64(&db, "poll_tick", 30); sweep(&cfg, &db); - let mut slept = 0; - while slept < tick && !stop.load(Ordering::SeqCst) { - std::thread::sleep(std::time::Duration::from_secs(1)); - slept += 1; + if !crate::time::wait( + std::time::Duration::from_secs(tick.max(0) as u64), + std::time::Duration::from_secs(1), + &stop, + ) { + break; } } - }) + })) .expect("spawn watcher") } |
