diff --git a/apps/auth-service/src/jobs.rs b/apps/auth-service/src/jobs.rs index 8b592140f..1430d6dcd 100644 --- a/apps/auth-service/src/jobs.rs +++ b/apps/auth-service/src/jobs.rs @@ -375,10 +375,25 @@ impl ExclusiveJob for AccountPurge { #[cfg(test)] mod tests { - //! Job runner failure isolation. + //! Job runner failure isolation and exclusivity across runners. use super::*; use piquel_repository::DatabaseConfig; - use std::sync::atomic::{AtomicU32, Ordering}; + use std::sync::{ + Mutex, + atomic::{AtomicU32, Ordering}, + }; + + /// Connects to the disposable database the `#[ignore]`d tests run against. + async fn database() -> Database { + let url = piquel_common::config::Variable::new("TEST_DATABASE_URL") + .required() + .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); + Database::connect( + DatabaseConfig::new(&url, 2, Duration::from_secs(5)).expect("database configuration"), + ) + .await + .expect("database") + } /// Panics on its first run and counts every run. struct PanicsOnce(Arc); @@ -404,17 +419,9 @@ mod tests { #[tokio::test] #[ignore = "requires TEST_DATABASE_URL"] async fn a_panicking_run_releases_its_lock_and_the_job_runs_again() { - let url = piquel_common::config::Variable::new("TEST_DATABASE_URL") - .required() - .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); - let database = Database::connect( - DatabaseConfig::new(&url, 2, Duration::from_secs(5)).expect("database configuration"), - ) - .await - .expect("database"); let runs = Arc::new(AtomicU32::new(0)); let mut jobs = Jobs::new(); - jobs.exclusive(PanicsOnce(Arc::clone(&runs)), database); + jobs.exclusive(PanicsOnce(Arc::clone(&runs)), database().await); tokio::time::timeout(Duration::from_secs(5), async { while runs.load(Ordering::SeqCst) < 2 { tokio::time::sleep(Duration::from_millis(10)).await; @@ -424,4 +431,145 @@ mod tests { .expect("the job runs again after panicking"); jobs.shutdown().await.expect("no job loop panicked"); } + + /// A run of [`Held`] by the runner it names starting, finishing or being + /// cancelled. + #[derive(Clone, Debug)] + enum Event { + Started(usize), + Finished(usize), + Cancelled(usize), + } + + /// Every [`Event`] of the runners sharing it, in order. + #[derive(Default)] + struct Log(Mutex>); + + impl Log { + fn push(&self, event: Event) { + self.0.lock().expect("log").push(event); + } + + fn events(&self) -> Vec { + self.0.lock().expect("log").clone() + } + + /// Waits until `found` returns something for the events so far. + async fn wait_for(&self, found: impl Fn(&[Event]) -> Option) -> T { + tokio::time::timeout(Duration::from_secs(5), async { + loop { + if let Some(found) = found(&self.0.lock().expect("log")) { + break found; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap_or_else(|_| panic!("the awaited events never happened: {:?}", self.events())) + } + } + + /// Holds its lock for [`Self::HOLD`], several periods, logging when each run + /// of `runner` starts and how it ends. + struct Held { + runner: usize, + log: Arc, + } + + impl Held { + const HOLD: Duration = Duration::from_millis(100); + } + + /// Logs how a [`Held`] run ended when dropped, so a cancelled run is logged + /// too. The run drops it before its connection, so before the lock is freed. + struct Running<'a> { + job: &'a Held, + finished: bool, + } + + impl Drop for Running<'_> { + fn drop(&mut self) { + let runner = self.job.runner; + self.job.log.push(if self.finished { + Event::Finished(runner) + } else { + Event::Cancelled(runner) + }); + } + } + + impl ExclusiveJob for Held { + const NAME: &'static str = "held"; + const LOCK: LockKey = LockKey::ExclusivityTest; + const EVERY: Duration = Duration::from_millis(20); + type Error = DatabaseError; + + async fn run( + &self, + _: &mut ExclusiveConnection, + _: &Shutdown, + ) -> Result<(), DatabaseError> { + self.log.push(Event::Started(self.runner)); + let mut running = Running { + job: self, + finished: false, + }; + tokio::time::sleep(Self::HOLD).await; + running.finished = true; + Ok(()) + } + } + + /// Two runners, as two replicas, never run the same exclusive job at once, + /// and dropping the one mid-run cancels its run, freeing the lock for the + /// other's next tick. + #[tokio::test] + #[ignore = "requires TEST_DATABASE_URL"] + async fn runners_never_overlap_and_a_dropped_holder_hands_over() { + let database = database().await; + let log = Arc::new(Log::default()); + let mut runners = [0, 1].map(|runner| { + let mut jobs = Jobs::new(); + let log = Arc::clone(&log); + jobs.exclusive(Held { runner, log }, database.clone()); + Some(jobs) + }); + // A few runs in, cancel whichever runner is mid-run. + let holder = log + .wait_for(|events| match events { + [.., Event::Started(holder)] if events.len() > 6 => Some(*holder), + _ => None, + }) + .await; + drop(runners[holder].take()); + let other = 1 - holder; + log.wait_for(|events| { + events + .windows(2) + .any(|pair| { + matches!( + pair, + [Event::Cancelled(cancelled), Event::Started(started)] + if *cancelled == holder && *started == other + ) + }) + .then_some(()) + }) + .await; + runners[other] + .take() + .expect("the other runner") + .shutdown() + .await + .expect("no job loop panicked"); + let events = log.events(); + assert!( + events.chunks(2).all(|run| matches!( + run, + [Event::Started(started), Event::Finished(ended) | Event::Cancelled(ended)] + if started == ended + )), + "runs overlapped: {events:?}" + ); + } } diff --git a/crates/database/src/exclusive/mod.rs b/crates/database/src/exclusive/mod.rs index e8d387fca..d3181db6b 100644 --- a/crates/database/src/exclusive/mod.rs +++ b/crates/database/src/exclusive/mod.rs @@ -23,9 +23,13 @@ pub enum LockKey { RelatedOrigins = 5, /// Sealing the audit chain and signing its checkpoints. AuditChain = 6, - /// Job runner tests in other crates; no release takes it. + /// The job runner panic test; no release takes it. #[cfg(feature = "test-support")] Test = -1, + /// The job runner exclusivity test, apart from [`Self::Test`] since tests + /// sharing a database run at once; no release takes it. + #[cfg(feature = "test-support")] + ExclusivityTest = -2, } impl LockKey {