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