use crate::journal::Journal;
use crate::report::{ScanPhase, ScannerKind};
use crate::scanner::session::ScanProgress;
pub const CHECKPOINT_EVERY: std::time::Duration = std::time::Duration::from_secs(3);
#[derive(Debug)]
pub struct Checkpointing {
done: tokio::sync::oneshot::Sender<Vec<ScanPhase>>,
task: tokio::task::JoinHandle<()>,
}
impl Checkpointing {
pub async fn finish(self, phases: &[ScanPhase]) {
let _ = self.done.send(phases.to_vec());
let _ = self.task.await;
}
}
pub fn spawn_checkpoints(mut journal: Journal, ctx: ScanProgress) -> Checkpointing {
let (done, mut stop) = tokio::sync::oneshot::channel::<Vec<ScanPhase>>();
let task = tokio::spawn(async move {
loop {
tokio::select! {
_ = tokio::time::sleep(CHECKPOINT_EVERY) => {
let changed = ctx.take_changed_hosts();
let outcome = if journal.should_compact(ctx.host_count()) {
journal.compact(&ctx.hosts_snapshot())
} else {
journal.record_hosts(&changed)
}
.and_then(|()| journal.checkpoint(ctx.settlements()));
if let Err(e) = outcome {
ctx.record_failure(
ScannerKind::Journal,
format!("journal checkpoint failed, so a resume would replay further back than it should: {e}"),
);
}
let _ = journal.record_detections(&ctx.take_tapes());
}
finished = &mut stop => {
let _ = journal.record_phases(&finished.unwrap_or_default());
break;
}
}
}
let _ = journal.record(&ctx.take_changed_hosts(), ctx.settlements());
let _ = journal.record_detections(&ctx.take_tapes());
let _ = journal.close();
});
Checkpointing { done, task }
}