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