printobserver-core 0.19.0

Supervision logic for printobserver.
Documentation
//! A print carrying on from a pause, and the pause its agent made.
//!
//! A planned change has its own record of the print carrying on
//! ([`crate::planned`]); a pause does not, because the printer is resumed by
//! whoever paused it or by a person at the machine, and often not through this
//! program at all. So the printer watch follows the job's state from one read
//! to the next for the print it is running.
//!
//! # Carried on
//!
//! A read finding the job printing when the watch's last read of it found it
//! paused — at no planned change — is the print carrying on. It is owed a look
//! at once: the camera's frame, written as a
//! [`PeriodicObservationPayload`](crate::kinds::PeriodicObservationPayload),
//! and the agent's turn on it, ahead of the scheduled check however soon that
//! was due. The print's next scheduled check is then one observation interval
//! after that look, as after a planned change's. A look the print could not be
//! given — another turn holds it — is owed still, and the next read gives it;
//! any check written for the print meanwhile is that look, and a scheduled
//! check that reads the job printing before the watch does has seen it carry
//! on, so the watch owes no second look.
//!
//! # While the agent's own pause holds
//!
//! A print the agent paused is given no scheduled check until it carries on:
//! the agent has stopped it for a person, and looking again at a stopped print
//! on a timer asks it to judge nothing new. Everything else still reaches it —
//! an alert, the printer acting on its own, and the look as the print carries
//! on, which is how a person's resume reaches it. A pause anybody else made
//! keeps its checks, as before.
//!
//! # Nothing here commands the machine
//!
//! This changes only when the print is looked at and when its agent is given
//! a turn. The look is a scheduled check's in everything but its time, judged
//! on the same evidence, and it sends the printer nothing.

use std::sync::PoisonError;

use printobserver_printer_api::{JobSnapshot, PrinterState};
use printobserver_types::PrintId;

use crate::error::CoreError;
use crate::events::PendingTurn;
use crate::records::PrintRecord;
use crate::supervisor::Supervisor;

/// What the printer watch holds of one print's pauses.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct PauseMemo {
    /// Whether the watch's last read of the job found it paused at no planned
    /// change.
    paused: bool,
    /// Whether the print's agent made the pause holding it.
    by_agent: bool,
    /// Whether the print is owed a look since it was found carrying on.
    look_owed: bool,
}

impl Supervisor {
    /// The memos, held for one read or write.
    fn pause_memos(
        &self,
    ) -> std::sync::MutexGuard<'_, std::collections::BTreeMap<PrintId, PauseMemo>> {
        self.pauses.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Note a pause the print's agent made, which went through.
    pub(crate) fn note_agent_pause(&self, print_id: PrintId) {
        self.pause_memos().entry(print_id).or_default().by_agent = true;
    }

    /// Note a resume or a cancel somebody asked for, which went through: the
    /// agent's pause no longer holds the print.
    pub(crate) fn note_pause_lifted(&self, print_id: PrintId) {
        if let Some(memo) = self.pause_memos().get_mut(&print_id) {
            memo.by_agent = false;
        }
    }

    /// Whether the agent's own pause holds a print, as a read of its job
    /// finds it.
    pub(crate) fn agent_pause_holds(&self, print_id: PrintId, job: &JobSnapshot) -> bool {
        job.state == PrinterState::Paused
            && self
                .pause_memos()
                .get(&print_id)
                .is_some_and(|memo| memo.by_agent)
    }

    /// Note that a check was written for a print, which is any look it was
    /// owed; one that read the job printing has seen it carry on from any
    /// pause the watch had last found it in, so the watch owes no look for it.
    pub(crate) fn note_looked(&self, print_id: PrintId, printing: bool) {
        if let Some(memo) = self.pause_memos().get_mut(&print_id) {
            memo.look_owed = false;
            if printing {
                memo.paused = false;
                memo.by_agent = false;
            }
        }
    }

    /// Forget a print's pauses, once it has closed.
    pub(crate) fn forget_pauses(&self, print_id: PrintId) {
        self.pause_memos().remove(&print_id);
    }

    /// Follow one read of the running print's job: note a pause, find it
    /// carried on from one, and give it the look that is then owed.
    ///
    /// # Errors
    ///
    /// The store's own error when the look could not be written down.
    pub(crate) async fn follow_pauses(
        &self,
        print: &PrintRecord,
        job: &JobSnapshot,
    ) -> Result<Option<PendingTurn>, CoreError> {
        let at_change = self.paused_at_a_change_ahead(print, job).await?;
        let owed = {
            let mut memos = self.pause_memos();
            let memo = memos.entry(print.id).or_default();
            match job.state {
                PrinterState::Paused if !at_change => memo.paused = true,
                PrinterState::Printing if memo.paused => {
                    memo.paused = false;
                    memo.by_agent = false;
                    memo.look_owed = true;
                }
                _ => {}
            }
            memo.look_owed
        };
        if !owed {
            return Ok(None);
        }
        let scoring_failed = self.read_scoring(std::slice::from_ref(print)).await;
        let turn = self
            .observe(print.clone(), scoring_failed.as_deref(), true)
            .await?;
        if turn.is_some() {
            self.checked_after_resume
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .insert(print.id, self.clock().elapsed());
        }
        Ok(turn)
    }
}