Skip to main content

printobserver_server/
alignment.rs

1//! Each print's first-layer alignment verdict and its camera view: whether the
2//! camera calibration's projection lands on that print's printed first layer,
3//! and the correction every later drawing of the print goes through.
4//!
5//! A projection can be wrong with the camera unmoved, and a camera that has
6//! shifted a little is ordinary on a real printer, so each print judges its
7//! own. Once the print's first object layer is down, every scheduled check's
8//! own stored frame is judged ([`Alignments::judge`]), at most once a check
9//! and with no camera fetch of its own, until one passes: the layer clearly
10//! found, on a frame the toolhead does not cover
11//! ([`printobserver_panels::judge_first_layer`]). A covered or unclear frame
12//! is inconclusive and the next check's is judged again. A check taken while
13//! the printer reports the print paused is not judged: its bed is lowered off
14//! the plan's height. Only a frame of another size or stream fails, and that
15//! holds for the rest of the print.
16//!
17//! A pass puts the print's correction in force, a translation every later
18//! drawing goes through, kept with the landmarks found agreeing on that frame as
19//! its reference. Its translation is the pass's found shift when the frame
20//! stood within one layer of the first layer
21//! ([`printobserver_panels::alignment::correction_shift`]), and none from a
22//! taller frame, where the search scores the part's body. Every later frame's view is judged against that
23//! reference ([`printobserver_panels::judge_found`]); one showing the camera
24//! moved again sets the alignment back to pending, to take a fresh correction
25//! from a later check. Nothing is kept across prints: a sheet sits a few
26//! millimetres apart from one print to the next.
27//!
28//! Every judgement is written into the print's history, naming the stored
29//! frame it was made on ([`crate::judgements`]).
30//!
31//! The verdict is written to `<state_dir>/alignment/<print id>.json` and the
32//! correction, the last inconclusive reason and the last check's image to
33//! `<state_dir>/camera-view/<print id>.json`, so they stand through a restart
34//! while the print is open, and are deleted once the print closes. A verdict
35//! file an earlier release left failed on its offset is read as pending and
36//! judged again.
37//!
38//! Which check draws the toolpath on its image reads the verdict through
39//! [`Alignments::print_alignment`] and draws only for a print that `Passed`.
40//!
41//! Beside each verdict is kept the frame the print's last check was given,
42//! which the next check's image shows as the previous one
43//! ([`Alignments::previous_check`]): written under
44//! `<state_dir>/previous-check/<print id>.json`, standing through a restart
45//! while the print is open, and swept with the verdict once it closes.
46//!
47//! And beside that, the frames of the print's recent checks with the height
48//! the plan had reached at each ([`Alignments::checked_frames`]): written
49//! under `<state_dir>/checked-frames/<print id>.json`, kept and swept the same
50//! way, so that a check can measure whether the parts grew since one far
51//! enough below it ([`Alignments::growth_reference`]).
52
53use std::path::{Path, PathBuf};
54use std::sync::Arc;
55use std::time::Duration;
56
57use printobserver_core::PlanPosition;
58use printobserver_core::store::PrintStore;
59use printobserver_panels::{
60    AlignmentInputs, CameraCalibration, ComposeError, FirstLayerInputs, FirstLayerVerdict,
61    FrameField, InconclusiveReason, ReferenceLandmark, ViewCorrection, ViewJudgement, ViewOutcome,
62    judge_first_layer, judge_found, landmarks_in_frame,
63};
64use printobserver_supervisor_api::{ImageFallback, ImageKind};
65use printobserver_types::contract::Sample;
66use printobserver_types::schemars::JsonSchema;
67use printobserver_types::serde::{Deserialize, Serialize};
68use printobserver_types::{EventBody, EventPayload, PrintId, Timestamp};
69
70/// Why a print's alignment failed.
71#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
72#[serde(
73    crate = "printobserver_types::serde",
74    tag = "failure",
75    rename_all = "snake_case"
76)]
77#[schemars(crate = "printobserver_types::schemars")]
78pub enum AlignmentFailure {
79    /// The printed first layer lies further from its projection than the
80    /// calibration allows. No longer written: a frame that does not clearly
81    /// find the layer is inconclusive, and a verdict file an earlier release
82    /// left holding this is read as pending.
83    Offset {
84        /// How far, in calibration pixels.
85        offset_px: f64,
86    },
87    /// The camera's frames are not the calibration's resolution.
88    Resolution {
89        /// The calibration's, `[width, height]`.
90        expected: [u32; 2],
91        /// The frame's.
92        got: [u32; 2],
93    },
94    /// The camera configured is not the stream the calibration was fitted on.
95    Stream,
96}
97
98/// One print's first-layer alignment verdict, as it is kept under the state
99/// directory — which the real-print suite's record reads.
100#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
101#[serde(
102    crate = "printobserver_types::serde",
103    tag = "verdict",
104    rename_all = "snake_case"
105)]
106#[schemars(crate = "printobserver_types::schemars")]
107pub enum PrintAlignment {
108    /// Nothing can be checked: no calibration is configured, or the print's
109    /// G-code lays no object.
110    Unavailable,
111    /// The first object layer is not down yet, or no frame of it has been
112    /// judged.
113    Pending,
114    /// The projected first layer lands on the printed one.
115    Passed {
116        /// How far it lies from it, in calibration pixels.
117        offset_px: f64,
118        /// The first-layer correction applied to every later drawing of the
119        /// print, `[dx, dy]` calibration pixels: the shift the layer was found
120        /// at. `[0, 0]` in a verdict an earlier release wrote.
121        #[serde(default)]
122        correction_px: [f64; 2],
123    },
124    /// It does not, or the frames cannot be judged against the calibration.
125    Failed {
126        /// Why.
127        reason: AlignmentFailure,
128    },
129}
130
131impl Sample for PrintAlignment {
132    fn sample_full() -> Self {
133        Self::Passed {
134            offset_px: 14.6,
135            correction_px: [14.0, 4.0],
136        }
137    }
138
139    fn sample_minimal() -> Self {
140        Self::Pending
141    }
142
143    fn sample_alternates() -> Vec<Self> {
144        vec![
145            Self::Unavailable,
146            Self::Failed {
147                reason: AlignmentFailure::Offset { offset_px: 48.5 },
148            },
149            Self::Failed {
150                reason: AlignmentFailure::Resolution {
151                    expected: [1920, 1080],
152                    got: [1280, 720],
153                },
154            },
155            Self::Failed {
156                reason: AlignmentFailure::Stream,
157            },
158        ]
159    }
160}
161
162/// The frame one print's last check was given, and when it was captured.
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
164#[serde(crate = "printobserver_types::serde")]
165pub struct PreviousCheck {
166    /// The stored frame's path.
167    pub frame: PathBuf,
168    /// When it was captured.
169    pub captured_at: printobserver_types::Timestamp,
170}
171
172/// One check's frame and the height the plan had reached as it was captured.
173#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
174#[serde(crate = "printobserver_types::serde")]
175pub struct CheckedFrame {
176    /// The stored frame's path.
177    pub frame: PathBuf,
178    /// When it was captured.
179    pub captured_at: printobserver_types::Timestamp,
180    /// The print's height in its plan then, in millimetres.
181    pub print_z_mm: f64,
182}
183
184/// The most checked frames one print keeps; past it the oldest are dropped.
185const MAX_CHECKED_FRAMES: usize = 512;
186
187/// The alignment verdicts of every print, what decides them, the frame each
188/// print's last check was given, and its recent checks' frames and heights.
189pub struct Alignments {
190    /// Where each print's verdict is kept.
191    directory: PathBuf,
192    /// Where each print's last check's frame is named.
193    previous_directory: PathBuf,
194    /// Where each print's recent checks' frames and heights are kept.
195    checked_directory: PathBuf,
196    /// Where each print's correction, last inconclusive reason and last
197    /// check's image are kept.
198    view_directory: PathBuf,
199    /// The camera's calibration, when one is configured.
200    calibration: Option<Arc<CameraCalibration>>,
201    /// The prints, to tell which are open.
202    prints: Arc<dyn PrintStore>,
203}
204
205impl core::fmt::Debug for Alignments {
206    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
207        formatter
208            .debug_struct("Alignments")
209            .field("directory", &self.directory)
210            .field("calibrated", &self.calibration.is_some())
211            .finish_non_exhaustive()
212    }
213}
214
215/// The directory verdicts are kept in, under a state directory.
216#[must_use]
217pub fn verdict_dir(state_dir: &Path) -> PathBuf {
218    state_dir.join("alignment")
219}
220
221/// The directory each print's last check's frame is named in, under a state
222/// directory.
223#[must_use]
224pub fn previous_check_dir(state_dir: &Path) -> PathBuf {
225    state_dir.join("previous-check")
226}
227
228/// The directory each print's recent checks' frames and heights are kept in,
229/// under a state directory.
230#[must_use]
231pub fn checked_frames_dir(state_dir: &Path) -> PathBuf {
232    state_dir.join("checked-frames")
233}
234
235/// The directory each print's correction, last inconclusive reason and last
236/// check's image are kept in, under a state directory.
237#[must_use]
238pub fn camera_view_dir(state_dir: &Path) -> PathBuf {
239    state_dir.join("camera-view")
240}
241
242impl Alignments {
243    /// The verdicts kept under one state directory.
244    ///
245    /// # Errors
246    ///
247    /// The filesystem's own error when the directory cannot be made.
248    pub fn new(
249        state_dir: &Path,
250        calibration: Option<Arc<CameraCalibration>>,
251        prints: Arc<dyn PrintStore>,
252    ) -> std::io::Result<Self> {
253        let directory = verdict_dir(state_dir);
254        std::fs::create_dir_all(&directory)?;
255        let previous_directory = previous_check_dir(state_dir);
256        std::fs::create_dir_all(&previous_directory)?;
257        let checked_directory = checked_frames_dir(state_dir);
258        std::fs::create_dir_all(&checked_directory)?;
259        let view_directory = camera_view_dir(state_dir);
260        std::fs::create_dir_all(&view_directory)?;
261        Ok(Self {
262            directory,
263            previous_directory,
264            checked_directory,
265            view_directory,
266            calibration,
267            prints,
268        })
269    }
270
271    /// Where one print's verdict is kept.
272    fn path_of(&self, print_id: PrintId) -> PathBuf {
273        self.directory.join(format!("{print_id}.json"))
274    }
275
276    /// The camera calibration in force, when one is configured.
277    #[must_use]
278    pub fn calibration(&self) -> Option<&CameraCalibration> {
279        self.calibration.as_deref()
280    }
281
282    /// Where one print's last check's frame is named.
283    fn previous_path_of(&self, print_id: PrintId) -> PathBuf {
284        self.previous_directory.join(format!("{print_id}.json"))
285    }
286
287    /// The frame one print's last check was given; nothing before its first
288    /// check, or when the record cannot be read back.
289    #[must_use]
290    pub fn previous_check(&self, print_id: PrintId) -> Option<PreviousCheck> {
291        std::fs::read(self.previous_path_of(print_id))
292            .ok()
293            .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
294    }
295
296    /// Name the frame one print's check was given, which its next check shows
297    /// as the previous. A record the filesystem refuses for a moment is
298    /// replaced once the refusal passes ([`replace_file`]); one it goes on
299    /// refusing is said on the log and leaves the record before it standing,
300    /// so the next check shows an older frame as the previous rather than
301    /// none. No test makes the refusal last: that needs the state directory
302    /// made to refuse writes beneath a running server, which refuses the
303    /// store's own writes first. What a check makes of a record it cannot use
304    /// — an empty panel 3 — is proved by
305    /// `a_lost_previous_frame_empties_panel_3_and_the_record_goes_with_the_print`.
306    pub fn record_check(&self, print_id: PrintId, check: &PreviousCheck) {
307        let Ok(bytes) = printobserver_types::serde_json::to_vec(check) else {
308            return;
309        };
310        if let Err(error) = replace_file(&self.previous_path_of(print_id), &bytes) {
311            eprintln!(
312                "printobserver: print {print_id}: the last check's frame could not be recorded, so the next check shows an older one or none: {error}"
313            );
314        }
315    }
316
317    /// Where one print's recent checks' frames and heights are kept.
318    fn checked_path_of(&self, print_id: PrintId) -> PathBuf {
319        self.checked_directory.join(format!("{print_id}.json"))
320    }
321
322    /// One print's recent checks' frames and heights, oldest first; none
323    /// before its first check with a height, or when the record cannot be
324    /// read back.
325    #[must_use]
326    pub fn checked_frames(&self, print_id: PrintId) -> Vec<CheckedFrame> {
327        std::fs::read(self.checked_path_of(print_id))
328            .ok()
329            .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
330            .unwrap_or_default()
331    }
332
333    /// Forget one print's checked frames, so its growth is measured only from
334    /// checks made after now: the print waited at a planned change, and a frame
335    /// from before the wait would count the wait as no growth. A record the
336    /// filesystem will not remove is said on the log and left, so a later check
337    /// measures from a frame before the wait, which says no more than that a
338    /// check could not tell.
339    pub fn restart_growth(&self, print_id: PrintId) {
340        let path = self.checked_path_of(print_id);
341        if let Err(error) = std::fs::remove_file(&path)
342            && error.kind() != std::io::ErrorKind::NotFound
343        {
344            eprintln!(
345                "printobserver: print {print_id}: its checked frames could not be forgotten after a planned change, so a later check may measure growth across the wait: {error}"
346            );
347        }
348    }
349
350    /// The frame a check at `print_z_mm` measures growth from: the newest
351    /// checked frame of the print at least `rise_mm` below it in the plan.
352    #[must_use]
353    pub fn growth_reference(
354        &self,
355        print_id: PrintId,
356        print_z_mm: f64,
357        rise_mm: f64,
358    ) -> Option<CheckedFrame> {
359        reference_in(&self.checked_frames(print_id), print_z_mm, rise_mm).cloned()
360    }
361
362    /// Keep one check's frame and height among the print's, keeping only what
363    /// a later check at `rise_mm` above some kept height can still measure
364    /// from: the newest frame at least that far below this one and every
365    /// frame after it. A height below the last kept one is a plan that went
366    /// back down, as a print of one object after another does, and starts the
367    /// record again. A record the filesystem refuses is said on the log and
368    /// leaves the one before standing, as [`record_check`](Self::record_check)
369    /// does.
370    pub fn record_checked_frame(&self, print_id: PrintId, checked: CheckedFrame, rise_mm: f64) {
371        let kept = kept_with(self.checked_frames(print_id), checked, rise_mm);
372        let Ok(bytes) = printobserver_types::serde_json::to_vec(&kept) else {
373            return;
374        };
375        if let Err(error) = replace_file(&self.checked_path_of(print_id), &bytes) {
376            eprintln!(
377                "printobserver: print {print_id}: a check's frame and height could not be recorded, so a later check measures growth from an older one or none: {error}"
378            );
379        }
380    }
381
382    /// One print's verdict as it stands.
383    #[must_use]
384    pub fn print_alignment(&self, print_id: PrintId) -> PrintAlignment {
385        if self.calibration.is_none() {
386            return PrintAlignment::Unavailable;
387        }
388        match std::fs::read(self.path_of(print_id))
389            .ok()
390            .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
391        {
392            // A failure on the offset is what an earlier release wrote for a
393            // frame that did not find the layer, which is now inconclusive.
394            Some(PrintAlignment::Failed {
395                reason: AlignmentFailure::Offset { .. },
396            })
397            | None => PrintAlignment::Pending,
398            Some(verdict) => verdict,
399        }
400    }
401
402    /// Where one print's camera view is kept.
403    fn view_path_of(&self, print_id: PrintId) -> PathBuf {
404        self.view_directory.join(format!("{print_id}.json"))
405    }
406
407    /// One print's camera view as it stands: nothing kept before its first
408    /// judgement, or when the record cannot be read back.
409    fn view_state(&self, print_id: PrintId) -> CameraViewState {
410        std::fs::read(self.view_path_of(print_id))
411            .ok()
412            .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
413            .unwrap_or_default()
414    }
415
416    /// Keep one print's camera view. A record the filesystem refuses is said
417    /// on the log and leaves the one before standing, as
418    /// [`record_check`](Self::record_check) does.
419    fn keep_view_state(&self, print_id: PrintId, state: &CameraViewState) {
420        let Ok(bytes) = printobserver_types::serde_json::to_vec(state) else {
421            return;
422        };
423        if let Err(error) = replace_file(&self.view_path_of(print_id), &bytes) {
424            eprintln!(
425                "printobserver: print {print_id}: its camera view could not be recorded, so a later check reads the one before: {error}"
426            );
427        }
428    }
429
430    /// Keep a verdict, and say it. A verdict the filesystem goes on refusing
431    /// ([`replace_file`]) is said on the log and leaves the one before
432    /// standing, so the next check judges again from it.
433    fn decide(&self, print_id: PrintId, verdict: &PrintAlignment) {
434        let Ok(bytes) = printobserver_types::serde_json::to_vec(verdict) else {
435            return;
436        };
437        match replace_file(&self.path_of(print_id), &bytes) {
438            Ok(()) => eprintln!(
439                "printobserver: print {print_id}: first-layer alignment {}",
440                said(verdict)
441            ),
442            Err(error) => eprintln!(
443                "printobserver: print {print_id}: first-layer alignment {} could not be recorded: {error}",
444                said(verdict)
445            ),
446        }
447    }
448
449    /// The correction in force for one print: the camera check's it started
450    /// under, when it started under one; else the one its last pass took, or,
451    /// for a pass an earlier release recorded with no reference, its
452    /// correction held against the calibration's own landmarks where it
453    /// placed them. Nothing unless the print's alignment passed.
454    #[must_use]
455    pub fn correction_in_force(&self, print_id: PrintId) -> Option<ViewCorrection> {
456        let calibration = self.calibration.as_deref()?;
457        if let Some(checked) = self.view_state(print_id).camera_check {
458            return Some(checked.correction);
459        }
460        let PrintAlignment::Passed { correction_px, .. } = self.print_alignment(print_id) else {
461            return None;
462        };
463        Some(self.view_state(print_id).correction.unwrap_or_else(|| {
464            ViewCorrection::translation(
465                correction_px,
466                calibration
467                    .landmarks
468                    .iter()
469                    .map(|landmark| ReferenceLandmark {
470                        name: landmark.name.clone(),
471                        offset_px: [0.0, 0.0],
472                        score: 1.0,
473                    })
474                    .collect(),
475            )
476        }))
477    }
478
479    /// Keep the camera check a print started under, from its record, so every
480    /// check of the print is drawn through its correction from now on: once,
481    /// on the first check handed it. A record that is no `aligned` check
482    /// carrying a correction — which a start refuses to name — puts nothing in
483    /// force.
484    pub fn adopt_camera_check(&self, print_id: PrintId, record: &printobserver_types::EventRecord) {
485        let mut state = self.view_state(print_id);
486        let Some(Ok(payload)) = record.payload_as::<crate::camera_check::CameraCheckedPayload>()
487        else {
488            return;
489        };
490        let check = payload.camera_check;
491        if state
492            .camera_check
493            .as_ref()
494            .is_some_and(|kept| kept.id == check.id)
495        {
496            return;
497        }
498        let (printobserver_core::CameraCheckVerdict::Aligned, Some(correction)) =
499            (check.verdict, check.correction)
500        else {
501            return;
502        };
503        eprintln!(
504            "printobserver: print {print_id}: drawn through camera check {} from its first check, corrected by [{:.1}, {:.1}] px",
505            check.id,
506            correction.shift_px()[0],
507            correction.shift_px()[1]
508        );
509        state.camera_check = Some(CheckedCamera {
510            id: check.id,
511            correction,
512        });
513        self.keep_view_state(print_id, &state);
514    }
515
516    /// Whether a print is drawn through the camera check it started under.
517    #[must_use]
518    pub fn started_under_a_camera_check(&self, print_id: PrintId) -> bool {
519        self.view_state(print_id).camera_check.is_some()
520    }
521
522    /// Why the print's alignment was last left pending, when the frame judged
523    /// last was inconclusive.
524    #[must_use]
525    pub fn inconclusive(&self, print_id: PrintId) -> Option<InconclusiveReason> {
526        self.view_state(print_id).inconclusive
527    }
528
529    /// The image the print's last check was shown, and when its frame was
530    /// captured; nothing before its first check.
531    #[must_use]
532    pub fn last_check_image(&self, print_id: PrintId) -> Option<LastCheckImage> {
533        self.view_state(print_id).last_check_image
534    }
535
536    /// Keep the image one check of a print was shown, and answer the change
537    /// notice owed for it: on the print's first check image, and whenever its
538    /// kind or its fallback's code differs from the last one kept.
539    #[must_use]
540    pub fn note_check_image(
541        &self,
542        print_id: PrintId,
543        shown: LastCheckImage,
544        frame_sha256: &str,
545    ) -> Option<EventBody> {
546        let mut state = self.view_state(print_id);
547        let code = |image: &LastCheckImage| image.fallback.as_ref().map(|fallback| fallback.code);
548        let changed = state
549            .last_check_image
550            .as_ref()
551            .is_none_or(|last| last.kind != shown.kind || code(last) != code(&shown));
552        let notice = changed.then(|| {
553            body_of(&crate::judgements::CheckImageChangedPayload {
554                kind: shown.kind,
555                fallback: shown.fallback.clone(),
556                frame_sha256: frame_sha256.to_owned(),
557            })
558        });
559        state.last_check_image = Some(shown);
560        self.keep_view_state(print_id, &state);
561        notice.flatten()
562    }
563
564    /// Judge one frame of a print — its view always, and its first-layer
565    /// alignment when `judging` asks and the alignment is due — keeping what
566    /// the judgement decided and answering it with the records to append.
567    ///
568    /// The alignment is due on a frame of the configured camera once the
569    /// plan has passed the print's first object layer: while it is pending,
570    /// for [`AlignmentJudging::WhilePending`], and whatever it stands at for
571    /// [`AlignmentJudging::Afresh`], a latched failure included. A frame whose
572    /// view shows the camera moved again since the correction in force was
573    /// taken sets the alignment back to pending, and is not judged for it: a
574    /// later check's frame takes the fresh correction.
575    ///
576    /// Nothing is judged without a calibration, and a frame that is no JPEG is
577    /// answered as such, with nothing recorded.
578    #[must_use]
579    pub fn judge(&self, print_id: PrintId, judging: &Judging<'_>) -> Judged {
580        let Some(calibration) = self.calibration.as_deref() else {
581            return Judged::unjudged(PrintAlignment::Unavailable);
582        };
583        let mut judged = Judged::unjudged(self.print_alignment(print_id));
584        let mut state = self.view_state(print_id);
585        let in_force = self.correction_in_force(print_id);
586        let sha = judging.frame_sha256;
587        let landmarks = match landmarks_in_frame(
588            calibration,
589            judging.frame_jpeg,
590            judging.camera_snapshot_url,
591        ) {
592            Ok(landmarks) => landmarks,
593            Err(error @ ComposeError::FrameMismatch { .. }) => {
594                return self.mismatched(print_id, calibration, &error, judging, in_force, judged);
595            }
596            Err(error) => {
597                judged.unreadable = Some(error.to_string());
598                return judged;
599            }
600        };
601        // A plan laying no object leaves nothing a frame could be judged
602        // against: the verdict file says so, and records nothing.
603        if judging.alignment != AlignmentJudging::Never
604            && judged.alignment == PrintAlignment::Pending
605            && judging
606                .plan
607                .is_some_and(|plan| plan.index.first_object_layer().is_none())
608        {
609            judged.alignment = PrintAlignment::Unavailable;
610            self.decide(print_id, &judged.alignment);
611        }
612        if let Some(checked) = state.camera_check.clone() {
613            return self.judge_under_check(
614                print_id,
615                calibration,
616                landmarks,
617                judging,
618                &checked,
619                &mut state,
620                judged,
621            );
622        }
623        let due = Self::alignment_due(&judged.alignment, judging);
624        let view = match (due, &judged.alignment) {
625            (None, PrintAlignment::Passed { .. }) => {
626                let view = judge_found(calibration, landmarks, in_force.as_ref());
627                if view.outcome == ViewOutcome::ViewRefitRejected {
628                    judged.alignment = PrintAlignment::Pending;
629                    self.decide(print_id, &judged.alignment);
630                    state.correction = None;
631                    state.inconclusive = None;
632                    self.keep_view_state(print_id, &state);
633                    judged.rejected.clone_from(&view.reason);
634                } else {
635                    judged.correction.clone_from(&in_force);
636                }
637                judged
638                    .records
639                    .extend(view_record(sha, &view, in_force.clone()));
640                view
641            }
642            (Some(first), _) => self.judge_alignment(
643                print_id,
644                calibration,
645                landmarks,
646                &first,
647                judging,
648                in_force,
649                &mut state,
650                &mut judged,
651            ),
652            (None, _) => {
653                let view = judge_found(calibration, landmarks, None);
654                judged.records.extend(view_record(sha, &view, None));
655                view
656            }
657        };
658        judged.inconclusive = state.inconclusive;
659        judged.view = Some((view.outcome, view.reason));
660        judged
661    }
662
663    /// What a frame of another size or stream than the calibration's
664    /// decides: its view refused, and — when the alignment is due on it — a
665    /// failure the rest of the print holds to.
666    fn mismatched(
667        &self,
668        print_id: PrintId,
669        calibration: &CameraCalibration,
670        error: &ComposeError,
671        judging: &Judging<'_>,
672        in_force: Option<ViewCorrection>,
673        mut judged: Judged,
674    ) -> Judged {
675        let sha = judging.frame_sha256;
676        let reason = error.to_string();
677        judged
678            .records
679            .extend(body_of(&crate::judgements::CameraViewJudgedPayload {
680                schema_version: crate::judgements::CAMERA_VIEW_JUDGED_SCHEMA_VERSION,
681                frame_sha256: sha.to_owned(),
682                outcome: ViewOutcome::FrameMismatch,
683                view_correction: in_force.clone(),
684                reason: Some(reason.clone()),
685                landmarks: Vec::new(),
686                residual_px: None,
687            }));
688        if Self::alignment_due(&judged.alignment, judging).is_some() {
689            let failure = failure_of(error, calibration);
690            judged.records.extend(body_of(
691                &crate::judgements::FirstLayerAlignmentJudgedPayload {
692                    verdict: crate::judgements::AlignmentJudgedVerdict::Failed,
693                    offset_px: None,
694                    correction_px: None,
695                    match_strength: None,
696                    reason: failure_sentence(&failure),
697                    frame_sha256: sha.to_owned(),
698                    view_correction: in_force.clone(),
699                },
700            ));
701            judged.alignment = PrintAlignment::Failed { reason: failure };
702            self.decide(print_id, &judged.alignment);
703            let mut state = self.view_state(print_id);
704            state.correction = None;
705            state.inconclusive = None;
706            self.keep_view_state(print_id, &state);
707        }
708        judged.correction = in_force.filter(|_| judged.alignment.passed());
709        judged.mismatch = Some(reason);
710        judged
711    }
712
713    /// Judge one frame of a print started under a camera check: its view
714    /// against the check's reference, and, when it is due, its first layer —
715    /// recorded, and kept as the print's verdict, but neither gating the
716    /// drawing nor taking it away. On the 2026-11-28 print the first-layer
717    /// search scored the toolhead at 46.04 and 42.38 px from a box the
718    /// calibration drew within 2 px, so its offset is no evidence the camera
719    /// moved. Only landmarks moved again beyond the check's reference refuse
720    /// the drawing.
721    #[expect(
722        clippy::too_many_arguments,
723        reason = "the one judgement's inputs and the two records it updates"
724    )]
725    fn judge_under_check(
726        &self,
727        print_id: PrintId,
728        calibration: &CameraCalibration,
729        landmarks: Vec<printobserver_panels::FoundLandmark>,
730        judging: &Judging<'_>,
731        checked: &CheckedCamera,
732        state: &mut CameraViewState,
733        mut judged: Judged,
734    ) -> Judged {
735        let sha = judging.frame_sha256;
736        if let Some(first) = Self::alignment_due(&judged.alignment, judging) {
737            self.record_first_layer(
738                print_id,
739                calibration,
740                &first,
741                judging,
742                checked,
743                state,
744                &mut judged,
745            );
746        }
747        let view = judge_found(calibration, landmarks, Some(&checked.correction));
748        if view.outcome == ViewOutcome::ViewRefitRejected {
749            judged.rejected.clone_from(&view.reason);
750        } else if view.outcome.drawable() {
751            judged.correction = Some(checked.correction.clone());
752        }
753        judged
754            .records
755            .extend(body_of(&crate::judgements::CameraViewJudgedPayload::of(
756                sha,
757                &view,
758                Some(checked.correction.clone()),
759                view.reason.clone(),
760            )));
761        judged.camera_check = Some(checked.id);
762        judged.inconclusive = state.inconclusive;
763        judged.view = Some((view.outcome, view.reason));
764        judged
765    }
766
767    /// Judge the first layer of a print started under a camera check, and keep
768    /// what it found as the print's verdict, leaving the check's correction in
769    /// force whatever it found.
770    #[expect(
771        clippy::too_many_arguments,
772        reason = "the one judgement's inputs and the two records it updates"
773    )]
774    fn record_first_layer(
775        &self,
776        print_id: PrintId,
777        calibration: &CameraCalibration,
778        first: &DueAlignment,
779        judging: &Judging<'_>,
780        checked: &CheckedCamera,
781        state: &mut CameraViewState,
782        judged: &mut Judged,
783    ) {
784        let Ok(judgement) = judge_first_layer(&FirstLayerInputs {
785            alignment: AlignmentInputs {
786                frame_jpeg: judging.frame_jpeg,
787                camera_snapshot_url: judging.camera_snapshot_url,
788                first_layer: &first.first_layer,
789                print_z_mm: first.print_z_mm,
790                calibration,
791            },
792            nozzle_xy_mm: first.nozzle_xy_mm,
793        }) else {
794            // The frame was decoded and held to the calibration already, so no
795            // refusal is reached here; one that is is judged again next check.
796            return;
797        };
798        let found = judgement.found;
799        let shift = |found: &printobserver_panels::AlignmentVerdict| {
800            printobserver_panels::alignment::correction_shift(
801                found,
802                &first.first_layer,
803                first.print_z_mm,
804            )
805        };
806        let (verdict, reason) = match judgement.verdict {
807            FirstLayerVerdict::Passed => (
808                crate::judgements::AlignmentJudgedVerdict::Passed,
809                "clearly_found".to_owned(),
810            ),
811            FirstLayerVerdict::Inconclusive(why) => (
812                crate::judgements::AlignmentJudgedVerdict::Inconclusive,
813                why.as_str().to_owned(),
814            ),
815        };
816        judged.records.extend(body_of(
817            &crate::judgements::FirstLayerAlignmentJudgedPayload {
818                verdict,
819                offset_px: found.map(|found| found.offset_px),
820                correction_px: (judgement.verdict == FirstLayerVerdict::Passed)
821                    .then(|| found.as_ref().map(shift))
822                    .flatten(),
823                match_strength: found.map(|found| found.match_strength),
824                reason,
825                frame_sha256: judging.frame_sha256.to_owned(),
826                view_correction: Some(checked.correction.clone()),
827            },
828        ));
829        match (judgement.verdict, found) {
830            (FirstLayerVerdict::Passed, Some(found)) => {
831                judged.alignment = PrintAlignment::Passed {
832                    offset_px: found.offset_px,
833                    correction_px: shift(&found),
834                };
835                state.inconclusive = None;
836            }
837            (FirstLayerVerdict::Inconclusive(why), _) => {
838                judged.alignment = PrintAlignment::Pending;
839                state.inconclusive = Some(why);
840            }
841            (FirstLayerVerdict::Passed, None) => return,
842        }
843        self.decide(print_id, &judged.alignment);
844        self.keep_view_state(print_id, state);
845    }
846
847    /// Judge the first layer on a frame it is due on, and the frame's view
848    /// against what that leaves in force.
849    #[expect(
850        clippy::too_many_arguments,
851        reason = "the one judgement's inputs and the two records it updates"
852    )]
853    fn judge_alignment(
854        &self,
855        print_id: PrintId,
856        calibration: &CameraCalibration,
857        landmarks: Vec<printobserver_panels::FoundLandmark>,
858        first: &DueAlignment,
859        judging: &Judging<'_>,
860        in_force: Option<ViewCorrection>,
861        state: &mut CameraViewState,
862        judged: &mut Judged,
863    ) -> ViewJudgement {
864        let sha = judging.frame_sha256;
865        let uncorrected = judge_found(calibration, landmarks.clone(), None);
866        let judgement = judge_first_layer(&FirstLayerInputs {
867            alignment: AlignmentInputs {
868                frame_jpeg: judging.frame_jpeg,
869                camera_snapshot_url: judging.camera_snapshot_url,
870                first_layer: &first.first_layer,
871                print_z_mm: first.print_z_mm,
872                calibration,
873            },
874            nozzle_xy_mm: first.nozzle_xy_mm,
875        });
876        let Ok(judgement) = judgement else {
877            // The frame was decoded and held to the calibration above, so no
878            // refusal is reached here; one that is leaves the alignment as it
879            // stood, judged again on the next check's frame.
880            judged.records.extend(view_record(sha, &uncorrected, None));
881            return uncorrected;
882        };
883        let found = judgement.found;
884        let (verdict, correction_px, reason) = match judgement.verdict {
885            FirstLayerVerdict::Passed => (
886                crate::judgements::AlignmentJudgedVerdict::Passed,
887                found.map(|found| {
888                    printobserver_panels::alignment::correction_shift(
889                        &found,
890                        &first.first_layer,
891                        first.print_z_mm,
892                    )
893                }),
894                "clearly_found".to_owned(),
895            ),
896            FirstLayerVerdict::Inconclusive(why) => (
897                crate::judgements::AlignmentJudgedVerdict::Inconclusive,
898                None,
899                why.as_str().to_owned(),
900            ),
901        };
902        judged.records.extend(body_of(
903            &crate::judgements::FirstLayerAlignmentJudgedPayload {
904                verdict,
905                offset_px: found.map(|found| found.offset_px),
906                correction_px,
907                match_strength: found.map(|found| found.match_strength),
908                reason,
909                frame_sha256: sha.to_owned(),
910                view_correction: in_force,
911            },
912        ));
913        match (judgement.verdict, found) {
914            (FirstLayerVerdict::Passed, Some(found)) => {
915                let shift = printobserver_panels::alignment::correction_shift(
916                    &found,
917                    &first.first_layer,
918                    first.print_z_mm,
919                );
920                eprintln!(
921                    "printobserver: print {print_id}: the first layer was found shifted [{:.0}, {:.0}] px at Z {:.2}, at a contrast of {:.1}; corrected by [{:.0}, {:.0}] px",
922                    found.shift_px[0],
923                    found.shift_px[1],
924                    first.print_z_mm,
925                    found.match_strength,
926                    shift[0],
927                    shift[1]
928                );
929                let correction = ViewCorrection::translation(shift, uncorrected.agreeing());
930                judged.alignment = PrintAlignment::Passed {
931                    offset_px: found.offset_px,
932                    correction_px: shift,
933                };
934                self.decide(print_id, &judged.alignment);
935                state.correction = Some(correction.clone());
936                state.inconclusive = None;
937                self.keep_view_state(print_id, state);
938                if uncorrected.moved(calibration) {
939                    judged
940                        .records
941                        .extend(body_of(&crate::judgements::CameraViewRefitPayload {
942                            frame_sha256: sha.to_owned(),
943                            view_correction: correction.clone(),
944                        }));
945                }
946                let view = judge_found(calibration, landmarks, Some(&correction));
947                judged
948                    .records
949                    .extend(view_record(sha, &view, Some(correction.clone())));
950                judged.correction = Some(correction);
951                view
952            }
953            (FirstLayerVerdict::Inconclusive(why), _) => {
954                // Written even when it was pending already: a reader of the
955                // verdict file learns a frame was judged.
956                judged.alignment = PrintAlignment::Pending;
957                self.decide(print_id, &judged.alignment);
958                state.correction = None;
959                state.inconclusive = Some(why);
960                self.keep_view_state(print_id, state);
961                judged.records.extend(view_record(sha, &uncorrected, None));
962                uncorrected
963            }
964            (FirstLayerVerdict::Passed, None) => {
965                judged.records.extend(view_record(sha, &uncorrected, None));
966                uncorrected
967            }
968        }
969    }
970
971    /// The first layer a frame's judgement scores, when the alignment is due
972    /// on it; nothing otherwise.
973    fn alignment_due(alignment: &PrintAlignment, judging: &Judging<'_>) -> Option<DueAlignment> {
974        let asked = match judging.alignment {
975            AlignmentJudging::Never => false,
976            AlignmentJudging::WhilePending => *alignment == PrintAlignment::Pending,
977            AlignmentJudging::Afresh => true,
978        };
979        if !asked {
980            return None;
981        }
982        let plan = judging.plan?;
983        let index = &plan.index;
984        let position = plan.file_position_bytes;
985        let (first, ends) = index.first_object_layer()?;
986        if position <= ends {
987            return None;
988        }
989        Some(DueAlignment {
990            first_layer: index.layer_toolpath(first).ok()?,
991            print_z_mm: index
992                .layer_at(position)
993                .and_then(|layer| index.layer_z_mm(layer))?,
994            nozzle_xy_mm: index.planned_head_at(position).ok().flatten(),
995        })
996    }
997
998    /// Delete the verdict, the last check's record, the checked frames and the
999    /// camera view of every print that is not open.
1000    ///
1001    /// An open print's record still being written — the `.json.part` beside it
1002    /// that [`replace_file`] renames over it — is its own, and kept: the watch
1003    /// sweeps after every read, so a sweep removing it between the write and the
1004    /// rename lost that record, and the print's next check showed no previous
1005    /// frame.
1006    ///
1007    /// A store that cannot list the open prints, a directory that cannot be
1008    /// listed and a file that cannot be removed each leave a verdict behind,
1009    /// which the next read's sweep tries again. No test makes either refuse,
1010    /// since that needs a store or filesystem made to fail beneath a running
1011    /// server; the `aligning` journeys prove the sweep removes a closed
1012    /// print's verdict and keeps an open one's, after a close and at start.
1013    pub async fn sweep(&self) {
1014        let Ok(open) = self.prints.open_prints().await else {
1015            return;
1016        };
1017        let open: Vec<String> = open
1018            .iter()
1019            .flat_map(|print| {
1020                [
1021                    format!("{}.json", print.id),
1022                    format!("{}.json.part", print.id),
1023                ]
1024            })
1025            .collect();
1026        for directory in [
1027            &self.directory,
1028            &self.previous_directory,
1029            &self.checked_directory,
1030            &self.view_directory,
1031        ] {
1032            let Ok(entries) = std::fs::read_dir(directory) else {
1033                continue;
1034            };
1035            for entry in entries.flatten() {
1036                let name = entry.file_name();
1037                if !open.iter().any(|kept| name.to_str() == Some(kept.as_str())) {
1038                    let _ = std::fs::remove_file(entry.path());
1039                }
1040            }
1041        }
1042    }
1043}
1044
1045/// The newest of a print's checked frames, oldest first, at least `rise_mm`
1046/// below `print_z_mm` in the plan.
1047fn reference_in(kept: &[CheckedFrame], print_z_mm: f64, rise_mm: f64) -> Option<&CheckedFrame> {
1048    kept.iter()
1049        .rev()
1050        .find(|checked| checked.print_z_mm <= print_z_mm - rise_mm)
1051}
1052
1053/// A print's checked frames once `checked` is kept among them: the newest
1054/// earlier frame at least `rise_mm` below it and every frame after that, then
1055/// it, at most [`MAX_CHECKED_FRAMES`] of them, the oldest dropped first; or it
1056/// alone when it is below the last kept, a plan gone back down.
1057fn kept_with(
1058    mut kept: Vec<CheckedFrame>,
1059    checked: CheckedFrame,
1060    rise_mm: f64,
1061) -> Vec<CheckedFrame> {
1062    if kept
1063        .last()
1064        .is_some_and(|last| checked.print_z_mm < last.print_z_mm)
1065    {
1066        kept.clear();
1067    }
1068    if let Some(reference) = kept
1069        .iter()
1070        .rposition(|earlier| earlier.print_z_mm <= checked.print_z_mm - rise_mm)
1071    {
1072        kept.drain(..reference);
1073    }
1074    kept.push(checked);
1075    if kept.len() > MAX_CHECKED_FRAMES {
1076        kept.drain(..kept.len() - MAX_CHECKED_FRAMES);
1077    }
1078    kept
1079}
1080
1081/// How many times one file's replacement is attempted while the filesystem
1082/// refuses it for a moment, and the pause between two attempts: half a second
1083/// in all, on a check that is otherwise waiting on no one.
1084const REPLACE_ATTEMPTS: u32 = 20;
1085const REPLACE_PAUSE: Duration = Duration::from_millis(25);
1086
1087/// Put `bytes` at `path` whole: written beside it, then renamed over it, so a
1088/// reader finds the old file or the new one and never part of either.
1089///
1090/// Windows refuses to replace a file another process holds open without
1091/// letting it be deleted — a scanner reading what was just written does — and
1092/// that refusal ends when the other process closes it. So a refusal of that
1093/// kind is attempted again, up to [`REPLACE_ATTEMPTS`] times; any other, or
1094/// one that outlasts them, is answered, with the file beside it removed.
1095///
1096/// # Errors
1097///
1098/// The filesystem's own error for the last attempt.
1099fn replace_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
1100    let held = path.with_extension("json.part");
1101    attempt_while_refused(
1102        || {
1103            std::fs::write(&held, bytes)?;
1104            std::fs::rename(&held, path)
1105        },
1106        refused_for_a_moment,
1107        REPLACE_ATTEMPTS,
1108        REPLACE_PAUSE,
1109    )
1110    .inspect_err(|_| {
1111        let _ = std::fs::remove_file(&held);
1112    })
1113}
1114
1115/// Run `attempt` until it succeeds, fails with an error `refused` does not
1116/// call momentary, or has been run `attempts` times, pausing between two.
1117fn attempt_while_refused(
1118    mut attempt: impl FnMut() -> std::io::Result<()>,
1119    refused: impl Fn(&std::io::Error) -> bool,
1120    attempts: u32,
1121    pause: Duration,
1122) -> std::io::Result<()> {
1123    let mut made = 1;
1124    loop {
1125        match attempt() {
1126            Err(error) if made < attempts && refused(&error) => {
1127                std::thread::sleep(pause);
1128                made += 1;
1129            }
1130            answered => return answered,
1131        }
1132    }
1133}
1134
1135/// Whether Windows refused a replacement only because another handle has the
1136/// file open: `ERROR_ACCESS_DENIED` (5) or `ERROR_SHARING_VIOLATION` (32).
1137#[cfg(windows)]
1138fn refused_for_a_moment(error: &std::io::Error) -> bool {
1139    matches!(error.raw_os_error(), Some(5 | 32))
1140}
1141
1142/// Elsewhere a rename replaces a file whoever has it open, so no refusal is
1143/// momentary.
1144#[cfg(not(windows))]
1145fn refused_for_a_moment(_error: &std::io::Error) -> bool {
1146    false
1147}
1148
1149/// A frame size as the refusal spells it, `<w>x<h>`.
1150fn size_of(text: &str) -> [u32; 2] {
1151    let mut parts = text.split('x').map(|part| part.parse().unwrap_or(0));
1152    [parts.next().unwrap_or(0), parts.next().unwrap_or(0)]
1153}
1154
1155/// A verdict as the log says it.
1156fn said(verdict: &PrintAlignment) -> String {
1157    match verdict {
1158        PrintAlignment::Unavailable => "unavailable: the G-code lays no object".to_owned(),
1159        PrintAlignment::Pending => "pending".to_owned(),
1160        PrintAlignment::Passed {
1161            offset_px,
1162            correction_px,
1163        } => format!(
1164            "passed, offset {offset_px:.1} px, corrected by [{:.0}, {:.0}] px",
1165            correction_px[0], correction_px[1]
1166        ),
1167        PrintAlignment::Failed {
1168            reason: AlignmentFailure::Offset { offset_px },
1169        } => format!("failed, offset {offset_px:.1} px"),
1170        PrintAlignment::Failed {
1171            reason: AlignmentFailure::Resolution { expected, got },
1172        } => format!(
1173            "failed: the camera's frames are {}x{}, the calibration's {}x{}",
1174            got[0], got[1], expected[0], expected[1]
1175        ),
1176        PrintAlignment::Failed {
1177            reason: AlignmentFailure::Stream,
1178        } => "failed: the camera is not the stream the calibration was fitted on".to_owned(),
1179    }
1180}
1181
1182/// One print's camera view as it is kept.
1183#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1184#[serde(crate = "printobserver_types::serde")]
1185struct CameraViewState {
1186    /// The correction the print's last pass took, with its reference.
1187    #[serde(default)]
1188    correction: Option<ViewCorrection>,
1189    /// Why the frame judged last was inconclusive, while the alignment is
1190    /// pending.
1191    #[serde(default)]
1192    inconclusive: Option<InconclusiveReason>,
1193    /// The image the print's last check was shown.
1194    #[serde(default)]
1195    last_check_image: Option<LastCheckImage>,
1196    /// The camera check the print started under, whose correction every
1197    /// check of it is drawn through from its first.
1198    #[serde(default)]
1199    camera_check: Option<CheckedCamera>,
1200}
1201
1202/// The camera check a print started under, as its view keeps it.
1203#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1204#[serde(crate = "printobserver_types::serde")]
1205struct CheckedCamera {
1206    /// The check.
1207    id: printobserver_core::CameraCheckId,
1208    /// The correction it put in force.
1209    correction: ViewCorrection,
1210}
1211
1212/// The image a print's last check was shown, and when its frame was captured.
1213#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1214#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1215#[schemars(crate = "printobserver_types::schemars")]
1216pub struct LastCheckImage {
1217    /// When the check's frame was captured.
1218    pub at: Timestamp,
1219    /// Which image the check was shown.
1220    pub kind: ImageKind,
1221    /// Why it was the whole frame; null for the three-panel image.
1222    pub fallback: Option<ImageFallback>,
1223}
1224
1225impl Sample for LastCheckImage {
1226    fn sample_full() -> Self {
1227        Self {
1228            at: Timestamp::sample_full(),
1229            kind: ImageKind::WholeFrame,
1230            fallback: Some(ImageFallback::sample_full()),
1231        }
1232    }
1233
1234    fn sample_minimal() -> Self {
1235        Self {
1236            at: Timestamp::sample_full(),
1237            kind: ImageKind::ThreePanel,
1238            fallback: None,
1239        }
1240    }
1241}
1242
1243/// Whether a judgement of a frame judges the print's first-layer alignment.
1244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1245pub enum AlignmentJudging {
1246    /// Never: a look, or a frame not the configured camera's own.
1247    Never,
1248    /// While the alignment is pending: every scheduled check's frame.
1249    WhilePending,
1250    /// Whatever it stands at, a latched failure included: the operator's
1251    /// recheck of the camera.
1252    Afresh,
1253}
1254
1255impl AlignmentJudging {
1256    /// How the operator's recheck of the camera judges the first layer: never
1257    /// while the printer reports the print paused, whose bed stands off the
1258    /// plan's height, and afresh otherwise.
1259    #[must_use]
1260    pub const fn of_recheck(paused: bool) -> Self {
1261        if paused { Self::Never } else { Self::Afresh }
1262    }
1263}
1264
1265/// One frame to judge.
1266#[derive(Debug, Clone, Copy)]
1267pub struct Judging<'a> {
1268    /// The frame's bytes.
1269    pub frame_jpeg: &'a [u8],
1270    /// The stored frame's SHA-256, which every record names.
1271    pub frame_sha256: &'a str,
1272    /// The stream it is of.
1273    pub camera_snapshot_url: &'a str,
1274    /// Where the print stood in its plan as it was taken.
1275    pub plan: Option<&'a PlanPosition>,
1276    /// Whether the first-layer alignment is judged.
1277    pub alignment: AlignmentJudging,
1278}
1279
1280/// What one judgement of a frame decided, and the records it owes.
1281#[derive(Debug, Clone, PartialEq)]
1282pub struct Judged {
1283    /// The records to append, in order, each naming the frame.
1284    pub records: Vec<EventBody>,
1285    /// The print's alignment once judged.
1286    pub alignment: PrintAlignment,
1287    /// The correction the frame may be drawn through, when the alignment
1288    /// passed and the view allows it.
1289    pub correction: Option<ViewCorrection>,
1290    /// The view's outcome and its refusal's reason; nothing when the frame was
1291    /// not judged for its view.
1292    pub view: Option<(ViewOutcome, Option<String>)>,
1293    /// Why the correction in force was given up on this frame: the camera
1294    /// moved again.
1295    pub rejected: Option<String>,
1296    /// Why the frame is not the calibration's size or stream.
1297    pub mismatch: Option<String>,
1298    /// Why the frame could not be read at all.
1299    pub unreadable: Option<String>,
1300    /// Why the alignment was left pending, when the frame judged last was
1301    /// inconclusive.
1302    pub inconclusive: Option<InconclusiveReason>,
1303    /// The camera check the print started under, when the frame was judged
1304    /// against its reference: the drawing then rests on the check alone.
1305    pub camera_check: Option<printobserver_core::CameraCheckId>,
1306}
1307
1308impl Judged {
1309    /// Nothing that could be judged of a frame — no calibration, or no stream
1310    /// it was fitted on — the alignment standing as it is, and the one record
1311    /// the frame is kept with.
1312    #[must_use]
1313    pub fn nothing_to_judge(alignment: PrintAlignment, kept_with: Option<EventBody>) -> Self {
1314        Self {
1315            records: kept_with.into_iter().collect(),
1316            ..Self::unjudged(alignment)
1317        }
1318    }
1319
1320    /// Nothing judged, the alignment standing as it is.
1321    const fn unjudged(alignment: PrintAlignment) -> Self {
1322        Self {
1323            records: Vec::new(),
1324            alignment,
1325            correction: None,
1326            view: None,
1327            rejected: None,
1328            mismatch: None,
1329            unreadable: None,
1330            inconclusive: None,
1331            camera_check: None,
1332        }
1333    }
1334}
1335
1336impl PrintAlignment {
1337    /// Whether it passed.
1338    #[must_use]
1339    pub const fn passed(&self) -> bool {
1340        matches!(self, Self::Passed { .. })
1341    }
1342}
1343
1344/// What a first-layer judgement due on a frame scores.
1345struct DueAlignment {
1346    /// The first object layer's toolpath.
1347    first_layer: printobserver_core::LayerToolpath,
1348    /// The print's height in its plan as the frame was taken.
1349    print_z_mm: f64,
1350    /// Where the plan has the nozzle then.
1351    nozzle_xy_mm: Option<[f64; 2]>,
1352}
1353
1354/// One payload as the body appended for it; nothing for one that will not
1355/// render, which no declared payload is.
1356fn body_of<P: EventPayload>(payload: &P) -> Option<EventBody> {
1357    EventBody::of(payload).ok()
1358}
1359
1360/// The record of one view judgement, its reason the fallback it leads to: a
1361/// refit view, its landmarks moved from the calibration, is drawn on no more
1362/// than a refused one.
1363fn view_record(
1364    frame_sha256: &str,
1365    view: &ViewJudgement,
1366    view_correction: Option<ViewCorrection>,
1367) -> Option<EventBody> {
1368    let reason = if view.outcome == ViewOutcome::Refit {
1369        Some(crate::check_images::CALIBRATION_STALE.to_owned())
1370    } else {
1371        view.reason.clone()
1372    };
1373    body_of(&crate::judgements::CameraViewJudgedPayload::of(
1374        frame_sha256,
1375        view,
1376        view_correction,
1377        reason,
1378    ))
1379}
1380
1381/// The failure a frame refused for its size or stream latches.
1382fn failure_of(error: &ComposeError, calibration: &CameraCalibration) -> AlignmentFailure {
1383    match error {
1384        ComposeError::FrameMismatch {
1385            field: FrameField::Resolution,
1386            got,
1387            ..
1388        } => AlignmentFailure::Resolution {
1389            expected: calibration.image_size_px,
1390            got: size_of(got),
1391        },
1392        _ => AlignmentFailure::Stream,
1393    }
1394}
1395
1396/// A failure in the sentence its record and its fallback give it in.
1397#[must_use]
1398pub fn failure_sentence(failure: &AlignmentFailure) -> String {
1399    match failure {
1400        AlignmentFailure::Offset { offset_px } => format!(
1401            "the printed first layer lies {offset_px:.1} px from where the calibration projects it"
1402        ),
1403        AlignmentFailure::Resolution { expected, got } => format!(
1404            "the camera's frames are {}x{} and the calibration's {}x{}",
1405            got[0], got[1], expected[0], expected[1]
1406        ),
1407        AlignmentFailure::Stream => {
1408            "the camera is not the stream the calibration was fitted on".to_owned()
1409        }
1410    }
1411}
1412
1413#[cfg(test)]
1414mod tests {
1415    use super::{CheckedFrame, MAX_CHECKED_FRAMES, attempt_while_refused, kept_with, reference_in};
1416    use std::cell::Cell;
1417    use std::io::{Error, ErrorKind};
1418    use std::time::Duration;
1419
1420    /// An attempt that is refused `refusals` times and then succeeds, counting
1421    /// how often it was made.
1422    fn refused_then_done(refusals: u32, made: &Cell<u32>) -> impl FnMut() -> std::io::Result<()> {
1423        move || {
1424            made.set(made.get() + 1);
1425            if made.get() <= refusals {
1426                Err(Error::from(ErrorKind::PermissionDenied))
1427            } else {
1428                Ok(())
1429            }
1430        }
1431    }
1432
1433    #[test]
1434    fn a_momentary_refusal_is_attempted_again_until_it_passes() {
1435        let made = Cell::new(0);
1436        let answered =
1437            attempt_while_refused(refused_then_done(2, &made), |_| true, 5, Duration::ZERO);
1438        assert!(answered.is_ok(), "{answered:?}");
1439        assert_eq!(made.get(), 3);
1440    }
1441
1442    #[test]
1443    fn a_refusal_that_outlasts_every_attempt_is_answered() {
1444        let made = Cell::new(0);
1445        let answered =
1446            attempt_while_refused(refused_then_done(9, &made), |_| true, 4, Duration::ZERO);
1447        assert_eq!(
1448            answered.map_err(|error| error.kind()),
1449            Err(ErrorKind::PermissionDenied)
1450        );
1451        assert_eq!(made.get(), 4);
1452    }
1453
1454    #[test]
1455    fn a_refusal_that_is_not_momentary_is_answered_at_once() {
1456        let made = Cell::new(0);
1457        let answered =
1458            attempt_while_refused(refused_then_done(9, &made), |_| false, 4, Duration::ZERO);
1459        assert!(answered.is_err());
1460        assert_eq!(made.get(), 1);
1461    }
1462
1463    /// The refusal the retry answers, made the way Windows makes it: the
1464    /// record held open by another handle that does not allow deleting it,
1465    /// and let go a moment later.
1466    #[cfg(windows)]
1467    #[test]
1468    fn a_record_held_open_by_another_handle_is_replaced_once_it_is_let_go() {
1469        use std::os::windows::fs::OpenOptionsExt;
1470        let directory = tempfile::TempDir::new().expect("a directory");
1471        let path = directory.path().join("record.json");
1472        std::fs::write(&path, b"before").expect("a record");
1473        let held = std::fs::OpenOptions::new()
1474            .read(true)
1475            .share_mode(0)
1476            .open(&path)
1477            .expect("the record held");
1478        let release = std::thread::spawn(move || {
1479            std::thread::sleep(Duration::from_millis(150));
1480            drop(held);
1481        });
1482        super::replace_file(&path, b"after").expect("the record replaced");
1483        release.join().expect("the handle let go");
1484        assert_eq!(std::fs::read(&path).expect("the record"), b"after");
1485        assert!(!path.with_extension("json.part").exists());
1486    }
1487
1488    #[cfg(windows)]
1489    #[test]
1490    fn only_a_held_file_is_a_momentary_refusal_on_windows() {
1491        assert!(super::refused_for_a_moment(&Error::from_raw_os_error(5)));
1492        assert!(super::refused_for_a_moment(&Error::from_raw_os_error(32)));
1493        assert!(!super::refused_for_a_moment(&Error::from_raw_os_error(2)));
1494    }
1495
1496    /// A checked frame at `z` mm, captured `second` seconds into a print.
1497    fn at(second: i64, z: f64) -> CheckedFrame {
1498        CheckedFrame {
1499            frame: format!("frame-{second}.jpg").into(),
1500            captured_at: printobserver_types::Timestamp::from_unix_seconds(1_791_489_600 + second)
1501                .expect("a time"),
1502            print_z_mm: z,
1503        }
1504    }
1505
1506    /// The heights of checked frames, in their order.
1507    fn heights(kept: &[CheckedFrame]) -> Vec<f64> {
1508        kept.iter().map(|checked| checked.print_z_mm).collect()
1509    }
1510
1511    /// Once a print carries on from a planned change, its growth is measured
1512    /// only from frames checked after: one from before the wait, however far
1513    /// below, is no longer a reference, and the first checked after it is.
1514    #[test]
1515    fn after_a_planned_change_growth_is_measured_from_frames_after_it() {
1516        let state = tempfile::TempDir::new().expect("a state directory");
1517        let store =
1518            printobserver_store_sqlite::MemoryStore::new(state.path()).expect("an in-memory store");
1519        let alignments = super::Alignments::new(state.path(), None, std::sync::Arc::new(store))
1520            .expect("the verdicts' directories");
1521        let print_id = printobserver_types::PrintId::new();
1522        for (second, z) in [(0, 0.2), (60, 0.6)] {
1523            alignments.record_checked_frame(print_id, at(second, z), 0.4);
1524        }
1525        let before = alignments.growth_reference(print_id, 1.0, 0.4);
1526        assert_eq!(before.map(|checked| checked.print_z_mm), Some(0.6));
1527
1528        alignments.restart_growth(print_id);
1529        assert_eq!(alignments.growth_reference(print_id, 1.0, 0.4), None);
1530        alignments.record_checked_frame(print_id, at(3_000, 0.8), 0.4);
1531        alignments.record_checked_frame(print_id, at(3_120, 1.4), 0.4);
1532        let after = alignments.growth_reference(print_id, 1.4, 0.4);
1533        assert_eq!(
1534            after.map(|checked| checked.captured_at),
1535            Some(at(3_000, 0.8).captured_at)
1536        );
1537        // A second change with nothing checked since forgets nothing more.
1538        alignments.restart_growth(print_id);
1539        alignments.restart_growth(print_id);
1540        assert!(alignments.checked_frames(print_id).is_empty());
1541    }
1542
1543    #[test]
1544    fn a_check_measures_from_the_newest_frame_far_enough_below_it() {
1545        let kept = [at(0, 0.2), at(60, 0.8), at(120, 2.0), at(180, 2.6)];
1546        assert_eq!(
1547            reference_in(&kept, 5.8, 3.0).map(|checked| checked.print_z_mm),
1548            Some(2.6)
1549        );
1550        assert_eq!(
1551            reference_in(&kept, 3.5, 3.0).map(|checked| checked.print_z_mm),
1552            Some(0.2)
1553        );
1554        assert_eq!(reference_in(&kept, 3.1, 3.0), None, "none is 3 mm below");
1555    }
1556
1557    #[test]
1558    fn only_what_a_later_check_can_measure_from_is_kept() {
1559        let mut kept = Vec::new();
1560        for (second, z) in [(0, 0.2), (60, 0.8), (120, 2.0), (180, 3.4), (240, 4.0)] {
1561            kept = kept_with(kept, at(second, z), 3.0);
1562        }
1563        assert_eq!(
1564            heights(&kept),
1565            [0.8, 2.0, 3.4, 4.0],
1566            "0.2 is below 0.8, which is itself 3 mm below 4.0, so no later check needs it"
1567        );
1568        assert_eq!(
1569            heights(&kept_with(kept, at(300, 1.0), 3.0)),
1570            [1.0],
1571            "a plan gone back down starts the record again"
1572        );
1573    }
1574
1575    #[test]
1576    fn the_oldest_checked_frames_go_past_the_most_kept() {
1577        let mut kept = Vec::new();
1578        for second in 0..=i64::try_from(MAX_CHECKED_FRAMES).expect("a count") {
1579            kept = kept_with(kept, at(second, 5.0), 3.0);
1580        }
1581        assert_eq!(kept.len(), MAX_CHECKED_FRAMES);
1582        assert_eq!(kept[0].captured_at, at(1, 5.0).captured_at);
1583    }
1584}