Skip to main content

printobserver_core/
recovery.rs

1//! Moving the printer after a print fails, through the one granted path.
2//!
3//! A recovery is asked of the printer rather than of a print, and is checked
4//! against what printobserver can work out about the machine rather than
5//! against a print's bounds:
6//!
7//! * **Configured.** With no `[recovery]` facts every action is refused
8//!   [`RecoveryNotConfigured`](RecoveryRejection::RecoveryNotConfigured).
9//! * **Granted.** The operator holds every action by default and the agent
10//!   none ([`RecoveryGrants`]); an ungranted one is refused
11//!   [`ActorMayNotRequest`](RecoveryRejection::ActorMayNotRequest).
12//! * **Not under a running print.** While the printer is printing or
13//!   cancelling every action is refused
14//!   [`PrintRunning`](RecoveryRejection::PrintRunning), and while it cannot be
15//!   read or reports itself offline or in error,
16//!   [`PrinterUnreachable`](RecoveryRejection::PrinterUnreachable). A paused
17//!   print admits them — and any recovery executed while it is paused makes it
18//!   non-resumable, which its resume is refused as
19//!   [`PrintNotResumable`](crate::records::RejectionReason::PrintNotResumable).
20//! * **Bounded.** A lift is above zero and at most `max_lift_mm`, and while Z
21//!   is trusted never past `max_z_mm` (or below zero, where away from the bed
22//!   is down the axis); a fan is 0 to 100 percent; a heat is inside the safety
23//!   envelope's range for that tool. Outside, it is refused
24//!   [`OutOfBounds`](RecoveryRejection::OutOfBounds).
25//! * **Clear of the part.** A heat, a park and an XY home need Z trusted, and
26//!   the nozzle at least `clearance_margin_mm` above the tallest part the last
27//!   print laid down — or the operator's word that it is clear. An agent's
28//!   word never counts. Homing Z needs the operator's word that the bed is
29//!   clear, and is never the agent's.
30//!
31//! # Where Z trust comes from
32//!
33//! Z is trusted from a Z home this supervisor executed, or a print it started,
34//! until the first of: the printer going offline or into error, a reset it
35//! pushed, a print ending `interrupted` or `failed`, a Z home or a lift the
36//! printer failed part-way, or this supervisor starting again. A position reply cannot say whether Z was homed, so trust
37//! is never read from one, and the position is read only while Z is trusted.
38//!
39//! The tallest part is read from the last print's own G-code, up to the last
40//! file position recorded for it.
41//!
42//! Every request is recorded — `recovery_requested`, then `recovery_executed`
43//! or `recovery_rejected` — printer-scoped, and reaches the machine through
44//! [`Supervisor::issue_decided_action`] alone.
45
46use printobserver_printer_api::{
47    Adjustable, AxisPosition, HomeAxes, PrinterCommand, PrinterSnapshot, PrinterState,
48};
49use printobserver_types::{EventId, EventKind, EventPayload as _, FileName, PrintId};
50
51use crate::error::CoreError;
52use crate::kinds::{RecoveryExecutedPayload, RecoveryRejectedPayload, RecoveryRequestedPayload};
53use crate::records::{
54    ActionAllowance, Actor, ActorClass, AwayFromBed, BedTemperature, ExecutionOutcome, LastPrint,
55    PausedPrint, PrintRecord, RecoveryAction, RecoveryActionKind, RecoveryConfig, RecoveryDecision,
56    RecoveryField, RecoveryGrants, RecoveryPosition, RecoveryRejection, RecoveryStatus,
57    RecoveryTemperatures, SafetyEnvelope, ToolTemperature, ZHome, ZTrust,
58};
59use crate::store::TimelineQuery;
60use crate::supervisor::{Decided, IssuedAs, PortCall, RecoveryIssued, Supervisor};
61
62/// Why Z is untrusted when this supervisor has done nothing to trust it.
63pub const UNTRUSTED_AT_START: &str =
64    "this server started and has neither homed Z nor started a print since";
65
66/// What one recovery is decided from.
67#[derive(Debug, Clone)]
68struct Facts {
69    /// The printer's state, when it could be read.
70    snapshot: Option<PrinterSnapshot>,
71    /// Whether Z is trusted, and what was read only because it is.
72    z: ZFacts,
73}
74
75/// What a recovery reads of Z: nothing while it is untrusted, because a
76/// position or an extent measured against an untrusted Z means nothing.
77#[derive(Debug, Clone)]
78enum ZFacts {
79    /// Z is untrusted.
80    Untrusted,
81    /// Z is trusted.
82    Trusted {
83        /// Where the head is, when it was read.
84        position: Option<Result<AxisPosition, String>>,
85        /// The tallest part the last print laid down, when it was read; zero
86        /// when no print has laid anything down.
87        tallest: Option<Result<f64, String>>,
88    },
89}
90
91/// The decision on one recovery request: the calls it makes, or its refusal.
92fn decide(
93    config: Option<&RecoveryConfig>,
94    grants: &RecoveryGrants,
95    envelope: &SafetyEnvelope,
96    class: ActorClass,
97    action: &RecoveryAction,
98    facts: &Facts,
99) -> Result<Vec<PortCall>, RecoveryRejection> {
100    let kind = action.kind();
101    let Some(config) = config else {
102        return Err(RecoveryRejection::RecoveryNotConfigured);
103    };
104    if !grants.grants(class, kind) {
105        return Err(RecoveryRejection::ActorMayNotRequest { action: kind });
106    }
107    let Some(snapshot) = facts.snapshot.as_ref() else {
108        return Err(RecoveryRejection::PrinterUnreachable);
109    };
110    match &snapshot.connection {
111        PrinterState::Offline | PrinterState::Error => {
112            return Err(RecoveryRejection::PrinterUnreachable);
113        }
114        PrinterState::Operational | PrinterState::Paused => {}
115        // A state this program has no word for is one something may be
116        // happening in, so it is treated as a running print.
117        state @ (PrinterState::Printing | PrinterState::Cancelling | PrinterState::Unknown(_)) => {
118            return Err(RecoveryRejection::PrintRunning {
119                state: state.clone(),
120            });
121        }
122    }
123    let calls = match action {
124        RecoveryAction::RecoverLift { mm } => vec![lift(config, facts, kind, *mm)?],
125        RecoveryAction::RecoverCool {} => cooling(snapshot),
126        RecoveryAction::RecoverFan { percent } => {
127            if !(percent.is_finite() && (0.0..=100.0).contains(percent)) {
128                return Err(RecoveryRejection::OutOfBounds {
129                    field: RecoveryField::Percent,
130                    requested: *percent,
131                    allowed: printobserver_types::Range::new(0.0, 100.0),
132                });
133            }
134            vec![PortCall::Fan { percent: *percent }]
135        }
136        RecoveryAction::RecoverHeat { tool, target_c, .. } => {
137            heat_bounded(envelope, *tool, *target_c)?;
138            clear_of_the_part(config, grants, class, action, facts)?;
139            vec![PortCall::ToolTarget {
140                tool: *tool,
141                target_c: *target_c,
142            }]
143        }
144        RecoveryAction::RecoverPark { .. } => {
145            clear_of_the_part(config, grants, class, action, facts)?;
146            vec![PortCall::Command(PrinterCommand::MoveXy {
147                x_mm: config.park_xy[0],
148                y_mm: config.park_xy[1],
149            })]
150        }
151        RecoveryAction::RecoverHomeXy { .. } => {
152            clear_of_the_part(config, grants, class, action, facts)?;
153            vec![PortCall::Command(PrinterCommand::Home {
154                axes: HomeAxes::Xy,
155            })]
156        }
157        RecoveryAction::RecoverHomeZ { bed_clear_asserted } => {
158            if !(*bed_clear_asserted && grants.assertion_counts(class)) {
159                return Err(RecoveryRejection::AssertionRequired {
160                    field: RecoveryField::BedClearAsserted,
161                });
162            }
163            vec![PortCall::Command(PrinterCommand::Home {
164                axes: HomeAxes::Z,
165            })]
166        }
167    };
168    Ok(calls)
169}
170
171/// A lift's one call, held to its bounds.
172fn lift(
173    config: &RecoveryConfig,
174    facts: &Facts,
175    kind: RecoveryActionKind,
176    mm: f64,
177) -> Result<PortCall, RecoveryRejection> {
178    if !(mm.is_finite() && mm > 0.0 && mm <= config.max_lift_mm) {
179        return Err(RecoveryRejection::OutOfBounds {
180            field: RecoveryField::Mm,
181            requested: mm,
182            allowed: printobserver_types::Range::new(0.0, config.max_lift_mm),
183        });
184    }
185    if let ZFacts::Trusted { position, .. } = &facts.z {
186        let at = position_of(position.as_ref(), kind)?;
187        // How far the head can still travel away from the bed.
188        let room = match config.away_from_bed {
189            AwayFromBed::ZPlus => config.max_z_mm - at.z,
190            AwayFromBed::ZMinus => at.z,
191        };
192        if mm > room {
193            return Err(RecoveryRejection::OutOfBounds {
194                field: RecoveryField::Mm,
195                requested: mm,
196                allowed: printobserver_types::Range::new(0.0, room.max(0.0)),
197            });
198        }
199    }
200    let signed = match config.away_from_bed {
201        AwayFromBed::ZPlus => mm,
202        AwayFromBed::ZMinus => -mm,
203    };
204    Ok(PortCall::Command(PrinterCommand::MoveZ { mm: signed }))
205}
206
207/// Every heater's target to zero: each tool the printer reports, tool 0 when
208/// it reports none, and the bed.
209fn cooling(snapshot: &PrinterSnapshot) -> Vec<PortCall> {
210    let tools = snapshot.tools.len().max(1);
211    let mut calls: Vec<PortCall> = (0..tools)
212        .map(|tool| PortCall::ToolTarget {
213            tool: i64::try_from(tool).unwrap_or(i64::MAX),
214            target_c: 0.0,
215        })
216        .collect();
217    calls.push(PortCall::BedTarget { target_c: 0.0 });
218    calls
219}
220
221/// A heat, held to the safety envelope's range for its tool.
222fn heat_bounded(
223    envelope: &SafetyEnvelope,
224    tool: i64,
225    target_c: f64,
226) -> Result<(), RecoveryRejection> {
227    let Some(allowed) = envelope.allowed.get(&Adjustable::ToolTarget { tool }) else {
228        // A tool the envelope bounds no target for is no tool a heat may name;
229        // the range answered is the tools it does bound.
230        let tools: Vec<i64> = envelope
231            .allowed
232            .keys()
233            .filter_map(|adjustable| match adjustable {
234                Adjustable::ToolTarget { tool } => Some(*tool),
235                _ => None,
236            })
237            .collect();
238        let lowest = tools.iter().min().copied().unwrap_or(0);
239        let highest = tools.iter().max().copied().unwrap_or(0);
240        #[expect(
241            clippy::cast_precision_loss,
242            reason = "a tool number is a handful, far inside what an f64 holds exactly"
243        )]
244        return Err(RecoveryRejection::OutOfBounds {
245            field: RecoveryField::Tool,
246            requested: tool as f64,
247            allowed: printobserver_types::Range::new(lowest as f64, highest as f64),
248        });
249    };
250    if !(target_c.is_finite() && allowed.contains(target_c)) {
251        return Err(RecoveryRejection::OutOfBounds {
252            field: RecoveryField::TargetC,
253            requested: target_c,
254            allowed: *allowed,
255        });
256    }
257    Ok(())
258}
259
260/// The nozzle is clear of the part: Z trusted, and either the operator's word
261/// or the nozzle measured at least the margin above the tallest part.
262fn clear_of_the_part(
263    config: &RecoveryConfig,
264    grants: &RecoveryGrants,
265    class: ActorClass,
266    action: &RecoveryAction,
267    facts: &Facts,
268) -> Result<(), RecoveryRejection> {
269    let ZFacts::Trusted { position, tallest } = &facts.z else {
270        return Err(RecoveryRejection::ZUntrusted);
271    };
272    if action.clearance_asserted() && grants.assertion_counts(class) {
273        return Ok(());
274    }
275    let kind = action.kind();
276    let at = position_of(position.as_ref(), kind)?;
277    let tallest = match tallest {
278        Some(Ok(tallest)) => *tallest,
279        Some(Err(detail)) => {
280            return Err(RecoveryRejection::PrinterCannot {
281                action: kind,
282                detail: format!("what the last print laid down could not be read: {detail}"),
283            });
284        }
285        None => {
286            return Err(RecoveryRejection::PrinterCannot {
287                action: kind,
288                detail: "what the last print laid down was not read".to_owned(),
289            });
290        }
291    };
292    if at.z < tallest + config.clearance_margin_mm {
293        return Err(RecoveryRejection::InsufficientClearance {
294            nozzle_z_mm: at.z,
295            tallest_mm: tallest,
296            margin_mm: config.clearance_margin_mm,
297        });
298    }
299    Ok(())
300}
301
302/// Where the head is, or the refusal of an action that needs it and cannot
303/// read it.
304fn position_of(
305    position: Option<&Result<AxisPosition, String>>,
306    kind: RecoveryActionKind,
307) -> Result<AxisPosition, RecoveryRejection> {
308    match position {
309        Some(Ok(at)) => Ok(*at),
310        Some(Err(detail)) => Err(RecoveryRejection::PrinterCannot {
311            action: kind,
312            detail: format!("the nozzle's position could not be read: {detail}"),
313        }),
314        None => Err(RecoveryRejection::PrinterCannot {
315            action: kind,
316            detail: "the nozzle's position was not read".to_owned(),
317        }),
318    }
319}
320
321/// Whether deciding one action reads where the head is.
322fn reads_position(action: &RecoveryAction, class: ActorClass, grants: &RecoveryGrants) -> bool {
323    match action.kind() {
324        RecoveryActionKind::RecoverLift => true,
325        kind if kind.needs_clearance() => {
326            !(action.clearance_asserted() && grants.assertion_counts(class))
327        }
328        _ => false,
329    }
330}
331
332/// The request one status entry is decided as: the action's least demanding
333/// form, carrying no assertion.
334fn representative(kind: RecoveryActionKind, config: Option<&RecoveryConfig>) -> RecoveryAction {
335    match kind {
336        RecoveryActionKind::RecoverLift => RecoveryAction::RecoverLift {
337            mm: config.map_or(1.0, |config| config.max_lift_mm.min(1.0)),
338        },
339        RecoveryActionKind::RecoverCool => RecoveryAction::RecoverCool {},
340        RecoveryActionKind::RecoverFan => RecoveryAction::RecoverFan { percent: 0.0 },
341        RecoveryActionKind::RecoverHeat => RecoveryAction::RecoverHeat {
342            tool: 0,
343            target_c: 0.0,
344            clearance_asserted: false,
345        },
346        RecoveryActionKind::RecoverPark => RecoveryAction::RecoverPark {
347            clearance_asserted: false,
348        },
349        RecoveryActionKind::RecoverHomeXy => RecoveryAction::RecoverHomeXy {
350            clearance_asserted: false,
351        },
352        RecoveryActionKind::RecoverHomeZ => RecoveryAction::RecoverHomeZ {
353            bed_clear_asserted: false,
354        },
355    }
356}
357
358/// Every heater one snapshot reports.
359fn temperatures_of(snapshot: Option<&PrinterSnapshot>) -> RecoveryTemperatures {
360    let Some(snapshot) = snapshot else {
361        return RecoveryTemperatures {
362            tools: Vec::new(),
363            bed: None,
364        };
365    };
366    let value = |reported: Option<&printobserver_types::Reported<f64>>| {
367        reported.map(printobserver_types::Reported::value)
368    };
369    RecoveryTemperatures {
370        tools: snapshot
371            .tools
372            .iter()
373            .enumerate()
374            .map(|(index, heater)| ToolTemperature {
375                tool: i64::try_from(index).unwrap_or(i64::MAX),
376                actual_c: value(heater.actual_c.as_ref()),
377                target_c: value(heater.target_c.as_ref()),
378            })
379            .collect(),
380        bed: snapshot.bed.as_ref().map(|bed| BedTemperature {
381            actual_c: value(bed.actual_c.as_ref()),
382            target_c: value(bed.target_c.as_ref()),
383        }),
384    }
385}
386
387/// What became of one recovery, in a sentence for a person: what it did, or
388/// why it was refused and what would let it go ahead.
389#[must_use]
390pub fn recovery_detail(
391    action: &RecoveryAction,
392    decision: &RecoveryDecision,
393    config: Option<&RecoveryConfig>,
394) -> String {
395    let kind = action.kind();
396    let rejection = match decision {
397        RecoveryDecision::Executed(ExecutionOutcome::Succeeded) => {
398            return format!("{kind} was carried out");
399        }
400        RecoveryDecision::Executed(ExecutionOutcome::Failed { reason }) => {
401            return format!("{kind} reached the printer, which refused it: {reason}");
402        }
403        RecoveryDecision::Rejected(rejection) => rejection,
404    };
405    match rejection {
406        RecoveryRejection::ActorMayNotRequest { action } => format!(
407            "{action} is not granted to this actor; `[policy.recovery]` in the server's \
408             configuration says who may ask for which"
409        ),
410        RecoveryRejection::PrintRunning { state } => format!(
411            "the printer is {state:?}, and nothing may move it under a running print; pause or \
412             cancel the print first"
413        ),
414        RecoveryRejection::PrinterUnreachable => {
415            "the printer cannot be read, or reports itself offline or in error".to_owned()
416        }
417        RecoveryRejection::ZUntrusted => format!(
418            "{kind} moves the head over the part or heats the nozzle above it, and Z is not \
419             trusted: home Z with `recover-home-z --bed-clear-asserted true` once the bed is \
420             clear"
421        ),
422        RecoveryRejection::InsufficientClearance {
423            nozzle_z_mm,
424            tallest_mm,
425            margin_mm,
426        } => format!(
427            "the nozzle is at Z {nozzle_z_mm} mm and the last print's tallest part is \
428             {tallest_mm} mm, so it is not {margin_mm} mm above it: lift it with `recover-lift`, \
429             or assert the clearance with `--clearance-asserted true` as the operator"
430        ),
431        RecoveryRejection::OutOfBounds {
432            field,
433            requested,
434            allowed,
435        } => format!(
436            "{field:?} {requested} is outside the {} to {} allowed",
437            allowed.min, allowed.max
438        ),
439        RecoveryRejection::AssertionRequired { field } => {
440            let sweeps = config.is_some_and(|config| config.z_home_sweeps_bed);
441            let said = if sweeps {
442                "homing Z on this printer brings a gantry down over the whole bed"
443            } else {
444                "homing Z on this printer brings the nozzle down onto the bed"
445            };
446            format!(
447                "{kind} needs `{}` true from the operator: {said}, and nothing on the bed may be \
448                 in its way",
449                match field {
450                    RecoveryField::ClearanceAsserted => "clearance_asserted",
451                    _ => "bed_clear_asserted",
452                }
453            )
454        }
455        RecoveryRejection::RecoveryNotConfigured => "the server's configuration carries no \
456             `[recovery]` section stating this printer's facts, so no recovery can be checked"
457            .to_owned(),
458        RecoveryRejection::PrinterCannot { action, detail } => {
459            format!("this printer cannot do what {action} needs: {detail}")
460        }
461    }
462}
463
464impl Supervisor {
465    /// Whether Z is trusted now, and since when or why not.
466    #[must_use]
467    pub fn z_trust(&self) -> ZTrust {
468        self.z_trust_held().clone()
469    }
470
471    /// Trust Z from now on: printobserver homed it, or started a print.
472    pub(crate) fn trust_z(&self) {
473        *self.z_trust_held() = ZTrust::TrustedSince(self.clock().now());
474    }
475
476    /// Stop trusting Z, saying why.
477    pub(crate) fn distrust_z(&self, why: impl Into<String>) {
478        *self.z_trust_held() = ZTrust::Untrusted(why.into());
479    }
480
481    /// Carry out one recovery action, or refuse it, recording either.
482    ///
483    /// # Errors
484    ///
485    /// Returns the store's own error when the request or what became of it
486    /// could not be recorded. A refusal is not an error: it is recorded and
487    /// answered in [`RecoveryIssued::decision`].
488    pub async fn request_recovery(
489        &self,
490        action: RecoveryAction,
491        actor: Actor,
492        reason: String,
493    ) -> Result<RecoveryIssued, CoreError> {
494        let class = actor.class();
495        let config = self.config().recovery;
496        let grants = &self.config().recovery_grants;
497        let granted =
498            config.is_some() && self.config().recovery_grants.grants(class, action.kind());
499        let facts = if granted {
500            self.facts(
501                reads_position(&action, class, grants),
502                action.kind().needs_clearance()
503                    && !(action.clearance_asserted() && grants.assertion_counts(class)),
504            )
505            .await
506        } else {
507            // A request refused before the printer matters reads nothing of it.
508            Facts {
509                snapshot: None,
510                z: ZFacts::Untrusted,
511            }
512        };
513        let calls = decide(
514            config.as_ref(),
515            &self.config().recovery_grants,
516            &self.config().envelope,
517            class,
518            &action,
519            &facts,
520        );
521        let requested = RecoveryRequestedPayload {
522            action,
523            actor,
524            reason,
525        };
526        let under_a_pause = facts
527            .snapshot
528            .as_ref()
529            .is_some_and(|snapshot| snapshot.connection == PrinterState::Paused);
530        match self
531            .issue_decided_action(Decided::Recovery {
532                requested: Box::new(requested),
533                calls,
534            })
535            .await?
536        {
537            IssuedAs::Recovery(issued) => {
538                // The head moved under a paused print, which the printer will
539                // not put back on resume.
540                if under_a_pause && matches!(issued.decision, RecoveryDecision::Executed(_)) {
541                    for print in self.stores().prints.open_prints().await? {
542                        self.moved_while_paused()
543                            .entry(print.id)
544                            .or_insert(issued.settled.id);
545                    }
546                }
547                Ok(issued)
548            }
549            // The chokepoint answers each request in its own kind, so this is
550            // a chokepoint that has come apart from its callers.
551            IssuedAs::Action(_) => Err(CoreError::Unrepresentable {
552                detail: "a recovery was answered as a print action".to_owned(),
553            }),
554        }
555    }
556
557    /// Write one recovery request down, before anything reaches the machine.
558    pub(crate) async fn write_recovery_request(
559        &self,
560        requested: &RecoveryRequestedPayload,
561    ) -> Result<printobserver_types::EventRecord, CoreError> {
562        let source = crate::actions::source_of(&requested.actor);
563        let draft = self.draft_of(None, source, requested)?;
564        Ok(self.stores().events.append_event(draft).await?)
565    }
566
567    /// Write down what became of one recovery the chokepoint has issued or
568    /// refused: trust Z after a Z home the printer took, and stop trusting it
569    /// after a Z home or a lift the printer failed, which may have stopped Z
570    /// anywhere along the way.
571    pub(crate) async fn recovery_settled(
572        &self,
573        requested: RecoveryRequestedPayload,
574        requested_event: printobserver_types::EventRecord,
575        decision: RecoveryDecision,
576    ) -> Result<RecoveryIssued, CoreError> {
577        let source = crate::actions::source_of(&requested.actor);
578        let RecoveryRequestedPayload {
579            action,
580            actor,
581            reason,
582        } = requested;
583        let moves_z = matches!(
584            action,
585            RecoveryAction::RecoverHomeZ { .. } | RecoveryAction::RecoverLift { .. }
586        );
587        let homed_z = matches!(action, RecoveryAction::RecoverHomeZ { .. })
588            && decision == RecoveryDecision::Executed(ExecutionOutcome::Succeeded);
589        let lost_z = moves_z
590            && matches!(
591                decision,
592                RecoveryDecision::Executed(ExecutionOutcome::Failed { .. })
593            );
594        let kind = action.kind();
595        let draft = match &decision {
596            RecoveryDecision::Executed(outcome) => self.draft_of(
597                None,
598                source,
599                &RecoveryExecutedPayload {
600                    action,
601                    actor,
602                    reason,
603                    outcome: outcome.clone(),
604                },
605            )?,
606            RecoveryDecision::Rejected(rejection) => self.draft_of(
607                None,
608                source,
609                &RecoveryRejectedPayload {
610                    action,
611                    actor,
612                    reason,
613                    rejection: rejection.clone(),
614                },
615            )?,
616        };
617        let settled = self.stores().events.append_event(draft).await?;
618        if homed_z {
619            self.trust_z();
620        }
621        if lost_z {
622            self.distrust_z(format!(
623                "a {} the printer failed may have stopped Z anywhere along the way",
624                kind.as_str()
625            ));
626        }
627        Ok(RecoveryIssued {
628            decision,
629            requested: requested_event,
630            settled,
631        })
632    }
633
634    /// Everything a recovery is checked against now, and what each action
635    /// would meet, for one actor class.
636    ///
637    /// # Errors
638    ///
639    /// Returns the store's own error when the prints or the events could not
640    /// be read.
641    pub async fn recovery_status(&self, class: ActorClass) -> Result<RecoveryStatus, CoreError> {
642        // The store answers which print was last before anything is read of
643        // the machine: a store that cannot is this server's own failure.
644        self.stores().prints.prints().await?;
645        let facts = self.facts(true, true).await;
646        let config = self.config().recovery;
647        let actions = RecoveryActionKind::ALL
648            .iter()
649            .map(|kind| ActionAllowance {
650                action: *kind,
651                refusal: decide(
652                    config.as_ref(),
653                    &self.config().recovery_grants,
654                    &self.config().envelope,
655                    class,
656                    &representative(*kind, config.as_ref()),
657                    &facts,
658                )
659                .err(),
660            })
661            .collect();
662        let state = facts
663            .snapshot
664            .as_ref()
665            .map_or(PrinterState::Offline, |snapshot| {
666                snapshot.connection.clone()
667            });
668        let paused_print = if state == PrinterState::Paused {
669            self.paused_print().await?
670        } else {
671            None
672        };
673        Ok(RecoveryStatus {
674            state,
675            z_trust: self.z_trust(),
676            position: match facts.z {
677                ZFacts::Trusted {
678                    position: Some(Ok(at)),
679                    ..
680                } => Some(RecoveryPosition {
681                    x: at.x,
682                    y: at.y,
683                    z: at.z,
684                }),
685                _ => None,
686            },
687            temperatures: temperatures_of(facts.snapshot.as_ref()),
688            last_print: self.last_print_extent().await.ok().flatten().and_then(
689                |(print_id, extent)| {
690                    extent.map(|extent| LastPrint {
691                        print_id,
692                        tallest_mm: extent.tallest_mm,
693                        footprint: extent.footprint,
694                    })
695                },
696            ),
697            paused_print,
698            z_home: config.map(|config| ZHome {
699                x: config.z_home_xy[0],
700                y: config.z_home_xy[1],
701                sweeps_bed: config.z_home_sweeps_bed,
702            }),
703            actions,
704        })
705    }
706
707    /// Read what a recovery is decided from: the printer's state, and — only
708    /// while Z is trusted — where the head is and what the last print laid
709    /// down, each when asked for.
710    async fn facts(&self, position: bool, tallest: bool) -> Facts {
711        let snapshot = self.read_snapshot().await.ok();
712        // A printer found offline or in error by this read may have reset or
713        // moved since, however briefly, and between two of the watch's reads.
714        if let Some(down) = snapshot
715            .as_ref()
716            .map(|snapshot| &snapshot.connection)
717            .filter(|state| matches!(state, PrinterState::Offline | PrinterState::Error))
718        {
719            self.distrust_z(format!(
720                "the printer was read {down:?}, and Z may have moved since"
721            ));
722        }
723        let trusted = matches!(self.z_trust(), ZTrust::TrustedSince(_));
724        let reachable = snapshot.as_ref().is_some_and(|snapshot| {
725            matches!(
726                snapshot.connection,
727                PrinterState::Operational | PrinterState::Paused
728            )
729        });
730        let z = if trusted {
731            ZFacts::Trusted {
732                position: if position && reachable {
733                    Some(
734                        self.read_position()
735                            .await
736                            .map_err(|error| error.to_string()),
737                    )
738                } else {
739                    None
740                },
741                tallest: if tallest && reachable {
742                    Some(match self.last_print_extent().await {
743                        Ok(Some((_, Some(extent)))) => Ok(extent.tallest_mm),
744                        Ok(None | Some((_, None))) => Ok(0.0),
745                        Err(error) => Err(error.to_string()),
746                    })
747                } else {
748                    None
749                },
750            }
751        } else {
752            ZFacts::Untrusted
753        };
754        Facts { snapshot, z }
755    }
756
757    /// The last print with a file, and what its G-code laid down up to the
758    /// last file position recorded for it: nothing when no print has a file.
759    async fn last_print_extent(
760        &self,
761    ) -> Result<Option<(PrintId, Option<printobserver_printer_api::PrintedExtent>)>, CoreError>
762    {
763        let prints = self.stores().prints.prints().await?;
764        let Some((print, file_name)) = prints
765            .iter()
766            .filter_map(|print| {
767                let file_name = FileName::new(print.file_name.as_deref()?).ok()?;
768                Some((print, file_name))
769            })
770            .max_by_key(|(print, _)| print.opened_at)
771        else {
772            return Ok(None);
773        };
774        let position = self
775            .stores()
776            .filament
777            .file_position(print.id)
778            .await?
779            .map_or(0, |position| position.bytes);
780        // A print no read found past its first byte sent nothing that could
781        // lay material down, so its file need not be read.
782        if position <= 0 {
783            return Ok(Some((print.id, None)));
784        }
785        let key = (print.id, position);
786        if let Some((cached, extent)) = self.recovery_extents().as_ref()
787            && *cached == key
788        {
789            return Ok(Some((print.id, *extent)));
790        }
791        let extent = self
792            .read_printed_extent(file_name, position)
793            .await
794            .map_err(CoreError::Printer)?;
795        *self.recovery_extents() = Some((key, extent));
796        Ok(Some((print.id, extent)))
797    }
798
799    /// The open print the printer is paused under, and whether it is still
800    /// resumable.
801    async fn paused_print(&self) -> Result<Option<PausedPrint>, CoreError> {
802        let Some(print) = self.stores().prints.open_prints().await?.into_iter().next() else {
803            return Ok(None);
804        };
805        Ok(Some(PausedPrint {
806            print_id: print.id,
807            resumable: self.recovery_while_open(&print).await?.is_none(),
808        }))
809    }
810
811    /// The recovery executed under one print while it was paused: what makes
812    /// it non-resumable.
813    ///
814    /// This supervisor notes each recovery it executes under a paused print.
815    /// What an earlier supervisor executed under a print still open it cannot
816    /// tell the printer's state for, so for a print opened before this one
817    /// started, any recovery recorded between the print opening and this
818    /// supervisor starting counts.
819    pub(crate) async fn recovery_while_open(
820        &self,
821        print: &PrintRecord,
822    ) -> Result<Option<EventId>, CoreError> {
823        if print.ended_at.is_some() {
824            return Ok(None);
825        }
826        if let Some(moved) = self.moved_while_paused().get(&print.id) {
827            return Ok(Some(*moved));
828        }
829        if print.opened_at >= self.started().wall {
830            return Ok(None);
831        }
832        let executed = EventKind::new(RecoveryExecutedPayload::KIND).map_err(|error| {
833            CoreError::Unrepresentable {
834                detail: error.to_string(),
835            }
836        })?;
837        Ok(self
838            .stores()
839            .timeline
840            .timeline(TimelineQuery {
841                kinds: vec![executed],
842                since: Some(print.opened_at),
843                until: Some(self.started().wall),
844                spool_id: None,
845                before: None,
846                limit: Some(1),
847            })
848            .await?
849            .into_iter()
850            .next()
851            .map(|event| event.id))
852    }
853}