Skip to main content

printobserver_core/
planned.rs

1//! A print waiting at a change its own G-code plans.
2//!
3//! A single-nozzle print sliced with colour changes stops at each `M600` so a
4//! person can load the next colour, and at an `M601` so a person can do
5//! whatever the pause was planned for. To everything else this supervisor
6//! watches that wait looks like a stall: the file position freezes, the parts
7//! stop growing, and the firmware's idle timeout turns the nozzle target to
8//! zero. So a planned stop is recognised, and the print is left alone until it
9//! carries on.
10//!
11//! # Reached
12//!
13//! A change is reached when a filament-change signal arrives with the job at
14//! it, or a read of the job finds its file position at the change's line or
15//! just past it ([`GcodeIndex::change_waiting_at`]). Either writes one
16//! [`FilamentChangePlannedReachedPayload`] per change of a print, and charges
17//! the spool on tool 0 up to the change's own offset, with the
18//! `filament_change_signalled` that is the accounting record of every change.
19//! A filament-change signal arriving again for a change already reached —
20//! `Obico` repeats one every ten minutes while the printer waits — writes
21//! nothing of its own and starts nothing.
22//!
23//! # While it waits
24//!
25//! No supervision turn runs for the print: no alert's, no scheduled check's
26//! and none the printer watch would give. A pause, a resume or an adjustment
27//! from any actor is refused
28//! [`PlannedChangeWaiting`](crate::records::RejectionReason::PlannedChangeWaiting);
29//! a cancel and every spool command are not, because a person may abandon the
30//! print or load the next spool while it waits.
31//!
32//! # Resumed
33//!
34//! A print has carried on once a read finds its file position moved on from
35//! where the job stood still at the change: the job stands at a position
36//! through the wait, and the host sends the next line only once the printer
37//! has finished the change, so the first read after the person confirms it on
38//! the printer is the one that sees the position move. A job read paused is
39//! never read as carrying on this way, and a position the job has not yet been
40//! read standing at for a whole [`CoreConfig::printer_poll`](crate::CoreConfig::printer_poll)
41//! is not one it stood at: the lines the host had already sent as the change
42//! was reached may still be moving it. A position past the change's reach
43//! ([`PLANNED_CHANGE_REACH_BYTES`](crate::gcode_index::PLANNED_CHANGE_REACH_BYTES))
44//! has carried on whatever was read before it, which is all a server restarted
45//! during the wait has to go on.
46//!
47//! Then one [`FilamentChangePlannedResumedPayload`] is written with the
48//! camera's frame, and that event is the print's next check, at once. The
49//! growth measurement starts again from frames taken after it, and the print's
50//! next scheduled check is one observation interval after it.
51//!
52//! # What is remembered, and where
53//!
54//! The store's history is the record; this supervisor keeps a copy of each
55//! print's planned changes so an alert or a request asks nothing of the store
56//! for a print whose file plans none. A print's copy is read from the history
57//! the first time its index, once built, plans a change, and for every open
58//! print as the server starts ([`Supervisor::restore_planned_changes`]).
59//! The index of a print found open as the server starts is built by the
60//! first read of its running job the printer watch makes, once, so a
61//! restarted server reaches a change by position before any check of it.
62
63use std::collections::{BTreeMap, BTreeSet};
64use std::sync::PoisonError;
65use std::time::Duration;
66
67use printobserver_printer_api::{JobSnapshot, PrinterState};
68use printobserver_types::{EventBody, EventKind, EventPayload, EventRecord, PrintId, Timestamp};
69
70use crate::accounting::{Whereabouts, spool_on_tool};
71use crate::clock::seconds_between;
72use crate::error::CoreError;
73use crate::events::PendingTurn;
74use crate::gcode_index::{GcodeIndex, PlannedChange, PlannedChanges};
75use crate::inbox::{AlertCameraFrame, Arrival};
76use crate::kinds::{
77    FilamentChangePlannedReachedPayload, FilamentChangePlannedResumedPayload, PlannedChangeTrigger,
78};
79use crate::look::Frame;
80use crate::records::{ActionKind, FilePosition, PrintRecord, RejectionReason};
81use crate::store::{HistoryQuery, MAX_HISTORY_LIMIT};
82use crate::supervisor::Supervisor;
83
84/// The actions a print waiting at a planned change refuses, whoever asks.
85pub const REFUSED_WHILE_WAITING: [ActionKind; 7] = [
86    ActionKind::Pause,
87    ActionKind::Resume,
88    ActionKind::SetFeedrateFactor,
89    ActionKind::SetFlowrateFactor,
90    ActionKind::SetToolTargetC,
91    ActionKind::SetBedTargetC,
92    ActionKind::SetFanPercent,
93];
94
95/// The change a print is waiting at, as its `reached` recorded it.
96#[derive(Debug, Clone, PartialEq)]
97pub struct Waiting {
98    /// What the `reached` event recorded.
99    pub reached: FilamentChangePlannedReachedPayload,
100    /// When it was recorded.
101    pub since: Timestamp,
102}
103
104impl Waiting {
105    /// The refusal a pause, a resume or an adjustment is answered while it
106    /// waits.
107    #[must_use]
108    pub fn refusal(&self) -> RejectionReason {
109        let change = &self.reached.change;
110        RejectionReason::PlannedChangeWaiting {
111            change_index: change.index,
112            layer: change.layer,
113            z_mm: change.z_mm,
114            color: change.color.clone(),
115        }
116    }
117}
118
119/// Where a print's job has stood since it reached the planned change it waits
120/// at.
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub(crate) struct Stand {
123    /// The change waited at, by index.
124    change: u32,
125    /// The file position the job was read at.
126    at: u64,
127    /// When it was first read there, on the clock nothing steps.
128    since: Duration,
129    /// Whether a read a whole printer poll after `since` found it still there.
130    still: bool,
131}
132
133/// A change one read has taken to record its resumption, and when the
134/// print's last check after a change had begun before it.
135#[derive(Debug)]
136struct Claimed {
137    /// The change the print waited at.
138    waiting: Waiting,
139    /// When the print's last check after a change had begun, if one had.
140    checked_before: Option<Duration>,
141}
142
143/// What this supervisor holds of one print's planned changes.
144#[derive(Debug, Clone, Default)]
145pub(crate) struct PlannedMemo {
146    /// Every change of the print's reached so far, by index.
147    reached: BTreeSet<u32>,
148    /// The change it is waiting at now.
149    waiting: Option<Waiting>,
150}
151
152/// One print's planned changes as its history records them, newest first.
153fn memo_of(history: &[EventRecord]) -> PlannedMemo {
154    let mut memo = PlannedMemo::default();
155    let mut resumed = BTreeSet::new();
156    for event in history.iter().rev() {
157        if let Some(Ok(reached)) = event.payload_as::<FilamentChangePlannedReachedPayload>() {
158            memo.reached.insert(reached.change.index);
159            memo.waiting = Some(Waiting {
160                reached,
161                since: event.received_at,
162            });
163        } else if let Some(Ok(done)) = event.payload_as::<FilamentChangePlannedResumedPayload>() {
164            resumed.insert(done.change.index);
165        }
166    }
167    memo.waiting = memo
168        .waiting
169        .filter(|waiting| !resumed.contains(&waiting.reached.change.index));
170    memo
171}
172
173/// How long a job read paused at a planned change stands at one position
174/// before that position alone reaches the change: long enough for the
175/// filament-change signal a pause there brings to arrive first, and well inside
176/// the interval between two scheduled checks.
177pub(crate) const PAUSED_AT_CHANGE_STAND: Duration = Duration::from_secs(30);
178
179/// The file position a job read reports for a print, when the job is that
180/// print's file, printing or paused, and reports one.
181fn position_of(print: &PrintRecord, job: &JobSnapshot) -> Option<u64> {
182    let running = matches!(job.state, PrinterState::Printing | PrinterState::Paused);
183    let same_file = print.file_name.is_none() || job.file_name == print.file_name;
184    job.file_position_bytes
185        .filter(|_| running && same_file)
186        .and_then(|bytes| u64::try_from(bytes).ok())
187}
188
189/// Whether an index plans any change.
190fn plans_changes(index: &GcodeIndex) -> bool {
191    index.planned_change(0).is_some()
192}
193
194impl Supervisor {
195    /// The memo of one print's planned changes, read from its history when
196    /// this supervisor holds none and its index, built, plans a change.
197    async fn planned_memo(&self, print_id: PrintId) -> Result<Option<PlannedMemo>, CoreError> {
198        if let Some(memo) = self.planned_memos().get(&print_id) {
199            return Ok(Some(memo.clone()));
200        }
201        let plans = self
202            .gcode_indexes()
203            .built(print_id)
204            .is_some_and(|index| plans_changes(&index));
205        if !plans {
206            return Ok(None);
207        }
208        self.load_planned_memo(print_id).await.map(Some)
209    }
210
211    /// Read one print's planned changes from its history into the memo.
212    async fn load_planned_memo(&self, print_id: PrintId) -> Result<PlannedMemo, CoreError> {
213        let kinds = [
214            FilamentChangePlannedReachedPayload::KIND,
215            FilamentChangePlannedResumedPayload::KIND,
216        ]
217        .into_iter()
218        .filter_map(|kind| EventKind::new(kind).ok())
219        .collect();
220        let history = self
221            .stores()
222            .events
223            .history(HistoryQuery {
224                print_id,
225                kinds,
226                since: None,
227                until: None,
228                limit: Some(MAX_HISTORY_LIMIT),
229            })
230            .await?;
231        let memo = memo_of(&history);
232        self.planned_memos().insert(print_id, memo.clone());
233        Ok(memo)
234    }
235
236    /// Take the change a print waits at from its memo, when it is still the
237    /// one numbered `index`, and mark the check after it begun, so that no
238    /// scheduled check runs while its resumption is being recorded. Nothing
239    /// when another read has claimed it first; otherwise the change and when
240    /// the print's last check after a change had begun, to put back.
241    ///
242    /// Proven against the real server by `tests/skilltest-wiring`'s replay of
243    /// the real two-colour print, whose watch and scheduled check land
244    /// together and which recorded a resumption twice before this claim, and
245    /// by the core journey `reads_past_a_change_at_once_record_its_resumption_once`,
246    /// which holds the write open to force the overlap every time.
247    fn claim_waiting(&self, print_id: PrintId, index: u32) -> Option<Claimed> {
248        let waiting = {
249            let mut memos = self.planned_memos();
250            let memo = memos.get_mut(&print_id)?;
251            if memo
252                .waiting
253                .as_ref()
254                .is_none_or(|waiting| waiting.reached.change.index != index)
255            {
256                return None;
257            }
258            memo.waiting.take()?
259        };
260        let checked_before = self
261            .checked_after_resume
262            .lock()
263            .unwrap_or_else(PoisonError::into_inner)
264            .insert(print_id, self.clock().elapsed());
265        Some(Claimed {
266            waiting,
267            checked_before,
268        })
269    }
270
271    /// Put a claimed change back as the one a print waits at, when recording
272    /// its resumption failed, so that the next read records it instead.
273    ///
274    /// No test drives this through the real server: making its store refuse
275    /// one append mid-resumption would mean building a fault-injecting store
276    /// into the server for this one path. The core journeys
277    /// `a_resumption_the_store_refused_is_recorded_by_the_next_read` (no
278    /// earlier check) and `a_later_refused_resumption_keeps_the_earlier_checks_schedule`
279    /// (an earlier one) drive both arms through the supervisor instead.
280    fn unclaim_waiting(&self, print_id: PrintId, claimed: Claimed) {
281        {
282            let mut checked = self
283                .checked_after_resume
284                .lock()
285                .unwrap_or_else(PoisonError::into_inner);
286            match claimed.checked_before {
287                Some(before) => checked.insert(print_id, before),
288                None => checked.remove(&print_id),
289            };
290        }
291        let mut memos = self.planned_memos();
292        let memo = memos.entry(print_id).or_default();
293        if memo.waiting.is_none() {
294            memo.waiting = Some(claimed.waiting);
295        }
296    }
297
298    /// The memos, held for one read or write.
299    fn planned_memos(&self) -> std::sync::MutexGuard<'_, BTreeMap<PrintId, PlannedMemo>> {
300        self.planned_memos
301            .lock()
302            .unwrap_or_else(PoisonError::into_inner)
303    }
304
305    /// Read every open print's planned changes from the history, as a server
306    /// starts: a print that was waiting at a change when the last one stopped
307    /// is still waiting at it, and is left alone from the first read on.
308    ///
309    /// # Errors
310    ///
311    /// The store's own error when the open prints or a history could not be
312    /// read.
313    pub async fn restore_planned_changes(&self) -> Result<(), CoreError> {
314        for print in self.stores().prints.open_prints().await? {
315            self.load_planned_memo(print.id).await?;
316            self.index_owed
317                .lock()
318                .unwrap_or_else(PoisonError::into_inner)
319                .insert(print.id);
320        }
321        Ok(())
322    }
323
324    /// The planned change one print is waiting at, when it is waiting at one.
325    ///
326    /// # Errors
327    ///
328    /// The store's own error when the print's history had to be read and
329    /// could not be.
330    pub async fn planned_change_waiting(
331        &self,
332        print_id: PrintId,
333    ) -> Result<Option<Waiting>, CoreError> {
334        Ok(self
335            .planned_memo(print_id)
336            .await?
337            .and_then(|memo| memo.waiting))
338    }
339
340    /// One print's planned changes, the one it waits at and the colour
341    /// expected where its job stands, as the status read answers them:
342    /// nothing for a print whose file plans none or could not be read.
343    ///
344    /// # Errors
345    ///
346    /// The store's own error when the print's history could not be read.
347    pub async fn planned_changes(
348        &self,
349        print: &PrintRecord,
350        job: Option<&JobSnapshot>,
351    ) -> Result<Option<PlannedChanges>, CoreError> {
352        if print.ended_at.is_some() {
353            return Ok(None);
354        }
355        let Some(index) = self.print_gcode_index(print.id).await else {
356            return Ok(None);
357        };
358        if !plans_changes(&index) {
359            return Ok(None);
360        }
361        let waiting = self.planned_change_waiting(print.id).await?;
362        let position = job.and_then(|job| position_of(print, job));
363        Ok(Some(PlannedChanges {
364            changes: index.planned_changes(),
365            segments: index.planned_segments(),
366            waiting: waiting.map(|waiting| waiting.reached.change.index),
367            expected_color: position.and_then(|position| {
368                index.expected_color_at(i64::try_from(position).unwrap_or(i64::MAX))
369            }),
370        }))
371    }
372
373    /// Whether a print may be given a supervision turn now: not while it
374    /// waits at a planned change.
375    pub(crate) async fn turns_allowed(&self, print_id: PrintId) -> Result<bool, CoreError> {
376        Ok(self.planned_change_waiting(print_id).await?.is_none())
377    }
378
379    /// Follow one read of a print's job against the changes its file plans:
380    /// record a change it has reached, or one it has carried on from, and
381    /// answer the check carrying on claims.
382    ///
383    /// A print a restart found open, whose index this supervisor has not
384    /// built, has its index built here when `build` asks, once per print: the
385    /// printer watch asks, so a change is reached by position from the first
386    /// read of the job after a restart, with no check or signal to build it
387    /// first. A scheduled check does not, so it is recorded as it begins
388    /// rather than after a whole file is read; it builds the index itself. A
389    /// print this supervisor started is never read here: its index is built
390    /// by its first check, as it always was, so a start whose preflight is off
391    /// reads nothing of its file. A build that fails is left to the next
392    /// check, as every failed build is.
393    ///
394    /// # Errors
395    ///
396    /// The store's own error when what changed could not be recorded.
397    pub(crate) async fn follow_planned_changes(
398        &self,
399        print: &PrintRecord,
400        job: &JobSnapshot,
401        build: bool,
402    ) -> Result<Option<PendingTurn>, CoreError> {
403        let Some(position) = position_of(print, job) else {
404            return Ok(None);
405        };
406        if build
407            && self.gcode_indexes().built(print.id).is_none()
408            && self
409                .index_owed
410                .lock()
411                .unwrap_or_else(PoisonError::into_inner)
412                .remove(&print.id)
413        {
414            // Built or not, the build is the index the next read finds.
415            let _ = self.print_gcode_index(print.id).await;
416        }
417        let Some(memo) = self.planned_memo(print.id).await? else {
418            return Ok(None);
419        };
420        if let Some(waiting) = memo.waiting {
421            let change = &waiting.reached.change;
422            let past_reach =
423                position > change.offset_bytes + crate::gcode_index::PLANNED_CHANGE_REACH_BYTES;
424            if past_reach || self.moved_on_from_the_stand(print.id, change.index, job, position) {
425                // Claimed before the first await, so that of two reads past the
426                // change at once only one records its resumption.
427                let Some(claimed) = self.claim_waiting(print.id, change.index) else {
428                    return Ok(None);
429                };
430                let resumed = self
431                    .resume_planned_change(print, claimed.waiting.clone(), job, position)
432                    .await;
433                if resumed.is_err() {
434                    self.unclaim_waiting(print.id, claimed);
435                }
436                return resumed;
437            }
438            return Ok(None);
439        }
440        let Some(index) = self.gcode_indexes().built(print.id) else {
441            return Ok(None);
442        };
443        let Some(change) = index.change_waiting_at(position).cloned() else {
444            self.forget_paused_at_change(print.id);
445            return Ok(None);
446        };
447        if !memo.reached.contains(&change.index)
448            && (job.state != PrinterState::Paused || self.stood_paused_at(print.id, position))
449        {
450            self.forget_paused_at_change(print.id);
451            self.reach_planned_change(
452                print,
453                &index,
454                change,
455                PlannedChangeTrigger::Position,
456                job,
457                None,
458            )
459            .await?;
460        }
461        Ok(None)
462    }
463
464    /// Whether a job read at a planned change it waits at has moved on from
465    /// the position it was read standing still at, which is how the first read
466    /// after the printer finished the change finds it: see the module's
467    /// "Resumed". Every other read is noted as where the job stands.
468    fn moved_on_from_the_stand(
469        &self,
470        print_id: PrintId,
471        change: u32,
472        job: &JobSnapshot,
473        position: u64,
474    ) -> bool {
475        let now = self.clock().elapsed();
476        let settle = self.config().printer_poll;
477        let mut stood = self
478            .stood_at_change
479            .lock()
480            .unwrap_or_else(PoisonError::into_inner);
481        let fresh = Stand {
482            change,
483            at: position,
484            since: now,
485            still: false,
486        };
487        let Some(stand) = stood
488            .get_mut(&print_id)
489            .filter(|stand| stand.change == change)
490        else {
491            stood.insert(print_id, fresh);
492            return false;
493        };
494        if position == stand.at {
495            stand.still |= now.saturating_sub(stand.since) >= settle;
496            return false;
497        }
498        if position > stand.at && stand.still && job.state != PrinterState::Paused {
499            return true;
500        }
501        *stand = fresh;
502        false
503    }
504
505    /// Note where a job stood as it reached a planned change.
506    fn stand_at_change(&self, print_id: PrintId, change: u32, position: Option<u64>) {
507        let mut stood = self
508            .stood_at_change
509            .lock()
510            .unwrap_or_else(PoisonError::into_inner);
511        match position {
512            Some(at) => {
513                stood.insert(
514                    print_id,
515                    Stand {
516                        change,
517                        at,
518                        since: self.clock().elapsed(),
519                        still: false,
520                    },
521                );
522            }
523            None => {
524                stood.remove(&print_id);
525            }
526        }
527    }
528
529    /// Whether a job read paused at a planned change has stood at this one
530    /// position for [`PAUSED_AT_CHANGE_STAND`], counting from the first such
531    /// read. A pause at the change is when `Obico`'s filament-change signal
532    /// arrives, so the signal reaches it first, and the position reaches it
533    /// alone only when no signal came, as at an `M601`.
534    fn stood_paused_at(&self, print_id: PrintId, position: u64) -> bool {
535        let now = self.clock().elapsed();
536        let mut held = self
537            .paused_at_change
538            .lock()
539            .unwrap_or_else(PoisonError::into_inner);
540        match held.get(&print_id) {
541            Some(&(at, since)) if at == position => {
542                now.saturating_sub(since) >= PAUSED_AT_CHANGE_STAND
543            }
544            _ => {
545                held.insert(print_id, (position, now));
546                false
547            }
548        }
549    }
550
551    /// Forget where a print's job stood paused at a planned change.
552    fn forget_paused_at_change(&self, print_id: PrintId) {
553        self.paused_at_change
554            .lock()
555            .unwrap_or_else(PoisonError::into_inner)
556            .remove(&print_id);
557    }
558
559    /// Whether a job stands paused at a planned change of its print's index:
560    /// reached or not, the print is a person's to change, and no check runs.
561    pub(crate) fn paused_at_planned_change(&self, print: &PrintRecord, job: &JobSnapshot) -> bool {
562        job.state == PrinterState::Paused
563            && position_of(print, job).is_some_and(|position| {
564                self.gcode_indexes()
565                    .built(print.id)
566                    .is_some_and(|index| index.change_waiting_at(position).is_some())
567            })
568    }
569
570    /// Whether a job read paused stands at a planned change it has yet to
571    /// carry on from: one it waits at, or one it stands at and has not
572    /// reached. A pause just past a change it has already carried on from is
573    /// a pause like any other.
574    ///
575    /// # Errors
576    ///
577    /// The store's own error when the print's history had to be read and
578    /// could not be.
579    pub(crate) async fn paused_at_a_change_ahead(
580        &self,
581        print: &PrintRecord,
582        job: &JobSnapshot,
583    ) -> Result<bool, CoreError> {
584        if job.state != PrinterState::Paused {
585            return Ok(false);
586        }
587        let Some(memo) = self.planned_memo(print.id).await? else {
588            return Ok(false);
589        };
590        if memo.waiting.is_some() {
591            return Ok(true);
592        }
593        Ok(position_of(print, job).is_some_and(|position| {
594            self.gcode_indexes().built(print.id).is_some_and(|index| {
595                index
596                    .change_waiting_at(position)
597                    .is_some_and(|change| !memo.reached.contains(&change.index))
598            })
599        }))
600    }
601
602    /// Whether a filament-change signal is one about a planned change: one
603    /// the print is already waiting at, which is answered with nothing more,
604    /// or one the job stands at now, which is recorded reached. Answers
605    /// whether it was, so a signal at no planned change is accounted as every
606    /// unplanned one is.
607    ///
608    /// # Errors
609    ///
610    /// The store's own error when what it reached could not be recorded.
611    pub(crate) async fn signal_at_planned_change(
612        &self,
613        print: &PrintRecord,
614        source_kind: &EventKind,
615    ) -> Result<bool, CoreError> {
616        if self.planned_change_waiting(print.id).await?.is_some() {
617            return Ok(true);
618        }
619        let Some(index) = self.print_gcode_index(print.id).await else {
620            return Ok(false);
621        };
622        if !plans_changes(&index) {
623            return Ok(false);
624        }
625        let Some(memo) = self.planned_memo(print.id).await? else {
626            return Ok(false);
627        };
628        let Ok(job) = self.read_job().await else {
629            return Ok(false);
630        };
631        let Some(change) = position_of(print, &job)
632            .and_then(|position| index.change_waiting_at(position))
633            .filter(|change| !memo.reached.contains(&change.index))
634            .cloned()
635        else {
636            return Ok(false);
637        };
638        self.reach_planned_change(
639            print,
640            &index,
641            change,
642            PlannedChangeTrigger::Signal,
643            &job,
644            Some(source_kind),
645        )
646        .await?;
647        Ok(true)
648    }
649
650    /// Record one planned change reached, and charge the spool feeding it up
651    /// to the change's offset.
652    async fn reach_planned_change(
653        &self,
654        print: &PrintRecord,
655        index: &GcodeIndex,
656        change: PlannedChange,
657        trigger: PlannedChangeTrigger,
658        job: &JobSnapshot,
659        signal_kind: Option<&EventKind>,
660    ) -> Result<(), CoreError> {
661        let now = self.clock().now();
662        let segments = index.planned_segments();
663        let segment = |at: u32| segments.iter().find(|segment| segment.segment == at);
664        let next = change.index + 1;
665        let next_spool_id = self
666            .stores()
667            .prints
668            .manifest(print.id)
669            .await?
670            .and_then(|manifest| {
671                manifest
672                    .segment_spools
673                    .iter()
674                    .find(|named| named.segment == next)
675                    .map(|named| named.spool_id)
676            });
677        let loaded = self.stores().filament.loaded_spools().await?;
678        let offset = i64::try_from(change.offset_bytes).unwrap_or(i64::MAX);
679        let payload = FilamentChangePlannedReachedPayload {
680            previous_color: segment(change.index).and_then(|segment| segment.color.clone()),
681            trigger,
682            position: FilePosition {
683                bytes: job.file_position_bytes.unwrap_or(offset),
684                size_bytes: job.size_bytes.filter(|size| *size > 0),
685                observed_at: now,
686            },
687            spool_id: spool_on_tool(&loaded, 0).map(|spool| spool.id),
688            next_spool_id,
689            next_segment_filament_mm: segment(next).map_or(0.0, |segment| segment.filament_mm),
690            change: change.clone(),
691        };
692        let event = self
693            .append_system_event(print.id, EventBody::of(&payload)?)
694            .await?;
695        {
696            let mut memos = self.planned_memos();
697            let memo = memos.entry(print.id).or_default();
698            memo.reached.insert(change.index);
699            memo.waiting = Some(Waiting {
700                reached: payload,
701                since: event.received_at,
702            });
703        }
704        self.stand_at_change(print.id, change.index, position_of(print, job));
705        let charged_at = FilePosition {
706            bytes: offset,
707            size_bytes: job.size_bytes.filter(|size| *size > 0),
708            observed_at: now,
709        };
710        let source_kind = signal_kind.cloned().unwrap_or_else(|| event.kind().clone());
711        self.charge_filament_change(
712            print,
713            &source_kind,
714            Whereabouts::ReadNow(charged_at),
715            Some(job.clone()),
716            Some(change.index),
717        )
718        .await
719    }
720
721    /// Record a print carried on from the change it waited at, with the
722    /// camera's frame, and claim the check that event is.
723    async fn resume_planned_change(
724        &self,
725        print: &PrintRecord,
726        waiting: Waiting,
727        job: &JobSnapshot,
728        position: u64,
729    ) -> Result<Option<PendingTurn>, CoreError> {
730        let now = self.clock().now();
731        let payload = FilamentChangePlannedResumedPayload {
732            change: waiting.reached.change.clone(),
733            previous_color: waiting.reached.previous_color.clone(),
734            waited_s: seconds_between(waiting.since, now).max(0),
735            position: FilePosition {
736                bytes: i64::try_from(position).unwrap_or(i64::MAX),
737                size_bytes: job.size_bytes.filter(|size| *size > 0),
738                observed_at: now,
739            },
740        };
741        let fetched = self.fetch_configured_frame(Some(print.id)).await;
742        let (fetched, degraded) = match fetched {
743            Some((_, Frame::Degraded(degraded))) => (None, Some(degraded)),
744            fetched => (fetched, None),
745        };
746        let event = self
747            .write_with_frame(Some(print.id), &payload, fetched)
748            .await?;
749        if let Some(degraded) = degraded {
750            self.append_system_event(print.id, EventBody::of(&degraded)?)
751                .await?;
752        }
753        if let Some(memo) = self.planned_memos().get_mut(&print.id) {
754            memo.waiting = None;
755        }
756        if let Some(images) = self.check_images.get() {
757            images.restart_growth(print.id);
758        }
759        self.checked_after_resume
760            .lock()
761            .unwrap_or_else(PoisonError::into_inner)
762            .insert(print.id, self.clock().elapsed());
763        let arrival = Arrival {
764            event,
765            detection: None,
766            frame_captured_at: None,
767            camera_frame: AlertCameraFrame::NotAsked,
768        };
769        Ok(self
770            .inboxes()
771            .claim_or_hand_over(print.id, arrival.clone())
772            .then(|| PendingTurn::new(print.clone(), arrival, Vec::new())))
773    }
774
775    /// Whether a print's scheduled check is due: not until one observation
776    /// interval after the check it was given as it last carried on, from a
777    /// planned change or from a pause.
778    pub(crate) fn observation_due(&self, print_id: PrintId) -> bool {
779        let checked = self
780            .checked_after_resume
781            .lock()
782            .unwrap_or_else(PoisonError::into_inner)
783            .get(&print_id)
784            .copied();
785        checked.is_none_or(|checked| {
786            self.clock().elapsed().saturating_sub(checked) >= self.config().observation_interval
787        })
788    }
789
790    /// How long the periodic observation should wait before its next round:
791    /// one interval, or less when a print's check as it carried on, from a
792    /// planned change or from a pause, makes its next scheduled check due
793    /// sooner.
794    #[must_use]
795    pub fn until_next_observation(&self) -> Duration {
796        let interval = self.config().observation_interval;
797        let now = self.clock().elapsed();
798        self.checked_after_resume
799            .lock()
800            .unwrap_or_else(PoisonError::into_inner)
801            .values()
802            .map(|checked| (*checked + interval).saturating_sub(now))
803            .filter(|left| !left.is_zero())
804            .min()
805            .map_or(interval, |left| left.min(interval))
806    }
807
808    /// Forget what this supervisor holds of a print's planned changes, once
809    /// it has closed.
810    pub(crate) fn forget_planned_changes(&self, print_id: PrintId) {
811        self.planned_memos().remove(&print_id);
812        self.index_owed
813            .lock()
814            .unwrap_or_else(PoisonError::into_inner)
815            .remove(&print_id);
816        self.checked_after_resume
817            .lock()
818            .unwrap_or_else(PoisonError::into_inner)
819            .remove(&print_id);
820        self.stood_at_change
821            .lock()
822            .unwrap_or_else(PoisonError::into_inner)
823            .remove(&print_id);
824        self.forget_pauses(print_id);
825    }
826}