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 core::time::Duration;
18use printobserver_printer_api::{Adjustable, PrinterState};
19
20use printobserver_types::Timestamp;
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    /// How long ago the agent last changed the machine on this print, if it
47    /// has, measured on [`Clock::elapsed`](crate::Clock::elapsed) — time
48    /// passing rather than the wall clock moving, so that a host's time
49    /// synchronisation stepping the wall clock neither lets the agent act again
50    /// early nor holds it back longer than the interval.
51    pub since_last_agent_action: Option<Duration>,
52}
53
54/// What an adjustment asks to change, and the value it asks for.
55///
56/// Absent for an action that changes no adjustable, which is what makes the
57/// bounds arms of the decision reachable from the action alone.
58#[must_use]
59pub fn adjustment(action: &PrintAction) -> Option<(Adjustable, f64)> {
60    match action {
61        PrintAction::SetFeedrateFactor { factor, .. } => Some((Adjustable::Feedrate, *factor)),
62        PrintAction::SetFlowrateFactor { factor, .. } => Some((Adjustable::Flowrate, *factor)),
63        PrintAction::SetToolTargetC { tool, target_c, .. } => {
64            Some((Adjustable::ToolTarget { tool: *tool }, *target_c))
65        }
66        PrintAction::SetBedTargetC { target_c, .. } => Some((Adjustable::BedTarget, *target_c)),
67        PrintAction::SetFanPercent { percent, .. } => Some((Adjustable::Fan, *percent)),
68        PrintAction::Pause { .. }
69        | PrintAction::Resume { .. }
70        | PrintAction::Cancel { .. }
71        | PrintAction::StartPrint { .. }
72        | PrintAction::AcknowledgeFailure { .. } => None,
73    }
74}
75
76/// Whether one action is valid from the state the printer is in.
77///
78/// Acknowledging a failure and every spool command are valid from every
79/// state, because none of them changes anything at the machine; everything
80/// else names the states it makes sense from.
81#[must_use]
82pub fn valid_from(kind: ActionKind, state: &PrinterState) -> bool {
83    match kind {
84        ActionKind::Pause => matches!(state, PrinterState::Printing),
85        ActionKind::Resume => matches!(state, PrinterState::Paused),
86        ActionKind::Cancel => matches!(state, PrinterState::Printing | PrinterState::Paused),
87        ActionKind::StartPrint => matches!(state, PrinterState::Operational),
88        ActionKind::SetFeedrateFactor
89        | ActionKind::SetFlowrateFactor
90        | ActionKind::SetToolTargetC
91        | ActionKind::SetBedTargetC
92        | ActionKind::SetFanPercent => {
93            matches!(state, PrinterState::Printing | PrinterState::Paused)
94        }
95        ActionKind::AcknowledgeFailure
96        | ActionKind::RegisterSpool
97        | ActionKind::LoadSpool
98        | ActionKind::UnloadSpool
99        | ActionKind::AdjustSpool
100        | ActionKind::RetireSpool => true,
101    }
102}
103
104/// Whether one action changes something at the machine.
105///
106/// Acknowledging a failure does not: it writes a decision into the print's
107/// record and asks nothing of the printer, whatever its disposition. Nor does
108/// any spool command, which writes the spool ledger and nothing else. The agent's minimum interval spaces out changes to the
109/// machine, so that each one's effect can show before the next is asked for;
110/// an acknowledgement neither waits on it nor restarts it. An adjustment asked
111/// for while the print is paused does not wait on it either: nothing it does
112/// can show until the print moves again.
113#[must_use]
114pub const fn changes_the_machine(kind: ActionKind) -> bool {
115    !matches!(
116        kind,
117        ActionKind::AcknowledgeFailure
118            | ActionKind::RegisterSpool
119            | ActionKind::LoadSpool
120            | ActionKind::UnloadSpool
121            | ActionKind::AdjustSpool
122            | ActionKind::RetireSpool
123    )
124}
125
126/// Whether a print is one an action may still be taken against.
127fn is_active(print: Option<&PrintRecord>) -> bool {
128    print.is_some_and(|record| record.ended_at.is_none())
129}
130
131/// The decision policy takes on one request.
132///
133/// Every action from every actor passes through this, and the arms are ordered
134/// so that each rejection is reachable: there is no point asking whether a
135/// value is in bounds for an actor that may not ask for the action at all.
136#[must_use]
137pub fn decide(input: &DecisionInput<'_>) -> PolicyDecision {
138    let kind = input.action.kind();
139    let actor_class = input.actor.class();
140
141    if !is_active(input.print) {
142        return PolicyDecision::Rejected(RejectionReason::NoActivePrint);
143    }
144
145    let granted = input.envelope.actions.get(&actor_class);
146    if !granted.is_some_and(|kinds| kinds.contains(&kind)) {
147        return PolicyDecision::Rejected(RejectionReason::ActorMayNotRequest {
148            actor_class,
149            action: kind,
150        });
151    }
152
153    // Nothing an adjustment does can show while the print is paused, so the
154    // interval that waits for it to show does not hold adjustments to a paused
155    // print back. Resuming, pausing and cancelling still wait on it: those are
156    // the flapping it exists to stop.
157    let adjusting_a_paused_print = adjustment(input.action).is_some()
158        && matches!(input.printer_state, Some(PrinterState::Paused));
159    if actor_class == ActorClass::Agent
160        && changes_the_machine(kind)
161        && !adjusting_a_paused_print
162        && let Some(since_last) = input.since_last_agent_action
163    {
164        let since_last_s = i64::try_from(since_last.as_secs()).unwrap_or(i64::MAX);
165        if since_last_s < input.envelope.agent_min_interval_s {
166            return PolicyDecision::Rejected(RejectionReason::MinIntervalNotElapsed {
167                interval_s: input.envelope.agent_min_interval_s,
168                since_last_s,
169            });
170        }
171    }
172
173    if let Some(state) = input.printer_state
174        && !valid_from(kind, state)
175    {
176        return PolicyDecision::Rejected(RejectionReason::InvalidFromState {
177            state: state.clone(),
178        });
179    }
180
181    if let Some((adjustable, requested)) = adjustment(input.action) {
182        let Some(allowed) = input.bounds.allowed.get(&adjustable) else {
183            return PolicyDecision::Rejected(RejectionReason::UnsupportedAdjustable { adjustable });
184        };
185        if !allowed.contains(requested) {
186            return PolicyDecision::Rejected(RejectionReason::OutOfBounds {
187                adjustable,
188                requested,
189                allowed: *allowed,
190            });
191        }
192    }
193
194    PolicyDecision::Accepted
195}