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 printobserver_types::{
28    Actor, Adjustable, Intervention, InterventionOutcome, PolicyDecision, PrintAction, PrintId,
29    RejectionReason,
30};
31
32use crate::decision::{DecisionInput, decide};
33use crate::error::CoreError;
34use crate::supervisor::Supervisor;
35
36/// The reason a restoring request carries, so the record says why it was made.
37const RESTORE_REASON: &str = "the bounded intervention expired";
38
39/// The request that puts one adjustable back to the value the print started at.
40///
41/// It carries no duration: a restoration opens no intervention of its own.
42#[must_use]
43pub fn restoring_action(adjustable: Adjustable, prior_value: f64) -> PrintAction {
44    match adjustable {
45        Adjustable::Feedrate => PrintAction::SetFeedrateFactor {
46            factor: prior_value,
47            duration_s: None,
48            reason: RESTORE_REASON.to_owned(),
49            actor: Actor::System,
50        },
51        Adjustable::Flowrate => PrintAction::SetFlowrateFactor {
52            factor: prior_value,
53            duration_s: None,
54            reason: RESTORE_REASON.to_owned(),
55            actor: Actor::System,
56        },
57        Adjustable::ToolTarget { tool } => PrintAction::SetToolTargetC {
58            tool,
59            target_c: prior_value,
60            duration_s: None,
61            reason: RESTORE_REASON.to_owned(),
62            actor: Actor::System,
63        },
64        Adjustable::BedTarget => PrintAction::SetBedTargetC {
65            target_c: prior_value,
66            duration_s: None,
67            reason: RESTORE_REASON.to_owned(),
68            actor: Actor::System,
69        },
70        Adjustable::Fan => PrintAction::SetFanPercent {
71            percent: prior_value,
72            duration_s: None,
73            reason: RESTORE_REASON.to_owned(),
74            actor: Actor::System,
75        },
76    }
77}
78
79/// Why policy refused a request, in words a reader of the record can act on.
80#[must_use]
81pub fn rejection_detail(reason: &RejectionReason) -> String {
82    match reason {
83        RejectionReason::OutOfBounds {
84            adjustable,
85            requested,
86            allowed,
87        } => format!(
88            "{requested} is outside the {} to {} allowed for {adjustable}",
89            allowed.min, allowed.max
90        ),
91        RejectionReason::ActorMayNotRequest {
92            actor_class,
93            action,
94        } => format!("{actor_class:?} may not request {action:?}"),
95        RejectionReason::NoActivePrint => "there is no active print to act on".to_owned(),
96        RejectionReason::InvalidFromState { state } => {
97            format!("this is not valid from {state:?}")
98        }
99        RejectionReason::MinIntervalNotElapsed {
100            interval_s,
101            since_last_s,
102        } => format!(
103            "the agent last acted {since_last_s}s ago and its minimum interval is {interval_s}s"
104        ),
105        RejectionReason::UnsupportedAdjustable { adjustable } => {
106            format!("this printer has no {adjustable}")
107        }
108    }
109}
110
111impl Supervisor {
112    /// Expire every bounded intervention that is due at the clock's own instant.
113    ///
114    /// One intervention's failure does not cost the rest: every one that is due
115    /// is attempted on the same sweep.
116    ///
117    /// The expiry driver calls this on its own poll, and a composition root
118    /// calls it once on start so that an intervention left past its expiry by a
119    /// restart is expired then rather than up to one poll later.
120    ///
121    /// # Errors
122    ///
123    /// Returns the store's own error when the due interventions could not be
124    /// read. A failure settling one of them is recorded on that intervention
125    /// rather than answered here.
126    pub async fn sweep_expired(&self) -> Result<(), CoreError> {
127        let at = self.clock().now();
128        for intervention in self.store().due_interventions(at).await? {
129            let _ = self.expire_intervention(&intervention).await;
130        }
131        Ok(())
132    }
133
134    /// Expire every intervention still active on one print.
135    ///
136    /// Each takes the same three-way behaviour an ordinary expiry takes, and
137    /// one that fails does not cost the rest.
138    ///
139    /// # Errors
140    ///
141    /// Returns the store's own error when the print's active interventions
142    /// could not be read.
143    pub(crate) async fn expire_all_active(&self, print_id: PrintId) -> Result<(), CoreError> {
144        for intervention in self.store().active_interventions(print_id).await? {
145            let _ = self.expire_intervention(&intervention).await;
146        }
147        Ok(())
148    }
149
150    /// Expire one intervention: restore, report nothing to restore, or record
151    /// that the restoration failed.
152    ///
153    /// Settling is once-only, so an intervention this and the expiry driver
154    /// both reach answers the outcome that won rather than being restored
155    /// twice. That is what lets a composition root expire what a restart left
156    /// past its bound and record the outcome, whichever of the two got there
157    /// first.
158    ///
159    /// # Errors
160    ///
161    /// Returns the store's own error when the outcome could not be settled.
162    pub async fn expire_intervention(
163        &self,
164        intervention: &Intervention,
165    ) -> Result<InterventionOutcome, CoreError> {
166        if intervention.outcome != InterventionOutcome::StillActive {
167            return Ok(intervention.outcome.clone());
168        }
169        let Some(prior_value) = intervention.prior_value else {
170            return self
171                .settle(intervention, InterventionOutcome::RestoreUnavailable)
172                .await;
173        };
174        let outcome = self.restore(intervention, prior_value).await?;
175        self.settle(intervention, outcome).await
176    }
177
178    /// Put one adjustable back, bounded by the same policy the request passed.
179    async fn restore(
180        &self,
181        intervention: &Intervention,
182        prior_value: f64,
183    ) -> Result<InterventionOutcome, CoreError> {
184        let requested_at = self.clock().now();
185        let action = restoring_action(intervention.adjustable, prior_value);
186        let actor = action.actor().clone();
187        let print = self.store().print(intervention.print_id).await?;
188        let bounds = self
189            .bounds_for(print.as_ref(), intervention.print_id)
190            .await?;
191        let decision = decide(&DecisionInput {
192            action: &action,
193            actor: &actor,
194            requested_at,
195            print: print.as_ref(),
196            // A restoration is judged from no state: see `DecisionInput`.
197            printer_state: None,
198            bounds: &bounds.effective,
199            envelope: &self.config().envelope,
200            last_agent_action: None,
201        });
202        let request = printobserver_types::ActionRequest {
203            action,
204            actor,
205            requested_at,
206        };
207        let issued = self.issue_decided_action(request, decision).await?;
208        if let PolicyDecision::Rejected(reason) = &issued.record.decision {
209            return Ok(InterventionOutcome::RestoreFailed {
210                reason: rejection_detail(reason),
211            });
212        }
213        if let Some(error) = issued.printer_error() {
214            return Ok(InterventionOutcome::RestoreFailed {
215                reason: error.to_string(),
216            });
217        }
218        Ok(InterventionOutcome::Restored)
219    }
220
221    /// Settle one intervention, answering the outcome that won.
222    async fn settle(
223        &self,
224        intervention: &Intervention,
225        outcome: InterventionOutcome,
226    ) -> Result<InterventionOutcome, CoreError> {
227        let settled = self
228            .store()
229            .settle_intervention(intervention.id, outcome)
230            .await?;
231        Ok(match settled {
232            // Written into the print's own history, because what became of a
233            // bounded change is the whole point of it having been bounded: an
234            // outcome that reached the intervention row and went no further
235            // would be one no read of this system could answer.
236            printobserver_store_api::SettleOutcome::Settled {
237                intervention: settled,
238            } => {
239                self.append_expiry_event(intervention, settled.outcome.clone())
240                    .await?;
241                settled.outcome
242            }
243            printobserver_store_api::SettleOutcome::AlreadySettled { outcome } => outcome,
244        })
245    }
246
247    /// Write what became of one bounded intervention into the print's history.
248    async fn append_expiry_event(
249        &self,
250        intervention: &Intervention,
251        outcome: InterventionOutcome,
252    ) -> Result<(), CoreError> {
253        self.store()
254            .append_event(printobserver_store_api::EventDraft {
255                print_id: Some(intervention.print_id),
256                source: printobserver_types::EventSource::System,
257                received_at: self.clock().now(),
258                payload: printobserver_types::EventPayload::InterventionExpired(
259                    printobserver_types::InterventionExpiredPayload {
260                        intervention_id: intervention.id,
261                        adjustable: intervention.adjustable,
262                        outcome,
263                    },
264                ),
265                raw: None,
266            })
267            .await?;
268        Ok(())
269    }
270}