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, MaterialObjection, PolicyDecision,
46    PrintAction, RejectionReason, SheetId, SheetObjection,
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/// What the material check objected to, naming what it compared.
157// llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
158fn material_detail(objection: &MaterialObjection) -> String {
159    match objection {
160        MaterialObjection::Mismatch(compared) => format!(
161            "the file was sliced for {}, and spool {} on tool {} is {}",
162            compared.sliced_for, compared.spool.name, compared.tool, compared.loaded
163        ),
164        MaterialObjection::Undeclared(uncompared) => format!(
165            "{} names no `filament_type`, so it cannot be compared with spool {} on tool {}, \
166             which is {}",
167            uncompared.file_name, uncompared.spool.name, uncompared.tool, uncompared.loaded
168        ),
169        MaterialObjection::Unread {
170            tool,
171            spool,
172            loaded,
173            file_name,
174            detail,
175        } => format!(
176            "the settings of {file_name} could not be read ({detail}), so it cannot be compared \
177             with spool {} on tool {tool}, which is {loaded}",
178            spool.name
179        ),
180    }
181}
182
183/// Sheets, as a list a sentence carries.
184fn listed(sheets: &[SheetId]) -> String {
185    sheets
186        .iter()
187        .map(SheetId::as_str)
188        .collect::<Vec<_>>()
189        .join(", ")
190}
191
192/// What the sheet check objected to, naming what it compared.
193// llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
194fn sheet_detail(objection: &SheetObjection) -> String {
195    match objection {
196        SheetObjection::NotAllowed(compared) => format!(
197            "the sheet table allows {} on {} and not on {}",
198            compared.material,
199            listed(&compared.allowed),
200            compared.sheet
201        ),
202        SheetObjection::UnlistedMaterial { sheet, material } => format!(
203            "the sheet table has no entry for {material}, so {sheet} is not known to suit it"
204        ),
205        SheetObjection::UnknownSheet {
206            sheet,
207            material,
208            known,
209        } => format!(
210            "no entry of the sheet table lists {sheet}, so it is not known to suit {material}; \
211             the sheets it names are {}",
212            listed(known)
213        ),
214    }
215}
216
217/// Why policy refused a request, in words a reader of the record can act on.
218#[must_use]
219pub fn rejection_detail(reason: &RejectionReason) -> String {
220    match reason {
221        RejectionReason::OutOfBounds {
222            adjustable,
223            requested,
224            allowed,
225        } => format!(
226            "{requested} is outside the {} to {} allowed for {adjustable}",
227            allowed.min, allowed.max
228        ),
229        RejectionReason::ActorMayNotRequest {
230            actor_class,
231            action,
232        } => format!("{actor_class:?} may not request {action:?}"),
233        RejectionReason::NoActivePrint => "there is no active print to act on".to_owned(),
234        RejectionReason::InvalidFromState { state } => {
235            format!("this is not valid from {state:?}")
236        }
237        RejectionReason::MinIntervalNotElapsed {
238            interval_s,
239            since_last_s,
240        } => format!(
241            "the agent last acted {since_last_s}s ago and its minimum interval is {interval_s}s"
242        ),
243        RejectionReason::UnsupportedAdjustable { adjustable } => {
244            format!("this printer has no {adjustable}")
245        }
246        RejectionReason::InsufficientFilament {
247            tool,
248            spool_name,
249            required_g,
250            buffer_g,
251            remaining_g,
252            ..
253        } => format!(
254            "spool {spool_name} on tool {tool} holds {remaining_g}g, and the print needs \
255             {required_g}g and a {buffer_g}g buffer"
256        ),
257        RejectionReason::UnverifiedSpool {
258            tool, spool_name, ..
259        } => format!("spool {spool_name} on tool {tool} is unverified"),
260        RejectionReason::AnalysisUnavailable {
261            file_name,
262            waited_s,
263        } => format!("{file_name} had no analysis after waiting {waited_s}s for one"),
264        RejectionReason::MaterialRefused { objection } => material_detail(objection),
265        RejectionReason::SheetRefused { objection } => sheet_detail(objection),
266        RejectionReason::SheetNotDeclared => "the manifest declares no `sheet`, and every start \
267             names the build sheet it goes down on; no override lets a start without one through"
268            .to_owned(),
269        RejectionReason::SpoolRefused { message, .. } => message.clone(),
270        RejectionReason::PrintAlreadyEnded => "this print's record has already ended".to_owned(),
271        RejectionReason::PrintStillActive { state } => {
272            format!("the printer shows this print's file still {state:?}")
273        }
274        RejectionReason::InterventionStillActive { intervention_id } => {
275            format!("intervention {intervention_id} has neither expired nor been restored")
276        }
277        RejectionReason::PrintNotResumable { recovery_event_id } => format!(
278            "recovery event {recovery_event_id} moved the printer while this print was paused, \
279             and resuming would print the rest of the layer at the wrong height"
280        ),
281    }
282}
283
284impl Supervisor {
285    /// Expire every bounded intervention whose time has passed.
286    ///
287    /// One intervention's failure does not cost the rest: every one that is due
288    /// is attempted on the same sweep.
289    ///
290    /// The expiry driver calls this on its own poll. Its first sweep reads the
291    /// interventions a previous supervisor left active and counts each down
292    /// from the reading this supervisor took as it started; every later one
293    /// reads nothing, because every intervention opened since is counted down
294    /// from the moment it was applied.
295    ///
296    /// # Errors
297    ///
298    /// Returns the store's own error when the interventions left active could
299    /// not be read, which the next sweep reads again. A failure settling one of
300    /// them is recorded on that intervention rather than answered here.
301    pub async fn sweep_expired(&self) -> Result<(), CoreError> {
302        self.adopt_left_active().await?;
303        for intervention in self.deadlines().due(self.clock().elapsed()) {
304            let _ = self.expire_intervention(&intervention).await;
305        }
306        Ok(())
307    }
308
309    /// Count down every intervention a previous supervisor left active, once.
310    async fn adopt_left_active(&self) -> Result<(), CoreError> {
311        let deadlines = self.deadlines();
312        if deadlines.adopted.load(Ordering::Acquire) {
313            return Ok(());
314        }
315        // Every active intervention is due by the latest instant a deadline can
316        // be recorded at, so this reads every one.
317        for intervention in self
318            .stores()
319            .actions
320            .due_interventions(Timestamp::latest())
321            .await?
322        {
323            deadlines.adopt(&intervention, self.started());
324        }
325        deadlines.adopted.store(true, Ordering::Release);
326        Ok(())
327    }
328
329    /// Count one intervention this supervisor just applied down from now.
330    pub(crate) fn count_down(&self, intervention: &Intervention) {
331        self.deadlines()
332            .count(intervention, ClockReading::of(self.clock().as_ref()));
333    }
334
335    /// Stop counting down one intervention settled other than by expiring.
336    pub(crate) fn stop_counting_down(&self, intervention_id: InterventionId) {
337        self.deadlines().forget(intervention_id);
338    }
339
340    /// Expire every intervention still active on one print.
341    ///
342    /// Each takes the same three-way behaviour an ordinary expiry takes, and
343    /// one that fails does not cost the rest.
344    ///
345    /// # Errors
346    ///
347    /// Returns the store's own error when the print's active interventions
348    /// could not be read.
349    pub(crate) async fn expire_all_active(&self, print_id: PrintId) -> Result<(), CoreError> {
350        for intervention in self.stores().actions.active_interventions(print_id).await? {
351            let _ = self.expire_intervention(&intervention).await;
352        }
353        Ok(())
354    }
355
356    /// Expire one intervention: restore, report nothing to restore, or record
357    /// that the restoration failed.
358    ///
359    /// Settling is once-only, so an intervention this and the expiry driver
360    /// both reach answers the outcome that won rather than being restored
361    /// twice. That is what lets a composition root expire what a restart left
362    /// past its bound and record the outcome, whichever of the two got there
363    /// first.
364    ///
365    /// # Errors
366    ///
367    /// Returns the store's own error when the outcome could not be settled.
368    pub async fn expire_intervention(
369        &self,
370        intervention: &Intervention,
371    ) -> Result<InterventionOutcome, CoreError> {
372        let outcome = self.expire_once(intervention).await?;
373        self.deadlines().forget(intervention.id);
374        Ok(outcome)
375    }
376
377    /// Expire one intervention, whatever was counting it down.
378    async fn expire_once(
379        &self,
380        intervention: &Intervention,
381    ) -> Result<InterventionOutcome, CoreError> {
382        if intervention.outcome != InterventionOutcome::StillActive {
383            return Ok(intervention.outcome.clone());
384        }
385        // Another expiry may have reached it first — the driver's sweep, a
386        // close-out, a start's reconciliation — so it is read again once this
387        // one holds the print's expiries, and one already settled is answered
388        // with the outcome that won rather than put back a second time.
389        let _expiring = self.expiring().acquire(intervention.print_id).await;
390        let still_active = self
391            .stores()
392            .actions
393            .active_interventions(intervention.print_id)
394            .await?
395            .iter()
396            .any(|active| active.id == intervention.id);
397        if !still_active {
398            // Settling is once-only, so this writes nothing and answers the
399            // outcome already settled.
400            return self
401                .settle(intervention, InterventionOutcome::RestoreUnavailable)
402                .await;
403        }
404        let Some(prior_value) = intervention.prior_value else {
405            return self
406                .settle(intervention, InterventionOutcome::RestoreUnavailable)
407                .await;
408        };
409        let outcome = self.restore(intervention, prior_value).await?;
410        self.settle(intervention, outcome).await
411    }
412
413    /// Put one adjustable back, bounded by the same policy the request passed.
414    async fn restore(
415        &self,
416        intervention: &Intervention,
417        prior_value: f64,
418    ) -> Result<InterventionOutcome, CoreError> {
419        let requested_at = self.clock().now();
420        let action = restoring_action(intervention.adjustable, prior_value);
421        let actor = action.actor().clone();
422        let print = self.stores().prints.print(intervention.print_id).await?;
423        let bounds = self
424            .bounds_for(print.as_ref(), intervention.print_id)
425            .await?;
426        let decision = decide(&DecisionInput {
427            action: &action,
428            actor: &actor,
429            requested_at,
430            print: print.as_ref(),
431            // A restoration is judged from no state: see `DecisionInput`.
432            printer_state: None,
433            bounds: &bounds.effective,
434            envelope: &self.config().envelope,
435            since_last_agent_action: None,
436        });
437        let request = crate::records::ActionRequest {
438            action,
439            actor,
440            requested_at,
441        };
442        let issued = self.issue_action(request, decision, None).await?;
443        if let PolicyDecision::Rejected(reason) = &issued.record.decision {
444            return Ok(InterventionOutcome::RestoreFailed {
445                reason: rejection_detail(reason),
446            });
447        }
448        if let Some(error) = issued.printer_error() {
449            return Ok(InterventionOutcome::RestoreFailed {
450                reason: error.to_string(),
451            });
452        }
453        Ok(InterventionOutcome::Restored)
454    }
455
456    /// Settle one intervention, answering the outcome that won.
457    async fn settle(
458        &self,
459        intervention: &Intervention,
460        outcome: InterventionOutcome,
461    ) -> Result<InterventionOutcome, CoreError> {
462        let settled = self
463            .stores()
464            .actions
465            .settle_intervention(intervention.id, outcome)
466            .await?;
467        Ok(match settled {
468            // Written into the print's own history, because what became of a
469            // bounded change is the whole point of it having been bounded: an
470            // outcome that reached the intervention row and went no further
471            // would be one no read of this system could answer.
472            SettleOutcome::Settled {
473                intervention: settled,
474            } => {
475                self.append_expiry_event(intervention, settled.outcome.clone())
476                    .await?;
477                settled.outcome
478            }
479            SettleOutcome::AlreadySettled { outcome } => outcome,
480        })
481    }
482
483    /// Write what became of one bounded intervention into the print's history.
484    async fn append_expiry_event(
485        &self,
486        intervention: &Intervention,
487        outcome: InterventionOutcome,
488    ) -> Result<(), CoreError> {
489        self.stores()
490            .events
491            .append_event(EventDraft {
492                print_id: Some(intervention.print_id),
493                source: crate::kinds::system_source(),
494                received_at: self.clock().now(),
495                body: printobserver_types::EventBody::of(
496                    &crate::kinds::InterventionExpiredPayload {
497                        intervention_id: intervention.id,
498                        adjustable: intervention.adjustable,
499                        outcome,
500                    },
501                )?,
502                raw: None,
503            })
504            .await?;
505        Ok(())
506    }
507}