Files
pruefwerk/compliance-agent/src/scan_gate.rs
T
sharang cc5b667870
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 6m28s
fix(scheduler): scheduled scans are spread out and at most two clones run per git host (#547)
2026-10-09 14:37:22 +00:00

286 lines
10 KiB
Rust

//! How many scans run at once, and what happens to a scan requested while the
//! same target is already 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):
//!
//! * **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.
//!
//! 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::time::Duration;
use dashmap::mapref::entry::Entry;
use dashmap::DashMap;
use rand::Rng;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
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 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.
pub fn start_delay(trigger: &ScanTrigger) -> Duration {
match trigger {
ScanTrigger::Scheduled => rand::rng().random_range(Duration::ZERO..=SCHEDULED_SCAN_JITTER),
ScanTrigger::Webhook | ScanTrigger::Manual | ScanTrigger::Support => Duration::ZERO,
}
}
/// 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.
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.
Dropped,
}
/// 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>>,
}
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(),
}
}
/// The key a target's scans are coalesced under.
pub fn key(tenant_id: &str, target_id: &str) -> String {
// NUL cannot appear in either id, so distinct pairs never collide.
format!("{tenant_id}\u{0}{target_id}")
}
/// 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()) {
Entry::Vacant(v) => {
v.insert(None);
Admission::Run
}
Entry::Occupied(mut o) if o.get().is_none() => {
o.insert(Some(trigger));
Admission::Coalesced
}
// 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
}
},
Entry::Vacant(_) => None,
}
}
/// 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);
}
/// Wait for one of the global scan slots. 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
}
}
/// Releases a target when the task holding it ends abnormally (panic, or the
/// future being dropped at shutdown). A normal finish disarms it.
pub struct HeldTarget<'a> {
gate: &'a ScanGate,
key: String,
armed: bool,
}
impl<'a> HeldTarget<'a> {
/// Hold `key` on `gate` until [`Self::disarm`] or drop.
pub fn new(gate: &'a ScanGate, key: String) -> Self {
Self {
gate,
key,
armed: true,
}
}
/// The target was released through [`ScanGate::finish`]; nothing to undo.
pub fn disarm(mut self) {
self.armed = false;
}
}
impl Drop for HeldTarget<'_> {
fn drop(&mut self) {
if self.armed {
self.gate.release(&self.key);
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::{start_delay, Admission, HeldTarget, ScanGate, SCHEDULED_SCAN_JITTER};
use compliance_core::models::ScanTrigger;
use std::time::Duration;
#[test]
fn a_scheduled_scan_waits_within_the_jitter() {
let delays: Vec<Duration> = (0..1000)
.map(|_| start_delay(&ScanTrigger::Scheduled))
.collect();
assert!(delays.iter().all(|d| *d <= SCHEDULED_SCAN_JITTER));
// Spread out, not one fixed delay.
assert!(delays.iter().any(|d| *d != delays[0]));
}
#[test]
fn webhook_manual_and_support_scans_start_at_once() {
for trigger in [
ScanTrigger::Webhook,
ScanTrigger::Manual,
ScanTrigger::Support,
] {
assert_eq!(start_delay(&trigger), Duration::ZERO);
}
}
#[test]
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);
}
// 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);
}
#[test]
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, ScanTrigger::Scheduled), Admission::Run);
assert_eq!(
gate.admit(&key, ScanTrigger::Scheduled),
Admission::Coalesced
);
// 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);
assert_eq!(gate.finish(&key), Some(ScanTrigger::Manual));
}
#[test]
fn targets_and_tenants_are_independent() {
let gate = ScanGate::new(2);
assert_eq!(
gate.admit(&ScanGate::key("acme", "t1"), ScanTrigger::Manual),
Admission::Run
);
assert_eq!(
gate.admit(&ScanGate::key("acme", "t2"), ScanTrigger::Manual),
Admission::Run
);
// Same target id in another tenant is another target.
assert_eq!(
gate.admit(&ScanGate::key("globex", "t1"), ScanTrigger::Manual),
Admission::Run
);
}
#[test]
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);
{
// 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);
}
#[test]
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);
HeldTarget::new(&gate, key.clone()).disarm();
// Still held: disarm does not release, finish does.
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced);
}
#[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();
// A third slot is not available until one is freed.
let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).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;
assert!(third.is_ok(), "a freed slot is reused");
}
}