diff --git a/compliance-agent/src/scan_gate.rs b/compliance-agent/src/scan_gate.rs index af12658..f1ef939 100644 --- a/compliance-agent/src/scan_gate.rs +++ b/compliance-agent/src/scan_gate.rs @@ -274,6 +274,71 @@ mod tests { assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced); } + /// What `ComplianceAgent::run_target_scan` does once admitted: take a + /// slot, scan (here: log), and run the pending follow-up, if any. + async fn hold_and_scan( + gate: std::sync::Arc, + key: String, + mut trigger: ScanTrigger, + log: std::sync::Arc>>, + ) { + loop { + { + let _slot = gate.slot().await.unwrap(); + log.lock().unwrap().push((key.clone(), trigger.clone())); + } + match gate.finish(&key) { + Some(next) => trigger = next, + None => break, + } + } + } + + #[tokio::test] + async fn a_persons_follow_up_runs_before_scheduled_scans_still_waiting() { + let gate = std::sync::Arc::new(ScanGate::new(1)); + let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + // Another tenant's scan has the only slot. + let busy = gate.slot().await.unwrap(); + + // A scheduler tick admits three targets; all wait for the slot. + let mut tasks = Vec::new(); + for target in ["t1", "t2", "t3"] { + let key = ScanGate::key("acme", target); + assert_eq!(gate.admit(&key, ScanTrigger::Scheduled), Admission::Run); + tasks.push(tokio::spawn(hold_and_scan( + gate.clone(), + key, + ScanTrigger::Scheduled, + log.clone(), + ))); + // Let it queue for the slot before the next one does. + tokio::task::yield_now().await; + } + + // A person asks for t1 while its scheduled scan still waits. + let t1 = ScanGate::key("acme", "t1"); + assert_eq!(gate.admit(&t1, ScanTrigger::Manual), Admission::Coalesced); + + drop(busy); + for task in tasks { + task.await.unwrap(); + } + let order: Vec<(String, ScanTrigger)> = log.lock().unwrap().clone(); + let manual = order + .iter() + .position(|(k, t)| *k == t1 && *t == ScanTrigger::Manual) + .expect("the person's scan runs"); + let last_scheduled = order + .iter() + .rposition(|(_, t)| *t == ScanTrigger::Scheduled) + .expect("the scheduled scans run"); + assert!( + manual < last_scheduled, + "the person's follow-up waited behind every scheduled scan: {order:?}" + ); + } + #[tokio::test] async fn slots_bound_how_many_scans_run_at_once() { let gate = ScanGate::new(2);