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    /// A store that cannot list the open prints, a directory that cannot be
336    /// listed and a file that cannot be removed each leave a verdict behind,
337    /// which the next read's sweep tries again. No test makes either refuse,
338    /// since that needs a store or filesystem made to fail beneath a running
339    /// server; the `aligning` journeys prove the sweep removes a closed
340    /// print's verdict and keeps an open one's, after a close and at start.
341    pub async fn sweep(&self) {
342        let Ok(open) = self.prints.open_prints().await else {
343            return;
344        };
345        let open: Vec<String> = open
346            .iter()
347            .map(|print| format!("{}.json", print.id))
348            .collect();
349        for directory in [&self.directory, &self.previous_directory] {
350            let Ok(entries) = std::fs::read_dir(directory) else {
351                continue;
352            };
353            for entry in entries.flatten() {
354                let name = entry.file_name();
355                if !open.iter().any(|kept| name.to_str() == Some(kept.as_str())) {
356                    let _ = std::fs::remove_file(entry.path());
357                }
358            }
359        }
360    }
361}
362
363/// How many times one file's replacement is attempted while the filesystem
364/// refuses it for a moment, and the pause between two attempts: half a second
365/// in all, on a check that is otherwise waiting on no one.
366const REPLACE_ATTEMPTS: u32 = 20;
367const REPLACE_PAUSE: Duration = Duration::from_millis(25);
368
369/// Put `bytes` at `path` whole: written beside it, then renamed over it, so a
370/// reader finds the old file or the new one and never part of either.
371///
372/// Windows refuses to replace a file another process holds open without
373/// letting it be deleted — a scanner reading what was just written does — and
374/// that refusal ends when the other process closes it. So a refusal of that
375/// kind is attempted again, up to [`REPLACE_ATTEMPTS`] times; any other, or
376/// one that outlasts them, is answered, with the file beside it removed.
377///
378/// # Errors
379///
380/// The filesystem's own error for the last attempt.
381fn replace_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
382    let held = path.with_extension("json.part");
383    attempt_while_refused(
384        || {
385            std::fs::write(&held, bytes)?;
386            std::fs::rename(&held, path)
387        },
388        refused_for_a_moment,
389        REPLACE_ATTEMPTS,
390        REPLACE_PAUSE,
391    )
392    .inspect_err(|_| {
393        let _ = std::fs::remove_file(&held);
394    })
395}
396
397/// Run `attempt` until it succeeds, fails with an error `refused` does not
398/// call momentary, or has been run `attempts` times, pausing between two.
399fn attempt_while_refused(
400    mut attempt: impl FnMut() -> std::io::Result<()>,
401    refused: impl Fn(&std::io::Error) -> bool,
402    attempts: u32,
403    pause: Duration,
404) -> std::io::Result<()> {
405    let mut made = 1;
406    loop {
407        match attempt() {
408            Err(error) if made < attempts && refused(&error) => {
409                std::thread::sleep(pause);
410                made += 1;
411            }
412            answered => return answered,
413        }
414    }
415}
416
417/// Whether Windows refused a replacement only because another handle has the
418/// file open: `ERROR_ACCESS_DENIED` (5) or `ERROR_SHARING_VIOLATION` (32).
419#[cfg(windows)]
420fn refused_for_a_moment(error: &std::io::Error) -> bool {
421    matches!(error.raw_os_error(), Some(5 | 32))
422}
423
424/// Elsewhere a rename replaces a file whoever has it open, so no refusal is
425/// momentary.
426#[cfg(not(windows))]
427fn refused_for_a_moment(_error: &std::io::Error) -> bool {
428    false
429}
430
431/// A frame size as the refusal spells it, `<w>x<h>`.
432fn size_of(text: &str) -> [u32; 2] {
433    let mut parts = text.split('x').map(|part| part.parse().unwrap_or(0));
434    [parts.next().unwrap_or(0), parts.next().unwrap_or(0)]
435}
436
437/// A verdict as the log says it.
438fn said(verdict: &PrintAlignment) -> String {
439    match verdict {
440        PrintAlignment::Unavailable => "unavailable: the G-code lays no object".to_owned(),
441        PrintAlignment::Pending => "pending".to_owned(),
442        PrintAlignment::Passed { offset_px } => format!("passed, offset {offset_px:.1} px"),
443        PrintAlignment::Failed {
444            reason: AlignmentFailure::Offset { offset_px },
445        } => format!("failed, offset {offset_px:.1} px"),
446        PrintAlignment::Failed {
447            reason: AlignmentFailure::Resolution { expected, got },
448        } => format!(
449            "failed: the camera's frames are {}x{}, the calibration's {}x{}",
450            got[0], got[1], expected[0], expected[1]
451        ),
452        PrintAlignment::Failed {
453            reason: AlignmentFailure::Stream,
454        } => "failed: the camera is not the stream the calibration was fitted on".to_owned(),
455    }
456}
457
458#[cfg(test)]
459mod tests {
460    use super::attempt_while_refused;
461    use std::cell::Cell;
462    use std::io::{Error, ErrorKind};
463    use std::time::Duration;
464
465    /// An attempt that is refused `refusals` times and then succeeds, counting
466    /// how often it was made.
467    fn refused_then_done(refusals: u32, made: &Cell<u32>) -> impl FnMut() -> std::io::Result<()> {
468        move || {
469            made.set(made.get() + 1);
470            if made.get() <= refusals {
471                Err(Error::from(ErrorKind::PermissionDenied))
472            } else {
473                Ok(())
474            }
475        }
476    }
477
478    #[test]
479    fn a_momentary_refusal_is_attempted_again_until_it_passes() {
480        let made = Cell::new(0);
481        let answered =
482            attempt_while_refused(refused_then_done(2, &made), |_| true, 5, Duration::ZERO);
483        assert!(answered.is_ok(), "{answered:?}");
484        assert_eq!(made.get(), 3);
485    }
486
487    #[test]
488    fn a_refusal_that_outlasts_every_attempt_is_answered() {
489        let made = Cell::new(0);
490        let answered =
491            attempt_while_refused(refused_then_done(9, &made), |_| true, 4, Duration::ZERO);
492        assert_eq!(
493            answered.map_err(|error| error.kind()),
494            Err(ErrorKind::PermissionDenied)
495        );
496        assert_eq!(made.get(), 4);
497    }
498
499    #[test]
500    fn a_refusal_that_is_not_momentary_is_answered_at_once() {
501        let made = Cell::new(0);
502        let answered =
503            attempt_while_refused(refused_then_done(9, &made), |_| false, 4, Duration::ZERO);
504        assert!(answered.is_err());
505        assert_eq!(made.get(), 1);
506    }
507
508    /// The refusal the retry answers, made the way Windows makes it: the
509    /// record held open by another handle that does not allow deleting it,
510    /// and let go a moment later.
511    #[cfg(windows)]
512    #[test]
513    fn a_record_held_open_by_another_handle_is_replaced_once_it_is_let_go() {
514        use std::os::windows::fs::OpenOptionsExt;
515        let directory = tempfile::TempDir::new().expect("a directory");
516        let path = directory.path().join("record.json");
517        std::fs::write(&path, b"before").expect("a record");
518        let held = std::fs::OpenOptions::new()
519            .read(true)
520            .share_mode(0)
521            .open(&path)
522            .expect("the record held");
523        let release = std::thread::spawn(move || {
524            std::thread::sleep(Duration::from_millis(150));
525            drop(held);
526        });
527        super::replace_file(&path, b"after").expect("the record replaced");
528        release.join().expect("the handle let go");
529        assert_eq!(std::fs::read(&path).expect("the record"), b"after");
530        assert!(!path.with_extension("json.part").exists());
531    }
532
533    #[cfg(windows)]
534    #[test]
535    fn only_a_held_file_is_a_momentary_refusal_on_windows() {
536        assert!(super::refused_for_a_moment(&Error::from_raw_os_error(5)));
537        assert!(super::refused_for_a_moment(&Error::from_raw_os_error(32)));
538        assert!(!super::refused_for_a_moment(&Error::from_raw_os_error(2)));
539    }
540}