use std::collections::BTreeMap;
use printobserver_types::{EventId, PrintId, Timestamp};
use printobserver_vision_api::Detection;
use crate::clock::plus_seconds;
use crate::kinds::PortFailureSite;
use crate::records::{Actor, PrintAction};
use crate::supervisor::Supervisor;
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct DetectorPause {
pub event_id: EventId,
pub detection: Detection,
pub adjusted: Option<Adjusted>,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Adjusted {
pub first: String,
pub later: Vec<String>,
pub resume_due: Timestamp,
}
impl Adjusted {
fn reasons(&self) -> Vec<&str> {
core::iter::once(self.first.as_str())
.chain(self.later.iter().map(String::as_str))
.collect()
}
}
pub(crate) type DetectorPauses = BTreeMap<PrintId, DetectorPause>;
impl Supervisor {
pub(crate) fn note_detector_pause(
&self,
print_id: PrintId,
event_id: EventId,
detection: Detection,
) {
self.detector_pauses()
.entry(print_id)
.and_modify(|held| {
held.event_id = event_id;
held.detection = detection;
})
.or_insert(DetectorPause {
event_id,
detection,
adjusted: None,
});
}
pub(crate) fn note_adjustment_while_paused(&self, print_id: PrintId, reason: &str) {
let now = self.clock().now();
let grace =
i64::try_from(self.config().detector_resume_grace.as_secs()).unwrap_or(i64::MAX);
let due = plus_seconds(now, grace).unwrap_or(now);
if let Some(pause) = self.detector_pauses().get_mut(&print_id) {
match &mut pause.adjusted {
Some(adjusted) => {
adjusted.later.push(reason.to_owned());
adjusted.resume_due = due;
}
None => {
pause.adjusted = Some(Adjusted {
first: reason.to_owned(),
later: Vec::new(),
resume_due: due,
});
}
}
}
}
pub(crate) fn forget_detector_pause(&self, print_id: PrintId) {
self.detector_pauses().remove(&print_id);
}
pub(crate) fn detector_paused(&self, print_id: PrintId) -> bool {
self.detector_pauses().contains_key(&print_id)
}
pub async fn resume_due_detector_pauses(&self) {
let now = self.clock().now();
let due: Vec<(PrintId, DetectorPause)> = {
let mut pauses = self.detector_pauses();
let ids: Vec<PrintId> = pauses
.iter()
.filter(|(_, pause)| {
pause
.adjusted
.as_ref()
.is_some_and(|adjusted| adjusted.resume_due <= now)
})
.map(|(id, _)| *id)
.collect();
ids.into_iter()
.filter_map(|id| pauses.remove(&id).map(|pause| (id, pause)))
.collect()
};
for (print_id, pause) in due {
self.resume_detector_pause(print_id, pause).await;
}
}
pub(crate) async fn resume_adjusted_detector_pause(&self, print_id: PrintId) {
let taken = {
let mut pauses = self.detector_pauses();
match pauses.get(&print_id) {
Some(pause) if pause.adjusted.is_some() => pauses.remove(&print_id),
_ => None,
}
};
if let Some(pause) = taken {
self.resume_detector_pause(print_id, pause).await;
}
}
async fn resume_detector_pause(&self, print_id: PrintId, pause: DetectorPause) {
let reason = format!(
"the detector paused this print and the supervising agent adjusted it while \
paused ({}); resuming so the adjustment takes effect",
pause
.adjusted
.as_ref()
.map(|adjusted| adjusted.reasons().join("; "))
.unwrap_or_default()
);
let resumed = self
.request_action(
print_id,
PrintAction::Resume {
reason,
actor: Actor::System,
},
)
.await;
if !resumed.is_ok_and(|outcome| matches!(outcome.executed, Some(Ok(())))) {
return;
}
if let Err(error) = self.vision().clear_detection(pause.detection).await {
self.record_port_failure(
print_id,
pause.event_id,
PortFailureSite::DetectorAcknowledgement,
error.to_string(),
)
.await;
}
}
}