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    }
111}
112
113impl Supervisor {
114    /// Expire every bounded intervention that is due at the clock's own instant.
115    ///
116    /// One intervention's failure does not cost the rest: every one that is due
117    /// is attempted on the same sweep.
118    ///
119    /// The expiry driver calls this on its own poll, and a composition root
120    /// calls it once on start so that an intervention left past its expiry by a
121    /// restart is expired then rather than up to one poll later.
122    ///
123    /// # Errors
124    ///
125    /// Returns the store's own error when the due interventions could not be
126    /// read. A failure settling one of them is recorded on that intervention
127    /// rather than answered here.
128    pub async fn sweep_expired(&self) -> Result<(), CoreError> {
129        let at = self.clock().now();
130        for intervention in self.stores().actions.due_interventions(at).await? {
131            let _ = self.expire_intervention(&intervention).await;
132        }
133        Ok(())
134    }
135
136    /// Expire every intervention still active on one print.
137    ///
138    /// Each takes the same three-way behaviour an ordinary expiry takes, and
139    /// one that fails does not cost the rest.
140    ///
141    /// # Errors
142    ///
143    /// Returns the store's own error when the print's active interventions
144    /// could not be read.
145    pub(crate) async fn expire_all_active(&self, print_id: PrintId) -> Result<(), CoreError> {
146        for intervention in self.stores().actions.active_interventions(print_id).await? {
147            let _ = self.expire_intervention(&intervention).await;
148        }
149        Ok(())
150    }
151
152    /// Expire one intervention: restore, report nothing to restore, or record
153    /// that the restoration failed.
154    ///
155    /// Settling is once-only, so an intervention this and the expiry driver
156    /// both reach answers the outcome that won rather than being restored
157    /// twice. That is what lets a composition root expire what a restart left
158    /// past its bound and record the outcome, whichever of the two got there
159    /// first.
160    ///
161    /// # Errors
162    ///
163    /// Returns the store's own error when the outcome could not be settled.
164    pub async fn expire_intervention(
165        &self,
166        intervention: &Intervention,
167    ) -> Result<InterventionOutcome, CoreError> {
168        if intervention.outcome != InterventionOutcome::StillActive {
169            return Ok(intervention.outcome.clone());
170        }
171        let Some(prior_value) = intervention.prior_value else {
172            return self
173                .settle(intervention, InterventionOutcome::RestoreUnavailable)
174                .await;
175        };
176        let outcome = self.restore(intervention, prior_value).await?;
177        self.settle(intervention, outcome).await
178    }
179
180    /// Put one adjustable back, bounded by the same policy the request passed.
181    async fn restore(
182        &self,
183        intervention: &Intervention,
184        prior_value: f64,
185    ) -> Result<InterventionOutcome, CoreError> {
186        let requested_at = self.clock().now();
187        let action = restoring_action(intervention.adjustable, prior_value);
188        let actor = action.actor().clone();
189        let print = self.stores().prints.print(intervention.print_id).await?;
190        let bounds = self
191            .bounds_for(print.as_ref(), intervention.print_id)
192            .await?;
193        let decision = decide(&DecisionInput {
194            action: &action,
195            actor: &actor,
196            requested_at,
197            print: print.as_ref(),
198            // A restoration is judged from no state: see `DecisionInput`.
199            printer_state: None,
200            bounds: &bounds.effective,
201            envelope: &self.config().envelope,
202            last_agent_action: None,
203        });
204        let request = crate::records::ActionRequest {
205            action,
206            actor,
207            requested_at,
208        };
209        let issued = self.issue_decided_action(request, decision).await?;
210        if let PolicyDecision::Rejected(reason) = &issued.record.decision {
211            return Ok(InterventionOutcome::RestoreFailed {
212                reason: rejection_detail(reason),
213            });
214        }
215        if let Some(error) = issued.printer_error() {
216            return Ok(InterventionOutcome::RestoreFailed {
217                reason: error.to_string(),
218            });
219        }
220        Ok(InterventionOutcome::Restored)
221    }
222
223    /// Settle one intervention, answering the outcome that won.
224    async fn settle(
225        &self,
226        intervention: &Intervention,
227        outcome: InterventionOutcome,
228    ) -> Result<InterventionOutcome, CoreError> {
229        let settled = self
230            .stores()
231            .actions
232            .settle_intervention(intervention.id, outcome)
233            .await?;
234        Ok(match settled {
235            // Written into the print's own history, because what became of a
236            // bounded change is the whole point of it having been bounded: an
237            // outcome that reached the intervention row and went no further
238            // would be one no read of this system could answer.
239            SettleOutcome::Settled {
240                intervention: settled,
241            } => {
242                self.append_expiry_event(intervention, settled.outcome.clone())
243                    .await?;
244                settled.outcome
245            }
246            SettleOutcome::AlreadySettled { outcome } => outcome,
247        })
248    }
249
250    /// Write what became of one bounded intervention into the print's history.
251    async fn append_expiry_event(
252        &self,
253        intervention: &Intervention,
254        outcome: InterventionOutcome,
255    ) -> Result<(), CoreError> {
256        self.stores()
257            .events
258            .append_event(EventDraft {
259                print_id: Some(intervention.print_id),
260                source: crate::kinds::system_source(),
261                received_at: self.clock().now(),
262                body: printobserver_types::EventBody::of(
263                    &crate::kinds::InterventionExpiredPayload {
264                        intervention_id: intervention.id,
265                        adjustable: intervention.adjustable,
266                        outcome,
267                    },
268                )?,
269                raw: None,
270            })
271            .await?;
272        Ok(())
273    }
274}