printobserver-core 0.18.0

Supervision logic for printobserver.
Documentation
//! The camera checks a start may name, read back from the printer timeline.
//!
//! A check is the server's record, written as a `camera_checked` event that
//! belongs to no print ([`CAMERA_CHECKED_KIND`]); it is read from the log
//! rather than held, so a server started again finds every check the one
//! before recorded. A start naming one is held to it here, and every check of
//! the print it starts is handed it ([`crate::CheckImageRequest`]).

use printobserver_types::{EventKind, EventRecord};

use crate::error::CoreError;
use crate::records::{
    CAMERA_CHECKED_KIND, CameraCheckId, CameraCheckObjection, CameraCheckStanding,
    CameraCheckVerdict, RejectionReason, SheetId,
};
use crate::store::{MAX_HISTORY_LIMIT, TimelineQuery};
use crate::supervisor::Supervisor;

impl Supervisor {
    /// The record of one camera check, when one is recorded: its event,
    /// newest first among the checks, whose record carries that identifier.
    ///
    /// # Errors
    ///
    /// Returns the store's own error when the log could not be read.
    pub async fn camera_check_record(
        &self,
        camera_check: CameraCheckId,
    ) -> Result<Option<EventRecord>, CoreError> {
        let kind =
            EventKind::new(CAMERA_CHECKED_KIND).map_err(|error| CoreError::Unrepresentable {
                detail: error.to_string(),
            })?;
        let mut before = None;
        loop {
            let page = self
                .stores()
                .timeline
                .timeline(TimelineQuery {
                    kinds: vec![kind.clone()],
                    since: None,
                    until: None,
                    spool_id: None,
                    before,
                    limit: Some(MAX_HISTORY_LIMIT),
                })
                .await?;
            let Some(last) = page.last() else {
                return Ok(None);
            };
            before = Some(last.id);
            if let Some(found) = page
                .into_iter()
                .find(|event| standing_of(event).is_some_and(|read| read.id == camera_check))
            {
                return Ok(Some(found));
            }
        }
    }

    /// The refusal a start naming `camera_check` on `declared` is held to:
    /// none for a check recorded `aligned` on that sheet.
    ///
    /// # Errors
    ///
    /// Returns the store's own error when the log could not be read.
    pub(crate) async fn camera_check_refusal(
        &self,
        camera_check: CameraCheckId,
        declared: &SheetId,
    ) -> Result<Option<RejectionReason>, CoreError> {
        let standing = self
            .camera_check_record(camera_check)
            .await?
            .as_ref()
            .and_then(standing_of);
        let objection = match standing {
            None => Some(CameraCheckObjection::Unknown),
            Some(read) if read.verdict != CameraCheckVerdict::Aligned => {
                Some(CameraCheckObjection::NotAligned {
                    verdict: read.verdict,
                })
            }
            Some(read) if read.sheet != *declared => Some(CameraCheckObjection::OtherSheet {
                checked_on: read.sheet,
                declared: declared.clone(),
            }),
            Some(_) => None,
        };
        Ok(
            objection.map(|objection| RejectionReason::CameraCheckRefused {
                camera_check,
                objection,
            }),
        )
    }
}

/// The fields of a camera check a start is held to, from its event; nothing
/// for an event of another kind, or a record that does not carry them.
#[must_use]
pub fn standing_of(event: &EventRecord) -> Option<CameraCheckStanding> {
    if event.kind().as_str() != CAMERA_CHECKED_KIND {
        return None;
    }
    printobserver_types::serde_json::from_value(event.body.payload.get("camera_check")?.clone())
        .ok()
}