fix(scan): a person's scan gets the next slot and shows as queued (t84) #940
No files matched your search
+106
-26
@@ -10,7 +10,7 @@ use crate::database::DatabasePool;
|
||||
use crate::llm::LlmClient;
|
||||
use crate::pipeline::orchestrator::PipelineOrchestrator;
|
||||
use crate::registry::RegistryClient;
|
||||
use crate::scan_gate::{Admission, HeldTarget, ScanGate};
|
||||
use crate::scan_gate::{Admission, HeldTarget, Job, Priority, ScanGate};
|
||||
use crate::secrets::SecretBox;
|
||||
|
||||
/// A target whose billing changed, with its new billing (t72).
|
||||
@@ -262,11 +262,16 @@ impl ComplianceAgent {
|
||||
}
|
||||
|
||||
/// Scan a target, through the [`ScanGate`]: at most `SCAN_CONCURRENCY` scans
|
||||
/// run at once, and a request for a target that is already being scanned is
|
||||
/// coalesced — it becomes the one pending follow-up that this task runs next,
|
||||
/// or it is dropped if a follow-up is already pending. A scheduled scan
|
||||
/// first waits a random [`crate::scan_gate::start_delay`]. Every trigger
|
||||
/// (click, webhook, scheduler, demo seed) comes through here.
|
||||
/// run at once, a person's before scheduled and webhook ones, and a request
|
||||
/// for a target that is already queued or being scanned is coalesced — it
|
||||
/// becomes the one pending follow-up that this task runs next, it takes over
|
||||
/// a queued scan that was not a person's, or it is dropped as covered. A
|
||||
/// scheduled scan first waits a random [`crate::scan_gate::start_delay`].
|
||||
/// Every trigger (click, webhook, scheduler, demo seed) comes through here.
|
||||
///
|
||||
/// Each request is recorded at once as a `queued` run, which shows that it
|
||||
/// waits for a slot (t84); a request that will not run has its queued run
|
||||
/// removed again.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
@@ -288,15 +293,22 @@ impl ComplianceAgent {
|
||||
);
|
||||
tokio::time::sleep(delay).await;
|
||||
}
|
||||
let db = self.db_pool.for_tenant_id(tenant_id).await?;
|
||||
let run_id = queue_run(&db, target_id, &trigger).await;
|
||||
let key = ScanGate::key(tenant_id, target_id);
|
||||
match self.scan_gate.admit(&key, trigger.clone()) {
|
||||
match self
|
||||
.scan_gate
|
||||
.admit(&key, Job::new(trigger, run_id.clone()))
|
||||
{
|
||||
Admission::Run => {}
|
||||
Admission::Coalesced => {
|
||||
Admission::Coalesced { replaced } => {
|
||||
tracing::info!(
|
||||
tenant_id,
|
||||
target_id,
|
||||
took_over = replaced.is_some(),
|
||||
"scan already running; follow-up queued"
|
||||
);
|
||||
discard_queued_run(&db, replaced.as_deref()).await;
|
||||
return Ok(());
|
||||
}
|
||||
Admission::Dropped => {
|
||||
@@ -305,41 +317,43 @@ impl ComplianceAgent {
|
||||
target_id,
|
||||
"scan and follow-up already queued; dropped"
|
||||
);
|
||||
discard_queued_run(&db, run_id.as_deref()).await;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
// Released on panic or cancellation; a normal finish disarms it.
|
||||
let held = HeldTarget::new(&self.scan_gate, key.clone());
|
||||
let mut trigger = trigger;
|
||||
let result = loop {
|
||||
let outcome = {
|
||||
let _slot = self
|
||||
.scan_gate
|
||||
.slot()
|
||||
.await
|
||||
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
|
||||
self.run_one_target_scan(tenant_id, target_id, trigger.clone())
|
||||
.await
|
||||
};
|
||||
// The scan to run is the one current when the slot is granted: a
|
||||
// person's request may have taken it over while it waited.
|
||||
let (slot, job) = self
|
||||
.scan_gate
|
||||
.start(&key)
|
||||
.await
|
||||
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
|
||||
let outcome = self.run_one_target_scan(tenant_id, target_id, &job).await;
|
||||
drop(slot);
|
||||
if let Err(e) = &outcome {
|
||||
tracing::error!(tenant_id, target_id, "scan failed: {e}");
|
||||
fail_queued_run(&db, job.run_id.as_deref(), e).await;
|
||||
}
|
||||
match self.scan_gate.finish(&key) {
|
||||
Some(next) => trigger = next,
|
||||
None => break outcome,
|
||||
if !self.scan_gate.finish(&key) {
|
||||
break outcome;
|
||||
}
|
||||
};
|
||||
held.disarm();
|
||||
result
|
||||
}
|
||||
|
||||
/// One scan of a target, with no gating: the pipeline plus its usage event.
|
||||
/// One scan of a target, with no gating: the pipeline plus its usage event,
|
||||
/// recorded on the run that waited for it and charged as `job` says.
|
||||
async fn run_one_target_scan(
|
||||
&self,
|
||||
tenant_id: &str,
|
||||
target_id: &str,
|
||||
trigger: compliance_core::models::ScanTrigger,
|
||||
job: &Job,
|
||||
) -> Result<(), crate::error::AgentError> {
|
||||
let trigger = job.trigger.clone();
|
||||
let db = self.db_pool.for_tenant_id(tenant_id).await?;
|
||||
// Whether this target is included or extra decides whether its scan
|
||||
// counts, and the plan's limits whether a counted one may run (t72).
|
||||
@@ -353,9 +367,12 @@ impl ComplianceAgent {
|
||||
.with_nuget_license_cache(self.nuget_license_cache.clone())
|
||||
.with_exploit_cache(self.exploit_cache.clone())
|
||||
.with_advisory_index(self.advisory_index.clone())
|
||||
.with_plan_limits(plan.map(|p| p.limits));
|
||||
.with_plan_limits(plan.map(|p| p.limits))
|
||||
.with_charged_as(job.charged_as.clone());
|
||||
let started = chrono::Utc::now();
|
||||
let outcome = orchestrator.run_target(target_id, trigger.clone()).await?;
|
||||
let outcome = orchestrator
|
||||
.run_target(target_id, trigger.clone(), job.run_id.as_deref())
|
||||
.await?;
|
||||
// Support's scans are ours, not the customer's usage; a scheduled scan
|
||||
// skipped because nothing changed scanned nothing (#465).
|
||||
if outcome.scanned && trigger != compliance_core::models::ScanTrigger::Support {
|
||||
@@ -424,7 +441,7 @@ impl ComplianceAgent {
|
||||
// slot too. Each PR is distinct work, so it is not coalesced.
|
||||
let _slot = self
|
||||
.scan_gate
|
||||
.slot()
|
||||
.slot(Priority::Background)
|
||||
.await
|
||||
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
|
||||
let db = self.db_pool.for_tenant_id(tenant_id).await?;
|
||||
@@ -500,6 +517,69 @@ impl ComplianceAgent {
|
||||
}
|
||||
}
|
||||
|
||||
/// Record a scan request for `target_id` as a run waiting for a slot (t84),
|
||||
/// so it shows at once. Returns its id, or `None` when it could not be
|
||||
/// written: the scan then runs on a run of its own when it starts.
|
||||
async fn queue_run(
|
||||
db: &crate::database::Database,
|
||||
target_id: &str,
|
||||
trigger: &compliance_core::models::ScanTrigger,
|
||||
) -> Option<String> {
|
||||
let run = compliance_core::models::ScanRun::queued(target_id.to_string(), trigger.clone());
|
||||
match db.scan_runs().insert_one(&run).await {
|
||||
Ok(insert) => insert.inserted_id.as_object_id().map(|id| id.to_hex()),
|
||||
Err(e) => {
|
||||
tracing::warn!(target_id, "queued scan run not recorded: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the queued run `run_id` of a request that will not run, because
|
||||
/// another queued scan covers it or took it over. A run that has started
|
||||
/// meanwhile is kept.
|
||||
async fn discard_queued_run(db: &crate::database::Database, run_id: Option<&str>) {
|
||||
let Some(oid) = run_id.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) else {
|
||||
return;
|
||||
};
|
||||
if let Err(e) = db
|
||||
.scan_runs()
|
||||
.delete_one(mongodb::bson::doc! { "_id": oid, "status": "queued" })
|
||||
.await
|
||||
{
|
||||
tracing::warn!(run_id = %oid, "queued scan run not removed: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Close the queued run `run_id` as failed when its scan ended with `error`
|
||||
/// before it started (an unknown target, an unreachable database), so it does
|
||||
/// not stay queued. A run the scan started records its own outcome.
|
||||
async fn fail_queued_run(
|
||||
db: &crate::database::Database,
|
||||
run_id: Option<&str>,
|
||||
error: &crate::error::AgentError,
|
||||
) {
|
||||
let Some(oid) = run_id.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) else {
|
||||
return;
|
||||
};
|
||||
let (code, message) = error.run_failure();
|
||||
if let Err(e) = db
|
||||
.scan_runs()
|
||||
.update_one(
|
||||
mongodb::bson::doc! { "_id": oid, "status": "queued" },
|
||||
mongodb::bson::doc! { "$set": {
|
||||
"status": "failed",
|
||||
"error_message": message,
|
||||
"error_code": mongodb::bson::to_bson(&code).unwrap_or_default(),
|
||||
"completed_at": mongodb::bson::DateTime::now(),
|
||||
} },
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(run_id = %oid, "queued scan run not closed: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Findings of `target_id` first stored since `since`, by severity; `None`
|
||||
/// when there are none.
|
||||
async fn new_findings_summary(
|
||||
|
||||
@@ -79,9 +79,14 @@ async fn load_inputs(
|
||||
.map_err(load_err)?,
|
||||
)
|
||||
.await,
|
||||
// A run still waiting for a slot has examined nothing yet (t84).
|
||||
last_run: db
|
||||
.scan_runs()
|
||||
.find_one(by_target)
|
||||
.find_one({
|
||||
let mut started = by_target;
|
||||
started.insert("status", doc! { "$ne": "queued" });
|
||||
started
|
||||
})
|
||||
.sort(doc! { "started_at": -1 })
|
||||
.await
|
||||
.map_err(load_err)?,
|
||||
|
||||
@@ -114,7 +114,7 @@ pub async fn list_targets(
|
||||
// `join!` borrows its futures' arguments, so the collections need names.
|
||||
let (runs, findings) = (db.scan_runs(), db.findings());
|
||||
let (mut last_scans, counts) = tokio::join!(
|
||||
latest_scan_runs(&runs, ids.clone()),
|
||||
latest_scan_runs(&runs, ids.clone(), true),
|
||||
findings_counts(&findings, ids),
|
||||
);
|
||||
let data = targets
|
||||
@@ -179,10 +179,13 @@ impl TargetFilter {
|
||||
}
|
||||
}
|
||||
|
||||
/// The newest scan run of each target in `target_ids`, in one query.
|
||||
/// The newest scan run of each target in `target_ids`, in one query; with
|
||||
/// `with_queued`, also a run still waiting for a slot (t84), which the
|
||||
/// dashboard shows but which has scanned nothing yet.
|
||||
pub(crate) async fn latest_scan_runs(
|
||||
runs: &mongodb::Collection<ScanRun>,
|
||||
target_ids: Vec<String>,
|
||||
with_queued: bool,
|
||||
) -> HashMap<String, ScanRun> {
|
||||
use futures_util::StreamExt;
|
||||
|
||||
@@ -190,8 +193,12 @@ pub(crate) async fn latest_scan_runs(
|
||||
return HashMap::new();
|
||||
}
|
||||
// Runs store their target's id as `repo_id`.
|
||||
let mut matching = doc! { "repo_id": { "$in": target_ids } };
|
||||
if !with_queued {
|
||||
matching.insert("status", doc! { "$ne": "queued" });
|
||||
}
|
||||
let pipeline = vec![
|
||||
doc! { "$match": { "repo_id": { "$in": target_ids } } },
|
||||
doc! { "$match": matching },
|
||||
doc! { "$sort": { "started_at": -1 } },
|
||||
doc! { "$group": { "_id": "$repo_id", "run": { "$first": "$$ROOT" } } },
|
||||
];
|
||||
|
||||
@@ -560,7 +560,7 @@ pub async fn list_targets(
|
||||
.collect();
|
||||
let runs = db.scan_runs();
|
||||
let (mut last_scans, open, vulns) = tokio::join!(
|
||||
super::onboarding::latest_scan_runs(&runs, ids.clone()),
|
||||
super::onboarding::latest_scan_runs(&runs, ids.clone(), false),
|
||||
open_findings_counts(&db, ids.clone()),
|
||||
open_vulnerabilities_counts(&db, ids),
|
||||
);
|
||||
|
||||
@@ -43,14 +43,15 @@ struct OrphanRule {
|
||||
}
|
||||
|
||||
/// Code scans are what customers see, so they get their own `interrupted`
|
||||
/// status. The rest close as `failed` with [`INTERRUPTED_MESSAGE`]: DAST and
|
||||
/// status, also those still waiting for a slot: the queue lives in the agent's
|
||||
/// memory and is gone after a restart (t84). The rest close as `failed` with [`INTERRUPTED_MESSAGE`]: DAST and
|
||||
/// pentest are off in production, and graph and embedding builds are steps of
|
||||
/// a scan. A paused pentest session can only be resumed through in-memory
|
||||
/// state, so after a restart it is as dead as a running one.
|
||||
const ORPHAN_RULES: [OrphanRule; 5] = [
|
||||
OrphanRule {
|
||||
collection: "scan_runs",
|
||||
open: &["running"],
|
||||
open: &["queued", "running"],
|
||||
closed_as: "interrupted",
|
||||
},
|
||||
OrphanRule {
|
||||
@@ -218,12 +219,16 @@ async fn targets_to_resume(
|
||||
.await?;
|
||||
let mut out = Vec::new();
|
||||
for id in ids.iter().filter_map(|v| v.as_str()) {
|
||||
// Only scans that had started count: one interrupted while it still
|
||||
// waited for a slot cannot be what stopped the agent. It never got a
|
||||
// start time of its own, so it still starts when it was requested.
|
||||
let interruptions = db
|
||||
.scan_runs()
|
||||
.count_documents(doc! {
|
||||
"repo_id": id,
|
||||
"status": "interrupted",
|
||||
"completed_at": { "$gte": window },
|
||||
"$expr": { "$ne": ["$started_at", "$queued_at"] },
|
||||
})
|
||||
.await?;
|
||||
if interruptions > MAX_RECENT_INTERRUPTIONS {
|
||||
@@ -243,12 +248,25 @@ async fn targets_to_resume(
|
||||
.await?;
|
||||
if active > 0 {
|
||||
// Resumed as it was started: a scan a person started runs even when
|
||||
// nothing changed since the last completed one (#465).
|
||||
let trigger = db
|
||||
// nothing changed since the last completed one (#465). Of a running
|
||||
// scan and its queued follow-up, a person's wins.
|
||||
let triggers = db
|
||||
.scan_runs()
|
||||
.find_one(doc! { "repo_id": id, "status": "interrupted", "completed_at": closed })
|
||||
.await?
|
||||
.map_or(ScanTrigger::Scheduled, |run| run.trigger);
|
||||
.distinct(
|
||||
"trigger",
|
||||
doc! { "repo_id": id, "status": "interrupted", "completed_at": closed },
|
||||
)
|
||||
.await?;
|
||||
let triggers: Vec<ScanTrigger> = triggers
|
||||
.into_iter()
|
||||
.filter_map(|t| mongodb::bson::from_bson(t).ok())
|
||||
.collect();
|
||||
let trigger = triggers
|
||||
.iter()
|
||||
.find(|t| t.started_by_person())
|
||||
.or_else(|| triggers.first())
|
||||
.cloned()
|
||||
.unwrap_or(ScanTrigger::Scheduled);
|
||||
out.push((id.to_string(), trigger));
|
||||
}
|
||||
}
|
||||
@@ -365,10 +383,11 @@ mod tests {
|
||||
let archived = insert(archived_target).await;
|
||||
let earlier_only = insert(target("earlier-only")).await;
|
||||
|
||||
// Arrange: runs left open, plus one interrupted an hour ago.
|
||||
// The scan to resume was started by a person.
|
||||
// Arrange: runs left open, plus one interrupted an hour ago. The
|
||||
// target to resume has a scheduled scan running and a person's
|
||||
// follow-up queued (t84): one interruption, resumed as the person's.
|
||||
for (id, trigger) in [
|
||||
(&resumes, ScanTrigger::Manual),
|
||||
(&resumes, ScanTrigger::Scheduled),
|
||||
(&looping, ScanTrigger::Scheduled),
|
||||
(&archived, ScanTrigger::Scheduled),
|
||||
] {
|
||||
@@ -377,6 +396,10 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
db.scan_runs()
|
||||
.insert_one(ScanRun::queued(resumes.clone(), ScanTrigger::Manual))
|
||||
.await
|
||||
.unwrap();
|
||||
for id in [&looping, &earlier_only] {
|
||||
let mut run = ScanRun::new(id.clone(), ScanTrigger::Scheduled);
|
||||
run.status = compliance_core::models::ScanRunStatus::Interrupted;
|
||||
@@ -423,6 +446,16 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queued_code_scans_are_closed_at_startup_too() {
|
||||
let scan_rule = ORPHAN_RULES
|
||||
.iter()
|
||||
.find(|r| r.collection == "scan_runs")
|
||||
.expect("scan_runs rule");
|
||||
assert!(scan_rule.open.contains(&"queued"));
|
||||
assert!(scan_rule.open.contains(&"running"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_scans_are_interrupted_not_failed() {
|
||||
let scan_rule = ORPHAN_RULES
|
||||
|
||||
@@ -82,6 +82,10 @@ pub struct PipelineOrchestrator {
|
||||
/// The tenant's plan limits for metering (t72); `None` when not known,
|
||||
/// and then counted Prüfungen are neither checked nor charged.
|
||||
pub(super) plan_limits: Option<PlanLimits>,
|
||||
/// Set when this person's scan took over a waiting scheduled, webhook or
|
||||
/// new-content scan (t84): the trigger it is charged as. Change detection
|
||||
/// then decides whether it counts, as for that scan.
|
||||
pub(super) charged_as: Option<ScanTrigger>,
|
||||
}
|
||||
|
||||
impl PipelineOrchestrator {
|
||||
@@ -99,9 +103,17 @@ impl PipelineOrchestrator {
|
||||
exploit_cache: None,
|
||||
advisory_index: None,
|
||||
plan_limits: None,
|
||||
charged_as: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Charge this run as a scan started by `trigger` would be, when a
|
||||
/// person's request took that waiting scan over (t84).
|
||||
pub(crate) fn with_charged_as(mut self, trigger: Option<ScanTrigger>) -> Self {
|
||||
self.charged_as = trigger;
|
||||
self
|
||||
}
|
||||
|
||||
/// Check and charge counted Prüfungen against `limits` (t72).
|
||||
pub(crate) fn with_plan_limits(mut self, limits: Option<PlanLimits>) -> Self {
|
||||
self.plan_limits = limits;
|
||||
@@ -227,6 +239,16 @@ impl PipelineOrchestrator {
|
||||
repo.billing,
|
||||
)
|
||||
.await?;
|
||||
} else if let Some(original) = &self.charged_as {
|
||||
let new_commits =
|
||||
GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())?;
|
||||
self.charge_as_taken_over(
|
||||
scan_run_id,
|
||||
&repo_id,
|
||||
ScanAttribution::detected(original, new_commits || repo.changed_besides_commits),
|
||||
repo.billing,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
// Submodules are part of what the product ships (a HAL, an RTOS).
|
||||
@@ -1159,7 +1181,9 @@ impl PipelineOrchestrator {
|
||||
/// `OnboardedTarget`. Mirrors [`Self::run`] but sources the target from
|
||||
/// `onboarded_targets` and dispatches by the scan plan.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %target_id, trigger = ?trigger))]
|
||||
/// Run one scan of the target `target_id`.
|
||||
/// Run one scan of the target `target_id`, recorded on the run `queued`
|
||||
/// that waited for this scan's slot (t84), or on a new run when there is
|
||||
/// none.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
@@ -1174,6 +1198,7 @@ impl PipelineOrchestrator {
|
||||
&self,
|
||||
target_id: &str,
|
||||
trigger: ScanTrigger,
|
||||
queued: Option<&str>,
|
||||
) -> Result<TargetScanOutcome, AgentError> {
|
||||
let oid = mongodb::bson::oid::ObjectId::parse_str(target_id)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
@@ -1189,14 +1214,15 @@ impl PipelineOrchestrator {
|
||||
// detection attributes the others (t72).
|
||||
if let Some(attribution) = ScanAttribution::of_person(&trigger) {
|
||||
scan_run.attribution = Some(attribution);
|
||||
scan_run.chargeable = attribution.chargeable(target.billing);
|
||||
// One that took over a waiting scan counts only as that scan
|
||||
// would have; change detection decides below (t84).
|
||||
scan_run.chargeable =
|
||||
self.charged_as.is_none() && attribution.chargeable(target.billing);
|
||||
}
|
||||
let insert = self.db.scan_runs().insert_one(&scan_run).await?;
|
||||
let scan_run_id = insert
|
||||
.inserted_id
|
||||
.as_object_id()
|
||||
.map(|id| id.to_hex())
|
||||
.unwrap_or_default();
|
||||
scan_run.charged_as = self.charged_as.clone();
|
||||
let run_oid = self.start_run(&scan_run, queued).await?;
|
||||
let scan_run_id = run_oid.to_hex();
|
||||
let run_id = mongodb::bson::Bson::ObjectId(run_oid);
|
||||
|
||||
// A counted Prüfung a person started is checked against the plan
|
||||
// before anything runs (t72).
|
||||
@@ -1230,10 +1256,7 @@ impl PipelineOrchestrator {
|
||||
}
|
||||
self.db
|
||||
.scan_runs()
|
||||
.update_one(
|
||||
doc! { "_id": &insert.inserted_id },
|
||||
doc! { "$set": completed },
|
||||
)
|
||||
.update_one(doc! { "_id": &run_id }, doc! { "$set": completed })
|
||||
.await?;
|
||||
// Refresh the target's cached findings count. The shared pipeline
|
||||
// (Stage 7) increments `repositories`, which the unified path does
|
||||
@@ -1270,7 +1293,7 @@ impl PipelineOrchestrator {
|
||||
self.db
|
||||
.scan_runs()
|
||||
.update_one(
|
||||
doc! { "_id": &insert.inserted_id },
|
||||
doc! { "_id": &run_id },
|
||||
doc! { "$set": {
|
||||
"status": "completed",
|
||||
"current_phase": "completed",
|
||||
@@ -1285,7 +1308,7 @@ impl PipelineOrchestrator {
|
||||
self.db
|
||||
.scan_runs()
|
||||
.update_one(
|
||||
doc! { "_id": &insert.inserted_id },
|
||||
doc! { "_id": &run_id },
|
||||
doc! { "$set": {
|
||||
"status": "failed",
|
||||
"error_message": message,
|
||||
@@ -1305,7 +1328,7 @@ impl PipelineOrchestrator {
|
||||
let run = self
|
||||
.db
|
||||
.scan_runs()
|
||||
.find_one(doc! { "_id": &insert.inserted_id })
|
||||
.find_one(doc! { "_id": &run_id })
|
||||
.await
|
||||
.ok()
|
||||
.flatten();
|
||||
@@ -1319,7 +1342,7 @@ impl PipelineOrchestrator {
|
||||
// A counted Prüfung is charged when it completed, or when it failed on
|
||||
// the customer's input; a failure of ours never is (t72).
|
||||
let charged = if chargeable && ((result.is_ok() && !unchanged) || invalid_input) {
|
||||
self.charge_run(&insert.inserted_id, target_id).await
|
||||
self.charge_run(&run_id, target_id).await
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -1334,6 +1357,59 @@ impl PipelineOrchestrator {
|
||||
})
|
||||
}
|
||||
|
||||
/// Record that `run` starts now: on the run `queued` that waited for the
|
||||
/// slot, which moves from `queued` to `running`, or as a new run when
|
||||
/// there is none or it is gone. Returns the run's id.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The run could not be written.
|
||||
async fn start_run(
|
||||
&self,
|
||||
run: &ScanRun,
|
||||
queued: Option<&str>,
|
||||
) -> Result<mongodb::bson::oid::ObjectId, AgentError> {
|
||||
if let Some(oid) = queued.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) {
|
||||
let mut started = doc! {
|
||||
"status": "running",
|
||||
"trigger": mongodb::bson::to_bson(&run.trigger)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?,
|
||||
"started_at": mongodb::bson::DateTime::from_chrono(run.started_at),
|
||||
"chargeable": run.chargeable,
|
||||
};
|
||||
if let Some(charged_as) = &run.charged_as {
|
||||
started.insert(
|
||||
"charged_as",
|
||||
mongodb::bson::to_bson(charged_as)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?,
|
||||
);
|
||||
}
|
||||
if let Some(attribution) = run.attribution {
|
||||
started.insert(
|
||||
"attribution",
|
||||
mongodb::bson::to_bson(&attribution)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?,
|
||||
);
|
||||
}
|
||||
let updated = self
|
||||
.db
|
||||
.scan_runs()
|
||||
.update_one(
|
||||
doc! { "_id": oid, "status": "queued" },
|
||||
doc! { "$set": started },
|
||||
)
|
||||
.await?;
|
||||
if updated.matched_count == 1 {
|
||||
return Ok(oid);
|
||||
}
|
||||
}
|
||||
let insert = self.db.scan_runs().insert_one(run).await?;
|
||||
insert
|
||||
.inserted_id
|
||||
.as_object_id()
|
||||
.ok_or_else(|| AgentError::Other("the scan run got no id".into()))
|
||||
}
|
||||
|
||||
/// Check a counted Prüfung against the plan before it scans (t72):
|
||||
/// the quota, today's Prüftag on the target, the customer's cap. It runs
|
||||
/// when the plan's limits or the usage are not known.
|
||||
@@ -1432,6 +1508,40 @@ impl PipelineOrchestrator {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Count the run `scan_run_id`, a person's request that took over a
|
||||
/// waiting scan, only when `detected` (that scan's attribution from change
|
||||
/// detection) counts on a target billed as `billing`, and then check it
|
||||
/// against the plan (t84). The run keeps the person's attribution, so its
|
||||
/// history shows that a person asked. Several code artifacts: a change in
|
||||
/// any of them counts it, as in [`Self::attribute_run`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`AgentError::NotAdmitted`] when the plan does not allow a counted
|
||||
/// Prüfung now.
|
||||
async fn charge_as_taken_over(
|
||||
&self,
|
||||
scan_run_id: &str,
|
||||
target_id: &str,
|
||||
detected: ScanAttribution,
|
||||
billing: TargetBilling,
|
||||
) -> Result<(), AgentError> {
|
||||
if !detected.chargeable(billing) {
|
||||
return Ok(());
|
||||
}
|
||||
if let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(scan_run_id) {
|
||||
if let Err(e) = self
|
||||
.db
|
||||
.scan_runs()
|
||||
.update_one(doc! { "_id": oid }, doc! { "$set": { "chargeable": true } })
|
||||
.await
|
||||
{
|
||||
tracing::warn!(scan_run_id, "scan run not marked as counted: {e}");
|
||||
}
|
||||
}
|
||||
self.admit_run(scan_run_id, target_id).await
|
||||
}
|
||||
|
||||
/// Store `attribution` and `chargeable` on the run, unless it already
|
||||
/// reads as a change.
|
||||
async fn record_attribution(
|
||||
@@ -1506,17 +1616,25 @@ impl PipelineOrchestrator {
|
||||
return Ok(0);
|
||||
}
|
||||
// A git target is attributed where its commits are compared.
|
||||
if !trigger.started_by_person() && !has_git {
|
||||
self.attribute_run(
|
||||
scan_run_id,
|
||||
&target_id,
|
||||
ScanAttribution::detected(
|
||||
trigger,
|
||||
crate::pipeline::change::content_changed(target),
|
||||
),
|
||||
target.billing,
|
||||
)
|
||||
.await?;
|
||||
if !has_git {
|
||||
let changed = crate::pipeline::change::content_changed(target);
|
||||
if !trigger.started_by_person() {
|
||||
self.attribute_run(
|
||||
scan_run_id,
|
||||
&target_id,
|
||||
ScanAttribution::detected(trigger, changed),
|
||||
target.billing,
|
||||
)
|
||||
.await?;
|
||||
} else if let Some(original) = &self.charged_as {
|
||||
self.charge_as_taken_over(
|
||||
scan_run_id,
|
||||
&target_id,
|
||||
ScanAttribution::detected(original, changed),
|
||||
target.billing,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
let plan = build_scan_plan(target);
|
||||
// An attached artifact nothing analyses is recorded, never passed over:
|
||||
|
||||
@@ -1,37 +1,55 @@
|
||||
//! How many scans run at once, and what happens to a scan requested while the
|
||||
//! same target is already being scanned.
|
||||
//! How many scans run at once, in which order they get a slot, and what
|
||||
//! happens to a scan requested while the same target is already queued or
|
||||
//! being scanned.
|
||||
//!
|
||||
//! Every scan used to be a bare `tokio::spawn` with no limit. A burst of pushes,
|
||||
//! a scheduler tick and a few clicks could start any number of scans side by
|
||||
//! side — each one a clone plus semgrep plus syft — on an 8 GB node, and two
|
||||
//! scans of the same target shared one checkout directory and corrupted each
|
||||
//! other. Two rules now apply to every trigger (click, webhook, scheduler):
|
||||
//! other. These rules now apply to every trigger (click, webhook, scheduler):
|
||||
//!
|
||||
//! * **Global:** at most `SCAN_CONCURRENCY` scans run at a time; the rest wait
|
||||
//! for a slot.
|
||||
//! * **Per target — coalesce:** one scan runs and at most one more is pending.
|
||||
//! A request that arrives while one is pending is dropped, because the pending
|
||||
//! scan will pick up the latest code anyway. Ten pushes during a long scan
|
||||
//! therefore cost two scans, not ten. Dropped requests are never billed: only
|
||||
//! a scan that actually ran emits usage.
|
||||
//! * **Order:** a scan a person started ([`Priority::Person`]) gets a free slot
|
||||
//! before scheduled, webhook and new-content scans ([`Priority::Background`]);
|
||||
//! within a class the first to ask is the first served. So that a stream of
|
||||
//! clicks never starves the scheduler, a waiting background scan gets the
|
||||
//! slot after [`PERSON_GRANTS_IN_A_ROW`] person scans in a row (t84).
|
||||
//! * **Per target — coalesce:** one scan of a target waits or runs, and while
|
||||
//! it runs at most one more is pending. A request while the scan still waits
|
||||
//! for its slot is covered by it (it reads the latest code once it starts);
|
||||
//! a request while one is pending is covered by that one. Ten pushes during
|
||||
//! a long scan therefore cost two scans, not ten. A person's request takes
|
||||
//! over a waiting or pending scan that was not a person's, so it runs at
|
||||
//! person priority and always scans. Requests that do not run are never
|
||||
//! billed: only a scan that actually ran emits usage.
|
||||
//!
|
||||
//! Each admitted request carries the id of the run recorded for it while it
|
||||
//! waits (status `queued`); the gate tells the caller which of those runs will
|
||||
//! not happen, so no queued run is left behind.
|
||||
//!
|
||||
//! A scheduled scan also starts after a random delay of up to
|
||||
//! [`SCHEDULED_SCAN_JITTER`], so the scans of a tenant's repositories (often
|
||||
//! all on one git host) do not start in the same second.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use dashmap::mapref::entry::Entry;
|
||||
use dashmap::DashMap;
|
||||
use rand::Rng;
|
||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use compliance_core::models::ScanTrigger;
|
||||
|
||||
/// The longest a scheduled scan waits before it starts.
|
||||
pub const SCHEDULED_SCAN_JITTER: Duration = Duration::from_secs(30);
|
||||
|
||||
/// How many slots in a row go to person-started scans while a background scan
|
||||
/// waits; the next one goes to the background scan.
|
||||
pub const PERSON_GRANTS_IN_A_ROW: u32 = 3;
|
||||
|
||||
/// How long a scan with `trigger` waits before it starts: a random delay of
|
||||
/// up to [`SCHEDULED_SCAN_JITTER`] for a scheduled scan, none for a scan a
|
||||
/// webhook or a person started.
|
||||
@@ -45,33 +63,108 @@ pub fn start_delay(trigger: &ScanTrigger) -> Duration {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which queue a scan waits in for a slot.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Priority {
|
||||
/// Started by a person (the customer or support): served first.
|
||||
Person,
|
||||
/// Scheduled, webhook and new-content scans, and PR reviews.
|
||||
Background,
|
||||
}
|
||||
|
||||
impl Priority {
|
||||
/// The queue a scan with `trigger` waits in.
|
||||
pub fn of(trigger: &ScanTrigger) -> Self {
|
||||
if trigger.started_by_person() {
|
||||
Self::Person
|
||||
} else {
|
||||
Self::Background
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One scan to run: what started it and the run recorded for it while it
|
||||
/// waits (`None` when that record could not be written).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Job {
|
||||
pub trigger: ScanTrigger,
|
||||
pub run_id: Option<String>,
|
||||
/// Set when a person's request took over a waiting scan that was not a
|
||||
/// person's: that scan's trigger, which the run is charged as (t84).
|
||||
pub charged_as: Option<ScanTrigger>,
|
||||
}
|
||||
|
||||
impl Job {
|
||||
/// A scan started by `trigger`, recorded as the run `run_id`.
|
||||
pub fn new(trigger: ScanTrigger, run_id: Option<String>) -> Self {
|
||||
Self {
|
||||
trigger,
|
||||
run_id,
|
||||
charged_as: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn priority(&self) -> Priority {
|
||||
Priority::of(&self.trigger)
|
||||
}
|
||||
}
|
||||
|
||||
/// What happened to a scan request.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Admission {
|
||||
/// Nothing was running for this target: the caller runs the scan now.
|
||||
/// Nothing was queued or running for this target: the caller now holds
|
||||
/// it and runs its scans through [`ScanGate::start`].
|
||||
Run,
|
||||
/// A scan is running; this request becomes the single pending follow-up,
|
||||
/// run by the task that holds the target once it finishes.
|
||||
Coalesced,
|
||||
/// A scan is running and a follow-up is already pending: nothing to do.
|
||||
/// The request will run: as the target's pending follow-up, or in place
|
||||
/// of the target's waiting scan. `replaced` is the run of the request it
|
||||
/// took over, which will not happen.
|
||||
Coalesced { replaced: Option<String> },
|
||||
/// A scan already queued for this target covers the request: its own run
|
||||
/// will not happen.
|
||||
Dropped,
|
||||
}
|
||||
|
||||
/// The scan queue is gone, or the target is no longer held.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum GateError {
|
||||
#[error("the scan queue was closed")]
|
||||
Closed,
|
||||
#[error("the target is not held")]
|
||||
NotHeld,
|
||||
}
|
||||
|
||||
/// Global scan slots plus the per-target coalescing state.
|
||||
#[derive(Debug)]
|
||||
pub struct ScanGate {
|
||||
slots: Arc<Semaphore>,
|
||||
/// Present while a scan of the key is running; the value is the pending
|
||||
/// follow-up's trigger, if one was requested meanwhile.
|
||||
running: DashMap<String, Option<ScanTrigger>>,
|
||||
slots: Arc<Slots>,
|
||||
/// Present while a scan of the key waits or runs.
|
||||
targets: DashMap<String, Held>,
|
||||
}
|
||||
|
||||
/// The scans of one target that are queued or running.
|
||||
#[derive(Debug)]
|
||||
struct Held {
|
||||
/// The scan that waits for a slot or runs now.
|
||||
current: Job,
|
||||
/// Whether `current` has its slot.
|
||||
running: bool,
|
||||
/// The follow-up requested while `current` runs.
|
||||
pending: Option<Job>,
|
||||
}
|
||||
|
||||
impl ScanGate {
|
||||
/// A gate allowing `concurrency` scans at once (at least one).
|
||||
pub fn new(concurrency: usize) -> Self {
|
||||
Self {
|
||||
slots: Arc::new(Semaphore::new(concurrency.max(1))),
|
||||
running: DashMap::new(),
|
||||
slots: Arc::new(Slots {
|
||||
queue: Mutex::new(Queue {
|
||||
free: concurrency.max(1),
|
||||
person: VecDeque::new(),
|
||||
background: VecDeque::new(),
|
||||
person_grants: 0,
|
||||
}),
|
||||
}),
|
||||
targets: DashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,60 +176,253 @@ impl ScanGate {
|
||||
|
||||
/// Decide what to do with a scan request for `key`. Atomic per key, so two
|
||||
/// simultaneous requests can never both be told to [`Admission::Run`].
|
||||
pub fn admit(&self, key: &str, trigger: ScanTrigger) -> Admission {
|
||||
match self.running.entry(key.to_string()) {
|
||||
pub fn admit(&self, key: &str, job: Job) -> Admission {
|
||||
// Lock order: a target's entry, then the slot queue (in `promote`).
|
||||
// `start` keeps the same order and `Permit::drop` takes only the queue.
|
||||
match self.targets.entry(key.to_string()) {
|
||||
Entry::Vacant(v) => {
|
||||
v.insert(None);
|
||||
v.insert(Held {
|
||||
current: job,
|
||||
running: false,
|
||||
pending: None,
|
||||
});
|
||||
Admission::Run
|
||||
}
|
||||
Entry::Occupied(mut o) if o.get().is_none() => {
|
||||
o.insert(Some(trigger));
|
||||
Admission::Coalesced
|
||||
Entry::Occupied(mut o) => {
|
||||
let held = o.get_mut();
|
||||
let person = job.trigger.started_by_person();
|
||||
// A person's request takes over a queued scan that is not a
|
||||
// person's: that one might skip as unchanged (#465), theirs
|
||||
// always scans, e.g. right after they uploaded new files.
|
||||
let takes_over = |queued: &Job| person && !queued.trigger.started_by_person();
|
||||
if !held.running {
|
||||
// The waiting scan reads the latest code once it starts,
|
||||
// so it covers the request, or the person's takes its
|
||||
// place, at person priority. It would have run anyway,
|
||||
// so it is charged as the scan it replaces.
|
||||
if !takes_over(&held.current) {
|
||||
return Admission::Dropped;
|
||||
}
|
||||
let job = Job {
|
||||
charged_as: Some(held.current.trigger.clone()),
|
||||
..job
|
||||
};
|
||||
let replaced = std::mem::replace(&mut held.current, job).run_id;
|
||||
self.slots.promote(key);
|
||||
return Admission::Coalesced { replaced };
|
||||
}
|
||||
match held.pending.as_ref().map(takes_over) {
|
||||
None => {
|
||||
held.pending = Some(job);
|
||||
Admission::Coalesced { replaced: None }
|
||||
}
|
||||
Some(true) => {
|
||||
let replaced = held.pending.replace(job).and_then(|p| p.run_id);
|
||||
Admission::Coalesced { replaced }
|
||||
}
|
||||
Some(false) => Admission::Dropped,
|
||||
}
|
||||
}
|
||||
// A person's request takes over a pending scheduled or webhook
|
||||
// follow-up: that one may skip as unchanged (#465), theirs always
|
||||
// scans, e.g. right after they uploaded new files.
|
||||
Entry::Occupied(mut o)
|
||||
if trigger.started_by_person()
|
||||
&& o.get().as_ref().is_some_and(|p| !p.started_by_person()) =>
|
||||
{
|
||||
o.insert(Some(trigger));
|
||||
Admission::Coalesced
|
||||
}
|
||||
Entry::Occupied(_) => Admission::Dropped,
|
||||
}
|
||||
}
|
||||
|
||||
/// Called by the task holding `key` after each scan. Returns the pending
|
||||
/// follow-up to run next (the target stays held), or `None` once there is
|
||||
/// nothing left, releasing the target.
|
||||
pub fn finish(&self, key: &str) -> Option<ScanTrigger> {
|
||||
match self.running.entry(key.to_string()) {
|
||||
Entry::Occupied(mut o) => match o.get_mut().take() {
|
||||
Some(next) => Some(next),
|
||||
None => {
|
||||
o.remove();
|
||||
None
|
||||
/// Wait for a slot for the held target `key`'s next scan, in the queue of
|
||||
/// its priority, and return the slot with the scan to run. The scan is the
|
||||
/// one current when the slot is granted: a person's request may have taken
|
||||
/// it over meanwhile.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`GateError::NotHeld`] if `key` was released meanwhile, and
|
||||
/// [`GateError::Closed`] if the queue is gone, which this gate never does.
|
||||
pub async fn start(&self, key: &str) -> Result<(Permit, Job), GateError> {
|
||||
let waiting = {
|
||||
let held = self.targets.get(key).ok_or(GateError::NotHeld)?;
|
||||
self.slots.enqueue(Some(key), held.current.priority())
|
||||
// The entry's guard is dropped here, before waiting.
|
||||
};
|
||||
let permit = waiting.wait().await?;
|
||||
let mut held = self.targets.get_mut(key).ok_or(GateError::NotHeld)?;
|
||||
held.running = true;
|
||||
Ok((permit, held.current.clone()))
|
||||
}
|
||||
|
||||
/// Called by the task holding `key` after each scan. Returns whether a
|
||||
/// follow-up is pending, to run next through [`Self::start`] (the target
|
||||
/// stays held), or `false` once there is nothing left, releasing it.
|
||||
pub fn finish(&self, key: &str) -> bool {
|
||||
match self.targets.entry(key.to_string()) {
|
||||
Entry::Occupied(mut o) => {
|
||||
let held = o.get_mut();
|
||||
match held.pending.take() {
|
||||
Some(next) => {
|
||||
held.current = next;
|
||||
held.running = false;
|
||||
true
|
||||
}
|
||||
None => {
|
||||
o.remove();
|
||||
false
|
||||
}
|
||||
}
|
||||
},
|
||||
Entry::Vacant(_) => None,
|
||||
}
|
||||
Entry::Vacant(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Release `key` unconditionally, dropping any pending follow-up. Used when
|
||||
/// the holding task dies, so the target does not stay "running" forever.
|
||||
pub fn release(&self, key: &str) {
|
||||
self.running.remove(key);
|
||||
self.targets.remove(key);
|
||||
}
|
||||
|
||||
/// Wait for one of the global scan slots. The slot is freed when the
|
||||
/// returned permit is dropped.
|
||||
/// Wait for a slot for work that is not a target's scan (a PR review).
|
||||
/// The slot is freed when the returned permit is dropped.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Only if the semaphore was closed, which this gate never does.
|
||||
pub async fn slot(&self) -> Result<OwnedSemaphorePermit, tokio::sync::AcquireError> {
|
||||
self.slots.clone().acquire_owned().await
|
||||
/// Only if the queue is gone, which this gate never does.
|
||||
pub async fn slot(&self, priority: Priority) -> Result<Permit, GateError> {
|
||||
self.slots.enqueue(None, priority).wait().await
|
||||
}
|
||||
}
|
||||
|
||||
/// The slots and the two queues waiting for them.
|
||||
#[derive(Debug)]
|
||||
struct Slots {
|
||||
queue: Mutex<Queue>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Queue {
|
||||
/// Slots nobody holds. Only above zero while nobody waits.
|
||||
free: usize,
|
||||
person: VecDeque<Waiter>,
|
||||
background: VecDeque<Waiter>,
|
||||
/// Person scans granted in a row while a background scan waited.
|
||||
person_grants: u32,
|
||||
}
|
||||
|
||||
/// One request waiting for a slot; the slot is handed over through `grant`.
|
||||
#[derive(Debug)]
|
||||
struct Waiter {
|
||||
/// The target it is for, so a person's request can move it forward.
|
||||
key: Option<String>,
|
||||
grant: oneshot::Sender<Permit>,
|
||||
}
|
||||
|
||||
/// A request in a queue, or a slot already granted.
|
||||
enum Waiting {
|
||||
Granted(Permit),
|
||||
Queued(oneshot::Receiver<Permit>),
|
||||
}
|
||||
|
||||
impl Waiting {
|
||||
async fn wait(self) -> Result<Permit, GateError> {
|
||||
match self {
|
||||
Self::Granted(permit) => Ok(permit),
|
||||
// The sender only goes away unsent with the gate itself.
|
||||
Self::Queued(grant) => grant.await.map_err(|_| GateError::Closed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Slots {
|
||||
/// The queue, also after a thread panicked while holding it: every change
|
||||
/// to it is a single push or pop, so it is never left half-changed.
|
||||
fn lock(&self) -> MutexGuard<'_, Queue> {
|
||||
self.queue.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Take a free slot, or join the queue of `priority`.
|
||||
fn enqueue(self: &Arc<Self>, key: Option<&str>, priority: Priority) -> Waiting {
|
||||
let mut queue = self.lock();
|
||||
if queue.free > 0 {
|
||||
queue.free -= 1;
|
||||
return Waiting::Granted(Permit::new(self));
|
||||
}
|
||||
let (grant, granted) = oneshot::channel();
|
||||
let waiter = Waiter {
|
||||
key: key.map(str::to_string),
|
||||
grant,
|
||||
};
|
||||
match priority {
|
||||
Priority::Person => queue.person.push_back(waiter),
|
||||
Priority::Background => queue.background.push_back(waiter),
|
||||
}
|
||||
Waiting::Queued(granted)
|
||||
}
|
||||
|
||||
/// Move the background request for `key`, if one waits, to the back of
|
||||
/// the person queue.
|
||||
fn promote(&self, key: &str) {
|
||||
let mut queue = self.lock();
|
||||
let found = queue
|
||||
.background
|
||||
.iter()
|
||||
.position(|w| w.key.as_deref() == Some(key));
|
||||
if let Some(waiter) = found.and_then(|i| queue.background.remove(i)) {
|
||||
queue.person.push_back(waiter);
|
||||
}
|
||||
}
|
||||
|
||||
/// Hand a freed slot to the next request, or keep it free.
|
||||
fn release(self: &Arc<Self>) {
|
||||
let mut queue = self.lock();
|
||||
while let Some(waiter) = queue.next() {
|
||||
match waiter.grant.send(Permit::new(self)) {
|
||||
Ok(()) => return,
|
||||
// The request was given up (its task ended): the permit comes
|
||||
// back unused, and the slot goes to the next one.
|
||||
Err(mut unused) => unused.slots = None,
|
||||
}
|
||||
}
|
||||
queue.free += 1;
|
||||
}
|
||||
}
|
||||
|
||||
impl Queue {
|
||||
/// The next request to serve: person scans first, except that a waiting
|
||||
/// background scan gets the slot after [`PERSON_GRANTS_IN_A_ROW`] person
|
||||
/// scans in a row.
|
||||
fn next(&mut self) -> Option<Waiter> {
|
||||
let background_due = self.person.is_empty() || self.person_grants >= PERSON_GRANTS_IN_A_ROW;
|
||||
if background_due {
|
||||
if let Some(waiter) = self.background.pop_front() {
|
||||
self.person_grants = 0;
|
||||
return Some(waiter);
|
||||
}
|
||||
}
|
||||
let waiter = self.person.pop_front()?;
|
||||
self.person_grants = if self.background.is_empty() {
|
||||
0
|
||||
} else {
|
||||
self.person_grants + 1
|
||||
};
|
||||
Some(waiter)
|
||||
}
|
||||
}
|
||||
|
||||
/// One scan slot; freed, and handed to the next request, when dropped.
|
||||
#[derive(Debug)]
|
||||
pub struct Permit {
|
||||
/// `None` once the permit was given back unused.
|
||||
slots: Option<Arc<Slots>>,
|
||||
}
|
||||
|
||||
impl Permit {
|
||||
fn new(slots: &Arc<Slots>) -> Self {
|
||||
Self {
|
||||
slots: Some(Arc::clone(slots)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Permit {
|
||||
fn drop(&mut self) {
|
||||
if let Some(slots) = self.slots.take() {
|
||||
slots.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,10 +461,20 @@ impl Drop for HeldTarget<'_> {
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::{start_delay, Admission, HeldTarget, ScanGate, SCHEDULED_SCAN_JITTER};
|
||||
use super::{
|
||||
start_delay, Admission, HeldTarget, Job, Priority, ScanGate, PERSON_GRANTS_IN_A_ROW,
|
||||
SCHEDULED_SCAN_JITTER,
|
||||
};
|
||||
use compliance_core::models::ScanTrigger;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
type Log = Arc<Mutex<Vec<(String, ScanTrigger)>>>;
|
||||
|
||||
fn job(trigger: ScanTrigger, run: &str) -> Job {
|
||||
Job::new(trigger, Some(run.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scheduled_scan_waits_within_the_jitter() {
|
||||
let delays: Vec<Duration> = (0..1000)
|
||||
@@ -202,52 +498,163 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_burst_coalesces_into_one_run_and_one_follow_up() {
|
||||
fn only_a_persons_scan_has_person_priority() {
|
||||
assert_eq!(Priority::of(&ScanTrigger::Manual), Priority::Person);
|
||||
assert_eq!(Priority::of(&ScanTrigger::Support), Priority::Person);
|
||||
for trigger in [
|
||||
ScanTrigger::Scheduled,
|
||||
ScanTrigger::Webhook,
|
||||
ScanTrigger::NewContent,
|
||||
] {
|
||||
assert_eq!(Priority::of(&trigger), Priority::Background);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_burst_coalesces_into_one_run_and_one_follow_up() {
|
||||
let gate = ScanGate::new(2);
|
||||
let key = ScanGate::key("acme", "t1");
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced);
|
||||
for _ in 0..8 {
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Dropped);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r1")),
|
||||
Admission::Run
|
||||
);
|
||||
let (_slot, running) = gate.start(&key).await.unwrap();
|
||||
assert_eq!(running, job(ScanTrigger::Manual, "r1"));
|
||||
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Webhook, "r2")),
|
||||
Admission::Coalesced { replaced: None }
|
||||
);
|
||||
for i in 0..8 {
|
||||
let run = format!("drop{i}");
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Webhook, &run)),
|
||||
Admission::Dropped
|
||||
);
|
||||
}
|
||||
// The holder runs the one follow-up, then releases the target.
|
||||
assert!(gate.finish(&key).is_some());
|
||||
assert!(gate.finish(&key).is_none());
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
|
||||
assert!(gate.finish(&key));
|
||||
let (_next, follow_up) = gate.start(&key).await.unwrap();
|
||||
assert_eq!(follow_up, job(ScanTrigger::Webhook, "r2"));
|
||||
assert!(!gate.finish(&key));
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r3")),
|
||||
Admission::Run
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_persons_request_takes_over_a_pending_scheduled_follow_up() {
|
||||
fn a_scan_still_waiting_covers_requests_that_are_not_a_persons() {
|
||||
let gate = ScanGate::new(1);
|
||||
let key = ScanGate::key("acme", "t1");
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Scheduled), Admission::Run);
|
||||
assert_eq!(
|
||||
gate.admit(&key, ScanTrigger::Scheduled),
|
||||
Admission::Coalesced
|
||||
gate.admit(&key, job(ScanTrigger::Scheduled, "r1")),
|
||||
Admission::Run
|
||||
);
|
||||
// Not started yet, so it will read the push's code anyway.
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Webhook, "r2")),
|
||||
Admission::Dropped
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_waiting_scan_taken_over_is_charged_as_the_scan_it_replaces() {
|
||||
let gate = ScanGate::new(1);
|
||||
let key = ScanGate::key("acme", "t1");
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Webhook, "r1")),
|
||||
Admission::Run
|
||||
);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r2")),
|
||||
Admission::Coalesced {
|
||||
replaced: Some("r1".into())
|
||||
}
|
||||
);
|
||||
let (_slot, run) = gate.start(&key).await.unwrap();
|
||||
assert_eq!(run.trigger, ScanTrigger::Manual);
|
||||
assert_eq!(run.charged_as, Some(ScanTrigger::Webhook));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_persons_follow_up_after_a_running_scan_is_charged_as_theirs() {
|
||||
let gate = ScanGate::new(1);
|
||||
let key = ScanGate::key("acme", "t1");
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Scheduled, "r1")),
|
||||
Admission::Run
|
||||
);
|
||||
let (running, _) = gate.start(&key).await.unwrap();
|
||||
// Pending behind the running scan, replacing a scheduled follow-up.
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Scheduled, "r2")),
|
||||
Admission::Coalesced { replaced: None }
|
||||
);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r3")),
|
||||
Admission::Coalesced {
|
||||
replaced: Some("r2".into())
|
||||
}
|
||||
);
|
||||
drop(running);
|
||||
assert!(gate.finish(&key));
|
||||
let (_slot, follow_up) = gate.start(&key).await.unwrap();
|
||||
assert_eq!(follow_up, job(ScanTrigger::Manual, "r3"));
|
||||
assert_eq!(follow_up.charged_as, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_persons_request_takes_over_a_pending_scheduled_follow_up() {
|
||||
let gate = ScanGate::new(1);
|
||||
let key = ScanGate::key("acme", "t1");
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Scheduled, "r1")),
|
||||
Admission::Run
|
||||
);
|
||||
let _slot = gate.start(&key).await.unwrap();
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Scheduled, "r2")),
|
||||
Admission::Coalesced { replaced: None }
|
||||
);
|
||||
|
||||
// Clicked after uploading new files: the follow-up scans in full.
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Coalesced);
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Dropped);
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Support), Admission::Dropped);
|
||||
// Clicked after uploading new files: the follow-up scans in full, and
|
||||
// the scheduled follow-up's queued run will not happen.
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r3")),
|
||||
Admission::Coalesced {
|
||||
replaced: Some("r2".into())
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Webhook, "r4")),
|
||||
Admission::Dropped
|
||||
);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Support, "r5")),
|
||||
Admission::Dropped
|
||||
);
|
||||
|
||||
assert_eq!(gate.finish(&key), Some(ScanTrigger::Manual));
|
||||
assert!(gate.finish(&key));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targets_and_tenants_are_independent() {
|
||||
let gate = ScanGate::new(2);
|
||||
assert_eq!(
|
||||
gate.admit(&ScanGate::key("acme", "t1"), ScanTrigger::Manual),
|
||||
gate.admit(&ScanGate::key("acme", "t1"), job(ScanTrigger::Manual, "a")),
|
||||
Admission::Run
|
||||
);
|
||||
assert_eq!(
|
||||
gate.admit(&ScanGate::key("acme", "t2"), ScanTrigger::Manual),
|
||||
gate.admit(&ScanGate::key("acme", "t2"), job(ScanTrigger::Manual, "b")),
|
||||
Admission::Run
|
||||
);
|
||||
// Same target id in another tenant is another target.
|
||||
assert_eq!(
|
||||
gate.admit(&ScanGate::key("globex", "t1"), ScanTrigger::Manual),
|
||||
gate.admit(
|
||||
&ScanGate::key("globex", "t1"),
|
||||
job(ScanTrigger::Manual, "c")
|
||||
),
|
||||
Admission::Run
|
||||
);
|
||||
}
|
||||
@@ -256,34 +663,228 @@ mod tests {
|
||||
fn a_dead_holder_does_not_leave_the_target_locked() {
|
||||
let gate = ScanGate::new(1);
|
||||
let key = ScanGate::key("acme", "t1");
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r1")),
|
||||
Admission::Run
|
||||
);
|
||||
{
|
||||
// The holding task ends without calling finish (panic / shutdown).
|
||||
let _held = HeldTarget::new(&gate, key.clone());
|
||||
}
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r2")),
|
||||
Admission::Run
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_disarmed_holder_leaves_the_state_to_finish() {
|
||||
#[tokio::test]
|
||||
async fn a_disarmed_holder_leaves_the_state_to_finish() {
|
||||
let gate = ScanGate::new(1);
|
||||
let key = ScanGate::key("acme", "t1");
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r1")),
|
||||
Admission::Run
|
||||
);
|
||||
let _slot = gate.start(&key).await.unwrap();
|
||||
HeldTarget::new(&gate, key.clone()).disarm();
|
||||
// Still held: disarm does not release, finish does.
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Webhook, "r2")),
|
||||
Admission::Coalesced { replaced: None }
|
||||
);
|
||||
}
|
||||
|
||||
/// 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: Arc<ScanGate>, key: String, log: Log) {
|
||||
loop {
|
||||
{
|
||||
let (_slot, job) = gate.start(&key).await.unwrap();
|
||||
log.lock().unwrap().push((key.clone(), job.trigger));
|
||||
}
|
||||
if !gate.finish(&key) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Admit `trigger` for each of `targets` of tenant `acme`, each with a
|
||||
/// task that scans it, queued in that order behind a slot held elsewhere.
|
||||
async fn queue_targets(
|
||||
gate: &Arc<ScanGate>,
|
||||
targets: &[&str],
|
||||
trigger: ScanTrigger,
|
||||
log: &Log,
|
||||
) -> Vec<tokio::task::JoinHandle<()>> {
|
||||
let mut tasks = Vec::new();
|
||||
for target in targets {
|
||||
let key = ScanGate::key("acme", target);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(trigger.clone(), target)),
|
||||
Admission::Run
|
||||
);
|
||||
tasks.push(tokio::spawn(hold_and_scan(gate.clone(), key, log.clone())));
|
||||
// Let it queue for the slot before the next one does.
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
tasks
|
||||
}
|
||||
|
||||
fn triggers(log: &Log) -> Vec<ScanTrigger> {
|
||||
log.lock().unwrap().iter().map(|(_, t)| t.clone()).collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_persons_scan_gets_the_next_slot_before_scheduled_scans() {
|
||||
let gate = Arc::new(ScanGate::new(1));
|
||||
let log = Log::default();
|
||||
// Another tenant's scan has the only slot.
|
||||
let busy = gate.slot(Priority::Background).await.unwrap();
|
||||
|
||||
let mut tasks = queue_targets(&gate, &["t1", "t2"], ScanTrigger::Scheduled, &log).await;
|
||||
tasks.extend(queue_targets(&gate, &["t3"], ScanTrigger::Manual, &log).await);
|
||||
|
||||
drop(busy);
|
||||
for task in tasks {
|
||||
task.await.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
triggers(&log),
|
||||
[
|
||||
ScanTrigger::Manual,
|
||||
ScanTrigger::Scheduled,
|
||||
ScanTrigger::Scheduled
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_persons_request_takes_over_a_scheduled_scan_still_waiting() {
|
||||
let gate = Arc::new(ScanGate::new(1));
|
||||
let log = Log::default();
|
||||
// Another tenant's scan has the only slot.
|
||||
let busy = gate.slot(Priority::Background).await.unwrap();
|
||||
|
||||
// A scheduler tick admits three targets; all wait for the slot.
|
||||
let tasks = queue_targets(&gate, &["t1", "t2", "t3"], ScanTrigger::Scheduled, &log).await;
|
||||
|
||||
// A person asks for t3 while its scheduled scan still waits, last.
|
||||
let t3 = ScanGate::key("acme", "t3");
|
||||
assert_eq!(
|
||||
gate.admit(&t3, job(ScanTrigger::Manual, "click")),
|
||||
Admission::Coalesced {
|
||||
replaced: Some("t3".into())
|
||||
}
|
||||
);
|
||||
|
||||
drop(busy);
|
||||
for task in tasks {
|
||||
task.await.unwrap();
|
||||
}
|
||||
// Their scan runs first, once, in place of the scheduled one, and
|
||||
// is charged as the scheduled one (asserted on the job below).
|
||||
let order: Vec<(String, ScanTrigger)> = log.lock().unwrap().clone();
|
||||
assert_eq!(
|
||||
order,
|
||||
[
|
||||
(t3, ScanTrigger::Manual),
|
||||
(ScanGate::key("acme", "t1"), ScanTrigger::Scheduled),
|
||||
(ScanGate::key("acme", "t2"), ScanTrigger::Scheduled),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_persons_follow_up_waits_only_for_the_running_scan() {
|
||||
let gate = Arc::new(ScanGate::new(1));
|
||||
let log = Log::default();
|
||||
let t1 = ScanGate::key("acme", "t1");
|
||||
assert_eq!(
|
||||
gate.admit(&t1, job(ScanTrigger::Scheduled, "t1")),
|
||||
Admission::Run
|
||||
);
|
||||
// t1's scheduled scan runs; two more targets queue behind it.
|
||||
let (running, _) = gate.start(&t1).await.unwrap();
|
||||
let tasks = queue_targets(&gate, &["t2", "t3"], ScanTrigger::Scheduled, &log).await;
|
||||
|
||||
assert_eq!(
|
||||
gate.admit(&t1, job(ScanTrigger::Manual, "click")),
|
||||
Admission::Coalesced { replaced: None }
|
||||
);
|
||||
// t1's scan ends; its follow-up queues as a person's.
|
||||
assert!(gate.finish(&t1));
|
||||
let follow_up = tokio::spawn(hold_and_scan(gate.clone(), t1.clone(), log.clone()));
|
||||
tokio::task::yield_now().await;
|
||||
drop(running);
|
||||
follow_up.await.unwrap();
|
||||
for task in tasks {
|
||||
task.await.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
triggers(&log),
|
||||
[
|
||||
ScanTrigger::Manual,
|
||||
ScanTrigger::Scheduled,
|
||||
ScanTrigger::Scheduled
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_stream_of_clicks_does_not_starve_scheduled_scans() {
|
||||
let gate = Arc::new(ScanGate::new(1));
|
||||
let log = Log::default();
|
||||
let busy = gate.slot(Priority::Background).await.unwrap();
|
||||
|
||||
let mut tasks = queue_targets(&gate, &["s1"], ScanTrigger::Scheduled, &log).await;
|
||||
let clicks: Vec<String> = (0..10).map(|i| format!("p{i}")).collect();
|
||||
let clicks: Vec<&str> = clicks.iter().map(String::as_str).collect();
|
||||
tasks.extend(queue_targets(&gate, &clicks, ScanTrigger::Manual, &log).await);
|
||||
|
||||
drop(busy);
|
||||
for task in tasks {
|
||||
task.await.unwrap();
|
||||
}
|
||||
let scheduled_at = triggers(&log)
|
||||
.iter()
|
||||
.position(|t| *t == ScanTrigger::Scheduled)
|
||||
.unwrap();
|
||||
assert_eq!(scheduled_at, PERSON_GRANTS_IN_A_ROW as usize);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_given_up_request_passes_its_slot_on() {
|
||||
let gate = Arc::new(ScanGate::new(1));
|
||||
let busy = gate.slot(Priority::Background).await.unwrap();
|
||||
// A request that waits and is then given up (its task ends).
|
||||
let gone = tokio::spawn({
|
||||
let gate = gate.clone();
|
||||
async move { gate.slot(Priority::Person).await.map(drop) }
|
||||
});
|
||||
tokio::task::yield_now().await;
|
||||
gone.abort();
|
||||
let _ = gone.await;
|
||||
|
||||
drop(busy);
|
||||
let next = tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Background));
|
||||
assert!(
|
||||
next.await.is_ok(),
|
||||
"the slot is not lost to the given-up request"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn slots_bound_how_many_scans_run_at_once() {
|
||||
let gate = ScanGate::new(2);
|
||||
let a = gate.slot().await.unwrap();
|
||||
let _b = gate.slot().await.unwrap();
|
||||
let a = gate.slot(Priority::Background).await.unwrap();
|
||||
let _b = gate.slot(Priority::Background).await.unwrap();
|
||||
// A third slot is not available until one is freed.
|
||||
let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await;
|
||||
let third =
|
||||
tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Person)).await;
|
||||
assert!(third.is_err(), "a third concurrent scan must wait");
|
||||
drop(a);
|
||||
let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await;
|
||||
let third =
|
||||
tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Person)).await;
|
||||
assert!(third.is_ok(), "a freed slot is reused");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
//! 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<ScanRun> {
|
||||
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<ScanRun> {
|
||||
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<ComplianceAgent>,
|
||||
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();
|
||||
}
|
||||
@@ -70,6 +70,9 @@ impl std::fmt::Display for ScanType {
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ScanRunStatus {
|
||||
/// Requested and waiting for one of the agent's scan slots (t84). Moves
|
||||
/// to `running` when it gets one.
|
||||
Queued,
|
||||
Running,
|
||||
Completed,
|
||||
/// The scan itself hit an error on the target (clone, tool, pipeline).
|
||||
@@ -80,6 +83,16 @@ pub enum ScanRunStatus {
|
||||
Interrupted,
|
||||
}
|
||||
|
||||
impl ScanRunStatus {
|
||||
/// Whether the run has not ended yet: it waits for a slot or runs.
|
||||
pub fn is_open(&self) -> bool {
|
||||
match self {
|
||||
Self::Queued | Self::Running => true,
|
||||
Self::Completed | Self::Failed | Self::Interrupted => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ScanPhase {
|
||||
@@ -154,8 +167,18 @@ pub struct ScanRun {
|
||||
/// absent on runs recorded before it existed.
|
||||
#[serde(default)]
|
||||
pub error_code: Option<RunErrorCode>,
|
||||
/// When the run started; for a queued run, when it was requested, until
|
||||
/// it starts.
|
||||
#[serde(with = "super::serde_helpers::bson_datetime")]
|
||||
pub started_at: DateTime<Utc>,
|
||||
/// When a run that waited for a slot was requested (t84); `None` for a
|
||||
/// run that started at once, and in runs from before it was recorded.
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "super::serde_helpers::opt_bson_datetime"
|
||||
)]
|
||||
pub queued_at: Option<DateTime<Utc>>,
|
||||
#[serde(default, with = "super::serde_helpers::opt_bson_datetime")]
|
||||
pub completed_at: Option<DateTime<Utc>>,
|
||||
/// Stages the pipeline deliberately did not run (e.g. a deployment
|
||||
@@ -194,6 +217,12 @@ pub struct ScanRun {
|
||||
/// billing when it was attributed).
|
||||
#[serde(default)]
|
||||
pub chargeable: bool,
|
||||
/// For a person's request that took over a scheduled, webhook or
|
||||
/// new-content scan still waiting for a slot (t84): that scan's trigger.
|
||||
/// The run has the person's priority and attribution, but it counts only
|
||||
/// as that scan would have: it would have run anyway, just later.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub charged_as: Option<ScanTrigger>,
|
||||
/// What the run was charged to once it counted; `None` while it runs,
|
||||
/// and for a run that did not count.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -426,6 +455,7 @@ impl ScanRun {
|
||||
error_message: None,
|
||||
error_code: None,
|
||||
started_at: Utc::now(),
|
||||
queued_at: None,
|
||||
completed_at: None,
|
||||
skipped_stages: Vec::new(),
|
||||
notes: Vec::new(),
|
||||
@@ -434,9 +464,20 @@ impl ScanRun {
|
||||
sbom_quality: None,
|
||||
attribution: None,
|
||||
chargeable: false,
|
||||
charged_as: None,
|
||||
charge: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A run requested by `trigger` that waits for a scan slot (t84).
|
||||
pub fn queued(repo_id: String, trigger: ScanTrigger) -> Self {
|
||||
let run = Self::new(repo_id, trigger);
|
||||
Self {
|
||||
status: ScanRunStatus::Queued,
|
||||
queued_at: Some(run.started_at),
|
||||
..run
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ScanRun {
|
||||
|
||||
@@ -108,9 +108,7 @@ pub fn ScanRunList(
|
||||
.peek()
|
||||
.as_ref()
|
||||
.and_then(|r| r.as_ref())
|
||||
.is_some_and(|list| {
|
||||
list.is_empty() || list.iter().any(|r| r.status == ScanRunStatus::Running)
|
||||
});
|
||||
.is_some_and(|list| list.is_empty() || list.iter().any(|r| r.status.is_open()));
|
||||
if waiting {
|
||||
runs.restart();
|
||||
}
|
||||
@@ -161,7 +159,8 @@ fn run_transitions(
|
||||
let mut finished = Vec::new();
|
||||
for run in runs {
|
||||
let id = run.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||
if run.status == ScanRunStatus::Running {
|
||||
// A queued run counts: it may finish before it is ever seen running.
|
||||
if run.status.is_open() {
|
||||
running.push(id);
|
||||
} else if seen_running.contains(&id) && !finished_here.contains(&id) {
|
||||
finished.push(id);
|
||||
@@ -176,13 +175,20 @@ fn scan_run_card(run: &ScanRun, lang: Lang) -> Element {
|
||||
let started = format_time(&run.started_at, lang);
|
||||
let finished = run.completed_at.as_ref().map(|t| format_time(t, lang));
|
||||
let running = run.status == ScanRunStatus::Running;
|
||||
// A queued run's time is when it was asked for: it has not started.
|
||||
let queued = run.status == ScanRunStatus::Queued;
|
||||
let started_label = if queued {
|
||||
scans::REQUESTED
|
||||
} else {
|
||||
scans::STARTED
|
||||
};
|
||||
|
||||
rsx! {
|
||||
div { style: "border-left: 3px solid var(--border); padding: 6px 10px; margin: 6px 0;",
|
||||
div { style: "display: flex; gap: 12px; align-items: center; flex-wrap: wrap;",
|
||||
span { class: "{badge}", {status.get(lang)} }
|
||||
span { style: "font-size: 0.9em;",
|
||||
{scans::STARTED.get(lang)} ": {started}"
|
||||
{started_label.get(lang)} ": {started}"
|
||||
}
|
||||
if let Some(finished) = finished {
|
||||
span { style: "font-size: 0.9em;",
|
||||
@@ -213,6 +219,11 @@ fn scan_run_card(run: &ScanRun, lang: Lang) -> Element {
|
||||
run_id: run.id.map(|id| id.to_hex()).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
if queued {
|
||||
div { style: "font-size: 0.85em; opacity: 0.8; margin-top: 4px;",
|
||||
{scans::QUEUED_HINT.get(lang)}
|
||||
}
|
||||
}
|
||||
if run.status == ScanRunStatus::Interrupted {
|
||||
div { style: "font-size: 0.85em; opacity: 0.8; margin-top: 4px;",
|
||||
{scans::INTERRUPTED_HINT.get(lang)}
|
||||
@@ -450,6 +461,7 @@ fn RunReveal(target_id: String, run_id: String, count: u32) -> Element {
|
||||
/// The badge class and label for a run status.
|
||||
pub fn status_badge(status: &ScanRunStatus) -> (&'static str, Text) {
|
||||
match status {
|
||||
ScanRunStatus::Queued => ("badge badge-neutral", scans::QUEUED),
|
||||
ScanRunStatus::Running => ("badge badge-info", scans::RUNNING),
|
||||
ScanRunStatus::Completed => ("badge badge-success", scans::COMPLETED),
|
||||
ScanRunStatus::Failed => ("badge badge-danger", scans::FAILED),
|
||||
@@ -542,6 +554,24 @@ mod tests {
|
||||
assert!(finished.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_queued_run_reads_as_waiting_for_a_slot_and_is_followed_to_its_end() {
|
||||
let mut run = ScanRun::queued("t".into(), compliance_core::models::ScanTrigger::Manual);
|
||||
let (_, label) = status_badge(&run.status);
|
||||
assert_eq!(label.get(Lang::De), "Wartet auf einen Platz");
|
||||
assert_eq!(label.get(Lang::En), "Waiting for a slot");
|
||||
|
||||
// Seen while it waits, so its end is revealed even if it is never
|
||||
// seen running.
|
||||
let none = HashSet::new();
|
||||
let (seen, _) = run_transitions(std::slice::from_ref(&run), &none, &none);
|
||||
assert_eq!(seen, vec![String::new()]);
|
||||
run.status = ScanRunStatus::Completed;
|
||||
let seen = HashSet::from([String::new()]);
|
||||
let (_, finished) = run_transitions(std::slice::from_ref(&run), &seen, &none);
|
||||
assert_eq!(finished, vec![String::new()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stepper_marks_done_current_and_pending_phases() {
|
||||
let mut run = ScanRun::new("t".into(), compliance_core::models::ScanTrigger::Manual);
|
||||
|
||||
@@ -367,6 +367,19 @@ pub mod scans {
|
||||
de: "Noch nicht geprüft",
|
||||
en: "Not scanned yet",
|
||||
};
|
||||
pub const QUEUED: Text = Text {
|
||||
de: "Wartet auf einen Platz",
|
||||
en: "Waiting for a slot",
|
||||
};
|
||||
pub const QUEUED_HINT: Text = Text {
|
||||
de: "Alle Prüfplätze sind gerade belegt. Die Prüfung startet, sobald einer \
|
||||
frei wird.",
|
||||
en: "All scan slots are busy right now. The scan starts as soon as one is free.",
|
||||
};
|
||||
pub const REQUESTED: Text = Text {
|
||||
de: "Angefordert",
|
||||
en: "Requested",
|
||||
};
|
||||
pub const RUNNING: Text = Text {
|
||||
de: "Läuft",
|
||||
en: "Running",
|
||||
|
||||
@@ -113,11 +113,15 @@ pub async fn set_archive_password(
|
||||
}
|
||||
|
||||
/// Whether any of `targets` (as the list endpoint returns them) has a scan
|
||||
/// running, so a page showing them should keep refreshing.
|
||||
/// running or waiting for a slot, so a page showing them should keep
|
||||
/// refreshing.
|
||||
pub fn any_scan_running(targets: &[serde_json::Value]) -> bool {
|
||||
targets
|
||||
.iter()
|
||||
.any(|t| t["last_scan"]["status"].as_str() == Some("running"))
|
||||
targets.iter().any(|t| {
|
||||
matches!(
|
||||
t["last_scan"]["status"].as_str(),
|
||||
Some("running" | "queued")
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
@@ -713,8 +717,10 @@ mod tests {
|
||||
let idle = serde_json::json!({ "last_scan": { "status": "completed" } });
|
||||
let fresh = serde_json::json!({ "last_scan": null });
|
||||
let busy = serde_json::json!({ "last_scan": { "status": "running" } });
|
||||
let queued = serde_json::json!({ "last_scan": { "status": "queued" } });
|
||||
assert!(!any_scan_running(&[idle.clone(), fresh.clone()]));
|
||||
assert!(any_scan_running(&[idle, fresh, busy]));
|
||||
assert!(any_scan_running(&[idle.clone(), fresh, busy]));
|
||||
assert!(any_scan_running(&[idle, queued]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user