printobserver-core 0.8.0

Supervision logic for printobserver.
Documentation
//! The one decision, as a total function over what it is given.
//!
//! Nothing here reaches a port. The decision is a pure function of the request,
//! the print, the state the printer is in, the bounds in force and when the
//! agent last acted, so that the rule can be read in one place and the
//! chokepoint that issues actions has only to record what this answered.
//!
//! **A request outside the bounds is rejected, not clamped.** Silently clamping
//! would leave an agent believing it had done something it had not, and would
//! leave the operator's own record saying it asked for a value it never asked
//! for.

use crate::records::{
    ActionKind, Actor, ActorClass, EffectiveBounds, PolicyDecision, PrintAction, PrintRecord,
    RejectionReason, SafetyEnvelope,
};
use core::time::Duration;
use printobserver_printer_api::{Adjustable, PrinterState};

use printobserver_types::Timestamp;

/// Everything one decision is taken from.
#[derive(Debug, Clone, Copy)]
pub struct DecisionInput<'a> {
    /// What is being asked for.
    pub action: &'a PrintAction,
    /// Who is asking.
    pub actor: &'a Actor,
    /// When they asked.
    pub requested_at: Timestamp,
    /// The print it is being asked against, when there is one.
    pub print: Option<&'a PrintRecord>,
    /// The state to judge this request from, when there is one to judge it from.
    ///
    /// Absent means the state check does not apply: either no snapshot could be
    /// taken, or the request is a **restoration**, which is the closing half of
    /// a change this policy already accepted rather than a fresh request for a
    /// machine change — the state that justified the original check is by
    /// definition the state that has just ended. The bounds check applies to a
    /// restoration exactly as it does to the request that opened it.
    pub printer_state: Option<&'a PrinterState>,
    /// The bounds in force for this print.
    pub bounds: &'a EffectiveBounds,
    /// The operator's safety envelope.
    pub envelope: &'a SafetyEnvelope,
    /// How long ago the agent last changed the machine on this print, if it
    /// has, measured on [`Clock::elapsed`](crate::Clock::elapsed) — time
    /// passing rather than the wall clock moving, so that a host's time
    /// synchronisation stepping the wall clock neither lets the agent act again
    /// early nor holds it back longer than the interval.
    pub since_last_agent_action: Option<Duration>,
}

/// What an adjustment asks to change, and the value it asks for.
///
/// Absent for an action that changes no adjustable, which is what makes the
/// bounds arms of the decision reachable from the action alone.
#[must_use]
pub fn adjustment(action: &PrintAction) -> Option<(Adjustable, f64)> {
    match action {
        PrintAction::SetFeedrateFactor { factor, .. } => Some((Adjustable::Feedrate, *factor)),
        PrintAction::SetFlowrateFactor { factor, .. } => Some((Adjustable::Flowrate, *factor)),
        PrintAction::SetToolTargetC { tool, target_c, .. } => {
            Some((Adjustable::ToolTarget { tool: *tool }, *target_c))
        }
        PrintAction::SetBedTargetC { target_c, .. } => Some((Adjustable::BedTarget, *target_c)),
        PrintAction::SetFanPercent { percent, .. } => Some((Adjustable::Fan, *percent)),
        PrintAction::Pause { .. }
        | PrintAction::Resume { .. }
        | PrintAction::Cancel { .. }
        | PrintAction::StartPrint { .. }
        | PrintAction::AcknowledgeFailure { .. }
        | PrintAction::ClosePrint { .. } => None,
    }
}

/// Whether one action is valid from the state the printer is in.
///
/// Acknowledging a failure, closing a print record and every spool command
/// are valid from every state, because none of them changes anything at the
/// machine; everything else names the states it makes sense from. Whether a
/// close may go ahead turns on the job of the record's own file rather than on
/// the printer's state, so it is read where the close is checked
/// ([`crate::closing`]).
#[must_use]
pub fn valid_from(kind: ActionKind, state: &PrinterState) -> bool {
    match kind {
        ActionKind::Pause => matches!(state, PrinterState::Printing),
        ActionKind::Resume => matches!(state, PrinterState::Paused),
        ActionKind::Cancel => matches!(state, PrinterState::Printing | PrinterState::Paused),
        ActionKind::StartPrint => matches!(state, PrinterState::Operational),
        ActionKind::SetFeedrateFactor
        | ActionKind::SetFlowrateFactor
        | ActionKind::SetToolTargetC
        | ActionKind::SetBedTargetC
        | ActionKind::SetFanPercent => {
            matches!(state, PrinterState::Printing | PrinterState::Paused)
        }
        ActionKind::AcknowledgeFailure
        | ActionKind::ClosePrint
        | ActionKind::RegisterSpool
        | ActionKind::LoadSpool
        | ActionKind::UnloadSpool
        | ActionKind::AdjustSpool
        | ActionKind::RetireSpool => true,
    }
}

/// Whether one action changes something at the machine.
///
/// Acknowledging a failure does not: it writes a decision into the print's
/// record and asks nothing of the printer, whatever its disposition. Nor does
/// any spool command, which writes the spool ledger and nothing else, nor
/// closing a print record, which writes that record and nothing else. The agent's minimum interval spaces out changes to the
/// machine, so that each one's effect can show before the next is asked for;
/// an acknowledgement neither waits on it nor restarts it. An adjustment asked
/// for while the print is paused does not wait on it either: nothing it does
/// can show until the print moves again.
#[must_use]
pub const fn changes_the_machine(kind: ActionKind) -> bool {
    !matches!(
        kind,
        ActionKind::AcknowledgeFailure
            | ActionKind::ClosePrint
            | ActionKind::RegisterSpool
            | ActionKind::LoadSpool
            | ActionKind::UnloadSpool
            | ActionKind::AdjustSpool
            | ActionKind::RetireSpool
    )
}

/// Whether a print is one an action may still be taken against.
fn is_active(print: Option<&PrintRecord>) -> bool {
    print.is_some_and(|record| record.ended_at.is_none())
}

/// The decision policy takes on one request.
///
/// Every action from every actor passes through this, and the arms are ordered
/// so that each rejection is reachable: there is no point asking whether a
/// value is in bounds for an actor that may not ask for the action at all.
#[must_use]
pub fn decide(input: &DecisionInput<'_>) -> PolicyDecision {
    let kind = input.action.kind();
    let actor_class = input.actor.class();

    // A close is asked of a record rather than of a running print, so a
    // record that has ended is refused as one, and one never recorded is
    // refused as every other action against no print is.
    if kind == ActionKind::ClosePrint && input.print.is_some() && !is_active(input.print) {
        return PolicyDecision::Rejected(RejectionReason::PrintAlreadyEnded);
    }
    if !is_active(input.print) {
        return PolicyDecision::Rejected(RejectionReason::NoActivePrint);
    }

    let granted = input.envelope.actions.get(&actor_class);
    if !granted.is_some_and(|kinds| kinds.contains(&kind)) {
        return PolicyDecision::Rejected(RejectionReason::ActorMayNotRequest {
            actor_class,
            action: kind,
        });
    }

    // Nothing an adjustment does can show while the print is paused, so the
    // interval that waits for it to show does not hold adjustments to a paused
    // print back. Resuming, pausing and cancelling still wait on it: those are
    // the flapping it exists to stop.
    let adjusting_a_paused_print = adjustment(input.action).is_some()
        && matches!(input.printer_state, Some(PrinterState::Paused));
    if actor_class == ActorClass::Agent
        && changes_the_machine(kind)
        && !adjusting_a_paused_print
        && let Some(since_last) = input.since_last_agent_action
    {
        let since_last_s = i64::try_from(since_last.as_secs()).unwrap_or(i64::MAX);
        if since_last_s < input.envelope.agent_min_interval_s {
            return PolicyDecision::Rejected(RejectionReason::MinIntervalNotElapsed {
                interval_s: input.envelope.agent_min_interval_s,
                since_last_s,
            });
        }
    }

    if let Some(state) = input.printer_state
        && !valid_from(kind, state)
    {
        return PolicyDecision::Rejected(RejectionReason::InvalidFromState {
            state: state.clone(),
        });
    }

    if let Some((adjustable, requested)) = adjustment(input.action) {
        let Some(allowed) = input.bounds.allowed.get(&adjustable) else {
            return PolicyDecision::Rejected(RejectionReason::UnsupportedAdjustable { adjustable });
        };
        if !allowed.contains(requested) {
            return PolicyDecision::Rejected(RejectionReason::OutOfBounds {
                adjustable,
                requested,
                allowed: *allowed,
            });
        }
    }

    PolicyDecision::Accepted
}