use tokio::task::JoinSet;
use crate::report::ScannerKind;
use crate::scanner::audit::ProbeAudit;
use crate::scanner::session::ScanContext;
use crate::{counted, error};
pub struct ProbePool<R, F: FnMut(R, &mut ProbeAudit)> {
set: JoinSet<R>,
limit: usize,
fold: F,
audit: ProbeAudit,
ctx: ScanContext,
kind: ScannerKind,
panicked: usize,
}
impl<R, F> ProbePool<R, F>
where
R: Send + 'static,
F: FnMut(R, &mut ProbeAudit),
{
pub fn new(limit: usize, ctx: ScanContext, kind: ScannerKind, fold: F) -> Self {
Self {
set: JoinSet::new(),
limit: limit.max(1),
fold,
audit: ProbeAudit::new(),
ctx,
kind,
panicked: 0,
}
}
pub fn audit(&mut self) -> &mut ProbeAudit {
&mut self.audit
}
pub fn into_audit(self) -> ProbeAudit {
self.audit
}
pub async fn admit(&mut self, task: impl Future<Output = R> + Send + 'static) {
while self.set.len() >= self.limit {
self.reap().await;
}
self.set.spawn(task);
}
pub async fn drain(&mut self) {
while !self.set.is_empty() {
self.reap().await;
}
if self.panicked > 0 {
self.ctx.record_failure(
self.kind,
format!(
"{} panicked and their targets have no verdict; this is a \
defect in the engine rather than a fact about the network",
counted(self.panicked as u128, "probe", "probes")
),
);
}
}
async fn reap(&mut self) {
match self.set.join_next().await {
Some(Ok(output)) => (self.fold)(output, &mut self.audit),
Some(Err(e)) => {
self.panicked += 1;
error!("probe task panicked: {e}");
}
None => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::scanner::session::ScanSession;
#[tokio::test]
async fn a_zero_limit_admits_one_probe_rather_than_spinning() {
let (_session, ctx) = ScanSession::new();
let mut done = 0usize;
let mut pool = ProbePool::new(0, ctx, ScannerKind::Connect, |_: (), _| done += 1);
pool.admit(async {}).await;
pool.admit(async {}).await;
pool.drain().await;
assert_eq!(done, 2, "both probes ran and both were folded");
}
#[tokio::test]
async fn the_pool_never_exceeds_its_limit() {
let (_session, ctx) = ScanSession::new();
let mut pool = ProbePool::new(2, ctx, ScannerKind::Connect, |_: (), _| {});
for _ in 0..8 {
pool.admit(async {}).await;
assert!(pool.set.len() <= 2, "the cap held while admitting");
}
pool.drain().await;
}
}