//! 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. 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. //! * **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::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::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. 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 | ScanTrigger::NewContent => Duration::ZERO, } } /// 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, /// 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, } impl Job { /// A scan started by `trigger`, recorded as the run `run_id`. pub fn new(trigger: ScanTrigger, run_id: Option) -> 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 queued or running for this target: the caller now holds /// it and runs its scans through [`ScanGate::start`]. Run, /// 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 }, /// 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, /// Present while a scan of the key waits or runs. targets: DashMap, } /// 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, } impl ScanGate { /// A gate allowing `concurrency` scans at once (at least one). pub fn new(concurrency: usize) -> Self { Self { slots: Arc::new(Slots { queue: Mutex::new(Queue { free: concurrency.max(1), person: VecDeque::new(), background: VecDeque::new(), person_grants: 0, }), }), targets: 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, 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(Held { current: job, running: false, pending: None, }); Admission::Run } 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, } } } } /// 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(_) => 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.targets.remove(key); } /// 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 queue is gone, which this gate never does. pub async fn slot(&self, priority: Priority) -> Result { self.slots.enqueue(None, priority).wait().await } } /// The slots and the two queues waiting for them. #[derive(Debug)] struct Slots { queue: Mutex, } #[derive(Debug)] struct Queue { /// Slots nobody holds. Only above zero while nobody waits. free: usize, person: VecDeque, background: VecDeque, /// 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, grant: oneshot::Sender, } /// A request in a queue, or a slot already granted. enum Waiting { Granted(Permit), Queued(oneshot::Receiver), } impl Waiting { async fn wait(self) -> Result { 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, 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) { 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 { 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>, } impl Permit { fn new(slots: &Arc) -> Self { Self { slots: Some(Arc::clone(slots)), } } } impl Drop for Permit { fn drop(&mut self) { if let Some(slots) = self.slots.take() { slots.release(); } } } /// 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, 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>>; 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 = (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_support_and_new_content_scans_start_at_once() { for trigger in [ ScanTrigger::Webhook, ScanTrigger::Manual, ScanTrigger::Support, ScanTrigger::NewContent, ] { assert_eq!(start_delay(&trigger), Duration::ZERO); } } #[test] 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, 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)); 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_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, 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, 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!(gate.finish(&key)); } #[test] fn targets_and_tenants_are_independent() { let gate = ScanGate::new(2); assert_eq!( gate.admit(&ScanGate::key("acme", "t1"), job(ScanTrigger::Manual, "a")), Admission::Run ); assert_eq!( 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"), job(ScanTrigger::Manual, "c") ), 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, 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, job(ScanTrigger::Manual, "r2")), Admission::Run ); } #[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, 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, 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, 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, targets: &[&str], trigger: ScanTrigger, log: &Log, ) -> Vec> { 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 { 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 = (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(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(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(Duration::from_millis(50), gate.slot(Priority::Person)).await; assert!(third.is_ok(), "a freed slot is reused"); } }