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//!
19//! # The material and the sheet
20//!
21//! Beside the weight, a start is held to two more checks, made the same way
22//! and under the same mode. The **material** check compares the material the
23//! file's own `filament_type` names for tool 0 with the material of the spool
24//! loaded there, trimmed and without regard to case; a file naming none, or
25//! whose settings cannot be read, is refused like a mismatch. The **sheet**
26//! check reads the build sheet the start's manifest declares against the
27//! configured [`SheetTable`](crate::SheetTable), keyed by that spool's
28//! material: a sheet the table does not allow the material on, a material the
29//! table has no entry for, and a sheet no entry lists are each refused. With
30//! no tracked spool on tool 0 there is nothing to compare, and both read
31//! unchecked.
32//!
33//! An operator overrides each check by its own flag, exactly as the weight is
34//! overridden, and the start's reason is the override's. One refusal takes no
35//! override and no mode: a manifest that declares no sheet at all.
36
37use std::time::Duration;
38
39use printobserver_printer_api::FileFacts;
40use printobserver_types::FileName;
41
42use crate::accounting::{NOTHING_MM, lengths_of, spool_on_tool};
43use crate::clock::seconds_between;
44use crate::config::PreflightMode;
45use crate::delay::Delay;
46use crate::error::CoreError;
47use crate::filament::{buffer_g, grams_for_length};
48use crate::records::{
49    ActionKind, Actor, ActorClass, DoubtedSpool, MaterialComparison, MaterialName,
50    MaterialObjection, MaterialResult, Preflight, PreflightNeed, PreflightObjection,
51    PreflightSpool, PreflightTool, PreflightToolResult, PreflightVerdict, RejectionReason,
52    SheetComparison, SheetId, SheetObjection, SheetResult, ShortSpool, SpoolRecord, SpoolTrust,
53    UnanalysedSpool, UncomparedMaterial, UnverifiedMarks,
54};
55use crate::supervisor::Supervisor;
56
57/// Whether a start asked to go ahead despite the filament check.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub(crate) enum Override {
60    /// It asked; only an operator's asking counts.
61    Asked,
62    /// It did not.
63    NotAsked,
64}
65
66impl From<bool> for Override {
67    fn from(asked: bool) -> Self {
68        if asked { Self::Asked } else { Self::NotAsked }
69    }
70}
71
72/// Which of the three checks a start asked to go ahead despite.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub(crate) struct Overrides {
75    /// The filament weight check.
76    pub(crate) filament: Override,
77    /// The material check.
78    pub(crate) material: Override,
79    /// The sheet check, which never lets through a manifest declaring none.
80    pub(crate) sheet: Override,
81}
82
83/// The tool the material and sheet checks are about: the one a single-tool
84/// print feeds, and the first a multi-tool slicer names.
85const CHECKED_TOOL: i64 = 0;
86
87/// How often a start waiting for an analysis reads the file again.
88pub const ANALYSIS_POLL: Duration = Duration::from_millis(250);
89
90/// How bad one verdict is, worst first, as a whole print's verdict is the
91/// worst of its tools'.
92const fn severity(verdict: PreflightVerdict) -> u8 {
93    match verdict {
94        PreflightVerdict::Insufficient => 0,
95        PreflightVerdict::UnverifiedSpool => 1,
96        PreflightVerdict::NoAnalysis => 2,
97        PreflightVerdict::Warned => 3,
98        PreflightVerdict::Overridden => 4,
99        PreflightVerdict::Unchecked => 5,
100        PreflightVerdict::Passed => 6,
101    }
102}
103
104/// The worst of the tools' verdicts; unchecked when there are none.
105fn worst(tools: &[PreflightTool]) -> PreflightVerdict {
106    tools
107        .iter()
108        .map(|tool| tool.result.verdict())
109        .min_by_key(|verdict| severity(*verdict))
110        .unwrap_or(PreflightVerdict::Unchecked)
111}
112
113/// The marks a spool holds, oldest first, when it holds any.
114fn marks(spool: &SpoolRecord) -> Option<UnverifiedMarks> {
115    match &spool.trust {
116        SpoolTrust::Verified => None,
117        SpoolTrust::Unverified { marks } => Some(marks.clone()),
118    }
119}
120
121/// A spool, as a check names it.
122fn named(spool: &SpoolRecord) -> PreflightSpool {
123    PreflightSpool {
124        id: spool.id,
125        name: spool.name.clone(),
126    }
127}
128
129/// What one tool's spool, judged against what the print needs from it, is
130/// found to be: short, in doubt, or enough.
131fn judged(spool: &SpoolRecord, need: PreflightNeed) -> PreflightToolResult {
132    let marks = marks(spool);
133    if spool.remaining_g < need.required_g + need.buffer_g {
134        return PreflightToolResult::Insufficient(ShortSpool {
135            spool: named(spool),
136            remaining_g: spool.remaining_g,
137            need,
138            marks: marks.map(UnverifiedMarks::into_vec).unwrap_or_default(),
139        });
140    }
141    match marks {
142        None => PreflightToolResult::Passed {
143            spool: named(spool),
144            remaining_g: spool.remaining_g,
145            need,
146        },
147        Some(marks) => PreflightToolResult::UnverifiedSpool(DoubtedSpool {
148            spool: named(spool),
149            remaining_g: spool.remaining_g,
150            need: Some(need),
151            marks,
152        }),
153    }
154}
155
156/// What one tool's spool is found to be when the file has no analysis: in
157/// doubt when it holds a mark, otherwise unanalysed.
158fn unanalysed(spool: &SpoolRecord) -> PreflightToolResult {
159    match marks(spool) {
160        None => PreflightToolResult::NoAnalysis(UnanalysedSpool {
161            spool: named(spool),
162            remaining_g: spool.remaining_g,
163        }),
164        Some(marks) => PreflightToolResult::UnverifiedSpool(DoubtedSpool {
165            spool: named(spool),
166            remaining_g: spool.remaining_g,
167            need: None,
168            marks,
169        }),
170    }
171}
172
173/// The refusal one check makes, when it makes one: the first short tool, else
174/// the first unverified one, else a file still unanalysed.
175fn refusal(preflight: &Preflight, waited_s: u64) -> Option<RejectionReason> {
176    let short = preflight.tools.iter().find_map(|tool| match &tool.result {
177        PreflightToolResult::Insufficient(short) => Some(RejectionReason::InsufficientFilament {
178            tool: tool.tool,
179            spool_id: short.spool.id,
180            spool_name: short.spool.name.clone(),
181            required_g: short.need.required_g,
182            buffer_g: short.need.buffer_g,
183            remaining_g: short.remaining_g,
184            unverified: short.marks.first().map(|mark| mark.reason.clone()),
185        }),
186        _ => None,
187    });
188    let unverified = || {
189        preflight.tools.iter().find_map(|tool| match &tool.result {
190            PreflightToolResult::UnverifiedSpool(doubted) => {
191                Some(RejectionReason::UnverifiedSpool {
192                    tool: tool.tool,
193                    spool_id: doubted.spool.id,
194                    spool_name: doubted.spool.name.clone(),
195                    reason: doubted.marks.oldest().reason.clone(),
196                })
197            }
198            _ => None,
199        })
200    };
201    let unanalysed = || {
202        preflight
203            .tools
204            .iter()
205            .any(|tool| matches!(tool.result, PreflightToolResult::NoAnalysis(_)))
206            .then(|| RejectionReason::AnalysisUnavailable {
207                file_name: preflight.file_name.clone(),
208                waited_s,
209            })
210    };
211    short.or_else(unverified).or_else(unanalysed)
212}
213
214/// The refusal the material check makes, when it makes one.
215fn material_refusal(preflight: &Preflight) -> Option<RejectionReason> {
216    match &preflight.material {
217        Some(MaterialResult::Refused { objection }) => Some(RejectionReason::MaterialRefused {
218            objection: objection.clone(),
219        }),
220        _ => None,
221    }
222}
223
224/// The refusal the sheet check makes, when it makes one.
225fn sheet_refusal(preflight: &Preflight) -> Option<RejectionReason> {
226    match &preflight.sheet {
227        Some(SheetResult::Refused { objection }) => Some(RejectionReason::SheetRefused {
228            objection: objection.clone(),
229        }),
230        _ => None,
231    }
232}
233
234/// How a start that went ahead despite an objection went ahead.
235#[derive(Debug, Clone, Copy)]
236enum LetThrough {
237    /// An operator overrode the check.
238    Overridden,
239    /// The check is set to warn.
240    Warned,
241}
242
243/// The same check, with every objecting tool's result replaced by one that
244/// let the start go ahead, carrying what it objected to.
245fn let_through(mut preflight: Preflight, how: LetThrough) -> Preflight {
246    for tool in &mut preflight.tools {
247        let objection = match tool.result.clone() {
248            PreflightToolResult::Insufficient(short) => PreflightObjection::Insufficient(short),
249            PreflightToolResult::UnverifiedSpool(doubted) => {
250                PreflightObjection::UnverifiedSpool(doubted)
251            }
252            PreflightToolResult::NoAnalysis(unanalysed) => {
253                PreflightObjection::NoAnalysis(unanalysed)
254            }
255            _ => continue,
256        };
257        tool.result = match how {
258            LetThrough::Overridden => PreflightToolResult::Overridden { objection },
259            LetThrough::Warned => PreflightToolResult::Warned { objection },
260        };
261    }
262    preflight.verdict = worst(&preflight.tools);
263    preflight
264}
265
266/// The same check, with each check that refused let through.
267fn let_all_through(mut preflight: Preflight, how: LetThrough) -> Preflight {
268    preflight = let_through(preflight, how);
269    if let Some(MaterialResult::Refused { objection }) = preflight.material.clone() {
270        preflight.material = Some(match how {
271            LetThrough::Overridden => MaterialResult::Overridden { objection },
272            LetThrough::Warned => MaterialResult::Warned { objection },
273        });
274    }
275    if let Some(SheetResult::Refused { objection }) = preflight.sheet.clone() {
276        preflight.sheet = Some(match how {
277            LetThrough::Overridden => SheetResult::Overridden { objection },
278            LetThrough::Warned => SheetResult::Warned { objection },
279        });
280    }
281    preflight
282}
283
284/// The material a spool was registered as, which a registration refuses to
285/// leave blank — so a spool always has one.
286fn material_of(spool: &SpoolRecord) -> Option<MaterialName> {
287    MaterialName::try_from(spool.material.clone()).ok()
288}
289
290/// Whether the spool's material is the one the file was sliced for, by what
291/// the printer read of the file's settings.
292// llmlint: ignore-block[invalid_states_unrepresentable] suppressions.toml has the reason.
293fn judged_material(
294    file_name: &FileName,
295    spool: &SpoolRecord,
296    loaded: MaterialName,
297    read: Result<Vec<Option<String>>, String>,
298) -> MaterialResult {
299    // llmlint: ignore-end[invalid_states_unrepresentable]
300    let types = match read {
301        Ok(types) => types,
302        Err(detail) => {
303            return MaterialResult::Refused {
304                objection: MaterialObjection::Unread {
305                    tool: CHECKED_TOOL,
306                    spool: named(spool),
307                    loaded,
308                    file_name: file_name.clone(),
309                    detail,
310                },
311            };
312        }
313    };
314    let declared = types
315        .into_iter()
316        .next()
317        .flatten()
318        .and_then(|named| MaterialName::try_from(named).ok());
319    let Some(sliced_for) = declared else {
320        return MaterialResult::Refused {
321            objection: MaterialObjection::Undeclared(UncomparedMaterial {
322                tool: CHECKED_TOOL,
323                spool: named(spool),
324                loaded,
325                file_name: file_name.clone(),
326            }),
327        };
328    };
329    let compared = MaterialComparison {
330        tool: CHECKED_TOOL,
331        spool: named(spool),
332        loaded,
333        sliced_for,
334    };
335    if compared.sliced_for.same(&compared.loaded) {
336        MaterialResult::Passed(compared)
337    } else {
338        MaterialResult::Refused {
339            objection: MaterialObjection::Mismatch(compared),
340        }
341    }
342}
343
344impl Supervisor {
345    /// Whether the spools loaded hold enough for one file, read now.
346    ///
347    /// A read: it records nothing and never waits. A file whose facts cannot
348    /// be read is a file with no analysis.
349    ///
350    /// # Errors
351    ///
352    /// Returns the store's own error when the loaded spools could not be read.
353    pub async fn preflight(
354        &self,
355        file_name: &FileName,
356        sheet: Option<&SheetId>,
357    ) -> Result<Preflight, CoreError> {
358        let facts = self.read_file_facts(file_name.clone()).await.ok();
359        let loaded = self.stores().filament.loaded_spools().await?;
360        let mut preflight = self.judge(file_name, facts.as_ref(), &loaded);
361        preflight.material = Some(self.judge_material(file_name, &loaded).await);
362        preflight.sheet = sheet.map(|sheet| self.judge_sheet(sheet, &loaded));
363        Ok(preflight)
364    }
365
366    /// Whether the file was sliced for the material of the spool on tool 0:
367    /// unchecked when no tracked spool is loaded there.
368    async fn judge_material(&self, file_name: &FileName, loaded: &[SpoolRecord]) -> MaterialResult {
369        let Some((spool, material)) = spool_on_tool(loaded, CHECKED_TOOL)
370            .and_then(|spool| Some((spool, material_of(spool)?)))
371        else {
372            return MaterialResult::Unchecked;
373        };
374        let read = self
375            .read_filament_types(file_name.clone())
376            .await
377            .map_err(|error| error.to_string());
378        judged_material(file_name, spool, material, read)
379    }
380
381    /// Whether the table allows the material of the spool on tool 0 on a
382    /// sheet: unchecked when no tracked spool is loaded there.
383    fn judge_sheet(&self, sheet: &SheetId, loaded: &[SpoolRecord]) -> SheetResult {
384        let Some(material) = spool_on_tool(loaded, CHECKED_TOOL).and_then(material_of) else {
385            return SheetResult::Unchecked;
386        };
387        let table = &self.config().sheets;
388        let sheet = sheet.clone();
389        let objection = if !table.lists(&sheet) {
390            SheetObjection::UnknownSheet {
391                sheet,
392                material,
393                known: table.sheets(),
394            }
395        } else if let Some(allowed) = table.allowed_for(&material) {
396            let compared = SheetComparison {
397                allowed: allowed.to_vec(),
398                sheet,
399                material,
400            };
401            if allowed.iter().any(|listed| listed.same(&compared.sheet)) {
402                return SheetResult::Passed(compared);
403            }
404            SheetObjection::NotAllowed(compared)
405        } else {
406            SheetObjection::UnlistedMaterial { sheet, material }
407        };
408        SheetResult::Refused { objection }
409    }
410
411    /// The check of one file's facts against the spools loaded.
412    fn judge(
413        &self,
414        file_name: &FileName,
415        facts: Option<&FileFacts>,
416        loaded: &[SpoolRecord],
417    ) -> Preflight {
418        let policy = &self.config().spools;
419        let on_tool = |tool: i64| {
420            loaded
421                .iter()
422                .find(|spool| spool.loaded_tool() == Some(tool))
423        };
424        let tools: Vec<PreflightTool> = match facts.and_then(|facts| facts.filament.as_deref()) {
425            Some(filament) => lengths_of(filament)
426                .into_iter()
427                .filter(|(_, length)| *length > NOTHING_MM)
428                .map(|(tool, length)| PreflightTool {
429                    tool,
430                    result: on_tool(tool).map_or(PreflightToolResult::Unchecked, |spool| {
431                        let required_g =
432                            grams_for_length(length, spool.diameter_mm, spool.density_g_cm3);
433                        judged(
434                            spool,
435                            PreflightNeed {
436                                required_g,
437                                buffer_g: buffer_g(required_g, policy),
438                            },
439                        )
440                    }),
441                })
442                .collect(),
443            None => loaded
444                .iter()
445                .filter_map(|spool| {
446                    Some(PreflightTool {
447                        tool: spool.loaded_tool()?,
448                        result: unanalysed(spool),
449                    })
450                })
451                .collect(),
452        };
453        Preflight {
454            file_name: file_name.as_str().to_owned(),
455            verdict: worst(&tools),
456            tools,
457            material: None,
458            sheet: None,
459            checked_at: self.clock().now(),
460        }
461    }
462
463    /// Wait for `OctoPrint`'s analysis of a file a start names, when the
464    /// check will need one: a tool holds a tracked spool, the check is on, the
465    /// actor may start a print at all, and the file has none yet.
466    ///
467    /// Returns once the analysis appears or the configured wait has elapsed on
468    /// the injected clock, re-reading the file every [`ANALYSIS_POLL`].
469    ///
470    /// # Errors
471    ///
472    /// Returns the store's own error when the loaded spools could not be read.
473    pub(crate) async fn await_analysis(
474        &self,
475        file_name: &FileName,
476        actor: &Actor,
477    ) -> Result<(), CoreError> {
478        let policy = &self.config().spools;
479        let granted = self
480            .config()
481            .envelope
482            .actions
483            .get(&actor.class())
484            .is_some_and(|kinds| kinds.contains(&ActionKind::StartPrint));
485        if policy.preflight == PreflightMode::Off || policy.analysis_wait_s == 0 || !granted {
486            return Ok(());
487        }
488        if self.stores().filament.loaded_spools().await?.is_empty() {
489            return Ok(());
490        }
491        let wait = i64::try_from(policy.analysis_wait_s).unwrap_or(i64::MAX);
492        let started = self.clock().now();
493        loop {
494            let analysed = self
495                .read_file_facts(file_name.clone())
496                .await
497                .is_ok_and(|facts| facts.filament.is_some());
498            if analysed || seconds_between(started, self.clock().now()) >= wait {
499                return Ok(());
500            }
501            // A wait the system will not take a thread for ends the wait: the
502            // start is judged on what the file says now.
503            if Delay::new(ANALYSIS_POLL).await.is_err() {
504                return Ok(());
505            }
506        }
507    }
508
509    /// The check a start the decision accepted is held to, and the refusal it
510    /// turns the decision into when it makes one.
511    ///
512    /// A manifest declaring no sheet is refused whatever the mode and whoever
513    /// overrides. Otherwise mode `off` checks nothing and records `unchecked`,
514    /// and a short, unverified or still-unanalysed tool, a material mismatch
515    /// or a sheet the table does not allow refuses the start in mode `refuse`
516    /// — unless an operator overrode every check that refused, each by its own
517    /// flag, which proceeds as `overridden` — and proceeds as `warned` in mode
518    /// `warn`.
519    ///
520    /// # Errors
521    ///
522    /// Returns the store's own error when the loaded spools could not be read.
523    pub(crate) async fn check_start(
524        &self,
525        file_name: &FileName,
526        sheet: Option<&str>,
527        actor: &Actor,
528        asked: Overrides,
529    ) -> Result<(Preflight, Option<RejectionReason>), CoreError> {
530        let policy = self.config().spools;
531        // A blank sheet names none, and is refused as declaring none.
532        let declared = sheet.and_then(|sheet| SheetId::try_from(sheet.to_owned()).ok());
533        let declared = declared.as_ref();
534        let mut preflight = if policy.preflight == PreflightMode::Off {
535            Preflight {
536                file_name: file_name.as_str().to_owned(),
537                tools: Vec::new(),
538                verdict: PreflightVerdict::Unchecked,
539                material: Some(MaterialResult::Unchecked),
540                sheet: Some(SheetResult::Unchecked),
541                checked_at: self.clock().now(),
542            }
543        } else {
544            self.preflight(file_name, declared).await?
545        };
546        if declared.is_none() {
547            preflight.sheet = Some(SheetResult::Undeclared);
548            return Ok((preflight, Some(RejectionReason::SheetNotDeclared)));
549        }
550        if policy.preflight == PreflightMode::Off {
551            return Ok((preflight, None));
552        }
553        let refusals = [
554            (refusal(&preflight, policy.analysis_wait_s), asked.filament),
555            (material_refusal(&preflight), asked.material),
556            (sheet_refusal(&preflight), asked.sheet),
557        ];
558        if refusals.iter().all(|(refused, _)| refused.is_none()) {
559            return Ok((preflight, None));
560        }
561        if policy.preflight == PreflightMode::Warn {
562            return Ok((let_all_through(preflight, LetThrough::Warned), None));
563        }
564        let operator = actor.class() == ActorClass::Operator;
565        let standing = refusals.into_iter().find_map(|(refused, asked)| {
566            refused.filter(|_| !(operator && asked == Override::Asked))
567        });
568        Ok(match standing {
569            Some(reason) => (preflight, Some(reason)),
570            None => (let_all_through(preflight, LetThrough::Overridden), None),
571        })
572    }
573}