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//! # Time passing, not the wall clock moving
8//!
9//! An intervention's deadline is persisted as an absolute instant, so that a
10//! restart knows when it was due. But a live expiry is decided on
11//! [`Clock::elapsed`](crate::Clock::elapsed), which nothing steps: each
12//! active intervention's remaining time is taken **once** from its persisted
13//! deadline — when this supervisor applies it, or, for one a previous
14//! supervisor left active, against the [`ClockReading`] this one took as it
15//! started — and is counted down on the clock nothing steps from then on. A
16//! host whose time synchronisation steps the wall clock therefore neither cuts
17//! a bounded change short nor draws it out.
18//!
19//! Expiry has exactly three outcomes and this module is the one place they are
20//! decided, so that the sweep and a print's terminal cleanup cannot drift into
21//! handling different sets of them:
22//!
23//! * **Restored** — the prior value went back, bounded by the same policy the
24//!   original request passed.
25//! * **Restore unavailable** — the printer reported no prior value, so there is
26//!   nothing to put back and nothing is sent to the machine. Writing a guessed
27//!   default would be inventing a value nobody observed.
28//! * **Restore failed** — the restoration was refused, by policy or by the
29//!   printer. The intervention is **settled** rather than left active, because
30//!   the expiry did happen, and it reads back carrying the applied value the
31//!   printer was left holding beside the prior value it should have been
32//!   returned to: a reason string alone would not say what the machine is
33//!   holding now, which is the whole point of recording it.
34//!
35//! Nothing here retries. A retry would be machinery this crate's manifest rule
36//! forbids it, and absorbing a transient store failure belongs behind the store
37//! port rather than here.
38
39use core::time::Duration;
40use std::collections::BTreeMap;
41use std::sync::Mutex;
42use std::sync::atomic::{AtomicBool, Ordering};
43
44use crate::records::{
45    Actor, Intervention, InterventionId, InterventionOutcome, PolicyDecision, PrintAction,
46    RejectionReason,
47};
48use printobserver_printer_api::Adjustable;
49use printobserver_types::{PrintId, Timestamp};
50
51use crate::clock::ClockReading;
52use crate::decision::{DecisionInput, decide};
53use crate::error::CoreError;
54use crate::store::{EventDraft, SettleOutcome};
55use crate::supervisor::Supervisor;
56
57/// The active interventions this supervisor is counting down, each with the
58/// reading of [`Clock::elapsed`](crate::Clock::elapsed) it expires at.
59#[derive(Debug, Default)]
60pub(crate) struct Deadlines {
61    /// Each intervention, by its identifier, and when it expires.
62    counting: Mutex<BTreeMap<InterventionId, (Intervention, Duration)>>,
63    /// Whether the interventions a previous supervisor left active have been
64    /// read and are being counted down.
65    adopted: AtomicBool,
66}
67
68impl Deadlines {
69    /// Count one intervention down from `reading`, replacing any count of it.
70    fn count(&self, intervention: &Intervention, reading: ClockReading) {
71        let due = reading.elapsed_at(intervention.expires_at);
72        self.counting()
73            .insert(intervention.id, (intervention.clone(), due));
74    }
75
76    /// Count one intervention down from `reading`, unless it is already.
77    fn adopt(&self, intervention: &Intervention, reading: ClockReading) {
78        let due = reading.elapsed_at(intervention.expires_at);
79        self.counting()
80            .entry(intervention.id)
81            .or_insert_with(|| (intervention.clone(), due));
82    }
83
84    /// Stop counting one intervention down.
85    fn forget(&self, intervention_id: InterventionId) {
86        self.counting().remove(&intervention_id);
87    }
88
89    /// Every intervention whose count has reached `elapsed`, soonest first.
90    fn due(&self, elapsed: Duration) -> Vec<Intervention> {
91        let mut due: Vec<(Duration, Intervention)> = self
92            .counting()
93            .values()
94            .filter(|(_, at)| *at <= elapsed)
95            .map(|(intervention, at)| (*at, intervention.clone()))
96            .collect();
97        due.sort_by_key(|(at, _)| *at);
98        due.into_iter()
99            .map(|(_, intervention)| intervention)
100            .collect()
101    }
102
103    /// The counts, held for one read or write.
104    fn counting(
105        &self,
106    ) -> std::sync::MutexGuard<'_, BTreeMap<InterventionId, (Intervention, Duration)>> {
107        self.counting
108            .lock()
109            .unwrap_or_else(std::sync::PoisonError::into_inner)
110    }
111}
112
113/// The reason a restoring request carries, so the record says why it was made.
114const RESTORE_REASON: &str = "the bounded intervention expired";
115
116/// The request that puts one adjustable back to the value the print started at.
117///
118/// It carries no duration: a restoration opens no intervention of its own.
119#[must_use]
120pub fn restoring_action(adjustable: Adjustable, prior_value: f64) -> PrintAction {
121    match adjustable {
122        Adjustable::Feedrate => PrintAction::SetFeedrateFactor {
123            factor: prior_value,
124            duration_s: None,
125            reason: RESTORE_REASON.to_owned(),
126            actor: Actor::System,
127        },
128        Adjustable::Flowrate => PrintAction::SetFlowrateFactor {
129            factor: prior_value,
130            duration_s: None,
131            reason: RESTORE_REASON.to_owned(),
132            actor: Actor::System,
133        },
134        Adjustable::ToolTarget { tool } => PrintAction::SetToolTargetC {
135            tool,
136            target_c: prior_value,
137            duration_s: None,
138            reason: RESTORE_REASON.to_owned(),
139            actor: Actor::System,
140        },
141        Adjustable::BedTarget => PrintAction::SetBedTargetC {
142            target_c: prior_value,
143            duration_s: None,
144            reason: RESTORE_REASON.to_owned(),
145            actor: Actor::System,
146        },
147        Adjustable::Fan => PrintAction::SetFanPercent {
148            percent: prior_value,
149            duration_s: None,
150            reason: RESTORE_REASON.to_owned(),
151            actor: Actor::System,
152        },
153    }
154}
155
156/// Why policy refused a request, in words a reader of the record can act on.
157#[must_use]
158pub fn rejection_detail(reason: &RejectionReason) -> String {
159    match reason {
160        RejectionReason::OutOfBounds {
161            adjustable,
162            requested,
163            allowed,
164        } => format!(
165            "{requested} is outside the {} to {} allowed for {adjustable}",
166            allowed.min, allowed.max
167        ),
168        RejectionReason::ActorMayNotRequest {
169            actor_class,
170            action,
171        } => format!("{actor_class:?} may not request {action:?}"),
172        RejectionReason::NoActivePrint => "there is no active print to act on".to_owned(),
173        RejectionReason::InvalidFromState { state } => {
174            format!("this is not valid from {state:?}")
175        }
176        RejectionReason::MinIntervalNotElapsed {
177            interval_s,
178            since_last_s,
179        } => format!(
180            "the agent last acted {since_last_s}s ago and its minimum interval is {interval_s}s"
181        ),
182        RejectionReason::UnsupportedAdjustable { adjustable } => {
183            format!("this printer has no {adjustable}")
184        }
185        RejectionReason::InsufficientFilament {
186            tool,
187            spool_name,
188            required_g,
189            buffer_g,
190            remaining_g,
191            ..
192        } => format!(
193            "spool {spool_name} on tool {tool} holds {remaining_g}g, and the print needs \
194             {required_g}g and a {buffer_g}g buffer"
195        ),
196        RejectionReason::UnverifiedSpool {
197            tool, spool_name, ..
198        } => format!("spool {spool_name} on tool {tool} is unverified"),
199        RejectionReason::AnalysisUnavailable {
200            file_name,
201            waited_s,
202        } => format!("{file_name} had no analysis after waiting {waited_s}s for one"),
203        RejectionReason::SpoolRefused { message, .. } => message.clone(),
204        RejectionReason::PrintAlreadyEnded => "this print's record has already ended".to_owned(),
205        RejectionReason::PrintStillActive { state } => {
206            format!("the printer shows this print's file still {state:?}")
207        }
208        RejectionReason::InterventionStillActive { intervention_id } => {
209            format!("intervention {intervention_id} has neither expired nor been restored")
210        }
211    }
212}
213
214impl Supervisor {
215    /// Expire every bounded intervention whose time has passed.
216    ///
217    /// One intervention's failure does not cost the rest: every one that is due
218    /// is attempted on the same sweep.
219    ///
220    /// The expiry driver calls this on its own poll. Its first sweep reads the
221    /// interventions a previous supervisor left active and counts each down
222    /// from the reading this supervisor took as it started; every later one
223    /// reads nothing, because every intervention opened since is counted down
224    /// from the moment it was applied.
225    ///
226    /// # Errors
227    ///
228    /// Returns the store's own error when the interventions left active could
229    /// not be read, which the next sweep reads again. A failure settling one of
230    /// them is recorded on that intervention rather than answered here.
231    pub async fn sweep_expired(&self) -> Result<(), CoreError> {
232        self.adopt_left_active().await?;
233        for intervention in self.deadlines().due(self.clock().elapsed()) {
234            let _ = self.expire_intervention(&intervention).await;
235        }
236        Ok(())
237    }
238
239    /// Count down every intervention a previous supervisor left active, once.
240    async fn adopt_left_active(&self) -> Result<(), CoreError> {
241        let deadlines = self.deadlines();
242        if deadlines.adopted.load(Ordering::Acquire) {
243            return Ok(());
244        }
245        // Every active intervention is due by the latest instant a deadline can
246        // be recorded at, so this reads every one.
247        for intervention in self
248            .stores()
249            .actions
250            .due_interventions(Timestamp::latest())
251            .await?
252        {
253            deadlines.adopt(&intervention, self.started());
254        }
255        deadlines.adopted.store(true, Ordering::Release);
256        Ok(())
257    }
258
259    /// Count one intervention this supervisor just applied down from now.
260    pub(crate) fn count_down(&self, intervention: &Intervention) {
261        self.deadlines()
262            .count(intervention, ClockReading::of(self.clock().as_ref()));
263    }
264
265    /// Stop counting down one intervention settled other than by expiring.
266    pub(crate) fn stop_counting_down(&self, intervention_id: InterventionId) {
267        self.deadlines().forget(intervention_id);
268    }
269
270    /// Expire every intervention still active on one print.
271    ///
272    /// Each takes the same three-way behaviour an ordinary expiry takes, and
273    /// one that fails does not cost the rest.
274    ///
275    /// # Errors
276    ///
277    /// Returns the store's own error when the print's active interventions
278    /// could not be read.
279    pub(crate) async fn expire_all_active(&self, print_id: PrintId) -> Result<(), CoreError> {
280        for intervention in self.stores().actions.active_interventions(print_id).await? {
281            let _ = self.expire_intervention(&intervention).await;
282        }
283        Ok(())
284    }
285
286    /// Expire one intervention: restore, report nothing to restore, or record
287    /// that the restoration failed.
288    ///
289    /// Settling is once-only, so an intervention this and the expiry driver
290    /// both reach answers the outcome that won rather than being restored
291    /// twice. That is what lets a composition root expire what a restart left
292    /// past its bound and record the outcome, whichever of the two got there
293    /// first.
294    ///
295    /// # Errors
296    ///
297    /// Returns the store's own error when the outcome could not be settled.
298    pub async fn expire_intervention(
299        &self,
300        intervention: &Intervention,
301    ) -> Result<InterventionOutcome, CoreError> {
302        let outcome = self.expire_once(intervention).await?;
303        self.deadlines().forget(intervention.id);
304        Ok(outcome)
305    }
306
307    /// Expire one intervention, whatever was counting it down.
308    async fn expire_once(
309        &self,
310        intervention: &Intervention,
311    ) -> Result<InterventionOutcome, CoreError> {
312        if intervention.outcome != InterventionOutcome::StillActive {
313            return Ok(intervention.outcome.clone());
314        }
315        // Another expiry may have reached it first — the driver's sweep, a
316        // close-out, a start's reconciliation — so it is read again once this
317        // one holds the print's expiries, and one already settled is answered
318        // with the outcome that won rather than put back a second time.
319        let _expiring = self.expiring().acquire(intervention.print_id).await;
320        let still_active = self
321            .stores()
322            .actions
323            .active_interventions(intervention.print_id)
324            .await?
325            .iter()
326            .any(|active| active.id == intervention.id);
327        if !still_active {
328            // Settling is once-only, so this writes nothing and answers the
329            // outcome already settled.
330            return self
331                .settle(intervention, InterventionOutcome::RestoreUnavailable)
332                .await;
333        }
334        let Some(prior_value) = intervention.prior_value else {
335            return self
336                .settle(intervention, InterventionOutcome::RestoreUnavailable)
337                .await;
338        };
339        let outcome = self.restore(intervention, prior_value).await?;
340        self.settle(intervention, outcome).await
341    }
342
343    /// Put one adjustable back, bounded by the same policy the request passed.
344    async fn restore(
345        &self,
346        intervention: &Intervention,
347        prior_value: f64,
348    ) -> Result<InterventionOutcome, CoreError> {
349        let requested_at = self.clock().now();
350        let action = restoring_action(intervention.adjustable, prior_value);
351        let actor = action.actor().clone();
352        let print = self.stores().prints.print(intervention.print_id).await?;
353        let bounds = self
354            .bounds_for(print.as_ref(), intervention.print_id)
355            .await?;
356        let decision = decide(&DecisionInput {
357            action: &action,
358            actor: &actor,
359            requested_at,
360            print: print.as_ref(),
361            // A restoration is judged from no state: see `DecisionInput`.
362            printer_state: None,
363            bounds: &bounds.effective,
364            envelope: &self.config().envelope,
365            since_last_agent_action: None,
366        });
367        let request = crate::records::ActionRequest {
368            action,
369            actor,
370            requested_at,
371        };
372        let issued = self.issue_decided_action(request, decision, None).await?;
373        if let PolicyDecision::Rejected(reason) = &issued.record.decision {
374            return Ok(InterventionOutcome::RestoreFailed {
375                reason: rejection_detail(reason),
376            });
377        }
378        if let Some(error) = issued.printer_error() {
379            return Ok(InterventionOutcome::RestoreFailed {
380                reason: error.to_string(),
381            });
382        }
383        Ok(InterventionOutcome::Restored)
384    }
385
386    /// Settle one intervention, answering the outcome that won.
387    async fn settle(
388        &self,
389        intervention: &Intervention,
390        outcome: InterventionOutcome,
391    ) -> Result<InterventionOutcome, CoreError> {
392        let settled = self
393            .stores()
394            .actions
395            .settle_intervention(intervention.id, outcome)
396            .await?;
397        Ok(match settled {
398            // Written into the print's own history, because what became of a
399            // bounded change is the whole point of it having been bounded: an
400            // outcome that reached the intervention row and went no further
401            // would be one no read of this system could answer.
402            SettleOutcome::Settled {
403                intervention: settled,
404            } => {
405                self.append_expiry_event(intervention, settled.outcome.clone())
406                    .await?;
407                settled.outcome
408            }
409            SettleOutcome::AlreadySettled { outcome } => outcome,
410        })
411    }
412
413    /// Write what became of one bounded intervention into the print's history.
414    async fn append_expiry_event(
415        &self,
416        intervention: &Intervention,
417        outcome: InterventionOutcome,
418    ) -> Result<(), CoreError> {
419        self.stores()
420            .events
421            .append_event(EventDraft {
422                print_id: Some(intervention.print_id),
423                source: crate::kinds::system_source(),
424                received_at: self.clock().now(),
425                body: printobserver_types::EventBody::of(
426                    &crate::kinds::InterventionExpiredPayload {
427                        intervention_id: intervention.id,
428                        adjustable: intervention.adjustable,
429                        outcome,
430                    },
431                )?,
432                raw: None,
433            })
434            .await?;
435        Ok(())
436    }
437}