printobserver-core 0.15.5

Supervision logic for printobserver.
Documentation
//! A periodic observation of every active print, which no detector asked for.
//!
//! A failure detector alerts on what it was trained to see, and a print can go
//! wrong in ways that stay below every one of its thresholds: firmware pausing
//! a print and cutting its heater while the host goes on reporting it printing,
//! a fan cut at a bridge, a wall going thin. Nothing in the machine's state or
//! the camera's frame is hidden from an agent that looks — so every interval
//! ([`CoreConfig::observation_interval`](crate::CoreConfig::observation_interval))
//! each active print is written a [`PeriodicObservationPayload`] event carrying
//! the printer's telemetry, with the camera's frame as its image, and the turn
//! that event claims is that print's agent looking at it.
//!
//! # Which prints are observed
//!
//! The printer's job is read and settled exactly as the listing's is
//! ([`crate::listing`]): a job found over closes its prints, and a running job
//! no open print records is adopted. When that read succeeds the print the job
//! is — when it is one — is the one active print; a printer whose job cannot be
//! read leaves every open print a candidate, because nothing then says which
//! of them stopped. A printer reporting one of
//! [`TERMINAL_STATES`](crate::TERMINAL_STATES) is not printing anything, and an
//! ended print has nothing left to act on, so neither is observed.
//!
//! # No pile-up
//!
//! An observation claims a print's turn only when nothing holds it
//! ([`Inboxes::claim_if_idle`](crate::Inboxes::claim_if_idle)). A print whose
//! turn is running — on an alert, or on the last observation — is being
//! watched already, and is given no observation to queue behind it; so at most
//! one observation per print is ever outstanding, and every turn the agent is
//! given still runs under the same one-agent-per-print rule and the same action
//! policy, `safety.agent_min_interval_s` included.
//!
//! # An idle compaction of the session ends first
//!
//! A supervisor port may compact a print's session while no turn of it runs
//! ([`SupervisorPort::idle_work_ended`](printobserver_supervisor_api::SupervisorPort::idle_work_ended)),
//! and every other event's turn cancels that compaction at once. A scheduled
//! check alone waits for it to end, bounded by the compaction's own timeout,
//! because it is the turn that continues that session on the port's own
//! cadence: cancelling it would leave the session as large as it was and the
//! next gap no longer.
//!
//! # The detector's record is read first
//!
//! Each round begins by reading the failure detector's own record of the
//! active print, when the composition root installed something to read it
//! with ([`crate::scoring`]), so that every turn the round claims reads the
//! detector's status as it stands now. A read that failed is recorded against
//! each observation the round writes, as a port failure.
//!
//! # The reads, and the frame, precede the append
//!
//! Everywhere else the event append is the first thing the loop does
//! ([`crate::events`]), because an alert arrives from outside and must be in
//! the history before anything can fail on its behalf. An observation is
//! raised here, and what it records *is* the reads, so they are taken first and
//! the event carries them. The camera is asked for its frame before the event
//! is written too, and the event is written together with that frame as its
//! image in one store write, so anybody following the log — the `events` read,
//! `printobserver watch` — reads the check with its frame the first time it
//! reads it, rather than an event with no image that nothing sends again. A
//! read that failed, a camera that would not answer however often it was
//! asked ([`crate::look`]), and a store that would not keep the frame are each
//! recorded against the event once it is written, as a port failure, as the
//! loop records one. A camera that gives only bad frames is recorded as a
//! `camera_degraded` after the observation, and that is the event the turn is
//! given, so the agent is told there is no frame rather than handed one.

use printobserver_printer_api::{JobSnapshot, PrinterError, PrinterSnapshot};
use printobserver_types::{EventBody, PrintId};

use crate::error::CoreError;
use crate::events::{PendingTurn, TERMINAL_STATES};
use crate::inbox::Arrival;
use crate::kinds::{PeriodicObservationPayload, PortFailureSite};
use crate::look::Frame;
use crate::records::PrintRecord;
use crate::supervisor::Supervisor;

/// What one round of observations claimed, and what it could not write down.
#[derive(Debug, Default)]
pub struct Observed {
    /// The turns the observations claimed, each to be run by
    /// [`Supervisor::run_supervision`]: a turn claimed and never run leaves its
    /// print claimed.
    pub turns: Vec<PendingTurn>,
    /// Each print whose observation the store would not write down, with the
    /// store's own error. Such a print claimed no turn, and the next round
    /// observes it again.
    pub refused: Vec<(PrintId, CoreError)>,
}

impl Supervisor {
    /// Observe every active print nobody is watching, and answer the turns
    /// those observations claimed.
    ///
    /// One print's observation that could not be written down is answered in
    /// [`Observed::refused`] and stops no other: every turn the round claimed
    /// is answered, because a claimed turn nobody runs is a print no later
    /// event could reach.
    ///
    /// # Errors
    ///
    /// Returns the store's own error when the open prints could not be read or
    /// settled, before any print was claimed.
    pub async fn observe_active_prints(&self) -> Result<Observed, CoreError> {
        let mut observed = Observed::default();
        let prints = self.prints_to_observe().await?;
        let scoring_failed = self.read_scoring(&prints).await;
        for print in prints {
            let print_id = print.id;
            match self.observe(print, scoring_failed.as_deref()).await {
                Ok(Some(turn)) => observed.turns.push(turn),
                Ok(None) => {}
                Err(error) => observed.refused.push((print_id, error)),
            }
        }
        Ok(observed)
    }

    /// The open prints an observation is owed to, once the printer's job has
    /// settled them.
    async fn prints_to_observe(&self) -> Result<Vec<PrintRecord>, CoreError> {
        let resolving = self.resolving().await;
        let active = match self.observe_job().await {
            Some(observed) => Some(self.settle_and_adopt(&observed).await?),
            None => None,
        };
        drop(resolving);
        let open = self.stores().prints.open_prints().await?;
        Ok(match active {
            Some(running) => open
                .into_iter()
                .filter(|print| Some(print.id) == running)
                .collect(),
            None => open,
        })
    }

    /// Observe one print, when it is printing and nobody is watching it.
    async fn observe(
        &self,
        print: PrintRecord,
        scoring_failed: Option<&str>,
    ) -> Result<Option<PendingTurn>, CoreError> {
        // A scheduled check continues the session it is about, so it lets an
        // idle compaction of that session end rather than cancel it, and reads
        // the printer once it has.
        // A wait that could not be taken leaves the check to run at once.
        let _ = self.agent().idle_work_ended(print.id).await;
        let printer = self.read_snapshot().await;
        if printer
            .as_ref()
            .is_ok_and(|snapshot| TERMINAL_STATES.contains(&snapshot.connection))
        {
            return Ok(None);
        }
        let job = self.read_job().await;
        if !self.inboxes().claim_if_idle(print.id) {
            return Ok(None);
        }
        match self
            .write_observation_down(&print, printer, job, scoring_failed)
            .await
        {
            Ok(arrival) => Ok(Some(PendingTurn::new(print, arrival, Vec::new()))),
            Err(error) => {
                // Anything handed to the print while it was claimed is owed a
                // turn of its own, and is answered as one rather than dropped.
                let Some(mut left) = self.inboxes().next_or_release(print.id) else {
                    return Err(error);
                };
                let latest = left.pop().ok_or(error)?;
                Ok(Some(PendingTurn::new(print, latest, left)))
            }
        }
    }

    /// Take the camera's frame, write one observation down with it as its
    /// image, and record a read that failed against it.
    async fn write_observation_down(
        &self,
        print: &PrintRecord,
        printer: Result<PrinterSnapshot, PrinterError>,
        job: Result<JobSnapshot, PrinterError>,
        scoring_failed: Option<&str>,
    ) -> Result<Arrival, CoreError> {
        let fetched = self.fetch_configured_frame(Some(print.id)).await;
        let payload = PeriodicObservationPayload {
            interval_s: self.config().observation_interval.as_secs(),
            printer: printer.as_ref().ok().cloned(),
            job: job.as_ref().ok().cloned(),
            frame_captured_at: self.frame_captured_at(fetched.as_ref()),
        };
        // The observation keeps the telemetry it read whatever the camera
        // gave; a camera giving only bad frames is the turn's event instead.
        let (fetched, degraded) = match fetched {
            Some((_, Frame::Degraded(degraded))) => (None, Some(degraded)),
            fetched => (fetched, None),
        };
        let event = self
            .write_with_frame(Some(print.id), &payload, fetched)
            .await?;
        if let Err(error) = printer {
            self.record_port_failure(
                print.id,
                event.id,
                PortFailureSite::PrinterSnapshot,
                error.to_string(),
            )
            .await;
        }
        if let Err(error) = job {
            self.record_port_failure(
                print.id,
                event.id,
                PortFailureSite::PrinterJob,
                error.to_string(),
            )
            .await;
        }
        if let Some(detail) = scoring_failed {
            self.record_port_failure(
                print.id,
                event.id,
                PortFailureSite::DetectorScoringRead,
                detail.to_owned(),
            )
            .await;
        }
        if let Some(degraded) = degraded {
            let degraded = self
                .append_system_event(print.id, EventBody::of(&degraded)?)
                .await?;
            return Ok(Arrival {
                event: degraded,
                detection: None,
                frame_captured_at: None,
                camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
            });
        }
        Ok(Arrival {
            event,
            detection: None,
            frame_captured_at: None,
            camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
        })
    }
}