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                frame_sha256: sha.to_owned(),
681                outcome: ViewOutcome::FrameMismatch,
682                view_correction: in_force.clone(),
683                reason: Some(reason.clone()),
684            }));
685        if Self::alignment_due(&judged.alignment, judging).is_some() {
686            let failure = failure_of(error, calibration);
687            judged.records.extend(body_of(
688                &crate::judgements::FirstLayerAlignmentJudgedPayload {
689                    verdict: crate::judgements::AlignmentJudgedVerdict::Failed,
690                    offset_px: None,
691                    correction_px: None,
692                    match_strength: None,
693                    reason: failure_sentence(&failure),
694                    frame_sha256: sha.to_owned(),
695                    view_correction: in_force.clone(),
696                },
697            ));
698            judged.alignment = PrintAlignment::Failed { reason: failure };
699            self.decide(print_id, &judged.alignment);
700            let mut state = self.view_state(print_id);
701            state.correction = None;
702            state.inconclusive = None;
703            self.keep_view_state(print_id, &state);
704        }
705        judged.correction = in_force.filter(|_| judged.alignment.passed());
706        judged.mismatch = Some(reason);
707        judged
708    }
709
710    /// Judge one frame of a print started under a camera check: its view
711    /// against the check's reference, and, when it is due, its first layer —
712    /// recorded, and kept as the print's verdict, but neither gating the
713    /// drawing nor taking it away. On the 2026-11-28 print the first-layer
714    /// search scored the toolhead at 46.04 and 42.38 px from a box the
715    /// calibration drew within 2 px, so its offset is no evidence the camera
716    /// moved. Only landmarks moved again beyond the check's reference refuse
717    /// the drawing.
718    #[expect(
719        clippy::too_many_arguments,
720        reason = "the one judgement's inputs and the two records it updates"
721    )]
722    fn judge_under_check(
723        &self,
724        print_id: PrintId,
725        calibration: &CameraCalibration,
726        landmarks: Vec<printobserver_panels::FoundLandmark>,
727        judging: &Judging<'_>,
728        checked: &CheckedCamera,
729        state: &mut CameraViewState,
730        mut judged: Judged,
731    ) -> Judged {
732        let sha = judging.frame_sha256;
733        if let Some(first) = Self::alignment_due(&judged.alignment, judging) {
734            self.record_first_layer(
735                print_id,
736                calibration,
737                &first,
738                judging,
739                checked,
740                state,
741                &mut judged,
742            );
743        }
744        let view = judge_found(calibration, landmarks, Some(&checked.correction));
745        if view.outcome == ViewOutcome::ViewRefitRejected {
746            judged.rejected.clone_from(&view.reason);
747        } else if view.outcome.drawable() {
748            judged.correction = Some(checked.correction.clone());
749        }
750        judged
751            .records
752            .extend(body_of(&crate::judgements::CameraViewJudgedPayload {
753                frame_sha256: sha.to_owned(),
754                outcome: view.outcome,
755                view_correction: Some(checked.correction.clone()),
756                reason: view.reason.clone(),
757            }));
758        judged.camera_check = Some(checked.id);
759        judged.inconclusive = state.inconclusive;
760        judged.view = Some((view.outcome, view.reason));
761        judged
762    }
763
764    /// Judge the first layer of a print started under a camera check, and keep
765    /// what it found as the print's verdict, leaving the check's correction in
766    /// force whatever it found.
767    #[expect(
768        clippy::too_many_arguments,
769        reason = "the one judgement's inputs and the two records it updates"
770    )]
771    fn record_first_layer(
772        &self,
773        print_id: PrintId,
774        calibration: &CameraCalibration,
775        first: &DueAlignment,
776        judging: &Judging<'_>,
777        checked: &CheckedCamera,
778        state: &mut CameraViewState,
779        judged: &mut Judged,
780    ) {
781        let Ok(judgement) = judge_first_layer(&FirstLayerInputs {
782            alignment: AlignmentInputs {
783                frame_jpeg: judging.frame_jpeg,
784                camera_snapshot_url: judging.camera_snapshot_url,
785                first_layer: &first.first_layer,
786                print_z_mm: first.print_z_mm,
787                calibration,
788            },
789            nozzle_xy_mm: first.nozzle_xy_mm,
790        }) else {
791            // The frame was decoded and held to the calibration already, so no
792            // refusal is reached here; one that is is judged again next check.
793            return;
794        };
795        let found = judgement.found;
796        let shift = |found: &printobserver_panels::AlignmentVerdict| {
797            printobserver_panels::alignment::correction_shift(
798                found,
799                &first.first_layer,
800                first.print_z_mm,
801            )
802        };
803        let (verdict, reason) = match judgement.verdict {
804            FirstLayerVerdict::Passed => (
805                crate::judgements::AlignmentJudgedVerdict::Passed,
806                "clearly_found".to_owned(),
807            ),
808            FirstLayerVerdict::Inconclusive(why) => (
809                crate::judgements::AlignmentJudgedVerdict::Inconclusive,
810                why.as_str().to_owned(),
811            ),
812        };
813        judged.records.extend(body_of(
814            &crate::judgements::FirstLayerAlignmentJudgedPayload {
815                verdict,
816                offset_px: found.map(|found| found.offset_px),
817                correction_px: (judgement.verdict == FirstLayerVerdict::Passed)
818                    .then(|| found.as_ref().map(shift))
819                    .flatten(),
820                match_strength: found.map(|found| found.match_strength),
821                reason,
822                frame_sha256: judging.frame_sha256.to_owned(),
823                view_correction: Some(checked.correction.clone()),
824            },
825        ));
826        match (judgement.verdict, found) {
827            (FirstLayerVerdict::Passed, Some(found)) => {
828                judged.alignment = PrintAlignment::Passed {
829                    offset_px: found.offset_px,
830                    correction_px: shift(&found),
831                };
832                state.inconclusive = None;
833            }
834            (FirstLayerVerdict::Inconclusive(why), _) => {
835                judged.alignment = PrintAlignment::Pending;
836                state.inconclusive = Some(why);
837            }
838            (FirstLayerVerdict::Passed, None) => return,
839        }
840        self.decide(print_id, &judged.alignment);
841        self.keep_view_state(print_id, state);
842    }
843
844    /// Judge the first layer on a frame it is due on, and the frame's view
845    /// against what that leaves in force.
846    #[expect(
847        clippy::too_many_arguments,
848        reason = "the one judgement's inputs and the two records it updates"
849    )]
850    fn judge_alignment(
851        &self,
852        print_id: PrintId,
853        calibration: &CameraCalibration,
854        landmarks: Vec<printobserver_panels::FoundLandmark>,
855        first: &DueAlignment,
856        judging: &Judging<'_>,
857        in_force: Option<ViewCorrection>,
858        state: &mut CameraViewState,
859        judged: &mut Judged,
860    ) -> ViewJudgement {
861        let sha = judging.frame_sha256;
862        let uncorrected = judge_found(calibration, landmarks.clone(), None);
863        let judgement = judge_first_layer(&FirstLayerInputs {
864            alignment: AlignmentInputs {
865                frame_jpeg: judging.frame_jpeg,
866                camera_snapshot_url: judging.camera_snapshot_url,
867                first_layer: &first.first_layer,
868                print_z_mm: first.print_z_mm,
869                calibration,
870            },
871            nozzle_xy_mm: first.nozzle_xy_mm,
872        });
873        let Ok(judgement) = judgement else {
874            // The frame was decoded and held to the calibration above, so no
875            // refusal is reached here; one that is leaves the alignment as it
876            // stood, judged again on the next check's frame.
877            judged.records.extend(view_record(sha, &uncorrected, None));
878            return uncorrected;
879        };
880        let found = judgement.found;
881        let (verdict, correction_px, reason) = match judgement.verdict {
882            FirstLayerVerdict::Passed => (
883                crate::judgements::AlignmentJudgedVerdict::Passed,
884                found.map(|found| {
885                    printobserver_panels::alignment::correction_shift(
886                        &found,
887                        &first.first_layer,
888                        first.print_z_mm,
889                    )
890                }),
891                "clearly_found".to_owned(),
892            ),
893            FirstLayerVerdict::Inconclusive(why) => (
894                crate::judgements::AlignmentJudgedVerdict::Inconclusive,
895                None,
896                why.as_str().to_owned(),
897            ),
898        };
899        judged.records.extend(body_of(
900            &crate::judgements::FirstLayerAlignmentJudgedPayload {
901                verdict,
902                offset_px: found.map(|found| found.offset_px),
903                correction_px,
904                match_strength: found.map(|found| found.match_strength),
905                reason,
906                frame_sha256: sha.to_owned(),
907                view_correction: in_force,
908            },
909        ));
910        match (judgement.verdict, found) {
911            (FirstLayerVerdict::Passed, Some(found)) => {
912                let shift = printobserver_panels::alignment::correction_shift(
913                    &found,
914                    &first.first_layer,
915                    first.print_z_mm,
916                );
917                eprintln!(
918                    "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",
919                    found.shift_px[0],
920                    found.shift_px[1],
921                    first.print_z_mm,
922                    found.match_strength,
923                    shift[0],
924                    shift[1]
925                );
926                let correction = ViewCorrection::translation(shift, uncorrected.agreeing());
927                judged.alignment = PrintAlignment::Passed {
928                    offset_px: found.offset_px,
929                    correction_px: shift,
930                };
931                self.decide(print_id, &judged.alignment);
932                state.correction = Some(correction.clone());
933                state.inconclusive = None;
934                self.keep_view_state(print_id, state);
935                if uncorrected.moved(calibration) {
936                    judged
937                        .records
938                        .extend(body_of(&crate::judgements::CameraViewRefitPayload {
939                            frame_sha256: sha.to_owned(),
940                            view_correction: correction.clone(),
941                        }));
942                }
943                let view = judge_found(calibration, landmarks, Some(&correction));
944                judged
945                    .records
946                    .extend(view_record(sha, &view, Some(correction.clone())));
947                judged.correction = Some(correction);
948                view
949            }
950            (FirstLayerVerdict::Inconclusive(why), _) => {
951                // Written even when it was pending already: a reader of the
952                // verdict file learns a frame was judged.
953                judged.alignment = PrintAlignment::Pending;
954                self.decide(print_id, &judged.alignment);
955                state.correction = None;
956                state.inconclusive = Some(why);
957                self.keep_view_state(print_id, state);
958                judged.records.extend(view_record(sha, &uncorrected, None));
959                uncorrected
960            }
961            (FirstLayerVerdict::Passed, None) => {
962                judged.records.extend(view_record(sha, &uncorrected, None));
963                uncorrected
964            }
965        }
966    }
967
968    /// The first layer a frame's judgement scores, when the alignment is due
969    /// on it; nothing otherwise.
970    fn alignment_due(alignment: &PrintAlignment, judging: &Judging<'_>) -> Option<DueAlignment> {
971        let asked = match judging.alignment {
972            AlignmentJudging::Never => false,
973            AlignmentJudging::WhilePending => *alignment == PrintAlignment::Pending,
974            AlignmentJudging::Afresh => true,
975        };
976        if !asked {
977            return None;
978        }
979        let plan = judging.plan?;
980        let index = &plan.index;
981        let position = plan.file_position_bytes;
982        let (first, ends) = index.first_object_layer()?;
983        if position <= ends {
984            return None;
985        }
986        Some(DueAlignment {
987            first_layer: index.layer_toolpath(first).ok()?,
988            print_z_mm: index
989                .layer_at(position)
990                .and_then(|layer| index.layer_z_mm(layer))?,
991            nozzle_xy_mm: index.planned_head_at(position).ok().flatten(),
992        })
993    }
994
995    /// Delete the verdict, the last check's record, the checked frames and the
996    /// camera view of every print that is not open.
997    ///
998    /// An open print's record still being written — the `.json.part` beside it
999    /// that [`replace_file`] renames over it — is its own, and kept: the watch
1000    /// sweeps after every read, so a sweep removing it between the write and the
1001    /// rename lost that record, and the print's next check showed no previous
1002    /// frame.
1003    ///
1004    /// A store that cannot list the open prints, a directory that cannot be
1005    /// listed and a file that cannot be removed each leave a verdict behind,
1006    /// which the next read's sweep tries again. No test makes either refuse,
1007    /// since that needs a store or filesystem made to fail beneath a running
1008    /// server; the `aligning` journeys prove the sweep removes a closed
1009    /// print's verdict and keeps an open one's, after a close and at start.
1010    pub async fn sweep(&self) {
1011        let Ok(open) = self.prints.open_prints().await else {
1012            return;
1013        };
1014        let open: Vec<String> = open
1015            .iter()
1016            .flat_map(|print| {
1017                [
1018                    format!("{}.json", print.id),
1019                    format!("{}.json.part", print.id),
1020                ]
1021            })
1022            .collect();
1023        for directory in [
1024            &self.directory,
1025            &self.previous_directory,
1026            &self.checked_directory,
1027            &self.view_directory,
1028        ] {
1029            let Ok(entries) = std::fs::read_dir(directory) else {
1030                continue;
1031            };
1032            for entry in entries.flatten() {
1033                let name = entry.file_name();
1034                if !open.iter().any(|kept| name.to_str() == Some(kept.as_str())) {
1035                    let _ = std::fs::remove_file(entry.path());
1036                }
1037            }
1038        }
1039    }
1040}
1041
1042/// The newest of a print's checked frames, oldest first, at least `rise_mm`
1043/// below `print_z_mm` in the plan.
1044fn reference_in(kept: &[CheckedFrame], print_z_mm: f64, rise_mm: f64) -> Option<&CheckedFrame> {
1045    kept.iter()
1046        .rev()
1047        .find(|checked| checked.print_z_mm <= print_z_mm - rise_mm)
1048}
1049
1050/// A print's checked frames once `checked` is kept among them: the newest
1051/// earlier frame at least `rise_mm` below it and every frame after that, then
1052/// it, at most [`MAX_CHECKED_FRAMES`] of them, the oldest dropped first; or it
1053/// alone when it is below the last kept, a plan gone back down.
1054fn kept_with(
1055    mut kept: Vec<CheckedFrame>,
1056    checked: CheckedFrame,
1057    rise_mm: f64,
1058) -> Vec<CheckedFrame> {
1059    if kept
1060        .last()
1061        .is_some_and(|last| checked.print_z_mm < last.print_z_mm)
1062    {
1063        kept.clear();
1064    }
1065    if let Some(reference) = kept
1066        .iter()
1067        .rposition(|earlier| earlier.print_z_mm <= checked.print_z_mm - rise_mm)
1068    {
1069        kept.drain(..reference);
1070    }
1071    kept.push(checked);
1072    if kept.len() > MAX_CHECKED_FRAMES {
1073        kept.drain(..kept.len() - MAX_CHECKED_FRAMES);
1074    }
1075    kept
1076}
1077
1078/// How many times one file's replacement is attempted while the filesystem
1079/// refuses it for a moment, and the pause between two attempts: half a second
1080/// in all, on a check that is otherwise waiting on no one.
1081const REPLACE_ATTEMPTS: u32 = 20;
1082const REPLACE_PAUSE: Duration = Duration::from_millis(25);
1083
1084/// Put `bytes` at `path` whole: written beside it, then renamed over it, so a
1085/// reader finds the old file or the new one and never part of either.
1086///
1087/// Windows refuses to replace a file another process holds open without
1088/// letting it be deleted — a scanner reading what was just written does — and
1089/// that refusal ends when the other process closes it. So a refusal of that
1090/// kind is attempted again, up to [`REPLACE_ATTEMPTS`] times; any other, or
1091/// one that outlasts them, is answered, with the file beside it removed.
1092///
1093/// # Errors
1094///
1095/// The filesystem's own error for the last attempt.
1096fn replace_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
1097    let held = path.with_extension("json.part");
1098    attempt_while_refused(
1099        || {
1100            std::fs::write(&held, bytes)?;
1101            std::fs::rename(&held, path)
1102        },
1103        refused_for_a_moment,
1104        REPLACE_ATTEMPTS,
1105        REPLACE_PAUSE,
1106    )
1107    .inspect_err(|_| {
1108        let _ = std::fs::remove_file(&held);
1109    })
1110}
1111
1112/// Run `attempt` until it succeeds, fails with an error `refused` does not
1113/// call momentary, or has been run `attempts` times, pausing between two.
1114fn attempt_while_refused(
1115    mut attempt: impl FnMut() -> std::io::Result<()>,
1116    refused: impl Fn(&std::io::Error) -> bool,
1117    attempts: u32,
1118    pause: Duration,
1119) -> std::io::Result<()> {
1120    let mut made = 1;
1121    loop {
1122        match attempt() {
1123            Err(error) if made < attempts && refused(&error) => {
1124                std::thread::sleep(pause);
1125                made += 1;
1126            }
1127            answered => return answered,
1128        }
1129    }
1130}
1131
1132/// Whether Windows refused a replacement only because another handle has the
1133/// file open: `ERROR_ACCESS_DENIED` (5) or `ERROR_SHARING_VIOLATION` (32).
1134#[cfg(windows)]
1135fn refused_for_a_moment(error: &std::io::Error) -> bool {
1136    matches!(error.raw_os_error(), Some(5 | 32))
1137}
1138
1139/// Elsewhere a rename replaces a file whoever has it open, so no refusal is
1140/// momentary.
1141#[cfg(not(windows))]
1142fn refused_for_a_moment(_error: &std::io::Error) -> bool {
1143    false
1144}
1145
1146/// A frame size as the refusal spells it, `<w>x<h>`.
1147fn size_of(text: &str) -> [u32; 2] {
1148    let mut parts = text.split('x').map(|part| part.parse().unwrap_or(0));
1149    [parts.next().unwrap_or(0), parts.next().unwrap_or(0)]
1150}
1151
1152/// A verdict as the log says it.
1153fn said(verdict: &PrintAlignment) -> String {
1154    match verdict {
1155        PrintAlignment::Unavailable => "unavailable: the G-code lays no object".to_owned(),
1156        PrintAlignment::Pending => "pending".to_owned(),
1157        PrintAlignment::Passed {
1158            offset_px,
1159            correction_px,
1160        } => format!(
1161            "passed, offset {offset_px:.1} px, corrected by [{:.0}, {:.0}] px",
1162            correction_px[0], correction_px[1]
1163        ),
1164        PrintAlignment::Failed {
1165            reason: AlignmentFailure::Offset { offset_px },
1166        } => format!("failed, offset {offset_px:.1} px"),
1167        PrintAlignment::Failed {
1168            reason: AlignmentFailure::Resolution { expected, got },
1169        } => format!(
1170            "failed: the camera's frames are {}x{}, the calibration's {}x{}",
1171            got[0], got[1], expected[0], expected[1]
1172        ),
1173        PrintAlignment::Failed {
1174            reason: AlignmentFailure::Stream,
1175        } => "failed: the camera is not the stream the calibration was fitted on".to_owned(),
1176    }
1177}
1178
1179/// One print's camera view as it is kept.
1180#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1181#[serde(crate = "printobserver_types::serde")]
1182struct CameraViewState {
1183    /// The correction the print's last pass took, with its reference.
1184    #[serde(default)]
1185    correction: Option<ViewCorrection>,
1186    /// Why the frame judged last was inconclusive, while the alignment is
1187    /// pending.
1188    #[serde(default)]
1189    inconclusive: Option<InconclusiveReason>,
1190    /// The image the print's last check was shown.
1191    #[serde(default)]
1192    last_check_image: Option<LastCheckImage>,
1193    /// The camera check the print started under, whose correction every
1194    /// check of it is drawn through from its first.
1195    #[serde(default)]
1196    camera_check: Option<CheckedCamera>,
1197}
1198
1199/// The camera check a print started under, as its view keeps it.
1200#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1201#[serde(crate = "printobserver_types::serde")]
1202struct CheckedCamera {
1203    /// The check.
1204    id: printobserver_core::CameraCheckId,
1205    /// The correction it put in force.
1206    correction: ViewCorrection,
1207}
1208
1209/// The image a print's last check was shown, and when its frame was captured.
1210#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1211#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1212#[schemars(crate = "printobserver_types::schemars")]
1213pub struct LastCheckImage {
1214    /// When the check's frame was captured.
1215    pub at: Timestamp,
1216    /// Which image the check was shown.
1217    pub kind: ImageKind,
1218    /// Why it was the whole frame; null for the three-panel image.
1219    pub fallback: Option<ImageFallback>,
1220}
1221
1222impl Sample for LastCheckImage {
1223    fn sample_full() -> Self {
1224        Self {
1225            at: Timestamp::sample_full(),
1226            kind: ImageKind::WholeFrame,
1227            fallback: Some(ImageFallback::sample_full()),
1228        }
1229    }
1230
1231    fn sample_minimal() -> Self {
1232        Self {
1233            at: Timestamp::sample_full(),
1234            kind: ImageKind::ThreePanel,
1235            fallback: None,
1236        }
1237    }
1238}
1239
1240/// Whether a judgement of a frame judges the print's first-layer alignment.
1241#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1242pub enum AlignmentJudging {
1243    /// Never: a look, or a frame not the configured camera's own.
1244    Never,
1245    /// While the alignment is pending: every scheduled check's frame.
1246    WhilePending,
1247    /// Whatever it stands at, a latched failure included: the operator's
1248    /// recheck of the camera.
1249    Afresh,
1250}
1251
1252impl AlignmentJudging {
1253    /// How the operator's recheck of the camera judges the first layer: never
1254    /// while the printer reports the print paused, whose bed stands off the
1255    /// plan's height, and afresh otherwise.
1256    #[must_use]
1257    pub const fn of_recheck(paused: bool) -> Self {
1258        if paused { Self::Never } else { Self::Afresh }
1259    }
1260}
1261
1262/// One frame to judge.
1263#[derive(Debug, Clone, Copy)]
1264pub struct Judging<'a> {
1265    /// The frame's bytes.
1266    pub frame_jpeg: &'a [u8],
1267    /// The stored frame's SHA-256, which every record names.
1268    pub frame_sha256: &'a str,
1269    /// The stream it is of.
1270    pub camera_snapshot_url: &'a str,
1271    /// Where the print stood in its plan as it was taken.
1272    pub plan: Option<&'a PlanPosition>,
1273    /// Whether the first-layer alignment is judged.
1274    pub alignment: AlignmentJudging,
1275}
1276
1277/// What one judgement of a frame decided, and the records it owes.
1278#[derive(Debug, Clone, PartialEq)]
1279pub struct Judged {
1280    /// The records to append, in order, each naming the frame.
1281    pub records: Vec<EventBody>,
1282    /// The print's alignment once judged.
1283    pub alignment: PrintAlignment,
1284    /// The correction the frame may be drawn through, when the alignment
1285    /// passed and the view allows it.
1286    pub correction: Option<ViewCorrection>,
1287    /// The view's outcome and its refusal's reason; nothing when the frame was
1288    /// not judged for its view.
1289    pub view: Option<(ViewOutcome, Option<String>)>,
1290    /// Why the correction in force was given up on this frame: the camera
1291    /// moved again.
1292    pub rejected: Option<String>,
1293    /// Why the frame is not the calibration's size or stream.
1294    pub mismatch: Option<String>,
1295    /// Why the frame could not be read at all.
1296    pub unreadable: Option<String>,
1297    /// Why the alignment was left pending, when the frame judged last was
1298    /// inconclusive.
1299    pub inconclusive: Option<InconclusiveReason>,
1300    /// The camera check the print started under, when the frame was judged
1301    /// against its reference: the drawing then rests on the check alone.
1302    pub camera_check: Option<printobserver_core::CameraCheckId>,
1303}
1304
1305impl Judged {
1306    /// Nothing that could be judged of a frame — no calibration, or no stream
1307    /// it was fitted on — the alignment standing as it is, and the one record
1308    /// the frame is kept with.
1309    #[must_use]
1310    pub fn nothing_to_judge(alignment: PrintAlignment, kept_with: Option<EventBody>) -> Self {
1311        Self {
1312            records: kept_with.into_iter().collect(),
1313            ..Self::unjudged(alignment)
1314        }
1315    }
1316
1317    /// Nothing judged, the alignment standing as it is.
1318    const fn unjudged(alignment: PrintAlignment) -> Self {
1319        Self {
1320            records: Vec::new(),
1321            alignment,
1322            correction: None,
1323            view: None,
1324            rejected: None,
1325            mismatch: None,
1326            unreadable: None,
1327            inconclusive: None,
1328            camera_check: None,
1329        }
1330    }
1331}
1332
1333impl PrintAlignment {
1334    /// Whether it passed.
1335    #[must_use]
1336    pub const fn passed(&self) -> bool {
1337        matches!(self, Self::Passed { .. })
1338    }
1339}
1340
1341/// What a first-layer judgement due on a frame scores.
1342struct DueAlignment {
1343    /// The first object layer's toolpath.
1344    first_layer: printobserver_core::LayerToolpath,
1345    /// The print's height in its plan as the frame was taken.
1346    print_z_mm: f64,
1347    /// Where the plan has the nozzle then.
1348    nozzle_xy_mm: Option<[f64; 2]>,
1349}
1350
1351/// One payload as the body appended for it; nothing for one that will not
1352/// render, which no declared payload is.
1353fn body_of<P: EventPayload>(payload: &P) -> Option<EventBody> {
1354    EventBody::of(payload).ok()
1355}
1356
1357/// The record of one view judgement, its reason the fallback it leads to: a
1358/// refit view, its landmarks moved from the calibration, is drawn on no more
1359/// than a refused one.
1360fn view_record(
1361    frame_sha256: &str,
1362    view: &ViewJudgement,
1363    view_correction: Option<ViewCorrection>,
1364) -> Option<EventBody> {
1365    let reason = if view.outcome == ViewOutcome::Refit {
1366        Some(crate::check_images::CALIBRATION_STALE.to_owned())
1367    } else {
1368        view.reason.clone()
1369    };
1370    body_of(&crate::judgements::CameraViewJudgedPayload {
1371        frame_sha256: frame_sha256.to_owned(),
1372        outcome: view.outcome,
1373        view_correction,
1374        reason,
1375    })
1376}
1377
1378/// The failure a frame refused for its size or stream latches.
1379fn failure_of(error: &ComposeError, calibration: &CameraCalibration) -> AlignmentFailure {
1380    match error {
1381        ComposeError::FrameMismatch {
1382            field: FrameField::Resolution,
1383            got,
1384            ..
1385        } => AlignmentFailure::Resolution {
1386            expected: calibration.image_size_px,
1387            got: size_of(got),
1388        },
1389        _ => AlignmentFailure::Stream,
1390    }
1391}
1392
1393/// A failure in the sentence its record and its fallback give it in.
1394#[must_use]
1395pub fn failure_sentence(failure: &AlignmentFailure) -> String {
1396    match failure {
1397        AlignmentFailure::Offset { offset_px } => format!(
1398            "the printed first layer lies {offset_px:.1} px from where the calibration projects it"
1399        ),
1400        AlignmentFailure::Resolution { expected, got } => format!(
1401            "the camera's frames are {}x{} and the calibration's {}x{}",
1402            got[0], got[1], expected[0], expected[1]
1403        ),
1404        AlignmentFailure::Stream => {
1405            "the camera is not the stream the calibration was fitted on".to_owned()
1406        }
1407    }
1408}
1409
1410#[cfg(test)]
1411mod tests {
1412    use super::{CheckedFrame, MAX_CHECKED_FRAMES, attempt_while_refused, kept_with, reference_in};
1413    use std::cell::Cell;
1414    use std::io::{Error, ErrorKind};
1415    use std::time::Duration;
1416
1417    /// An attempt that is refused `refusals` times and then succeeds, counting
1418    /// how often it was made.
1419    fn refused_then_done(refusals: u32, made: &Cell<u32>) -> impl FnMut() -> std::io::Result<()> {
1420        move || {
1421            made.set(made.get() + 1);
1422            if made.get() <= refusals {
1423                Err(Error::from(ErrorKind::PermissionDenied))
1424            } else {
1425                Ok(())
1426            }
1427        }
1428    }
1429
1430    #[test]
1431    fn a_momentary_refusal_is_attempted_again_until_it_passes() {
1432        let made = Cell::new(0);
1433        let answered =
1434            attempt_while_refused(refused_then_done(2, &made), |_| true, 5, Duration::ZERO);
1435        assert!(answered.is_ok(), "{answered:?}");
1436        assert_eq!(made.get(), 3);
1437    }
1438
1439    #[test]
1440    fn a_refusal_that_outlasts_every_attempt_is_answered() {
1441        let made = Cell::new(0);
1442        let answered =
1443            attempt_while_refused(refused_then_done(9, &made), |_| true, 4, Duration::ZERO);
1444        assert_eq!(
1445            answered.map_err(|error| error.kind()),
1446            Err(ErrorKind::PermissionDenied)
1447        );
1448        assert_eq!(made.get(), 4);
1449    }
1450
1451    #[test]
1452    fn a_refusal_that_is_not_momentary_is_answered_at_once() {
1453        let made = Cell::new(0);
1454        let answered =
1455            attempt_while_refused(refused_then_done(9, &made), |_| false, 4, Duration::ZERO);
1456        assert!(answered.is_err());
1457        assert_eq!(made.get(), 1);
1458    }
1459
1460    /// The refusal the retry answers, made the way Windows makes it: the
1461    /// record held open by another handle that does not allow deleting it,
1462    /// and let go a moment later.
1463    #[cfg(windows)]
1464    #[test]
1465    fn a_record_held_open_by_another_handle_is_replaced_once_it_is_let_go() {
1466        use std::os::windows::fs::OpenOptionsExt;
1467        let directory = tempfile::TempDir::new().expect("a directory");
1468        let path = directory.path().join("record.json");
1469        std::fs::write(&path, b"before").expect("a record");
1470        let held = std::fs::OpenOptions::new()
1471            .read(true)
1472            .share_mode(0)
1473            .open(&path)
1474            .expect("the record held");
1475        let release = std::thread::spawn(move || {
1476            std::thread::sleep(Duration::from_millis(150));
1477            drop(held);
1478        });
1479        super::replace_file(&path, b"after").expect("the record replaced");
1480        release.join().expect("the handle let go");
1481        assert_eq!(std::fs::read(&path).expect("the record"), b"after");
1482        assert!(!path.with_extension("json.part").exists());
1483    }
1484
1485    #[cfg(windows)]
1486    #[test]
1487    fn only_a_held_file_is_a_momentary_refusal_on_windows() {
1488        assert!(super::refused_for_a_moment(&Error::from_raw_os_error(5)));
1489        assert!(super::refused_for_a_moment(&Error::from_raw_os_error(32)));
1490        assert!(!super::refused_for_a_moment(&Error::from_raw_os_error(2)));
1491    }
1492
1493    /// A checked frame at `z` mm, captured `second` seconds into a print.
1494    fn at(second: i64, z: f64) -> CheckedFrame {
1495        CheckedFrame {
1496            frame: format!("frame-{second}.jpg").into(),
1497            captured_at: printobserver_types::Timestamp::from_unix_seconds(1_791_489_600 + second)
1498                .expect("a time"),
1499            print_z_mm: z,
1500        }
1501    }
1502
1503    /// The heights of checked frames, in their order.
1504    fn heights(kept: &[CheckedFrame]) -> Vec<f64> {
1505        kept.iter().map(|checked| checked.print_z_mm).collect()
1506    }
1507
1508    /// Once a print carries on from a planned change, its growth is measured
1509    /// only from frames checked after: one from before the wait, however far
1510    /// below, is no longer a reference, and the first checked after it is.
1511    #[test]
1512    fn after_a_planned_change_growth_is_measured_from_frames_after_it() {
1513        let state = tempfile::TempDir::new().expect("a state directory");
1514        let store =
1515            printobserver_store_sqlite::MemoryStore::new(state.path()).expect("an in-memory store");
1516        let alignments = super::Alignments::new(state.path(), None, std::sync::Arc::new(store))
1517            .expect("the verdicts' directories");
1518        let print_id = printobserver_types::PrintId::new();
1519        for (second, z) in [(0, 0.2), (60, 0.6)] {
1520            alignments.record_checked_frame(print_id, at(second, z), 0.4);
1521        }
1522        let before = alignments.growth_reference(print_id, 1.0, 0.4);
1523        assert_eq!(before.map(|checked| checked.print_z_mm), Some(0.6));
1524
1525        alignments.restart_growth(print_id);
1526        assert_eq!(alignments.growth_reference(print_id, 1.0, 0.4), None);
1527        alignments.record_checked_frame(print_id, at(3_000, 0.8), 0.4);
1528        alignments.record_checked_frame(print_id, at(3_120, 1.4), 0.4);
1529        let after = alignments.growth_reference(print_id, 1.4, 0.4);
1530        assert_eq!(
1531            after.map(|checked| checked.captured_at),
1532            Some(at(3_000, 0.8).captured_at)
1533        );
1534        // A second change with nothing checked since forgets nothing more.
1535        alignments.restart_growth(print_id);
1536        alignments.restart_growth(print_id);
1537        assert!(alignments.checked_frames(print_id).is_empty());
1538    }
1539
1540    #[test]
1541    fn a_check_measures_from_the_newest_frame_far_enough_below_it() {
1542        let kept = [at(0, 0.2), at(60, 0.8), at(120, 2.0), at(180, 2.6)];
1543        assert_eq!(
1544            reference_in(&kept, 5.8, 3.0).map(|checked| checked.print_z_mm),
1545            Some(2.6)
1546        );
1547        assert_eq!(
1548            reference_in(&kept, 3.5, 3.0).map(|checked| checked.print_z_mm),
1549            Some(0.2)
1550        );
1551        assert_eq!(reference_in(&kept, 3.1, 3.0), None, "none is 3 mm below");
1552    }
1553
1554    #[test]
1555    fn only_what_a_later_check_can_measure_from_is_kept() {
1556        let mut kept = Vec::new();
1557        for (second, z) in [(0, 0.2), (60, 0.8), (120, 2.0), (180, 3.4), (240, 4.0)] {
1558            kept = kept_with(kept, at(second, z), 3.0);
1559        }
1560        assert_eq!(
1561            heights(&kept),
1562            [0.8, 2.0, 3.4, 4.0],
1563            "0.2 is below 0.8, which is itself 3 mm below 4.0, so no later check needs it"
1564        );
1565        assert_eq!(
1566            heights(&kept_with(kept, at(300, 1.0), 3.0)),
1567            [1.0],
1568            "a plan gone back down starts the record again"
1569        );
1570    }
1571
1572    #[test]
1573    fn the_oldest_checked_frames_go_past_the_most_kept() {
1574        let mut kept = Vec::new();
1575        for second in 0..=i64::try_from(MAX_CHECKED_FRAMES).expect("a count") {
1576            kept = kept_with(kept, at(second, 5.0), 3.0);
1577        }
1578        assert_eq!(kept.len(), MAX_CHECKED_FRAMES);
1579        assert_eq!(kept[0].captured_at, at(1, 5.0).captured_at);
1580    }
1581}