use std::collections::{BTreeMap, BTreeSet};
use std::time::Duration;
use printobserver_printer_api::BoxFuture;
use printobserver_types::{EventKind, PrintId, Timestamp};
use printobserver_vision_api::ProviderPrint;
use crate::clock::seconds_between;
use crate::error::CoreError;
use crate::listing::JOB_IDENTITY_TOLERANCE_S;
use crate::records::PrintRecord;
use crate::store::HistoryQuery;
use crate::supervisor::Supervisor;
use crate::watch::ScoringVerdict;
pub const EVIDENCE_INTERVALS: u32 = 2;
pub trait ScoringProbe: Send + Sync {
fn read_scoring(&self) -> BoxFuture<'_, ScoringRead>;
fn alert_kind(&self) -> EventKind;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScoringRead {
NotRead(String),
Failed(String),
Read(ScoringReading),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScoringReading {
pub print: Option<ProviderPrint>,
pub evidence: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Scoring {
pub since: Timestamp,
pub verdict: ScoringVerdict,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct ScoringState {
last: Option<(PrintId, u64, Duration)>,
evidence: Option<(PrintId, Duration, Timestamp)>,
flagged: BTreeSet<PrintId>,
unread: Option<String>,
first_starts: BTreeMap<PrintId, Timestamp>,
}
impl ScoringState {
pub(crate) fn scoring(
&self,
print_id: Option<PrintId>,
now: Duration,
window: Duration,
) -> Option<Scoring> {
let (of, moved, since) = self.evidence?;
if print_id.is_some_and(|wanted| wanted != of) || now.saturating_sub(moved) > window {
return None;
}
Some(Scoring {
since,
verdict: if self.flagged.contains(&of) {
ScoringVerdict::Flagged
} else {
ScoringVerdict::NothingFlagged
},
})
}
pub(crate) fn unread(&self) -> Option<&str> {
self.unread.as_deref()
}
}
fn names(print: &PrintRecord, first_start: Option<Timestamp>, named: &ProviderPrint) -> bool {
match print.provider_print_id {
Some(id) => id == named.id,
None => {
named.file_name.is_some()
&& print.file_name == named.file_name
&& match (first_start, named.started_at) {
(Some(ours), Some(theirs)) => {
seconds_between(ours, theirs).abs() <= JOB_IDENTITY_TOLERANCE_S
}
_ => false,
}
}
}
}
impl Supervisor {
pub(crate) fn note_sighted_start(&self, print_id: PrintId, started_at: Timestamp) {
self.watch_state()
.scoring
.first_starts
.entry(print_id)
.and_modify(|held| *held = (*held).min(started_at))
.or_insert(started_at);
}
pub(crate) fn note_flagged(&self, print_id: PrintId) {
self.watch_state().scoring.flagged.insert(print_id);
}
pub(crate) async fn read_scoring(&self, active: &[PrintRecord]) -> Option<String> {
let probe = self.scoring_probe()?;
if active.is_empty() {
let mut held = self.watch_state();
held.scoring.last = None;
held.scoring.evidence = None;
return None;
}
let read = probe.read_scoring().await;
let reading = match read {
ScoringRead::NotRead(why) => {
self.watch_state().scoring.unread = Some(why);
return None;
}
ScoringRead::Failed(detail) => {
self.watch_state().scoring.unread = Some(format!(
"the last read of the detector's record failed: {detail}"
));
return Some(detail);
}
ScoringRead::Read(reading) => reading,
};
for print in active {
if let Some(started_at) = print.job_started_at {
self.note_sighted_start(print.id, started_at);
}
}
let first_starts = {
let mut held = self.watch_state();
held.scoring
.first_starts
.retain(|print_id, _| active.iter().any(|print| print.id == *print_id));
held.scoring.first_starts.clone()
};
let named = reading.print.as_ref().and_then(|named| {
active
.iter()
.find(|print| names(print, first_starts.get(&print.id).copied(), named))
.map(|print| print.id)
});
let flagged = match named {
Some(print_id) => match self.flagged_in_history(print_id, probe.alert_kind()).await {
Ok(flagged) => flagged,
Err(error) => {
let detail = format!(
"the print's history could not be read to say whether the detector \
flagged it: {error}"
);
self.watch_state().scoring.unread = Some(detail.clone());
return Some(detail);
}
},
None => false,
};
let now = self.clock().elapsed();
let wall = self.clock().now();
let window = self
.config()
.observation_interval
.saturating_mul(EVIDENCE_INTERVALS);
let mut held = self.watch_state();
let state = &mut held.scoring;
state.unread = None;
let Some(print_id) = named else {
state.last = None;
state.evidence = None;
return None;
};
if flagged {
state.flagged.insert(print_id);
}
let moved = state.last.is_some_and(|(last, evidence, read_at)| {
last == print_id
&& evidence != reading.evidence
&& now.saturating_sub(read_at) <= window
});
state.last = Some((print_id, reading.evidence, now));
if moved {
let since = match state.evidence {
Some((of, last_moved, since))
if of == print_id && now.saturating_sub(last_moved) <= window =>
{
since
}
_ => wall,
};
state.evidence = Some((print_id, now, since));
} else if state.evidence.is_some_and(|(of, _, _)| of != print_id) {
state.evidence = None;
}
None
}
async fn flagged_in_history(
&self,
print_id: PrintId,
kind: EventKind,
) -> Result<bool, CoreError> {
Ok(!self
.stores()
.events
.history(HistoryQuery {
print_id,
kinds: vec![kind],
since: None,
until: None,
limit: Some(1),
})
.await?
.is_empty())
}
}