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    /// The frame a check at `print_z_mm` measures growth from: the newest
284    /// checked frame of the print at least `rise_mm` below it in the plan.
285    #[must_use]
286    pub fn growth_reference(
287        &self,
288        print_id: PrintId,
289        print_z_mm: f64,
290        rise_mm: f64,
291    ) -> Option<CheckedFrame> {
292        reference_in(&self.checked_frames(print_id), print_z_mm, rise_mm).cloned()
293    }
294
295    /// Keep one check's frame and height among the print's, keeping only what
296    /// a later check at `rise_mm` above some kept height can still measure
297    /// from: the newest frame at least that far below this one and every
298    /// frame after it. A height below the last kept one is a plan that went
299    /// back down, as a print of one object after another does, and starts the
300    /// record again. A record the filesystem refuses is said on the log and
301    /// leaves the one before standing, as [`record_check`](Self::record_check)
302    /// does.
303    pub fn record_checked_frame(&self, print_id: PrintId, checked: CheckedFrame, rise_mm: f64) {
304        let kept = kept_with(self.checked_frames(print_id), checked, rise_mm);
305        let Ok(bytes) = printobserver_types::serde_json::to_vec(&kept) else {
306            return;
307        };
308        if let Err(error) = replace_file(&self.checked_path_of(print_id), &bytes) {
309            eprintln!(
310                "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}"
311            );
312        }
313    }
314
315    /// One print's verdict as it stands.
316    #[must_use]
317    pub fn print_alignment(&self, print_id: PrintId) -> PrintAlignment {
318        if self.calibration.is_none() {
319            return PrintAlignment::Unavailable;
320        }
321        std::fs::read(self.path_of(print_id))
322            .ok()
323            .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
324            .unwrap_or(PrintAlignment::Pending)
325    }
326
327    /// Rule on the running print's alignment once its first object layer is
328    /// down, when it has no verdict yet. Answers the verdict it wrote, and
329    /// nothing when it wrote none — not yet due, or no good frame came.
330    pub async fn check(
331        &self,
332        supervisor: &Supervisor,
333        active: ActiveJob,
334    ) -> Option<PrintAlignment> {
335        let calibration = self.calibration.as_ref()?;
336        // A verdict file that cannot be read back is no verdict, and is
337        // decided again over it.
338        if self.print_alignment(active.print_id) != PrintAlignment::Pending {
339            return None;
340        }
341        let position = u64::try_from(active.file_position_bytes?).ok()?;
342        let index = supervisor.print_gcode_index(active.print_id).await?;
343        let Some((first, ends)) = index.first_object_layer() else {
344            return self.decide(active.print_id, PrintAlignment::Unavailable);
345        };
346        if position <= ends {
347            return None;
348        }
349        let first_layer = index.layer_toolpath(first).ok()?;
350        let print_z_mm = index
351            .layer_at(position)
352            .and_then(|layer| index.layer_z_mm(layer))?;
353        let (url, frame) = supervisor.fetch_camera_frame(active.print_id).await?;
354        let verdict = match verify_first_layer_alignment(&AlignmentInputs {
355            frame_jpeg: &frame,
356            camera_snapshot_url: &url,
357            first_layer: &first_layer,
358            print_z_mm,
359            calibration,
360        }) {
361            Ok(found) if found.passed => PrintAlignment::Passed {
362                offset_px: found.offset_px,
363            },
364            Ok(found) => PrintAlignment::Failed {
365                reason: AlignmentFailure::Offset {
366                    offset_px: found.offset_px,
367                },
368            },
369            Err(ComposeError::FrameMismatch {
370                field: FrameField::Resolution,
371                got,
372                ..
373            }) => PrintAlignment::Failed {
374                reason: AlignmentFailure::Resolution {
375                    expected: calibration.image_size_px,
376                    got: size_of(&got),
377                },
378            },
379            Err(ComposeError::FrameMismatch {
380                field: FrameField::Stream,
381                ..
382            }) => PrintAlignment::Failed {
383                reason: AlignmentFailure::Stream,
384            },
385            // A first layer projecting nowhere in the frame is as far from
386            // it as the check looks.
387            Err(ComposeError::OutlineOffFrame) => PrintAlignment::Failed {
388                reason: AlignmentFailure::Offset {
389                    offset_px: f64::from(SEARCH_PX),
390                },
391            },
392            Err(_) => return None,
393        };
394        self.decide(active.print_id, verdict)
395    }
396
397    /// Keep a verdict, and say it. A verdict the filesystem goes on refusing
398    /// ([`replace_file`]) is
399    /// decided again at the next read rather than lost; no test makes the
400    /// state directory refuse a write, which needs a filesystem made to fail
401    /// beneath a running server, and the retry is the same path a fetch that
402    /// gave no frame takes, which `aligning` proves.
403    fn decide(&self, print_id: PrintId, verdict: PrintAlignment) -> Option<PrintAlignment> {
404        let bytes = printobserver_types::serde_json::to_vec(&verdict).ok()?;
405        replace_file(&self.path_of(print_id), &bytes).ok()?;
406        eprintln!(
407            "printobserver: print {print_id}: first-layer alignment {}",
408            said(&verdict)
409        );
410        Some(verdict)
411    }
412
413    /// Delete the verdict, the last check's record and the checked frames of
414    /// every print that is not open.
415    ///
416    /// An open print's record still being written — the `.json.part` beside it
417    /// that [`replace_file`] renames over it — is its own, and kept: the watch
418    /// sweeps after every read, so a sweep removing it between the write and the
419    /// rename lost that record, and the print's next check showed no previous
420    /// frame.
421    ///
422    /// A store that cannot list the open prints, a directory that cannot be
423    /// listed and a file that cannot be removed each leave a verdict behind,
424    /// which the next read's sweep tries again. No test makes either refuse,
425    /// since that needs a store or filesystem made to fail beneath a running
426    /// server; the `aligning` journeys prove the sweep removes a closed
427    /// print's verdict and keeps an open one's, after a close and at start.
428    pub async fn sweep(&self) {
429        let Ok(open) = self.prints.open_prints().await else {
430            return;
431        };
432        let open: Vec<String> = open
433            .iter()
434            .flat_map(|print| {
435                [
436                    format!("{}.json", print.id),
437                    format!("{}.json.part", print.id),
438                ]
439            })
440            .collect();
441        for directory in [
442            &self.directory,
443            &self.previous_directory,
444            &self.checked_directory,
445        ] {
446            let Ok(entries) = std::fs::read_dir(directory) else {
447                continue;
448            };
449            for entry in entries.flatten() {
450                let name = entry.file_name();
451                if !open.iter().any(|kept| name.to_str() == Some(kept.as_str())) {
452                    let _ = std::fs::remove_file(entry.path());
453                }
454            }
455        }
456    }
457}
458
459/// The newest of a print's checked frames, oldest first, at least `rise_mm`
460/// below `print_z_mm` in the plan.
461fn reference_in(kept: &[CheckedFrame], print_z_mm: f64, rise_mm: f64) -> Option<&CheckedFrame> {
462    kept.iter()
463        .rev()
464        .find(|checked| checked.print_z_mm <= print_z_mm - rise_mm)
465}
466
467/// A print's checked frames once `checked` is kept among them: the newest
468/// earlier frame at least `rise_mm` below it and every frame after that, then
469/// it, at most [`MAX_CHECKED_FRAMES`] of them, the oldest dropped first; or it
470/// alone when it is below the last kept, a plan gone back down.
471fn kept_with(
472    mut kept: Vec<CheckedFrame>,
473    checked: CheckedFrame,
474    rise_mm: f64,
475) -> Vec<CheckedFrame> {
476    if kept
477        .last()
478        .is_some_and(|last| checked.print_z_mm < last.print_z_mm)
479    {
480        kept.clear();
481    }
482    if let Some(reference) = kept
483        .iter()
484        .rposition(|earlier| earlier.print_z_mm <= checked.print_z_mm - rise_mm)
485    {
486        kept.drain(..reference);
487    }
488    kept.push(checked);
489    if kept.len() > MAX_CHECKED_FRAMES {
490        kept.drain(..kept.len() - MAX_CHECKED_FRAMES);
491    }
492    kept
493}
494
495/// How many times one file's replacement is attempted while the filesystem
496/// refuses it for a moment, and the pause between two attempts: half a second
497/// in all, on a check that is otherwise waiting on no one.
498const REPLACE_ATTEMPTS: u32 = 20;
499const REPLACE_PAUSE: Duration = Duration::from_millis(25);
500
501/// Put `bytes` at `path` whole: written beside it, then renamed over it, so a
502/// reader finds the old file or the new one and never part of either.
503///
504/// Windows refuses to replace a file another process holds open without
505/// letting it be deleted — a scanner reading what was just written does — and
506/// that refusal ends when the other process closes it. So a refusal of that
507/// kind is attempted again, up to [`REPLACE_ATTEMPTS`] times; any other, or
508/// one that outlasts them, is answered, with the file beside it removed.
509///
510/// # Errors
511///
512/// The filesystem's own error for the last attempt.
513fn replace_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
514    let held = path.with_extension("json.part");
515    attempt_while_refused(
516        || {
517            std::fs::write(&held, bytes)?;
518            std::fs::rename(&held, path)
519        },
520        refused_for_a_moment,
521        REPLACE_ATTEMPTS,
522        REPLACE_PAUSE,
523    )
524    .inspect_err(|_| {
525        let _ = std::fs::remove_file(&held);
526    })
527}
528
529/// Run `attempt` until it succeeds, fails with an error `refused` does not
530/// call momentary, or has been run `attempts` times, pausing between two.
531fn attempt_while_refused(
532    mut attempt: impl FnMut() -> std::io::Result<()>,
533    refused: impl Fn(&std::io::Error) -> bool,
534    attempts: u32,
535    pause: Duration,
536) -> std::io::Result<()> {
537    let mut made = 1;
538    loop {
539        match attempt() {
540            Err(error) if made < attempts && refused(&error) => {
541                std::thread::sleep(pause);
542                made += 1;
543            }
544            answered => return answered,
545        }
546    }
547}
548
549/// Whether Windows refused a replacement only because another handle has the
550/// file open: `ERROR_ACCESS_DENIED` (5) or `ERROR_SHARING_VIOLATION` (32).
551#[cfg(windows)]
552fn refused_for_a_moment(error: &std::io::Error) -> bool {
553    matches!(error.raw_os_error(), Some(5 | 32))
554}
555
556/// Elsewhere a rename replaces a file whoever has it open, so no refusal is
557/// momentary.
558#[cfg(not(windows))]
559fn refused_for_a_moment(_error: &std::io::Error) -> bool {
560    false
561}
562
563/// A frame size as the refusal spells it, `<w>x<h>`.
564fn size_of(text: &str) -> [u32; 2] {
565    let mut parts = text.split('x').map(|part| part.parse().unwrap_or(0));
566    [parts.next().unwrap_or(0), parts.next().unwrap_or(0)]
567}
568
569/// A verdict as the log says it.
570fn said(verdict: &PrintAlignment) -> String {
571    match verdict {
572        PrintAlignment::Unavailable => "unavailable: the G-code lays no object".to_owned(),
573        PrintAlignment::Pending => "pending".to_owned(),
574        PrintAlignment::Passed { offset_px } => format!("passed, offset {offset_px:.1} px"),
575        PrintAlignment::Failed {
576            reason: AlignmentFailure::Offset { offset_px },
577        } => format!("failed, offset {offset_px:.1} px"),
578        PrintAlignment::Failed {
579            reason: AlignmentFailure::Resolution { expected, got },
580        } => format!(
581            "failed: the camera's frames are {}x{}, the calibration's {}x{}",
582            got[0], got[1], expected[0], expected[1]
583        ),
584        PrintAlignment::Failed {
585            reason: AlignmentFailure::Stream,
586        } => "failed: the camera is not the stream the calibration was fitted on".to_owned(),
587    }
588}
589
590#[cfg(test)]
591mod tests {
592    use super::{CheckedFrame, MAX_CHECKED_FRAMES, attempt_while_refused, kept_with, reference_in};
593    use std::cell::Cell;
594    use std::io::{Error, ErrorKind};
595    use std::time::Duration;
596
597    /// An attempt that is refused `refusals` times and then succeeds, counting
598    /// how often it was made.
599    fn refused_then_done(refusals: u32, made: &Cell<u32>) -> impl FnMut() -> std::io::Result<()> {
600        move || {
601            made.set(made.get() + 1);
602            if made.get() <= refusals {
603                Err(Error::from(ErrorKind::PermissionDenied))
604            } else {
605                Ok(())
606            }
607        }
608    }
609
610    #[test]
611    fn a_momentary_refusal_is_attempted_again_until_it_passes() {
612        let made = Cell::new(0);
613        let answered =
614            attempt_while_refused(refused_then_done(2, &made), |_| true, 5, Duration::ZERO);
615        assert!(answered.is_ok(), "{answered:?}");
616        assert_eq!(made.get(), 3);
617    }
618
619    #[test]
620    fn a_refusal_that_outlasts_every_attempt_is_answered() {
621        let made = Cell::new(0);
622        let answered =
623            attempt_while_refused(refused_then_done(9, &made), |_| true, 4, Duration::ZERO);
624        assert_eq!(
625            answered.map_err(|error| error.kind()),
626            Err(ErrorKind::PermissionDenied)
627        );
628        assert_eq!(made.get(), 4);
629    }
630
631    #[test]
632    fn a_refusal_that_is_not_momentary_is_answered_at_once() {
633        let made = Cell::new(0);
634        let answered =
635            attempt_while_refused(refused_then_done(9, &made), |_| false, 4, Duration::ZERO);
636        assert!(answered.is_err());
637        assert_eq!(made.get(), 1);
638    }
639
640    /// The refusal the retry answers, made the way Windows makes it: the
641    /// record held open by another handle that does not allow deleting it,
642    /// and let go a moment later.
643    #[cfg(windows)]
644    #[test]
645    fn a_record_held_open_by_another_handle_is_replaced_once_it_is_let_go() {
646        use std::os::windows::fs::OpenOptionsExt;
647        let directory = tempfile::TempDir::new().expect("a directory");
648        let path = directory.path().join("record.json");
649        std::fs::write(&path, b"before").expect("a record");
650        let held = std::fs::OpenOptions::new()
651            .read(true)
652            .share_mode(0)
653            .open(&path)
654            .expect("the record held");
655        let release = std::thread::spawn(move || {
656            std::thread::sleep(Duration::from_millis(150));
657            drop(held);
658        });
659        super::replace_file(&path, b"after").expect("the record replaced");
660        release.join().expect("the handle let go");
661        assert_eq!(std::fs::read(&path).expect("the record"), b"after");
662        assert!(!path.with_extension("json.part").exists());
663    }
664
665    #[cfg(windows)]
666    #[test]
667    fn only_a_held_file_is_a_momentary_refusal_on_windows() {
668        assert!(super::refused_for_a_moment(&Error::from_raw_os_error(5)));
669        assert!(super::refused_for_a_moment(&Error::from_raw_os_error(32)));
670        assert!(!super::refused_for_a_moment(&Error::from_raw_os_error(2)));
671    }
672
673    /// A checked frame at `z` mm, captured `second` seconds into a print.
674    fn at(second: i64, z: f64) -> CheckedFrame {
675        CheckedFrame {
676            frame: format!("frame-{second}.jpg").into(),
677            captured_at: printobserver_types::Timestamp::from_unix_seconds(1_791_489_600 + second)
678                .expect("a time"),
679            print_z_mm: z,
680        }
681    }
682
683    /// The heights of checked frames, in their order.
684    fn heights(kept: &[CheckedFrame]) -> Vec<f64> {
685        kept.iter().map(|checked| checked.print_z_mm).collect()
686    }
687
688    #[test]
689    fn a_check_measures_from_the_newest_frame_far_enough_below_it() {
690        let kept = [at(0, 0.2), at(60, 0.8), at(120, 2.0), at(180, 2.6)];
691        assert_eq!(
692            reference_in(&kept, 5.8, 3.0).map(|checked| checked.print_z_mm),
693            Some(2.6)
694        );
695        assert_eq!(
696            reference_in(&kept, 3.5, 3.0).map(|checked| checked.print_z_mm),
697            Some(0.2)
698        );
699        assert_eq!(reference_in(&kept, 3.1, 3.0), None, "none is 3 mm below");
700    }
701
702    #[test]
703    fn only_what_a_later_check_can_measure_from_is_kept() {
704        let mut kept = Vec::new();
705        for (second, z) in [(0, 0.2), (60, 0.8), (120, 2.0), (180, 3.4), (240, 4.0)] {
706            kept = kept_with(kept, at(second, z), 3.0);
707        }
708        assert_eq!(
709            heights(&kept),
710            [0.8, 2.0, 3.4, 4.0],
711            "0.2 is below 0.8, which is itself 3 mm below 4.0, so no later check needs it"
712        );
713        assert_eq!(
714            heights(&kept_with(kept, at(300, 1.0), 3.0)),
715            [1.0],
716            "a plan gone back down starts the record again"
717        );
718    }
719
720    #[test]
721    fn the_oldest_checked_frames_go_past_the_most_kept() {
722        let mut kept = Vec::new();
723        for second in 0..=i64::try_from(MAX_CHECKED_FRAMES).expect("a count") {
724            kept = kept_with(kept, at(second, 5.0), 3.0);
725        }
726        assert_eq!(kept.len(), MAX_CHECKED_FRAMES);
727        assert_eq!(kept[0].captured_at, at(1, 5.0).captured_at);
728    }
729}