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