Skip to main content

printobserver_server/
alignment.rs

1//! Each print's first-layer alignment verdict: whether the camera
2//! calibration's projection lands on that print's printed first layer.
3//!
4//! A projection can be wrong with the camera unmoved, so each print verifies
5//! it once. The first time the printer watch finds a print's file position
6//! past the end of its first object layer, one frame is fetched from the
7//! camera and [`verify_first_layer_alignment`] rules on it; a fetch that gives
8//! no good frame is tried again at the next read. The verdict is written to
9//! `<state_dir>/alignment/<print id>.json`, so it stands through a restart
10//! while the print is open, and is deleted once the print closes. A print is
11//! checked once, and a failed print stays failed.
12//!
13//! Which check draws the toolpath on its image reads the verdict through
14//! [`Alignments::print_alignment`] and draws only for a print that `Passed`.
15//!
16//! Beside each verdict is kept the frame the print's last check was given,
17//! which the next check's image shows as the previous one
18//! ([`Alignments::previous_check`]): written under
19//! `<state_dir>/previous-check/<print id>.json`, standing through a restart
20//! while the print is open, and swept with the verdict once it closes.
21//!
22//! And beside that, the frames of the print's recent checks with the height
23//! the plan had reached at each ([`Alignments::checked_frames`]): written
24//! under `<state_dir>/checked-frames/<print id>.json`, kept and swept the same
25//! way, so that a check can measure whether the parts grew since one far
26//! enough below it ([`Alignments::growth_reference`]).
27
28use std::path::{Path, PathBuf};
29use std::sync::Arc;
30use std::time::Duration;
31
32use printobserver_core::store::PrintStore;
33use printobserver_core::{ActiveJob, Supervisor};
34use printobserver_panels::alignment::SEARCH_PX;
35use printobserver_panels::{
36    AlignmentInputs, CameraCalibration, ComposeError, FrameField, verify_first_layer_alignment,
37};
38use printobserver_types::PrintId;
39use printobserver_types::contract::Sample;
40use printobserver_types::schemars::JsonSchema;
41use printobserver_types::serde::{Deserialize, Serialize};
42
43/// Why a print's alignment failed.
44#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
45#[serde(
46    crate = "printobserver_types::serde",
47    tag = "failure",
48    rename_all = "snake_case"
49)]
50#[schemars(crate = "printobserver_types::schemars")]
51pub enum AlignmentFailure {
52    /// The printed first layer lies further from its projection than the
53    /// calibration allows.
54    Offset {
55        /// How far, in calibration pixels.
56        offset_px: f64,
57    },
58    /// The camera's frames are not the calibration's resolution.
59    Resolution {
60        /// The calibration's, `[width, height]`.
61        expected: [u32; 2],
62        /// The frame's.
63        got: [u32; 2],
64    },
65    /// The camera configured is not the stream the calibration was fitted on.
66    Stream,
67}
68
69/// One print's first-layer alignment verdict, as it is kept under the state
70/// directory — which the real-print suite's record reads.
71#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
72#[serde(
73    crate = "printobserver_types::serde",
74    tag = "verdict",
75    rename_all = "snake_case"
76)]
77#[schemars(crate = "printobserver_types::schemars")]
78pub enum PrintAlignment {
79    /// Nothing can be checked: no calibration is configured, or the print's
80    /// G-code lays no object.
81    Unavailable,
82    /// The first object layer is not down yet, or no frame of it has been
83    /// judged.
84    Pending,
85    /// The projected first layer lands on the printed one.
86    Passed {
87        /// How far it lies from it, in calibration pixels.
88        offset_px: f64,
89    },
90    /// It does not, or the frames cannot be judged against the calibration.
91    Failed {
92        /// Why.
93        reason: AlignmentFailure,
94    },
95}
96
97impl Sample for PrintAlignment {
98    fn sample_full() -> Self {
99        Self::Passed { offset_px: 14.5 }
100    }
101
102    fn sample_minimal() -> Self {
103        Self::Pending
104    }
105
106    fn sample_alternates() -> Vec<Self> {
107        vec![
108            Self::Unavailable,
109            Self::Failed {
110                reason: AlignmentFailure::Offset { offset_px: 48.5 },
111            },
112            Self::Failed {
113                reason: AlignmentFailure::Resolution {
114                    expected: [1920, 1080],
115                    got: [1280, 720],
116                },
117            },
118            Self::Failed {
119                reason: AlignmentFailure::Stream,
120            },
121        ]
122    }
123}
124
125/// The frame one print's last check was given, and when it was captured.
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
127#[serde(crate = "printobserver_types::serde")]
128pub struct PreviousCheck {
129    /// The stored frame's path.
130    pub frame: PathBuf,
131    /// When it was captured.
132    pub captured_at: printobserver_types::Timestamp,
133}
134
135/// One check's frame and the height the plan had reached as it was captured.
136#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
137#[serde(crate = "printobserver_types::serde")]
138pub struct CheckedFrame {
139    /// The stored frame's path.
140    pub frame: PathBuf,
141    /// When it was captured.
142    pub captured_at: printobserver_types::Timestamp,
143    /// The print's height in its plan then, in millimetres.
144    pub print_z_mm: f64,
145}
146
147/// The most checked frames one print keeps; past it the oldest are dropped.
148const MAX_CHECKED_FRAMES: usize = 512;
149
150/// The alignment verdicts of every print, what decides them, the frame each
151/// print's last check was given, and its recent checks' frames and heights.
152pub struct Alignments {
153    /// Where each print's verdict is kept.
154    directory: PathBuf,
155    /// Where each print's last check's frame is named.
156    previous_directory: PathBuf,
157    /// Where each print's recent checks' frames and heights are kept.
158    checked_directory: PathBuf,
159    /// The camera's calibration, when one is configured.
160    calibration: Option<Arc<CameraCalibration>>,
161    /// The prints, to tell which are open.
162    prints: Arc<dyn PrintStore>,
163}
164
165impl core::fmt::Debug for Alignments {
166    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
167        formatter
168            .debug_struct("Alignments")
169            .field("directory", &self.directory)
170            .field("calibrated", &self.calibration.is_some())
171            .finish_non_exhaustive()
172    }
173}
174
175/// The directory verdicts are kept in, under a state directory.
176#[must_use]
177pub fn verdict_dir(state_dir: &Path) -> PathBuf {
178    state_dir.join("alignment")
179}
180
181/// The directory each print's last check's frame is named in, under a state
182/// directory.
183#[must_use]
184pub fn previous_check_dir(state_dir: &Path) -> PathBuf {
185    state_dir.join("previous-check")
186}
187
188/// The directory each print's recent checks' frames and heights are kept in,
189/// under a state directory.
190#[must_use]
191pub fn checked_frames_dir(state_dir: &Path) -> PathBuf {
192    state_dir.join("checked-frames")
193}
194
195impl Alignments {
196    /// The verdicts kept under one state directory.
197    ///
198    /// # Errors
199    ///
200    /// The filesystem's own error when the directory cannot be made.
201    pub fn new(
202        state_dir: &Path,
203        calibration: Option<Arc<CameraCalibration>>,
204        prints: Arc<dyn PrintStore>,
205    ) -> std::io::Result<Self> {
206        let directory = verdict_dir(state_dir);
207        std::fs::create_dir_all(&directory)?;
208        let previous_directory = previous_check_dir(state_dir);
209        std::fs::create_dir_all(&previous_directory)?;
210        let checked_directory = checked_frames_dir(state_dir);
211        std::fs::create_dir_all(&checked_directory)?;
212        Ok(Self {
213            directory,
214            previous_directory,
215            checked_directory,
216            calibration,
217            prints,
218        })
219    }
220
221    /// Where one print's verdict is kept.
222    fn path_of(&self, print_id: PrintId) -> PathBuf {
223        self.directory.join(format!("{print_id}.json"))
224    }
225
226    /// The camera calibration in force, when one is configured.
227    #[must_use]
228    pub fn calibration(&self) -> Option<&CameraCalibration> {
229        self.calibration.as_deref()
230    }
231
232    /// Where one print's last check's frame is named.
233    fn previous_path_of(&self, print_id: PrintId) -> PathBuf {
234        self.previous_directory.join(format!("{print_id}.json"))
235    }
236
237    /// The frame one print's last check was given; nothing before its first
238    /// check, or when the record cannot be read back.
239    #[must_use]
240    pub fn previous_check(&self, print_id: PrintId) -> Option<PreviousCheck> {
241        std::fs::read(self.previous_path_of(print_id))
242            .ok()
243            .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
244    }
245
246    /// Name the frame one print's check was given, which its next check shows
247    /// as the previous. A record the filesystem refuses for a moment is
248    /// replaced once the refusal passes ([`replace_file`]); one it goes on
249    /// refusing is said on the log and leaves the record before it standing,
250    /// so the next check shows an older frame as the previous rather than
251    /// none. No test makes the refusal last: that needs the state directory
252    /// made to refuse writes beneath a running server, which refuses the
253    /// store's own writes first. What a check makes of a record it cannot use
254    /// — an empty panel 3 — is proved by
255    /// `a_lost_previous_frame_empties_panel_3_and_the_record_goes_with_the_print`.
256    pub fn record_check(&self, print_id: PrintId, check: &PreviousCheck) {
257        let Ok(bytes) = printobserver_types::serde_json::to_vec(check) else {
258            return;
259        };
260        if let Err(error) = replace_file(&self.previous_path_of(print_id), &bytes) {
261            eprintln!(
262                "printobserver: print {print_id}: the last check's frame could not be recorded, so the next check shows an older one or none: {error}"
263            );
264        }
265    }
266
267    /// Where one print's recent checks' frames and heights are kept.
268    fn checked_path_of(&self, print_id: PrintId) -> PathBuf {
269        self.checked_directory.join(format!("{print_id}.json"))
270    }
271
272    /// One print's recent checks' frames and heights, oldest first; none
273    /// before its first check with a height, or when the record cannot be
274    /// read back.
275    #[must_use]
276    pub fn checked_frames(&self, print_id: PrintId) -> Vec<CheckedFrame> {
277        std::fs::read(self.checked_path_of(print_id))
278            .ok()
279            .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
280            .unwrap_or_default()
281    }
282
283    /// Forget one print's checked frames, so its growth is measured only from
284    /// checks made after now: the print waited at a planned change, and a frame
285    /// from before the wait would count the wait as no growth. A record the
286    /// filesystem will not remove is said on the log and left, so a later check
287    /// measures from a frame before the wait, which says no more than that a
288    /// check could not tell.
289    pub fn restart_growth(&self, print_id: PrintId) {
290        let path = self.checked_path_of(print_id);
291        if let Err(error) = std::fs::remove_file(&path)
292            && error.kind() != std::io::ErrorKind::NotFound
293        {
294            eprintln!(
295                "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}"
296            );
297        }
298    }
299
300    /// The frame a check at `print_z_mm` measures growth from: the newest
301    /// checked frame of the print at least `rise_mm` below it in the plan.
302    #[must_use]
303    pub fn growth_reference(
304        &self,
305        print_id: PrintId,
306        print_z_mm: f64,
307        rise_mm: f64,
308    ) -> Option<CheckedFrame> {
309        reference_in(&self.checked_frames(print_id), print_z_mm, rise_mm).cloned()
310    }
311
312    /// Keep one check's frame and height among the print's, keeping only what
313    /// a later check at `rise_mm` above some kept height can still measure
314    /// from: the newest frame at least that far below this one and every
315    /// frame after it. A height below the last kept one is a plan that went
316    /// back down, as a print of one object after another does, and starts the
317    /// record again. A record the filesystem refuses is said on the log and
318    /// leaves the one before standing, as [`record_check`](Self::record_check)
319    /// does.
320    pub fn record_checked_frame(&self, print_id: PrintId, checked: CheckedFrame, rise_mm: f64) {
321        let kept = kept_with(self.checked_frames(print_id), checked, rise_mm);
322        let Ok(bytes) = printobserver_types::serde_json::to_vec(&kept) else {
323            return;
324        };
325        if let Err(error) = replace_file(&self.checked_path_of(print_id), &bytes) {
326            eprintln!(
327                "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}"
328            );
329        }
330    }
331
332    /// One print's verdict as it stands.
333    #[must_use]
334    pub fn print_alignment(&self, print_id: PrintId) -> PrintAlignment {
335        if self.calibration.is_none() {
336            return PrintAlignment::Unavailable;
337        }
338        std::fs::read(self.path_of(print_id))
339            .ok()
340            .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
341            .unwrap_or(PrintAlignment::Pending)
342    }
343
344    /// Rule on the running print's alignment once its first object layer is
345    /// down, when it has no verdict yet. Answers the verdict it wrote, and
346    /// nothing when it wrote none — not yet due, or no good frame came.
347    pub async fn check(
348        &self,
349        supervisor: &Supervisor,
350        active: ActiveJob,
351    ) -> Option<PrintAlignment> {
352        let calibration = self.calibration.as_ref()?;
353        // A verdict file that cannot be read back is no verdict, and is
354        // decided again over it.
355        if self.print_alignment(active.print_id) != PrintAlignment::Pending {
356            return None;
357        }
358        let position = u64::try_from(active.file_position_bytes?).ok()?;
359        let index = supervisor.print_gcode_index(active.print_id).await?;
360        let Some((first, ends)) = index.first_object_layer() else {
361            return self.decide(active.print_id, PrintAlignment::Unavailable);
362        };
363        if position <= ends {
364            return None;
365        }
366        let first_layer = index.layer_toolpath(first).ok()?;
367        let print_z_mm = index
368            .layer_at(position)
369            .and_then(|layer| index.layer_z_mm(layer))?;
370        let (url, frame) = supervisor.fetch_camera_frame(active.print_id).await?;
371        let verdict = match verify_first_layer_alignment(&AlignmentInputs {
372            frame_jpeg: &frame,
373            camera_snapshot_url: &url,
374            first_layer: &first_layer,
375            print_z_mm,
376            calibration,
377        }) {
378            Ok(found) if found.passed => PrintAlignment::Passed {
379                offset_px: found.offset_px,
380            },
381            Ok(found) => PrintAlignment::Failed {
382                reason: AlignmentFailure::Offset {
383                    offset_px: found.offset_px,
384                },
385            },
386            Err(ComposeError::FrameMismatch {
387                field: FrameField::Resolution,
388                got,
389                ..
390            }) => PrintAlignment::Failed {
391                reason: AlignmentFailure::Resolution {
392                    expected: calibration.image_size_px,
393                    got: size_of(&got),
394                },
395            },
396            Err(ComposeError::FrameMismatch {
397                field: FrameField::Stream,
398                ..
399            }) => PrintAlignment::Failed {
400                reason: AlignmentFailure::Stream,
401            },
402            // A first layer projecting nowhere in the frame is as far from
403            // it as the check looks.
404            Err(ComposeError::OutlineOffFrame) => PrintAlignment::Failed {
405                reason: AlignmentFailure::Offset {
406                    offset_px: f64::from(SEARCH_PX),
407                },
408            },
409            Err(_) => return None,
410        };
411        self.decide(active.print_id, verdict)
412    }
413
414    /// Keep a verdict, and say it. A verdict the filesystem goes on refusing
415    /// ([`replace_file`]) is
416    /// decided again at the next read rather than lost; no test makes the
417    /// state directory refuse a write, which needs a filesystem made to fail
418    /// beneath a running server, and the retry is the same path a fetch that
419    /// gave no frame takes, which `aligning` proves.
420    fn decide(&self, print_id: PrintId, verdict: PrintAlignment) -> Option<PrintAlignment> {
421        let bytes = printobserver_types::serde_json::to_vec(&verdict).ok()?;
422        replace_file(&self.path_of(print_id), &bytes).ok()?;
423        eprintln!(
424            "printobserver: print {print_id}: first-layer alignment {}",
425            said(&verdict)
426        );
427        Some(verdict)
428    }
429
430    /// Delete the verdict, the last check's record and the checked frames of
431    /// every print that is not open.
432    ///
433    /// An open print's record still being written — the `.json.part` beside it
434    /// that [`replace_file`] renames over it — is its own, and kept: the watch
435    /// sweeps after every read, so a sweep removing it between the write and the
436    /// rename lost that record, and the print's next check showed no previous
437    /// frame.
438    ///
439    /// A store that cannot list the open prints, a directory that cannot be
440    /// listed and a file that cannot be removed each leave a verdict behind,
441    /// which the next read's sweep tries again. No test makes either refuse,
442    /// since that needs a store or filesystem made to fail beneath a running
443    /// server; the `aligning` journeys prove the sweep removes a closed
444    /// print's verdict and keeps an open one's, after a close and at start.
445    pub async fn sweep(&self) {
446        let Ok(open) = self.prints.open_prints().await else {
447            return;
448        };
449        let open: Vec<String> = open
450            .iter()
451            .flat_map(|print| {
452                [
453                    format!("{}.json", print.id),
454                    format!("{}.json.part", print.id),
455                ]
456            })
457            .collect();
458        for directory in [
459            &self.directory,
460            &self.previous_directory,
461            &self.checked_directory,
462        ] {
463            let Ok(entries) = std::fs::read_dir(directory) else {
464                continue;
465            };
466            for entry in entries.flatten() {
467                let name = entry.file_name();
468                if !open.iter().any(|kept| name.to_str() == Some(kept.as_str())) {
469                    let _ = std::fs::remove_file(entry.path());
470                }
471            }
472        }
473    }
474}
475
476/// The newest of a print's checked frames, oldest first, at least `rise_mm`
477/// below `print_z_mm` in the plan.
478fn reference_in(kept: &[CheckedFrame], print_z_mm: f64, rise_mm: f64) -> Option<&CheckedFrame> {
479    kept.iter()
480        .rev()
481        .find(|checked| checked.print_z_mm <= print_z_mm - rise_mm)
482}
483
484/// A print's checked frames once `checked` is kept among them: the newest
485/// earlier frame at least `rise_mm` below it and every frame after that, then
486/// it, at most [`MAX_CHECKED_FRAMES`] of them, the oldest dropped first; or it
487/// alone when it is below the last kept, a plan gone back down.
488fn kept_with(
489    mut kept: Vec<CheckedFrame>,
490    checked: CheckedFrame,
491    rise_mm: f64,
492) -> Vec<CheckedFrame> {
493    if kept
494        .last()
495        .is_some_and(|last| checked.print_z_mm < last.print_z_mm)
496    {
497        kept.clear();
498    }
499    if let Some(reference) = kept
500        .iter()
501        .rposition(|earlier| earlier.print_z_mm <= checked.print_z_mm - rise_mm)
502    {
503        kept.drain(..reference);
504    }
505    kept.push(checked);
506    if kept.len() > MAX_CHECKED_FRAMES {
507        kept.drain(..kept.len() - MAX_CHECKED_FRAMES);
508    }
509    kept
510}
511
512/// How many times one file's replacement is attempted while the filesystem
513/// refuses it for a moment, and the pause between two attempts: half a second
514/// in all, on a check that is otherwise waiting on no one.
515const REPLACE_ATTEMPTS: u32 = 20;
516const REPLACE_PAUSE: Duration = Duration::from_millis(25);
517
518/// Put `bytes` at `path` whole: written beside it, then renamed over it, so a
519/// reader finds the old file or the new one and never part of either.
520///
521/// Windows refuses to replace a file another process holds open without
522/// letting it be deleted — a scanner reading what was just written does — and
523/// that refusal ends when the other process closes it. So a refusal of that
524/// kind is attempted again, up to [`REPLACE_ATTEMPTS`] times; any other, or
525/// one that outlasts them, is answered, with the file beside it removed.
526///
527/// # Errors
528///
529/// The filesystem's own error for the last attempt.
530fn replace_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
531    let held = path.with_extension("json.part");
532    attempt_while_refused(
533        || {
534            std::fs::write(&held, bytes)?;
535            std::fs::rename(&held, path)
536        },
537        refused_for_a_moment,
538        REPLACE_ATTEMPTS,
539        REPLACE_PAUSE,
540    )
541    .inspect_err(|_| {
542        let _ = std::fs::remove_file(&held);
543    })
544}
545
546/// Run `attempt` until it succeeds, fails with an error `refused` does not
547/// call momentary, or has been run `attempts` times, pausing between two.
548fn attempt_while_refused(
549    mut attempt: impl FnMut() -> std::io::Result<()>,
550    refused: impl Fn(&std::io::Error) -> bool,
551    attempts: u32,
552    pause: Duration,
553) -> std::io::Result<()> {
554    let mut made = 1;
555    loop {
556        match attempt() {
557            Err(error) if made < attempts && refused(&error) => {
558                std::thread::sleep(pause);
559                made += 1;
560            }
561            answered => return answered,
562        }
563    }
564}
565
566/// Whether Windows refused a replacement only because another handle has the
567/// file open: `ERROR_ACCESS_DENIED` (5) or `ERROR_SHARING_VIOLATION` (32).
568#[cfg(windows)]
569fn refused_for_a_moment(error: &std::io::Error) -> bool {
570    matches!(error.raw_os_error(), Some(5 | 32))
571}
572
573/// Elsewhere a rename replaces a file whoever has it open, so no refusal is
574/// momentary.
575#[cfg(not(windows))]
576fn refused_for_a_moment(_error: &std::io::Error) -> bool {
577    false
578}
579
580/// A frame size as the refusal spells it, `<w>x<h>`.
581fn size_of(text: &str) -> [u32; 2] {
582    let mut parts = text.split('x').map(|part| part.parse().unwrap_or(0));
583    [parts.next().unwrap_or(0), parts.next().unwrap_or(0)]
584}
585
586/// A verdict as the log says it.
587fn said(verdict: &PrintAlignment) -> String {
588    match verdict {
589        PrintAlignment::Unavailable => "unavailable: the G-code lays no object".to_owned(),
590        PrintAlignment::Pending => "pending".to_owned(),
591        PrintAlignment::Passed { offset_px } => format!("passed, offset {offset_px:.1} px"),
592        PrintAlignment::Failed {
593            reason: AlignmentFailure::Offset { offset_px },
594        } => format!("failed, offset {offset_px:.1} px"),
595        PrintAlignment::Failed {
596            reason: AlignmentFailure::Resolution { expected, got },
597        } => format!(
598            "failed: the camera's frames are {}x{}, the calibration's {}x{}",
599            got[0], got[1], expected[0], expected[1]
600        ),
601        PrintAlignment::Failed {
602            reason: AlignmentFailure::Stream,
603        } => "failed: the camera is not the stream the calibration was fitted on".to_owned(),
604    }
605}
606
607#[cfg(test)]
608mod tests {
609    use super::{CheckedFrame, MAX_CHECKED_FRAMES, attempt_while_refused, kept_with, reference_in};
610    use std::cell::Cell;
611    use std::io::{Error, ErrorKind};
612    use std::time::Duration;
613
614    /// An attempt that is refused `refusals` times and then succeeds, counting
615    /// how often it was made.
616    fn refused_then_done(refusals: u32, made: &Cell<u32>) -> impl FnMut() -> std::io::Result<()> {
617        move || {
618            made.set(made.get() + 1);
619            if made.get() <= refusals {
620                Err(Error::from(ErrorKind::PermissionDenied))
621            } else {
622                Ok(())
623            }
624        }
625    }
626
627    #[test]
628    fn a_momentary_refusal_is_attempted_again_until_it_passes() {
629        let made = Cell::new(0);
630        let answered =
631            attempt_while_refused(refused_then_done(2, &made), |_| true, 5, Duration::ZERO);
632        assert!(answered.is_ok(), "{answered:?}");
633        assert_eq!(made.get(), 3);
634    }
635
636    #[test]
637    fn a_refusal_that_outlasts_every_attempt_is_answered() {
638        let made = Cell::new(0);
639        let answered =
640            attempt_while_refused(refused_then_done(9, &made), |_| true, 4, Duration::ZERO);
641        assert_eq!(
642            answered.map_err(|error| error.kind()),
643            Err(ErrorKind::PermissionDenied)
644        );
645        assert_eq!(made.get(), 4);
646    }
647
648    #[test]
649    fn a_refusal_that_is_not_momentary_is_answered_at_once() {
650        let made = Cell::new(0);
651        let answered =
652            attempt_while_refused(refused_then_done(9, &made), |_| false, 4, Duration::ZERO);
653        assert!(answered.is_err());
654        assert_eq!(made.get(), 1);
655    }
656
657    /// The refusal the retry answers, made the way Windows makes it: the
658    /// record held open by another handle that does not allow deleting it,
659    /// and let go a moment later.
660    #[cfg(windows)]
661    #[test]
662    fn a_record_held_open_by_another_handle_is_replaced_once_it_is_let_go() {
663        use std::os::windows::fs::OpenOptionsExt;
664        let directory = tempfile::TempDir::new().expect("a directory");
665        let path = directory.path().join("record.json");
666        std::fs::write(&path, b"before").expect("a record");
667        let held = std::fs::OpenOptions::new()
668            .read(true)
669            .share_mode(0)
670            .open(&path)
671            .expect("the record held");
672        let release = std::thread::spawn(move || {
673            std::thread::sleep(Duration::from_millis(150));
674            drop(held);
675        });
676        super::replace_file(&path, b"after").expect("the record replaced");
677        release.join().expect("the handle let go");
678        assert_eq!(std::fs::read(&path).expect("the record"), b"after");
679        assert!(!path.with_extension("json.part").exists());
680    }
681
682    #[cfg(windows)]
683    #[test]
684    fn only_a_held_file_is_a_momentary_refusal_on_windows() {
685        assert!(super::refused_for_a_moment(&Error::from_raw_os_error(5)));
686        assert!(super::refused_for_a_moment(&Error::from_raw_os_error(32)));
687        assert!(!super::refused_for_a_moment(&Error::from_raw_os_error(2)));
688    }
689
690    /// A checked frame at `z` mm, captured `second` seconds into a print.
691    fn at(second: i64, z: f64) -> CheckedFrame {
692        CheckedFrame {
693            frame: format!("frame-{second}.jpg").into(),
694            captured_at: printobserver_types::Timestamp::from_unix_seconds(1_791_489_600 + second)
695                .expect("a time"),
696            print_z_mm: z,
697        }
698    }
699
700    /// The heights of checked frames, in their order.
701    fn heights(kept: &[CheckedFrame]) -> Vec<f64> {
702        kept.iter().map(|checked| checked.print_z_mm).collect()
703    }
704
705    /// Once a print carries on from a planned change, its growth is measured
706    /// only from frames checked after: one from before the wait, however far
707    /// below, is no longer a reference, and the first checked after it is.
708    #[test]
709    fn after_a_planned_change_growth_is_measured_from_frames_after_it() {
710        let state = tempfile::TempDir::new().expect("a state directory");
711        let store =
712            printobserver_store_sqlite::MemoryStore::new(state.path()).expect("an in-memory store");
713        let alignments = super::Alignments::new(state.path(), None, std::sync::Arc::new(store))
714            .expect("the verdicts' directories");
715        let print_id = printobserver_types::PrintId::new();
716        for (second, z) in [(0, 0.2), (60, 0.6)] {
717            alignments.record_checked_frame(print_id, at(second, z), 0.4);
718        }
719        let before = alignments.growth_reference(print_id, 1.0, 0.4);
720        assert_eq!(before.map(|checked| checked.print_z_mm), Some(0.6));
721
722        alignments.restart_growth(print_id);
723        assert_eq!(alignments.growth_reference(print_id, 1.0, 0.4), None);
724        alignments.record_checked_frame(print_id, at(3_000, 0.8), 0.4);
725        alignments.record_checked_frame(print_id, at(3_120, 1.4), 0.4);
726        let after = alignments.growth_reference(print_id, 1.4, 0.4);
727        assert_eq!(
728            after.map(|checked| checked.captured_at),
729            Some(at(3_000, 0.8).captured_at)
730        );
731        // A second change with nothing checked since forgets nothing more.
732        alignments.restart_growth(print_id);
733        alignments.restart_growth(print_id);
734        assert!(alignments.checked_frames(print_id).is_empty());
735    }
736
737    #[test]
738    fn a_check_measures_from_the_newest_frame_far_enough_below_it() {
739        let kept = [at(0, 0.2), at(60, 0.8), at(120, 2.0), at(180, 2.6)];
740        assert_eq!(
741            reference_in(&kept, 5.8, 3.0).map(|checked| checked.print_z_mm),
742            Some(2.6)
743        );
744        assert_eq!(
745            reference_in(&kept, 3.5, 3.0).map(|checked| checked.print_z_mm),
746            Some(0.2)
747        );
748        assert_eq!(reference_in(&kept, 3.1, 3.0), None, "none is 3 mm below");
749    }
750
751    #[test]
752    fn only_what_a_later_check_can_measure_from_is_kept() {
753        let mut kept = Vec::new();
754        for (second, z) in [(0, 0.2), (60, 0.8), (120, 2.0), (180, 3.4), (240, 4.0)] {
755            kept = kept_with(kept, at(second, z), 3.0);
756        }
757        assert_eq!(
758            heights(&kept),
759            [0.8, 2.0, 3.4, 4.0],
760            "0.2 is below 0.8, which is itself 3 mm below 4.0, so no later check needs it"
761        );
762        assert_eq!(
763            heights(&kept_with(kept, at(300, 1.0), 3.0)),
764            [1.0],
765            "a plan gone back down starts the record again"
766        );
767    }
768
769    #[test]
770    fn the_oldest_checked_frames_go_past_the_most_kept() {
771        let mut kept = Vec::new();
772        for second in 0..=i64::try_from(MAX_CHECKED_FRAMES).expect("a count") {
773            kept = kept_with(kept, at(second, 5.0), 3.0);
774        }
775        assert_eq!(kept.len(), MAX_CHECKED_FRAMES);
776        assert_eq!(kept[0].captured_at, at(1, 5.0).captured_at);
777    }
778}