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 { .. }
73 | PrintAction::ClosePrint { .. } => None,
74 }
75}
76
77/// Whether one action is valid from the state the printer is in.
78///
79/// Acknowledging a failure, closing a print record and every spool command
80/// are valid from every state, because none of them changes anything at the
81/// machine; everything else names the states it makes sense from. Whether a
82/// close may go ahead turns on the job of the record's own file rather than on
83/// the printer's state, so it is read where the close is checked
84/// ([`crate::closing`]).
85#[must_use]
86pub fn valid_from(kind: ActionKind, state: &PrinterState) -> bool {
87 match kind {
88 ActionKind::Pause => matches!(state, PrinterState::Printing),
89 ActionKind::Resume => matches!(state, PrinterState::Paused),
90 ActionKind::Cancel => matches!(state, PrinterState::Printing | PrinterState::Paused),
91 ActionKind::StartPrint => matches!(state, PrinterState::Operational),
92 ActionKind::SetFeedrateFactor
93 | ActionKind::SetFlowrateFactor
94 | ActionKind::SetToolTargetC
95 | ActionKind::SetBedTargetC
96 | ActionKind::SetFanPercent => {
97 matches!(state, PrinterState::Printing | PrinterState::Paused)
98 }
99 ActionKind::AcknowledgeFailure
100 | ActionKind::ClosePrint
101 | ActionKind::RegisterSpool
102 | ActionKind::LoadSpool
103 | ActionKind::UnloadSpool
104 | ActionKind::AdjustSpool
105 | ActionKind::RetireSpool => true,
106 }
107}
108
109/// Whether one action changes something at the machine.
110///
111/// Acknowledging a failure does not: it writes a decision into the print's
112/// record and asks nothing of the printer, whatever its disposition. Nor does
113/// any spool command, which writes the spool ledger and nothing else, nor
114/// closing a print record, which writes that record and nothing else. The agent's minimum interval spaces out changes to the
115/// machine, so that each one's effect can show before the next is asked for;
116/// an acknowledgement neither waits on it nor restarts it. An adjustment asked
117/// for while the print is paused does not wait on it either: nothing it does
118/// can show until the print moves again.
119#[must_use]
120pub const fn changes_the_machine(kind: ActionKind) -> bool {
121 !matches!(
122 kind,
123 ActionKind::AcknowledgeFailure
124 | ActionKind::ClosePrint
125 | ActionKind::RegisterSpool
126 | ActionKind::LoadSpool
127 | ActionKind::UnloadSpool
128 | ActionKind::AdjustSpool
129 | ActionKind::RetireSpool
130 )
131}
132
133/// Whether a print is one an action may still be taken against.
134fn is_active(print: Option<&PrintRecord>) -> bool {
135 print.is_some_and(|record| record.ended_at.is_none())
136}
137
138/// The decision policy takes on one request.
139///
140/// Every action from every actor passes through this, and the arms are ordered
141/// so that each rejection is reachable: there is no point asking whether a
142/// value is in bounds for an actor that may not ask for the action at all.
143#[must_use]
144pub fn decide(input: &DecisionInput<'_>) -> PolicyDecision {
145 let kind = input.action.kind();
146 let actor_class = input.actor.class();
147
148 // A close is asked of a record rather than of a running print, so a
149 // record that has ended is refused as one, and one never recorded is
150 // refused as every other action against no print is.
151 if kind == ActionKind::ClosePrint && input.print.is_some() && !is_active(input.print) {
152 return PolicyDecision::Rejected(RejectionReason::PrintAlreadyEnded);
153 }
154 if !is_active(input.print) {
155 return PolicyDecision::Rejected(RejectionReason::NoActivePrint);
156 }
157
158 let granted = input.envelope.actions.get(&actor_class);
159 if !granted.is_some_and(|kinds| kinds.contains(&kind)) {
160 return PolicyDecision::Rejected(RejectionReason::ActorMayNotRequest {
161 actor_class,
162 action: kind,
163 });
164 }
165
166 // Nothing an adjustment does can show while the print is paused, so the
167 // interval that waits for it to show does not hold adjustments to a paused
168 // print back. Nor does it hold back a pause: pausing is how the agent stops
169 // a print going wrong, on the image in hand, and an agent granted no resume
170 // cannot flap a print by pausing it. A pause still starts the interval.
171 // Resuming and cancelling still wait on it.
172 let adjusting_a_paused_print = adjustment(input.action).is_some()
173 && matches!(input.printer_state, Some(PrinterState::Paused));
174 if actor_class == ActorClass::Agent
175 && changes_the_machine(kind)
176 && kind != ActionKind::Pause
177 && !adjusting_a_paused_print
178 && let Some(since_last) = input.since_last_agent_action
179 {
180 let since_last_s = i64::try_from(since_last.as_secs()).unwrap_or(i64::MAX);
181 if since_last_s < input.envelope.agent_min_interval_s {
182 return PolicyDecision::Rejected(RejectionReason::MinIntervalNotElapsed {
183 interval_s: input.envelope.agent_min_interval_s,
184 since_last_s,
185 });
186 }
187 }
188
189 if let Some(state) = input.printer_state
190 && !valid_from(kind, state)
191 {
192 return PolicyDecision::Rejected(RejectionReason::InvalidFromState {
193 state: state.clone(),
194 });
195 }
196
197 if let Some((adjustable, requested)) = adjustment(input.action) {
198 let Some(allowed) = input.bounds.allowed.get(&adjustable) else {
199 return PolicyDecision::Rejected(RejectionReason::UnsupportedAdjustable { adjustable });
200 };
201 if !allowed.contains(requested) {
202 return PolicyDecision::Rejected(RejectionReason::OutOfBounds {
203 adjustable,
204 requested,
205 allowed: *allowed,
206 });
207 }
208 }
209
210 PolicyDecision::Accepted
211}