Skip to main content

printobserver_core/
decision.rs

1//! The one decision, as a total function over what it is given.
2//!
3//! Nothing here reaches a port. The decision is a pure function of the request,
4//! the print, the state the printer is in, the bounds in force and when the
5//! agent last acted, so that the rule can be read in one place and the
6//! chokepoint that issues actions has only to record what this answered.
7//!
8//! **A request outside the bounds is rejected, not clamped.** Silently clamping
9//! would leave an agent believing it had done something it had not, and would
10//! leave the operator's own record saying it asked for a value it never asked
11//! for.
12
13use crate::records::{
14    ActionKind, Actor, ActorClass, EffectiveBounds, PolicyDecision, PrintAction, PrintRecord,
15    RejectionReason, SafetyEnvelope,
16};
17use printobserver_printer_api::{Adjustable, PrinterState};
18use printobserver_types::Timestamp;
19
20use crate::clock::seconds_between;
21
22/// Everything one decision is taken from.
23#[derive(Debug, Clone, Copy)]
24pub struct DecisionInput<'a> {
25    /// What is being asked for.
26    pub action: &'a PrintAction,
27    /// Who is asking.
28    pub actor: &'a Actor,
29    /// When they asked.
30    pub requested_at: Timestamp,
31    /// The print it is being asked against, when there is one.
32    pub print: Option<&'a PrintRecord>,
33    /// The state to judge this request from, when there is one to judge it from.
34    ///
35    /// Absent means the state check does not apply: either no snapshot could be
36    /// taken, or the request is a **restoration**, which is the closing half of
37    /// a change this policy already accepted rather than a fresh request for a
38    /// machine change — the state that justified the original check is by
39    /// definition the state that has just ended. The bounds check applies to a
40    /// restoration exactly as it does to the request that opened it.
41    pub printer_state: Option<&'a PrinterState>,
42    /// The bounds in force for this print.
43    pub bounds: &'a EffectiveBounds,
44    /// The operator's safety envelope.
45    pub envelope: &'a SafetyEnvelope,
46    /// When the agent last acted on this print, if it has.
47    pub last_agent_action: Option<Timestamp>,
48}
49
50/// What an adjustment asks to change, and the value it asks for.
51///
52/// Absent for an action that changes no adjustable, which is what makes the
53/// bounds arms of the decision reachable from the action alone.
54#[must_use]
55pub fn adjustment(action: &PrintAction) -> Option<(Adjustable, f64)> {
56    match action {
57        PrintAction::SetFeedrateFactor { factor, .. } => Some((Adjustable::Feedrate, *factor)),
58        PrintAction::SetFlowrateFactor { factor, .. } => Some((Adjustable::Flowrate, *factor)),
59        PrintAction::SetToolTargetC { tool, target_c, .. } => {
60            Some((Adjustable::ToolTarget { tool: *tool }, *target_c))
61        }
62        PrintAction::SetBedTargetC { target_c, .. } => Some((Adjustable::BedTarget, *target_c)),
63        PrintAction::SetFanPercent { percent, .. } => Some((Adjustable::Fan, *percent)),
64        PrintAction::Pause { .. }
65        | PrintAction::Resume { .. }
66        | PrintAction::Cancel { .. }
67        | PrintAction::StartPrint { .. }
68        | PrintAction::AcknowledgeFailure { .. } => None,
69    }
70}
71
72/// Whether one action is valid from the state the printer is in.
73///
74/// Acknowledging a failure is valid from every state, because it changes
75/// nothing at the machine; everything else names the states it makes sense
76/// from.
77#[must_use]
78pub fn valid_from(kind: ActionKind, state: &PrinterState) -> bool {
79    match kind {
80        ActionKind::Pause => matches!(state, PrinterState::Printing),
81        ActionKind::Resume => matches!(state, PrinterState::Paused),
82        ActionKind::Cancel => matches!(state, PrinterState::Printing | PrinterState::Paused),
83        ActionKind::StartPrint => matches!(state, PrinterState::Operational),
84        ActionKind::SetFeedrateFactor
85        | ActionKind::SetFlowrateFactor
86        | ActionKind::SetToolTargetC
87        | ActionKind::SetBedTargetC
88        | ActionKind::SetFanPercent => {
89            matches!(state, PrinterState::Printing | PrinterState::Paused)
90        }
91        ActionKind::AcknowledgeFailure => true,
92    }
93}
94
95/// Whether a print is one an action may still be taken against.
96fn is_active(print: Option<&PrintRecord>) -> bool {
97    print.is_some_and(|record| record.ended_at.is_none())
98}
99
100/// The decision policy takes on one request.
101///
102/// Every action from every actor passes through this, and the arms are ordered
103/// so that each rejection is reachable: there is no point asking whether a
104/// value is in bounds for an actor that may not ask for the action at all.
105#[must_use]
106pub fn decide(input: &DecisionInput<'_>) -> PolicyDecision {
107    let kind = input.action.kind();
108    let actor_class = input.actor.class();
109
110    if !is_active(input.print) {
111        return PolicyDecision::Rejected(RejectionReason::NoActivePrint);
112    }
113
114    let granted = input.envelope.actions.get(&actor_class);
115    if !granted.is_some_and(|kinds| kinds.contains(&kind)) {
116        return PolicyDecision::Rejected(RejectionReason::ActorMayNotRequest {
117            actor_class,
118            action: kind,
119        });
120    }
121
122    if actor_class == ActorClass::Agent
123        && let Some(last) = input.last_agent_action
124    {
125        let since_last_s = seconds_between(last, input.requested_at);
126        if since_last_s < input.envelope.agent_min_interval_s {
127            return PolicyDecision::Rejected(RejectionReason::MinIntervalNotElapsed {
128                interval_s: input.envelope.agent_min_interval_s,
129                since_last_s,
130            });
131        }
132    }
133
134    if let Some(state) = input.printer_state
135        && !valid_from(kind, state)
136    {
137        return PolicyDecision::Rejected(RejectionReason::InvalidFromState {
138            state: state.clone(),
139        });
140    }
141
142    if let Some((adjustable, requested)) = adjustment(input.action) {
143        let Some(allowed) = input.bounds.allowed.get(&adjustable) else {
144            return PolicyDecision::Rejected(RejectionReason::UnsupportedAdjustable { adjustable });
145        };
146        if !allowed.contains(requested) {
147            return PolicyDecision::Rejected(RejectionReason::OutOfBounds {
148                adjustable,
149                requested,
150                allowed: *allowed,
151            });
152        }
153    }
154
155    PolicyDecision::Accepted
156}