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
22use std::path::{Path, PathBuf};
23use std::sync::Arc;
24use std::time::Duration;
25
26use printobserver_core::store::PrintStore;
27use printobserver_core::{ActiveJob, Supervisor};
28use printobserver_panels::alignment::SEARCH_PX;
29use printobserver_panels::{
30    AlignmentInputs, CameraCalibration, ComposeError, FrameField, verify_first_layer_alignment,
31};
32use printobserver_types::PrintId;
33use printobserver_types::contract::Sample;
34use printobserver_types::schemars::JsonSchema;
35use printobserver_types::serde::{Deserialize, Serialize};
36
37/// Why a print's alignment failed.
38#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
39#[serde(
40    crate = "printobserver_types::serde",
41    tag = "failure",
42    rename_all = "snake_case"
43)]
44#[schemars(crate = "printobserver_types::schemars")]
45pub enum AlignmentFailure {
46    /// The printed first layer lies further from its projection than the
47    /// calibration allows.
48    Offset {
49        /// How far, in calibration pixels.
50        offset_px: f64,
51    },
52    /// The camera's frames are not the calibration's resolution.
53    Resolution {
54        /// The calibration's, `[width, height]`.
55        expected: [u32; 2],
56        /// The frame's.
57        got: [u32; 2],
58    },
59    /// The camera configured is not the stream the calibration was fitted on.
60    Stream,
61}
62
63/// One print's first-layer alignment verdict, as it is kept under the state
64/// directory — which the real-print suite's record reads.
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
66#[serde(
67    crate = "printobserver_types::serde",
68    tag = "verdict",
69    rename_all = "snake_case"
70)]
71#[schemars(crate = "printobserver_types::schemars")]
72pub enum PrintAlignment {
73    /// Nothing can be checked: no calibration is configured, or the print's
74    /// G-code lays no object.
75    Unavailable,
76    /// The first object layer is not down yet, or no frame of it has been
77    /// judged.
78    Pending,
79    /// The projected first layer lands on the printed one.
80    Passed {
81        /// How far it lies from it, in calibration pixels.
82        offset_px: f64,
83    },
84    /// It does not, or the frames cannot be judged against the calibration.
85    Failed {
86        /// Why.
87        reason: AlignmentFailure,
88    },
89}
90
91impl Sample for PrintAlignment {
92    fn sample_full() -> Self {
93        Self::Passed { offset_px: 14.5 }
94    }
95
96    fn sample_minimal() -> Self {
97        Self::Pending
98    }
99
100    fn sample_alternates() -> Vec<Self> {
101        vec![
102            Self::Unavailable,
103            Self::Failed {
104                reason: AlignmentFailure::Offset { offset_px: 48.5 },
105            },
106            Self::Failed {
107                reason: AlignmentFailure::Resolution {
108                    expected: [1920, 1080],
109                    got: [1280, 720],
110                },
111            },
112            Self::Failed {
113                reason: AlignmentFailure::Stream,
114            },
115        ]
116    }
117}
118
119/// The frame one print's last check was given, and when it was captured.
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(crate = "printobserver_types::serde")]
122pub struct PreviousCheck {
123    /// The stored frame's path.
124    pub frame: PathBuf,
125    /// When it was captured.
126    pub captured_at: printobserver_types::Timestamp,
127}
128
129/// The alignment verdicts of every print, what decides them, and the frame
130/// each print's last check was given.
131pub struct Alignments {
132    /// Where each print's verdict is kept.
133    directory: PathBuf,
134    /// Where each print's last check's frame is named.
135    previous_directory: PathBuf,
136    /// The camera's calibration, when one is configured.
137    calibration: Option<Arc<CameraCalibration>>,
138    /// The prints, to tell which are open.
139    prints: Arc<dyn PrintStore>,
140}
141
142impl core::fmt::Debug for Alignments {
143    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
144        formatter
145            .debug_struct("Alignments")
146            .field("directory", &self.directory)
147            .field("calibrated", &self.calibration.is_some())
148            .finish_non_exhaustive()
149    }
150}
151
152/// The directory verdicts are kept in, under a state directory.
153#[must_use]
154pub fn verdict_dir(state_dir: &Path) -> PathBuf {
155    state_dir.join("alignment")
156}
157
158/// The directory each print's last check's frame is named in, under a state
159/// directory.
160#[must_use]
161pub fn previous_check_dir(state_dir: &Path) -> PathBuf {
162    state_dir.join("previous-check")
163}
164
165impl Alignments {
166    /// The verdicts kept under one state directory.
167    ///
168    /// # Errors
169    ///
170    /// The filesystem's own error when the directory cannot be made.
171    pub fn new(
172        state_dir: &Path,
173        calibration: Option<Arc<CameraCalibration>>,
174        prints: Arc<dyn PrintStore>,
175    ) -> std::io::Result<Self> {
176        let directory = verdict_dir(state_dir);
177        std::fs::create_dir_all(&directory)?;
178        let previous_directory = previous_check_dir(state_dir);
179        std::fs::create_dir_all(&previous_directory)?;
180        Ok(Self {
181            directory,
182            previous_directory,
183            calibration,
184            prints,
185        })
186    }
187
188    /// Where one print's verdict is kept.
189    fn path_of(&self, print_id: PrintId) -> PathBuf {
190        self.directory.join(format!("{print_id}.json"))
191    }
192
193    /// The camera calibration in force, when one is configured.
194    #[must_use]
195    pub fn calibration(&self) -> Option<&CameraCalibration> {
196        self.calibration.as_deref()
197    }
198
199    /// Where one print's last check's frame is named.
200    fn previous_path_of(&self, print_id: PrintId) -> PathBuf {
201        self.previous_directory.join(format!("{print_id}.json"))
202    }
203
204    /// The frame one print's last check was given; nothing before its first
205    /// check, or when the record cannot be read back.
206    #[must_use]
207    pub fn previous_check(&self, print_id: PrintId) -> Option<PreviousCheck> {
208        std::fs::read(self.previous_path_of(print_id))
209            .ok()
210            .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
211    }
212
213    /// Name the frame one print's check was given, which its next check shows
214    /// as the previous. A record the filesystem refuses for a moment is
215    /// replaced once the refusal passes ([`replace_file`]); one it goes on
216    /// refusing is said on the log and leaves the record before it standing,
217    /// so the next check shows an older frame as the previous rather than
218    /// none. No test makes the refusal last: that needs the state directory
219    /// made to refuse writes beneath a running server, which refuses the
220    /// store's own writes first. What a check makes of a record it cannot use
221    /// — an empty panel 3 — is proved by
222    /// `a_lost_previous_frame_empties_panel_3_and_the_record_goes_with_the_print`.
223    pub fn record_check(&self, print_id: PrintId, check: &PreviousCheck) {
224        let Ok(bytes) = printobserver_types::serde_json::to_vec(check) else {
225            return;
226        };
227        if let Err(error) = replace_file(&self.previous_path_of(print_id), &bytes) {
228            eprintln!(
229                "printobserver: print {print_id}: the last check's frame could not be recorded, so the next check shows an older one or none: {error}"
230            );
231        }
232    }
233
234    /// One print's verdict as it stands.
235    #[must_use]
236    pub fn print_alignment(&self, print_id: PrintId) -> PrintAlignment {
237        if self.calibration.is_none() {
238            return PrintAlignment::Unavailable;
239        }
240        std::fs::read(self.path_of(print_id))
241            .ok()
242            .and_then(|bytes| printobserver_types::serde_json::from_slice(&bytes).ok())
243            .unwrap_or(PrintAlignment::Pending)
244    }
245
246    /// Rule on the running print's alignment once its first object layer is
247    /// down, when it has no verdict yet. Answers the verdict it wrote, and
248    /// nothing when it wrote none — not yet due, or no good frame came.
249    pub async fn check(
250        &self,
251        supervisor: &Supervisor,
252        active: ActiveJob,
253    ) -> Option<PrintAlignment> {
254        let calibration = self.calibration.as_ref()?;
255        // A verdict file that cannot be read back is no verdict, and is
256        // decided again over it.
257        if self.print_alignment(active.print_id) != PrintAlignment::Pending {
258            return None;
259        }
260        let position = u64::try_from(active.file_position_bytes?).ok()?;
261        let index = supervisor.print_gcode_index(active.print_id).await?;
262        let Some((first, ends)) = index.first_object_layer() else {
263            return self.decide(active.print_id, PrintAlignment::Unavailable);
264        };
265        if position <= ends {
266            return None;
267        }
268        let first_layer = index.layer_toolpath(first).ok()?;
269        let print_z_mm = index
270            .layer_at(position)
271            .and_then(|layer| index.layer_z_mm(layer))?;
272        let (url, frame) = supervisor.fetch_camera_frame(active.print_id).await?;
273        let verdict = match verify_first_layer_alignment(&AlignmentInputs {
274            frame_jpeg: &frame,
275            camera_snapshot_url: &url,
276            first_layer: &first_layer,
277            print_z_mm,
278            calibration,
279        }) {
280            Ok(found) if found.passed => PrintAlignment::Passed {
281                offset_px: found.offset_px,
282            },
283            Ok(found) => PrintAlignment::Failed {
284                reason: AlignmentFailure::Offset {
285                    offset_px: found.offset_px,
286                },
287            },
288            Err(ComposeError::FrameMismatch {
289                field: FrameField::Resolution,
290                got,
291                ..
292            }) => PrintAlignment::Failed {
293                reason: AlignmentFailure::Resolution {
294                    expected: calibration.image_size_px,
295                    got: size_of(&got),
296                },
297            },
298            Err(ComposeError::FrameMismatch {
299                field: FrameField::Stream,
300                ..
301            }) => PrintAlignment::Failed {
302                reason: AlignmentFailure::Stream,
303            },
304            // A first layer projecting nowhere in the frame is as far from
305            // it as the check looks.
306            Err(ComposeError::OutlineOffFrame) => PrintAlignment::Failed {
307                reason: AlignmentFailure::Offset {
308                    offset_px: f64::from(SEARCH_PX),
309                },
310            },
311            Err(_) => return None,
312        };
313        self.decide(active.print_id, verdict)
314    }
315
316    /// Keep a verdict, and say it. A verdict the filesystem goes on refusing
317    /// ([`replace_file`]) is
318    /// decided again at the next read rather than lost; no test makes the
319    /// state directory refuse a write, which needs a filesystem made to fail
320    /// beneath a running server, and the retry is the same path a fetch that
321    /// gave no frame takes, which `aligning` proves.
322    fn decide(&self, print_id: PrintId, verdict: PrintAlignment) -> Option<PrintAlignment> {
323        let bytes = printobserver_types::serde_json::to_vec(&verdict).ok()?;
324        replace_file(&self.path_of(print_id), &bytes).ok()?;
325        eprintln!(
326            "printobserver: print {print_id}: first-layer alignment {}",
327            said(&verdict)
328        );
329        Some(verdict)
330    }
331
332    /// Delete the verdict and the last check's record of every print that is
333    /// not open.
334    ///
335    /// An open print's record still being written — the `.json.part` beside it
336    /// that [`replace_file`] renames over it — is its own, and kept: the watch
337    /// sweeps after every read, so a sweep removing it between the write and the
338    /// rename lost that record, and the print's next check showed no previous
339    /// frame.
340    ///
341    /// A store that cannot list the open prints, a directory that cannot be
342    /// listed and a file that cannot be removed each leave a verdict behind,
343    /// which the next read's sweep tries again. No test makes either refuse,
344    /// since that needs a store or filesystem made to fail beneath a running
345    /// server; the `aligning` journeys prove the sweep removes a closed
346    /// print's verdict and keeps an open one's, after a close and at start.
347    pub async fn sweep(&self) {
348        let Ok(open) = self.prints.open_prints().await else {
349            return;
350        };
351        let open: Vec<String> = open
352            .iter()
353            .flat_map(|print| {
354                [
355                    format!("{}.json", print.id),
356                    format!("{}.json.part", print.id),
357                ]
358            })
359            .collect();
360        for directory in [&self.directory, &self.previous_directory] {
361            let Ok(entries) = std::fs::read_dir(directory) else {
362                continue;
363            };
364            for entry in entries.flatten() {
365                let name = entry.file_name();
366                if !open.iter().any(|kept| name.to_str() == Some(kept.as_str())) {
367                    let _ = std::fs::remove_file(entry.path());
368                }
369            }
370        }
371    }
372}
373
374/// How many times one file's replacement is attempted while the filesystem
375/// refuses it for a moment, and the pause between two attempts: half a second
376/// in all, on a check that is otherwise waiting on no one.
377const REPLACE_ATTEMPTS: u32 = 20;
378const REPLACE_PAUSE: Duration = Duration::from_millis(25);
379
380/// Put `bytes` at `path` whole: written beside it, then renamed over it, so a
381/// reader finds the old file or the new one and never part of either.
382///
383/// Windows refuses to replace a file another process holds open without
384/// letting it be deleted — a scanner reading what was just written does — and
385/// that refusal ends when the other process closes it. So a refusal of that
386/// kind is attempted again, up to [`REPLACE_ATTEMPTS`] times; any other, or
387/// one that outlasts them, is answered, with the file beside it removed.
388///
389/// # Errors
390///
391/// The filesystem's own error for the last attempt.
392fn replace_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
393    let held = path.with_extension("json.part");
394    attempt_while_refused(
395        || {
396            std::fs::write(&held, bytes)?;
397            std::fs::rename(&held, path)
398        },
399        refused_for_a_moment,
400        REPLACE_ATTEMPTS,
401        REPLACE_PAUSE,
402    )
403    .inspect_err(|_| {
404        let _ = std::fs::remove_file(&held);
405    })
406}
407
408/// Run `attempt` until it succeeds, fails with an error `refused` does not
409/// call momentary, or has been run `attempts` times, pausing between two.
410fn attempt_while_refused(
411    mut attempt: impl FnMut() -> std::io::Result<()>,
412    refused: impl Fn(&std::io::Error) -> bool,
413    attempts: u32,
414    pause: Duration,
415) -> std::io::Result<()> {
416    let mut made = 1;
417    loop {
418        match attempt() {
419            Err(error) if made < attempts && refused(&error) => {
420                std::thread::sleep(pause);
421                made += 1;
422            }
423            answered => return answered,
424        }
425    }
426}
427
428/// Whether Windows refused a replacement only because another handle has the
429/// file open: `ERROR_ACCESS_DENIED` (5) or `ERROR_SHARING_VIOLATION` (32).
430#[cfg(windows)]
431fn refused_for_a_moment(error: &std::io::Error) -> bool {
432    matches!(error.raw_os_error(), Some(5 | 32))
433}
434
435/// Elsewhere a rename replaces a file whoever has it open, so no refusal is
436/// momentary.
437#[cfg(not(windows))]
438fn refused_for_a_moment(_error: &std::io::Error) -> bool {
439    false
440}
441
442/// A frame size as the refusal spells it, `<w>x<h>`.
443fn size_of(text: &str) -> [u32; 2] {
444    let mut parts = text.split('x').map(|part| part.parse().unwrap_or(0));
445    [parts.next().unwrap_or(0), parts.next().unwrap_or(0)]
446}
447
448/// A verdict as the log says it.
449fn said(verdict: &PrintAlignment) -> String {
450    match verdict {
451        PrintAlignment::Unavailable => "unavailable: the G-code lays no object".to_owned(),
452        PrintAlignment::Pending => "pending".to_owned(),
453        PrintAlignment::Passed { offset_px } => format!("passed, offset {offset_px:.1} px"),
454        PrintAlignment::Failed {
455            reason: AlignmentFailure::Offset { offset_px },
456        } => format!("failed, offset {offset_px:.1} px"),
457        PrintAlignment::Failed {
458            reason: AlignmentFailure::Resolution { expected, got },
459        } => format!(
460            "failed: the camera's frames are {}x{}, the calibration's {}x{}",
461            got[0], got[1], expected[0], expected[1]
462        ),
463        PrintAlignment::Failed {
464            reason: AlignmentFailure::Stream,
465        } => "failed: the camera is not the stream the calibration was fitted on".to_owned(),
466    }
467}
468
469#[cfg(test)]
470mod tests {
471    use super::attempt_while_refused;
472    use std::cell::Cell;
473    use std::io::{Error, ErrorKind};
474    use std::time::Duration;
475
476    /// An attempt that is refused `refusals` times and then succeeds, counting
477    /// how often it was made.
478    fn refused_then_done(refusals: u32, made: &Cell<u32>) -> impl FnMut() -> std::io::Result<()> {
479        move || {
480            made.set(made.get() + 1);
481            if made.get() <= refusals {
482                Err(Error::from(ErrorKind::PermissionDenied))
483            } else {
484                Ok(())
485            }
486        }
487    }
488
489    #[test]
490    fn a_momentary_refusal_is_attempted_again_until_it_passes() {
491        let made = Cell::new(0);
492        let answered =
493            attempt_while_refused(refused_then_done(2, &made), |_| true, 5, Duration::ZERO);
494        assert!(answered.is_ok(), "{answered:?}");
495        assert_eq!(made.get(), 3);
496    }
497
498    #[test]
499    fn a_refusal_that_outlasts_every_attempt_is_answered() {
500        let made = Cell::new(0);
501        let answered =
502            attempt_while_refused(refused_then_done(9, &made), |_| true, 4, Duration::ZERO);
503        assert_eq!(
504            answered.map_err(|error| error.kind()),
505            Err(ErrorKind::PermissionDenied)
506        );
507        assert_eq!(made.get(), 4);
508    }
509
510    #[test]
511    fn a_refusal_that_is_not_momentary_is_answered_at_once() {
512        let made = Cell::new(0);
513        let answered =
514            attempt_while_refused(refused_then_done(9, &made), |_| false, 4, Duration::ZERO);
515        assert!(answered.is_err());
516        assert_eq!(made.get(), 1);
517    }
518
519    /// The refusal the retry answers, made the way Windows makes it: the
520    /// record held open by another handle that does not allow deleting it,
521    /// and let go a moment later.
522    #[cfg(windows)]
523    #[test]
524    fn a_record_held_open_by_another_handle_is_replaced_once_it_is_let_go() {
525        use std::os::windows::fs::OpenOptionsExt;
526        let directory = tempfile::TempDir::new().expect("a directory");
527        let path = directory.path().join("record.json");
528        std::fs::write(&path, b"before").expect("a record");
529        let held = std::fs::OpenOptions::new()
530            .read(true)
531            .share_mode(0)
532            .open(&path)
533            .expect("the record held");
534        let release = std::thread::spawn(move || {
535            std::thread::sleep(Duration::from_millis(150));
536            drop(held);
537        });
538        super::replace_file(&path, b"after").expect("the record replaced");
539        release.join().expect("the handle let go");
540        assert_eq!(std::fs::read(&path).expect("the record"), b"after");
541        assert!(!path.with_extension("json.part").exists());
542    }
543
544    #[cfg(windows)]
545    #[test]
546    fn only_a_held_file_is_a_momentary_refusal_on_windows() {
547        assert!(super::refused_for_a_moment(&Error::from_raw_os_error(5)));
548        assert!(super::refused_for_a_moment(&Error::from_raw_os_error(32)));
549        assert!(!super::refused_for_a_moment(&Error::from_raw_os_error(2)));
550    }
551}