//! A scan request shows at once as a run waiting for a slot (t84): the run is //! recorded `queued` before the scan gets one of the agent's slots, a person's //! request takes over a waiting webhook scan without leaving its queued run //! behind, a request covered by the waiting scan leaves none, and the run //! leaves `queued` once its scan had its turn. Runs against a live Mongo //! (`TEST_MONGODB_URI`) and skips cleanly without one. #![allow(clippy::expect_used, clippy::unwrap_used)] mod common; use std::sync::Arc; use std::time::Duration; use futures_util::TryStreamExt; use mongodb::bson::doc; use compliance_agent::agent::ComplianceAgent; use compliance_agent::database::Database; use compliance_agent::scan_gate::Priority; use compliance_core::models::{ScanRun, ScanRunStatus, ScanTrigger}; use common::dev_config; const TENANT: &str = "scanqueue"; async fn runs(db: &Database, target_id: &str) -> Vec { db.scan_runs() .find(doc! { "repo_id": target_id }) .await .unwrap() .try_collect() .await .unwrap() } /// Wait until the runs of `target_id` satisfy `done`, and return them. async fn until(db: &Database, target_id: &str, done: impl Fn(&[ScanRun]) -> bool) -> Vec { for _ in 0..200 { let found = runs(db, target_id).await; if done(&found) { return found; } tokio::time::sleep(Duration::from_millis(25)).await; } panic!( "runs never reached the expected state: {:?}", runs(db, target_id).await ); } #[tokio::test] async fn a_request_shows_as_queued_until_its_scan_has_a_slot() { let uri = std::env::var("TEST_MONGODB_URI") .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]); let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else { eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}"); return; }; let db = pool.for_tenant_id(TENANT).await.unwrap(); let mut config = dev_config(uri, db_name); config.scan_concurrency = 1; let agent = Arc::new(ComplianceAgent::new(config, pool.clone())); // No such target, so its scan ends at once when it gets the slot. let target = mongodb::bson::oid::ObjectId::new().to_hex(); // Arrange: another scan has the only slot. let busy = agent.scan_gate.slot(Priority::Background).await.unwrap(); // Act 1: a push asks for a scan; it waits, recorded as queued. let holder = tokio::spawn({ let (agent, target) = (agent.clone(), target.clone()); async move { agent .run_target_scan(TENANT, &target, ScanTrigger::Webhook) .await } }); let queued = until(&db, &target, |r| r.len() == 1).await; assert_eq!(queued[0].status, ScanRunStatus::Queued); assert_eq!(queued[0].trigger, ScanTrigger::Webhook); assert!(queued[0].queued_at.is_some()); // Act 2: a person asks while it waits: theirs takes its place, and only // their queued run is left. Another push is covered and leaves none. agent .run_target_scan(TENANT, &target, ScanTrigger::Manual) .await .unwrap(); agent .run_target_scan(TENANT, &target, ScanTrigger::Webhook) .await .unwrap(); let waiting = runs(&db, &target).await; assert_eq!(waiting.len(), 1, "one queued run: {waiting:?}"); assert_eq!(waiting[0].status, ScanRunStatus::Queued); assert_eq!(waiting[0].trigger, ScanTrigger::Manual); // Act 3: the slot frees; the person's scan has its turn. drop(busy); assert!(holder.await.unwrap().is_err(), "the unknown target fails"); // Assert: the same run, no longer queued. let done = runs(&db, &target).await; assert_eq!(done.len(), 1); assert_eq!(done[0].id, waiting[0].id); assert_eq!(done[0].status, ScanRunStatus::Failed); assert!(done[0].completed_at.is_some()); pool.drop_tenant(TENANT).await.ok(); } #[tokio::test] async fn the_scan_runs_on_the_run_that_waited() { use compliance_core::models::{OnboardedTarget, TargetType}; let uri = std::env::var("TEST_MONGODB_URI") .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]); let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else { eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}"); return; }; let db = pool.for_tenant_id(TENANT).await.unwrap(); let mut config = dev_config(uri, db_name); config.scan_concurrency = 1; let agent = Arc::new(ComplianceAgent::new(config, pool.clone())); // A target with nothing attached yet: its scan has nothing to read. let target = db .onboarded_targets() .insert_one(OnboardedTarget::new( "empty".into(), TargetType::BackendService, )) .await .unwrap() .inserted_id .as_object_id() .unwrap() .to_hex(); let busy = agent.scan_gate.slot(Priority::Background).await.unwrap(); let holder = tokio::spawn({ let (agent, target) = (agent.clone(), target.clone()); async move { agent .run_target_scan(TENANT, &target, ScanTrigger::Manual) .await } }); let queued = until(&db, &target, |r| r.len() == 1).await; assert_eq!(queued[0].status, ScanRunStatus::Queued); tokio::time::sleep(Duration::from_millis(20)).await; drop(busy); holder.await.unwrap().ok(); // The scan used the queued run: one run, started after it was requested. let done = runs(&db, &target).await; assert_eq!(done.len(), 1, "{done:?}"); assert_eq!(done[0].id, queued[0].id); assert_ne!(done[0].status, ScanRunStatus::Queued); assert!(done[0].started_at > done[0].queued_at.unwrap()); pool.drop_tenant(TENANT).await.ok(); } /// The run of `target`'s scan by `trigger`, started while another scan has the /// only slot; with `takes_over`, a webhook scan waits first and the person's /// request takes it over. async fn scan_with_slot_busy( agent: &Arc, db: &Database, target: &str, takes_over: bool, ) -> ScanRun { let busy = agent.scan_gate.slot(Priority::Background).await.unwrap(); let first = if takes_over { ScanTrigger::Webhook } else { ScanTrigger::Manual }; let holder = tokio::spawn({ let (agent, target) = (agent.clone(), target.to_string()); async move { agent.run_target_scan(TENANT, &target, first).await } }); until(db, target, |r| r.len() == 1).await; if takes_over { agent .run_target_scan(TENANT, target, ScanTrigger::Manual) .await .unwrap(); } drop(busy); holder.await.unwrap().ok(); let mut done = runs(db, target).await; assert_eq!(done.len(), 1, "{done:?}"); done.remove(0) } #[tokio::test] async fn a_taken_over_scan_is_charged_as_the_scan_it_replaces() { use compliance_core::models::{OnboardedTarget, ScanAttribution, TargetType}; let uri = std::env::var("TEST_MONGODB_URI") .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]); let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else { eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}"); return; }; let db = pool.for_tenant_id(TENANT).await.unwrap(); let mut config = dev_config(uri, db_name); config.scan_concurrency = 1; let agent = Arc::new(ComplianceAgent::new(config, pool.clone())); let new_target = || { let db = db.clone(); async move { let target = OnboardedTarget::new("t".into(), TargetType::BackendService); db.onboarded_targets() .insert_one(target) .await .unwrap() .inserted_id .as_object_id() .unwrap() .to_hex() } }; // A person's request that took over a waiting webhook scan of an // included target: their priority and attribution, but not counted, as // the webhook scan would not have been. let included = new_target().await; let run = scan_with_slot_busy(&agent, &db, &included, true).await; assert_eq!(run.trigger, ScanTrigger::Manual); assert_eq!(run.attribution, Some(ScanAttribution::Request)); assert_eq!(run.charged_as, Some(ScanTrigger::Webhook)); assert!(!run.chargeable, "it would have run anyway: {run:?}"); // A person's own scan, not taking any over, counts as their request. let asked = new_target().await; let run = scan_with_slot_busy(&agent, &db, &asked, false).await; assert_eq!(run.attribution, Some(ScanAttribution::Request)); assert_eq!(run.charged_as, None); assert!(run.chargeable); pool.drop_tenant(TENANT).await.ok(); }