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 and every spool command are valid from every
75/// state, because none of them changes anything at the machine; everything
76/// else names the states it makes sense 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
92        | ActionKind::RegisterSpool
93        | ActionKind::LoadSpool
94        | ActionKind::UnloadSpool
95        | ActionKind::AdjustSpool
96        | ActionKind::RetireSpool => true,
97    }
98}
99
100/// Whether one action changes something at the machine.
101///
102/// Acknowledging a failure does not: it writes a decision into the print's
103/// record and asks nothing of the printer, whatever its disposition. Nor does
104/// any spool command, which writes the spool ledger and nothing else. The agent's minimum interval spaces out changes to the
105/// machine, so that each one's effect can show before the next is asked for;
106/// an acknowledgement neither waits on it nor restarts it. An adjustment asked
107/// for while the print is paused does not wait on it either: nothing it does
108/// can show until the print moves again.
109#[must_use]
110pub const fn changes_the_machine(kind: ActionKind) -> bool {
111    !matches!(
112        kind,
113        ActionKind::AcknowledgeFailure
114            | ActionKind::RegisterSpool
115            | ActionKind::LoadSpool
116            | ActionKind::UnloadSpool
117            | ActionKind::AdjustSpool
118            | ActionKind::RetireSpool
119    )
120}
121
122/// Whether a print is one an action may still be taken against.
123fn is_active(print: Option<&PrintRecord>) -> bool {
124    print.is_some_and(|record| record.ended_at.is_none())
125}
126
127/// The decision policy takes on one request.
128///
129/// Every action from every actor passes through this, and the arms are ordered
130/// so that each rejection is reachable: there is no point asking whether a
131/// value is in bounds for an actor that may not ask for the action at all.
132#[must_use]
133pub fn decide(input: &DecisionInput<'_>) -> PolicyDecision {
134    let kind = input.action.kind();
135    let actor_class = input.actor.class();
136
137    if !is_active(input.print) {
138        return PolicyDecision::Rejected(RejectionReason::NoActivePrint);
139    }
140
141    let granted = input.envelope.actions.get(&actor_class);
142    if !granted.is_some_and(|kinds| kinds.contains(&kind)) {
143        return PolicyDecision::Rejected(RejectionReason::ActorMayNotRequest {
144            actor_class,
145            action: kind,
146        });
147    }
148
149    // Nothing an adjustment does can show while the print is paused, so the
150    // interval that waits for it to show does not hold adjustments to a paused
151    // print back. Resuming, pausing and cancelling still wait on it: those are
152    // the flapping it exists to stop.
153    let adjusting_a_paused_print = adjustment(input.action).is_some()
154        && matches!(input.printer_state, Some(PrinterState::Paused));
155    if actor_class == ActorClass::Agent
156        && changes_the_machine(kind)
157        && !adjusting_a_paused_print
158        && let Some(last) = input.last_agent_action
159    {
160        let since_last_s = seconds_between(last, input.requested_at);
161        if since_last_s < input.envelope.agent_min_interval_s {
162            return PolicyDecision::Rejected(RejectionReason::MinIntervalNotElapsed {
163                interval_s: input.envelope.agent_min_interval_s,
164                since_last_s,
165            });
166        }
167    }
168
169    if let Some(state) = input.printer_state
170        && !valid_from(kind, state)
171    {
172        return PolicyDecision::Rejected(RejectionReason::InvalidFromState {
173            state: state.clone(),
174        });
175    }
176
177    if let Some((adjustable, requested)) = adjustment(input.action) {
178        let Some(allowed) = input.bounds.allowed.get(&adjustable) else {
179            return PolicyDecision::Rejected(RejectionReason::UnsupportedAdjustable { adjustable });
180        };
181        if !allowed.contains(requested) {
182            return PolicyDecision::Rejected(RejectionReason::OutOfBounds {
183                adjustable,
184                requested,
185                allowed: *allowed,
186            });
187        }
188    }
189
190    PolicyDecision::Accepted
191}