Skip to main content

printobserver_core/
expiry.rs

1//! A bounded intervention expires on its own, and nothing has to ask it to.
2//!
3//! The expiry driver is a thread [`Supervisor::new`] starts. It reads the
4//! injected clock and nothing else, so expiry is driven by time passing and by
5//! nothing else, and a test drives it by advancing that clock alone.
6//!
7//! Expiry has exactly three outcomes and this module is the one place they are
8//! decided, so that the sweep and a print's terminal cleanup cannot drift into
9//! handling different sets of them:
10//!
11//! * **Restored** — the prior value went back, bounded by the same policy the
12//!   original request passed.
13//! * **Restore unavailable** — the printer reported no prior value, so there is
14//!   nothing to put back and nothing is sent to the machine. Writing a guessed
15//!   default would be inventing a value nobody observed.
16//! * **Restore failed** — the restoration was refused, by policy or by the
17//!   printer. The intervention is **settled** rather than left active, because
18//!   the expiry did happen, and it reads back carrying the applied value the
19//!   printer was left holding beside the prior value it should have been
20//!   returned to: a reason string alone would not say what the machine is
21//!   holding now, which is the whole point of recording it.
22//!
23//! Nothing here retries. A retry would be machinery this crate's manifest rule
24//! forbids it, and absorbing a transient store failure belongs behind the store
25//! port rather than here.
26
27use crate::records::{
28    Actor, Intervention, InterventionOutcome, PolicyDecision, PrintAction, RejectionReason,
29};
30use printobserver_printer_api::Adjustable;
31use printobserver_types::PrintId;
32
33use crate::decision::{DecisionInput, decide};
34use crate::error::CoreError;
35use crate::store::{EventDraft, SettleOutcome};
36use crate::supervisor::Supervisor;
37
38/// The reason a restoring request carries, so the record says why it was made.
39const RESTORE_REASON: &str = "the bounded intervention expired";
40
41/// The request that puts one adjustable back to the value the print started at.
42///
43/// It carries no duration: a restoration opens no intervention of its own.
44#[must_use]
45pub fn restoring_action(adjustable: Adjustable, prior_value: f64) -> PrintAction {
46    match adjustable {
47        Adjustable::Feedrate => PrintAction::SetFeedrateFactor {
48            factor: prior_value,
49            duration_s: None,
50            reason: RESTORE_REASON.to_owned(),
51            actor: Actor::System,
52        },
53        Adjustable::Flowrate => PrintAction::SetFlowrateFactor {
54            factor: prior_value,
55            duration_s: None,
56            reason: RESTORE_REASON.to_owned(),
57            actor: Actor::System,
58        },
59        Adjustable::ToolTarget { tool } => PrintAction::SetToolTargetC {
60            tool,
61            target_c: prior_value,
62            duration_s: None,
63            reason: RESTORE_REASON.to_owned(),
64            actor: Actor::System,
65        },
66        Adjustable::BedTarget => PrintAction::SetBedTargetC {
67            target_c: prior_value,
68            duration_s: None,
69            reason: RESTORE_REASON.to_owned(),
70            actor: Actor::System,
71        },
72        Adjustable::Fan => PrintAction::SetFanPercent {
73            percent: prior_value,
74            duration_s: None,
75            reason: RESTORE_REASON.to_owned(),
76            actor: Actor::System,
77        },
78    }
79}
80
81/// Why policy refused a request, in words a reader of the record can act on.
82#[must_use]
83pub fn rejection_detail(reason: &RejectionReason) -> String {
84    match reason {
85        RejectionReason::OutOfBounds {
86            adjustable,
87            requested,
88            allowed,
89        } => format!(
90            "{requested} is outside the {} to {} allowed for {adjustable}",
91            allowed.min, allowed.max
92        ),
93        RejectionReason::ActorMayNotRequest {
94            actor_class,
95            action,
96        } => format!("{actor_class:?} may not request {action:?}"),
97        RejectionReason::NoActivePrint => "there is no active print to act on".to_owned(),
98        RejectionReason::InvalidFromState { state } => {
99            format!("this is not valid from {state:?}")
100        }
101        RejectionReason::MinIntervalNotElapsed {
102            interval_s,
103            since_last_s,
104        } => format!(
105            "the agent last acted {since_last_s}s ago and its minimum interval is {interval_s}s"
106        ),
107        RejectionReason::UnsupportedAdjustable { adjustable } => {
108            format!("this printer has no {adjustable}")
109        }
110        RejectionReason::InsufficientFilament {
111            tool,
112            spool_name,
113            required_g,
114            buffer_g,
115            remaining_g,
116            ..
117        } => format!(
118            "spool {spool_name} on tool {tool} holds {remaining_g}g, and the print needs \
119             {required_g}g and a {buffer_g}g buffer"
120        ),
121        RejectionReason::UnverifiedSpool {
122            tool, spool_name, ..
123        } => format!("spool {spool_name} on tool {tool} is unverified"),
124        RejectionReason::AnalysisUnavailable {
125            file_name,
126            waited_s,
127        } => format!("{file_name} had no analysis after waiting {waited_s}s for one"),
128        RejectionReason::SpoolRefused { detail } => detail.clone(),
129    }
130}
131
132impl Supervisor {
133    /// Expire every bounded intervention that is due at the clock's own instant.
134    ///
135    /// One intervention's failure does not cost the rest: every one that is due
136    /// is attempted on the same sweep.
137    ///
138    /// The expiry driver calls this on its own poll, and a composition root
139    /// calls it once on start so that an intervention left past its expiry by a
140    /// restart is expired then rather than up to one poll later.
141    ///
142    /// # Errors
143    ///
144    /// Returns the store's own error when the due interventions could not be
145    /// read. A failure settling one of them is recorded on that intervention
146    /// rather than answered here.
147    pub async fn sweep_expired(&self) -> Result<(), CoreError> {
148        let at = self.clock().now();
149        for intervention in self.stores().actions.due_interventions(at).await? {
150            let _ = self.expire_intervention(&intervention).await;
151        }
152        Ok(())
153    }
154
155    /// Expire every intervention still active on one print.
156    ///
157    /// Each takes the same three-way behaviour an ordinary expiry takes, and
158    /// one that fails does not cost the rest.
159    ///
160    /// # Errors
161    ///
162    /// Returns the store's own error when the print's active interventions
163    /// could not be read.
164    pub(crate) async fn expire_all_active(&self, print_id: PrintId) -> Result<(), CoreError> {
165        for intervention in self.stores().actions.active_interventions(print_id).await? {
166            let _ = self.expire_intervention(&intervention).await;
167        }
168        Ok(())
169    }
170
171    /// Expire one intervention: restore, report nothing to restore, or record
172    /// that the restoration failed.
173    ///
174    /// Settling is once-only, so an intervention this and the expiry driver
175    /// both reach answers the outcome that won rather than being restored
176    /// twice. That is what lets a composition root expire what a restart left
177    /// past its bound and record the outcome, whichever of the two got there
178    /// first.
179    ///
180    /// # Errors
181    ///
182    /// Returns the store's own error when the outcome could not be settled.
183    pub async fn expire_intervention(
184        &self,
185        intervention: &Intervention,
186    ) -> Result<InterventionOutcome, CoreError> {
187        if intervention.outcome != InterventionOutcome::StillActive {
188            return Ok(intervention.outcome.clone());
189        }
190        // Another expiry may have reached it first — the driver's sweep, a
191        // close-out, a start's reconciliation — so it is read again once this
192        // one holds the print's expiries, and one already settled is answered
193        // with the outcome that won rather than put back a second time.
194        let _expiring = self.expiring().acquire(intervention.print_id).await;
195        let still_active = self
196            .stores()
197            .actions
198            .active_interventions(intervention.print_id)
199            .await?
200            .iter()
201            .any(|active| active.id == intervention.id);
202        if !still_active {
203            // Settling is once-only, so this writes nothing and answers the
204            // outcome already settled.
205            return self
206                .settle(intervention, InterventionOutcome::RestoreUnavailable)
207                .await;
208        }
209        let Some(prior_value) = intervention.prior_value else {
210            return self
211                .settle(intervention, InterventionOutcome::RestoreUnavailable)
212                .await;
213        };
214        let outcome = self.restore(intervention, prior_value).await?;
215        self.settle(intervention, outcome).await
216    }
217
218    /// Put one adjustable back, bounded by the same policy the request passed.
219    async fn restore(
220        &self,
221        intervention: &Intervention,
222        prior_value: f64,
223    ) -> Result<InterventionOutcome, CoreError> {
224        let requested_at = self.clock().now();
225        let action = restoring_action(intervention.adjustable, prior_value);
226        let actor = action.actor().clone();
227        let print = self.stores().prints.print(intervention.print_id).await?;
228        let bounds = self
229            .bounds_for(print.as_ref(), intervention.print_id)
230            .await?;
231        let decision = decide(&DecisionInput {
232            action: &action,
233            actor: &actor,
234            requested_at,
235            print: print.as_ref(),
236            // A restoration is judged from no state: see `DecisionInput`.
237            printer_state: None,
238            bounds: &bounds.effective,
239            envelope: &self.config().envelope,
240            last_agent_action: None,
241        });
242        let request = crate::records::ActionRequest {
243            action,
244            actor,
245            requested_at,
246        };
247        let issued = self.issue_decided_action(request, decision).await?;
248        if let PolicyDecision::Rejected(reason) = &issued.record.decision {
249            return Ok(InterventionOutcome::RestoreFailed {
250                reason: rejection_detail(reason),
251            });
252        }
253        if let Some(error) = issued.printer_error() {
254            return Ok(InterventionOutcome::RestoreFailed {
255                reason: error.to_string(),
256            });
257        }
258        Ok(InterventionOutcome::Restored)
259    }
260
261    /// Settle one intervention, answering the outcome that won.
262    async fn settle(
263        &self,
264        intervention: &Intervention,
265        outcome: InterventionOutcome,
266    ) -> Result<InterventionOutcome, CoreError> {
267        let settled = self
268            .stores()
269            .actions
270            .settle_intervention(intervention.id, outcome)
271            .await?;
272        Ok(match settled {
273            // Written into the print's own history, because what became of a
274            // bounded change is the whole point of it having been bounded: an
275            // outcome that reached the intervention row and went no further
276            // would be one no read of this system could answer.
277            SettleOutcome::Settled {
278                intervention: settled,
279            } => {
280                self.append_expiry_event(intervention, settled.outcome.clone())
281                    .await?;
282                settled.outcome
283            }
284            SettleOutcome::AlreadySettled { outcome } => outcome,
285        })
286    }
287
288    /// Write what became of one bounded intervention into the print's history.
289    async fn append_expiry_event(
290        &self,
291        intervention: &Intervention,
292        outcome: InterventionOutcome,
293    ) -> Result<(), CoreError> {
294        self.stores()
295            .events
296            .append_event(EventDraft {
297                print_id: Some(intervention.print_id),
298                source: crate::kinds::system_source(),
299                received_at: self.clock().now(),
300                body: printobserver_types::EventBody::of(
301                    &crate::kinds::InterventionExpiredPayload {
302                        intervention_id: intervention.id,
303                        adjustable: intervention.adjustable,
304                        outcome,
305                    },
306                )?,
307                raw: None,
308            })
309            .await?;
310        Ok(())
311    }
312}