Skip to main content

printobserver_core/
preflight.rs

1//! Whether the spools loaded hold enough for a print, asked before it starts.
2//!
3//! [`Supervisor::preflight`] is the read: for every tool the file uses it names
4//! the spool loaded there, every mark that spool holds, what the print needs
5//! from it by `OctoPrint`'s analysis and the spool's own diameter and density,
6//! the buffer asked beyond that, and a verdict. It answers at once, records
7//! nothing, and never waits.
8//!
9//! A start is where the check bites. After the decision accepts a start, and
10//! before the printer is asked, the check is made and a refusal turns the
11//! decision into one of the filament rejections — written down like every
12//! rejection. When a tool holds a tracked spool and the file has no analysis
13//! yet, the start first waits for `OctoPrint`'s, re-reading the file until it
14//! appears or [`SpoolPolicy::analysis_wait_s`](crate::SpoolPolicy) elapses on
15//! the injected clock: this system computes no whole-file estimate of its own.
16//! That wait is taken before the start holds the resolution of prints, so a
17//! start waiting on an analysis holds up no alert and no read.
18
19use std::time::Duration;
20
21use printobserver_printer_api::FileFacts;
22use printobserver_types::FileName;
23
24use crate::accounting::{NOTHING_MM, lengths_of};
25use crate::clock::seconds_between;
26use crate::config::PreflightMode;
27use crate::delay::Delay;
28use crate::error::CoreError;
29use crate::filament::{buffer_g, grams_for_length};
30use crate::records::{
31    ActionKind, Actor, ActorClass, DoubtedSpool, Preflight, PreflightNeed, PreflightObjection,
32    PreflightSpool, PreflightTool, PreflightToolResult, PreflightVerdict, RejectionReason,
33    ShortSpool, SpoolRecord, SpoolTrust, UnanalysedSpool, UnverifiedMarks,
34};
35use crate::supervisor::Supervisor;
36
37/// Whether a start asked to go ahead despite the filament check.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub(crate) enum Override {
40    /// It asked; only an operator's asking counts.
41    Asked,
42    /// It did not.
43    NotAsked,
44}
45
46impl From<bool> for Override {
47    fn from(asked: bool) -> Self {
48        if asked { Self::Asked } else { Self::NotAsked }
49    }
50}
51
52/// How often a start waiting for an analysis reads the file again.
53pub const ANALYSIS_POLL: Duration = Duration::from_millis(250);
54
55/// How bad one verdict is, worst first, as a whole print's verdict is the
56/// worst of its tools'.
57const fn severity(verdict: PreflightVerdict) -> u8 {
58    match verdict {
59        PreflightVerdict::Insufficient => 0,
60        PreflightVerdict::UnverifiedSpool => 1,
61        PreflightVerdict::NoAnalysis => 2,
62        PreflightVerdict::Warned => 3,
63        PreflightVerdict::Overridden => 4,
64        PreflightVerdict::Unchecked => 5,
65        PreflightVerdict::Passed => 6,
66    }
67}
68
69/// The worst of the tools' verdicts; unchecked when there are none.
70fn worst(tools: &[PreflightTool]) -> PreflightVerdict {
71    tools
72        .iter()
73        .map(|tool| tool.result.verdict())
74        .min_by_key(|verdict| severity(*verdict))
75        .unwrap_or(PreflightVerdict::Unchecked)
76}
77
78/// The marks a spool holds, oldest first, when it holds any.
79fn marks(spool: &SpoolRecord) -> Option<UnverifiedMarks> {
80    match &spool.trust {
81        SpoolTrust::Verified => None,
82        SpoolTrust::Unverified { marks } => Some(marks.clone()),
83    }
84}
85
86/// A spool, as a check names it.
87fn named(spool: &SpoolRecord) -> PreflightSpool {
88    PreflightSpool {
89        id: spool.id,
90        name: spool.name.clone(),
91    }
92}
93
94/// What one tool's spool, judged against what the print needs from it, is
95/// found to be: short, in doubt, or enough.
96fn judged(spool: &SpoolRecord, need: PreflightNeed) -> PreflightToolResult {
97    let marks = marks(spool);
98    if spool.remaining_g < need.required_g + need.buffer_g {
99        return PreflightToolResult::Insufficient(ShortSpool {
100            spool: named(spool),
101            remaining_g: spool.remaining_g,
102            need,
103            marks: marks.map(UnverifiedMarks::into_vec).unwrap_or_default(),
104        });
105    }
106    match marks {
107        None => PreflightToolResult::Passed {
108            spool: named(spool),
109            remaining_g: spool.remaining_g,
110            need,
111        },
112        Some(marks) => PreflightToolResult::UnverifiedSpool(DoubtedSpool {
113            spool: named(spool),
114            remaining_g: spool.remaining_g,
115            need: Some(need),
116            marks,
117        }),
118    }
119}
120
121/// What one tool's spool is found to be when the file has no analysis: in
122/// doubt when it holds a mark, otherwise unanalysed.
123fn unanalysed(spool: &SpoolRecord) -> PreflightToolResult {
124    match marks(spool) {
125        None => PreflightToolResult::NoAnalysis(UnanalysedSpool {
126            spool: named(spool),
127            remaining_g: spool.remaining_g,
128        }),
129        Some(marks) => PreflightToolResult::UnverifiedSpool(DoubtedSpool {
130            spool: named(spool),
131            remaining_g: spool.remaining_g,
132            need: None,
133            marks,
134        }),
135    }
136}
137
138/// The refusal one check makes, when it makes one: the first short tool, else
139/// the first unverified one, else a file still unanalysed.
140fn refusal(preflight: &Preflight, waited_s: u64) -> Option<RejectionReason> {
141    let short = preflight.tools.iter().find_map(|tool| match &tool.result {
142        PreflightToolResult::Insufficient(short) => Some(RejectionReason::InsufficientFilament {
143            tool: tool.tool,
144            spool_id: short.spool.id,
145            spool_name: short.spool.name.clone(),
146            required_g: short.need.required_g,
147            buffer_g: short.need.buffer_g,
148            remaining_g: short.remaining_g,
149            unverified: short.marks.first().map(|mark| mark.reason.clone()),
150        }),
151        _ => None,
152    });
153    let unverified = || {
154        preflight.tools.iter().find_map(|tool| match &tool.result {
155            PreflightToolResult::UnverifiedSpool(doubted) => {
156                Some(RejectionReason::UnverifiedSpool {
157                    tool: tool.tool,
158                    spool_id: doubted.spool.id,
159                    spool_name: doubted.spool.name.clone(),
160                    reason: doubted.marks.oldest().reason.clone(),
161                })
162            }
163            _ => None,
164        })
165    };
166    let unanalysed = || {
167        preflight
168            .tools
169            .iter()
170            .any(|tool| matches!(tool.result, PreflightToolResult::NoAnalysis(_)))
171            .then(|| RejectionReason::AnalysisUnavailable {
172                file_name: preflight.file_name.clone(),
173                waited_s,
174            })
175    };
176    short.or_else(unverified).or_else(unanalysed)
177}
178
179/// How a start that went ahead despite an objection went ahead.
180#[derive(Debug, Clone, Copy)]
181enum LetThrough {
182    /// An operator overrode the check.
183    Overridden,
184    /// The check is set to warn.
185    Warned,
186}
187
188/// The same check, with every objecting tool's result replaced by one that
189/// let the start go ahead, carrying what it objected to.
190fn let_through(mut preflight: Preflight, how: LetThrough) -> Preflight {
191    for tool in &mut preflight.tools {
192        let objection = match tool.result.clone() {
193            PreflightToolResult::Insufficient(short) => PreflightObjection::Insufficient(short),
194            PreflightToolResult::UnverifiedSpool(doubted) => {
195                PreflightObjection::UnverifiedSpool(doubted)
196            }
197            PreflightToolResult::NoAnalysis(unanalysed) => {
198                PreflightObjection::NoAnalysis(unanalysed)
199            }
200            _ => continue,
201        };
202        tool.result = match how {
203            LetThrough::Overridden => PreflightToolResult::Overridden { objection },
204            LetThrough::Warned => PreflightToolResult::Warned { objection },
205        };
206    }
207    preflight.verdict = worst(&preflight.tools);
208    preflight
209}
210
211impl Supervisor {
212    /// Whether the spools loaded hold enough for one file, read now.
213    ///
214    /// A read: it records nothing and never waits. A file whose facts cannot
215    /// be read is a file with no analysis.
216    ///
217    /// # Errors
218    ///
219    /// Returns the store's own error when the loaded spools could not be read.
220    pub async fn preflight(&self, file_name: &FileName) -> Result<Preflight, CoreError> {
221        let facts = self.read_file_facts(file_name.clone()).await.ok();
222        let loaded = self.stores().filament.loaded_spools().await?;
223        Ok(self.judge(file_name, facts.as_ref(), &loaded))
224    }
225
226    /// The check of one file's facts against the spools loaded.
227    fn judge(
228        &self,
229        file_name: &FileName,
230        facts: Option<&FileFacts>,
231        loaded: &[SpoolRecord],
232    ) -> Preflight {
233        let policy = &self.config().spools;
234        let on_tool = |tool: i64| {
235            loaded
236                .iter()
237                .find(|spool| spool.loaded_tool() == Some(tool))
238        };
239        let tools: Vec<PreflightTool> = match facts.and_then(|facts| facts.filament.as_deref()) {
240            Some(filament) => lengths_of(filament)
241                .into_iter()
242                .filter(|(_, length)| *length > NOTHING_MM)
243                .map(|(tool, length)| PreflightTool {
244                    tool,
245                    result: on_tool(tool).map_or(PreflightToolResult::Unchecked, |spool| {
246                        let required_g =
247                            grams_for_length(length, spool.diameter_mm, spool.density_g_cm3);
248                        judged(
249                            spool,
250                            PreflightNeed {
251                                required_g,
252                                buffer_g: buffer_g(required_g, policy),
253                            },
254                        )
255                    }),
256                })
257                .collect(),
258            None => loaded
259                .iter()
260                .filter_map(|spool| {
261                    Some(PreflightTool {
262                        tool: spool.loaded_tool()?,
263                        result: unanalysed(spool),
264                    })
265                })
266                .collect(),
267        };
268        Preflight {
269            file_name: file_name.as_str().to_owned(),
270            verdict: worst(&tools),
271            tools,
272            checked_at: self.clock().now(),
273        }
274    }
275
276    /// Wait for `OctoPrint`'s analysis of a file a start names, when the
277    /// check will need one: a tool holds a tracked spool, the check is on, the
278    /// actor may start a print at all, and the file has none yet.
279    ///
280    /// Returns once the analysis appears or the configured wait has elapsed on
281    /// the injected clock, re-reading the file every [`ANALYSIS_POLL`].
282    ///
283    /// # Errors
284    ///
285    /// Returns the store's own error when the loaded spools could not be read.
286    pub(crate) async fn await_analysis(
287        &self,
288        file_name: &FileName,
289        actor: &Actor,
290    ) -> Result<(), CoreError> {
291        let policy = &self.config().spools;
292        let granted = self
293            .config()
294            .envelope
295            .actions
296            .get(&actor.class())
297            .is_some_and(|kinds| kinds.contains(&ActionKind::StartPrint));
298        if policy.preflight == PreflightMode::Off || policy.analysis_wait_s == 0 || !granted {
299            return Ok(());
300        }
301        if self.stores().filament.loaded_spools().await?.is_empty() {
302            return Ok(());
303        }
304        let wait = i64::try_from(policy.analysis_wait_s).unwrap_or(i64::MAX);
305        let started = self.clock().now();
306        loop {
307            let analysed = self
308                .read_file_facts(file_name.clone())
309                .await
310                .is_ok_and(|facts| facts.filament.is_some());
311            if analysed || seconds_between(started, self.clock().now()) >= wait {
312                return Ok(());
313            }
314            // A wait the system will not take a thread for ends the wait: the
315            // start is judged on what the file says now.
316            if Delay::new(ANALYSIS_POLL).await.is_err() {
317                return Ok(());
318            }
319        }
320    }
321
322    /// The check a start the decision accepted is held to, and the refusal it
323    /// turns the decision into when it makes one.
324    ///
325    /// Mode `off` checks nothing and records `unchecked`. Otherwise a short,
326    /// unverified or still-unanalysed tool refuses the start in mode `refuse`
327    /// — unless an operator overrode the check, which proceeds as
328    /// `overridden` — and proceeds as `warned` in mode `warn`.
329    ///
330    /// # Errors
331    ///
332    /// Returns the store's own error when the loaded spools could not be read.
333    pub(crate) async fn check_start(
334        &self,
335        file_name: &FileName,
336        actor: &Actor,
337        asked: Override,
338    ) -> Result<(Preflight, Option<RejectionReason>), CoreError> {
339        let policy = self.config().spools;
340        if policy.preflight == PreflightMode::Off {
341            return Ok((
342                Preflight {
343                    file_name: file_name.as_str().to_owned(),
344                    tools: Vec::new(),
345                    verdict: PreflightVerdict::Unchecked,
346                    checked_at: self.clock().now(),
347                },
348                None,
349            ));
350        }
351        let preflight = self.preflight(file_name).await?;
352        let Some(reason) = refusal(&preflight, policy.analysis_wait_s) else {
353            return Ok((preflight, None));
354        };
355        Ok(match policy.preflight {
356            PreflightMode::Warn => (let_through(preflight, LetThrough::Warned), None),
357            _ if asked == Override::Asked && actor.class() == ActorClass::Operator => {
358                (let_through(preflight, LetThrough::Overridden), None)
359            }
360            _ => (preflight, Some(reason)),
361        })
362    }
363}