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//!
37//! # A file with planned colour changes
38//!
39//! A single-nozzle print sliced with colour changes is fed by one spool per
40//! stretch between them, so its whole length is no one spool's. The file is
41//! read once through the G-code index ([`crate::gcode_index`]): when it plans a
42//! change, the spool on tool 0 is checked against segment 0's filament alone,
43//! every segment's filament is recorded with the spool meant for it, and each
44//! later segment a start's manifest names a spool for in `segment_spools` is
45//! checked against that spool, a short or doubted one refused naming the
46//! segment. A file planning no change, or one that cannot be read, is checked
47//! as a whole, as before.
48
49use std::time::Duration;
50
51use printobserver_printer_api::FileFacts;
52use printobserver_types::FileName;
53
54use crate::accounting::{NOTHING_MM, lengths_of, spool_on_tool};
55use crate::clock::seconds_between;
56use crate::config::{PreflightMode, SpoolPolicy};
57use crate::delay::Delay;
58use crate::error::CoreError;
59use crate::filament::{buffer_g, grams_for_length};
60use crate::gcode_index::{GcodeIndex, IndexBuilder, PlannedSegment};
61use crate::records::{
62    ActionKind, Actor, ActorClass, DoubtedSpool, MaterialComparison, MaterialName,
63    MaterialObjection, MaterialResult, Preflight, PreflightNeed, PreflightObjection,
64    PreflightSegment, PreflightSpool, PreflightTool, PreflightToolResult, PreflightVerdict,
65    RejectionReason, SegmentSpool, SheetComparison, SheetId, SheetObjection, SheetResult,
66    ShortSpool, SpoolRecord, SpoolTrust, UnanalysedSpool, UncomparedMaterial, UnverifiedMarks,
67};
68use crate::supervisor::Supervisor;
69
70/// Whether a start asked to go ahead despite the filament check.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub(crate) enum Override {
73    /// It asked; only an operator's asking counts.
74    Asked,
75    /// It did not.
76    NotAsked,
77}
78
79impl From<bool> for Override {
80    fn from(asked: bool) -> Self {
81        if asked { Self::Asked } else { Self::NotAsked }
82    }
83}
84
85/// Which of the three checks a start asked to go ahead despite.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub(crate) struct Overrides {
88    /// The filament weight check.
89    pub(crate) filament: Override,
90    /// The material check.
91    pub(crate) material: Override,
92    /// The sheet check, which never lets through a manifest declaring none.
93    pub(crate) sheet: Override,
94}
95
96/// The tool the material and sheet checks are about: the one a single-tool
97/// print feeds, and the first a multi-tool slicer names.
98const CHECKED_TOOL: i64 = 0;
99
100/// How often a start waiting for an analysis reads the file again.
101pub const ANALYSIS_POLL: Duration = Duration::from_millis(250);
102
103/// How bad one verdict is, worst first, as a whole print's verdict is the
104/// worst of its tools'.
105const fn severity(verdict: PreflightVerdict) -> u8 {
106    match verdict {
107        PreflightVerdict::Insufficient => 0,
108        PreflightVerdict::UnverifiedSpool => 1,
109        PreflightVerdict::NoAnalysis => 2,
110        PreflightVerdict::Warned => 3,
111        PreflightVerdict::Overridden => 4,
112        PreflightVerdict::Unchecked => 5,
113        PreflightVerdict::Passed => 6,
114    }
115}
116
117/// The worst of the tools' verdicts; unchecked when there are none.
118fn worst(tools: &[PreflightTool]) -> PreflightVerdict {
119    tools
120        .iter()
121        .map(|tool| tool.result.verdict())
122        .min_by_key(|verdict| severity(*verdict))
123        .unwrap_or(PreflightVerdict::Unchecked)
124}
125
126/// The marks a spool holds, oldest first, when it holds any.
127fn marks(spool: &SpoolRecord) -> Option<UnverifiedMarks> {
128    match &spool.trust {
129        SpoolTrust::Verified => None,
130        SpoolTrust::Unverified { marks } => Some(marks.clone()),
131    }
132}
133
134/// A spool, as a check names it.
135fn named(spool: &SpoolRecord) -> PreflightSpool {
136    PreflightSpool {
137        id: spool.id,
138        name: spool.name.clone(),
139    }
140}
141
142/// What one tool's spool, judged against what the print needs from it, is
143/// found to be: short, in doubt, or enough.
144fn judged(spool: &SpoolRecord, need: PreflightNeed) -> PreflightToolResult {
145    let marks = marks(spool);
146    if spool.remaining_g < need.required_g + need.buffer_g {
147        return PreflightToolResult::Insufficient(ShortSpool {
148            spool: named(spool),
149            remaining_g: spool.remaining_g,
150            need,
151            marks: marks.map(UnverifiedMarks::into_vec).unwrap_or_default(),
152        });
153    }
154    match marks {
155        None => PreflightToolResult::Passed {
156            spool: named(spool),
157            remaining_g: spool.remaining_g,
158            need,
159        },
160        Some(marks) => PreflightToolResult::UnverifiedSpool(DoubtedSpool {
161            spool: named(spool),
162            remaining_g: spool.remaining_g,
163            need: Some(need),
164            marks,
165        }),
166    }
167}
168
169/// What one tool's spool is found to be when the file has no analysis: in
170/// doubt when it holds a mark, otherwise unanalysed.
171fn unanalysed(spool: &SpoolRecord) -> PreflightToolResult {
172    match marks(spool) {
173        None => PreflightToolResult::NoAnalysis(UnanalysedSpool {
174            spool: named(spool),
175            remaining_g: spool.remaining_g,
176        }),
177        Some(marks) => PreflightToolResult::UnverifiedSpool(DoubtedSpool {
178            spool: named(spool),
179            remaining_g: spool.remaining_g,
180            need: None,
181            marks,
182        }),
183    }
184}
185
186/// The refusal one check makes, when it makes one: the first short tool, else
187/// the first unverified one, else a file still unanalysed.
188fn refusal(preflight: &Preflight, waited_s: u64) -> Option<RejectionReason> {
189    // With planned changes, tool 0 was checked against segment 0 alone.
190    let segment_of =
191        |tool: i64| (tool == CHECKED_TOOL && !preflight.segments.is_empty()).then_some(0);
192    let short = preflight.tools.iter().find_map(|tool| match &tool.result {
193        PreflightToolResult::Insufficient(short) => Some(RejectionReason::InsufficientFilament {
194            tool: tool.tool,
195            spool_id: short.spool.id,
196            spool_name: short.spool.name.clone(),
197            required_g: short.need.required_g,
198            buffer_g: short.need.buffer_g,
199            remaining_g: short.remaining_g,
200            unverified: short.marks.first().map(|mark| mark.reason.clone()),
201            segment: segment_of(tool.tool),
202        }),
203        _ => None,
204    });
205    let unverified = || {
206        preflight.tools.iter().find_map(|tool| match &tool.result {
207            PreflightToolResult::UnverifiedSpool(doubted) => {
208                Some(RejectionReason::UnverifiedSpool {
209                    tool: tool.tool,
210                    spool_id: doubted.spool.id,
211                    spool_name: doubted.spool.name.clone(),
212                    reason: doubted.marks.oldest().reason.clone(),
213                    segment: segment_of(tool.tool),
214                })
215            }
216            _ => None,
217        })
218    };
219    let unanalysed = || {
220        preflight
221            .tools
222            .iter()
223            .any(|tool| matches!(tool.result, PreflightToolResult::NoAnalysis(_)))
224            .then(|| RejectionReason::AnalysisUnavailable {
225                file_name: preflight.file_name.clone(),
226                waited_s,
227            })
228    };
229    short.or_else(unverified).or_else(unanalysed)
230}
231
232/// The refusal one later segment's named spool makes, judged against that
233/// segment's filament: short, else in doubt.
234fn segment_refusal(segment: u32, result: &PreflightToolResult) -> Option<RejectionReason> {
235    match result {
236        PreflightToolResult::Insufficient(short) => Some(RejectionReason::InsufficientFilament {
237            tool: CHECKED_TOOL,
238            spool_id: short.spool.id,
239            spool_name: short.spool.name.clone(),
240            required_g: short.need.required_g,
241            buffer_g: short.need.buffer_g,
242            remaining_g: short.remaining_g,
243            unverified: short.marks.first().map(|mark| mark.reason.clone()),
244            segment: Some(segment),
245        }),
246        PreflightToolResult::UnverifiedSpool(doubted) => Some(RejectionReason::UnverifiedSpool {
247            tool: CHECKED_TOOL,
248            spool_id: doubted.spool.id,
249            spool_name: doubted.spool.name.clone(),
250            reason: doubted.marks.oldest().reason.clone(),
251            segment: Some(segment),
252        }),
253        _ => None,
254    }
255}
256
257/// What one spool must hold for one segment: its filament as that spool's
258/// grams, and the buffer the policy asks beyond them.
259fn need_for(segment: &PlannedSegment, spool: &SpoolRecord, policy: &SpoolPolicy) -> PreflightNeed {
260    let required_g = grams_for_length(segment.filament_mm, spool.diameter_mm, spool.density_g_cm3);
261    PreflightNeed {
262        required_g,
263        buffer_g: buffer_g(required_g, policy),
264    }
265}
266
267/// The refusal the material check makes, when it makes one.
268fn material_refusal(preflight: &Preflight) -> Option<RejectionReason> {
269    match &preflight.material {
270        Some(MaterialResult::Refused { objection }) => Some(RejectionReason::MaterialRefused {
271            objection: objection.clone(),
272        }),
273        _ => None,
274    }
275}
276
277/// The refusal the sheet check makes, when it makes one.
278fn sheet_refusal(preflight: &Preflight) -> Option<RejectionReason> {
279    match &preflight.sheet {
280        Some(SheetResult::Refused { objection }) => Some(RejectionReason::SheetRefused {
281            objection: objection.clone(),
282        }),
283        _ => None,
284    }
285}
286
287/// How a start that went ahead despite an objection went ahead.
288#[derive(Debug, Clone, Copy)]
289enum LetThrough {
290    /// An operator overrode the check.
291    Overridden,
292    /// The check is set to warn.
293    Warned,
294}
295
296/// The same check, with every objecting tool's result replaced by one that
297/// let the start go ahead, carrying what it objected to.
298fn let_through(mut preflight: Preflight, how: LetThrough) -> Preflight {
299    for tool in &mut preflight.tools {
300        let objection = match tool.result.clone() {
301            PreflightToolResult::Insufficient(short) => PreflightObjection::Insufficient(short),
302            PreflightToolResult::UnverifiedSpool(doubted) => {
303                PreflightObjection::UnverifiedSpool(doubted)
304            }
305            PreflightToolResult::NoAnalysis(unanalysed) => {
306                PreflightObjection::NoAnalysis(unanalysed)
307            }
308            _ => continue,
309        };
310        tool.result = match how {
311            LetThrough::Overridden => PreflightToolResult::Overridden { objection },
312            LetThrough::Warned => PreflightToolResult::Warned { objection },
313        };
314    }
315    preflight.verdict = worst(&preflight.tools);
316    preflight
317}
318
319/// The same check, with each check that refused let through.
320fn let_all_through(mut preflight: Preflight, how: LetThrough) -> Preflight {
321    preflight = let_through(preflight, how);
322    if let Some(MaterialResult::Refused { objection }) = preflight.material.clone() {
323        preflight.material = Some(match how {
324            LetThrough::Overridden => MaterialResult::Overridden { objection },
325            LetThrough::Warned => MaterialResult::Warned { objection },
326        });
327    }
328    if let Some(SheetResult::Refused { objection }) = preflight.sheet.clone() {
329        preflight.sheet = Some(match how {
330            LetThrough::Overridden => SheetResult::Overridden { objection },
331            LetThrough::Warned => SheetResult::Warned { objection },
332        });
333    }
334    preflight
335}
336
337/// The material a spool was registered as, which a registration refuses to
338/// leave blank — so a spool always has one.
339fn material_of(spool: &SpoolRecord) -> Option<MaterialName> {
340    MaterialName::try_from(spool.material.clone()).ok()
341}
342
343/// Whether the spool's material is the one the file was sliced for, by what
344/// the printer read of the file's settings.
345// llmlint: ignore-block[invalid_states_unrepresentable] suppressions.toml has the reason.
346fn judged_material(
347    file_name: &FileName,
348    spool: &SpoolRecord,
349    loaded: MaterialName,
350    read: Result<Vec<Option<String>>, String>,
351) -> MaterialResult {
352    // llmlint: ignore-end[invalid_states_unrepresentable]
353    let types = match read {
354        Ok(types) => types,
355        Err(detail) => {
356            return MaterialResult::Refused {
357                objection: MaterialObjection::Unread {
358                    tool: CHECKED_TOOL,
359                    spool: named(spool),
360                    loaded,
361                    file_name: file_name.clone(),
362                    detail,
363                },
364            };
365        }
366    };
367    let declared = types
368        .into_iter()
369        .next()
370        .flatten()
371        .and_then(|named| MaterialName::try_from(named).ok());
372    let Some(sliced_for) = declared else {
373        return MaterialResult::Refused {
374            objection: MaterialObjection::Undeclared(UncomparedMaterial {
375                tool: CHECKED_TOOL,
376                spool: named(spool),
377                loaded,
378                file_name: file_name.clone(),
379            }),
380        };
381    };
382    let compared = MaterialComparison {
383        tool: CHECKED_TOOL,
384        spool: named(spool),
385        loaded,
386        sliced_for,
387    };
388    if compared.sliced_for.same(&compared.loaded) {
389        MaterialResult::Passed(compared)
390    } else {
391        MaterialResult::Refused {
392            objection: MaterialObjection::Mismatch(compared),
393        }
394    }
395}
396
397impl Supervisor {
398    /// Whether the spools loaded hold enough for one file, read now.
399    ///
400    /// A read: it records nothing and never waits. A file whose facts cannot
401    /// be read is a file with no analysis.
402    ///
403    /// # Errors
404    ///
405    /// Returns the store's own error when the loaded spools could not be read.
406    pub async fn preflight(
407        &self,
408        file_name: &FileName,
409        sheet: Option<&SheetId>,
410    ) -> Result<Preflight, CoreError> {
411        Ok(self.preflight_for(file_name, sheet, &[]).await?.0)
412    }
413
414    /// The check of one file, with every later segment the manifest names a
415    /// spool for checked against that spool, and the refusal the first short
416    /// or doubted one of them makes.
417    async fn preflight_for(
418        &self,
419        file_name: &FileName,
420        sheet: Option<&SheetId>,
421        named: &[SegmentSpool],
422    ) -> Result<(Preflight, Option<RejectionReason>), CoreError> {
423        let facts = self.read_file_facts(file_name.clone()).await.ok();
424        let loaded = self.stores().filament.loaded_spools().await?;
425        let mut preflight = self.judge(file_name, facts.as_ref(), &loaded);
426        let refused = match self.planned_index_of(file_name).await {
427            Some(index) => {
428                self.judge_segments(&mut preflight, &index, &loaded, named)
429                    .await?
430            }
431            None => None,
432        };
433        preflight.material = Some(self.judge_material(file_name, &loaded).await);
434        preflight.sheet = sheet.map(|sheet| self.judge_sheet(sheet, &loaded));
435        Ok((preflight, refused))
436    }
437
438    /// The index of a file a start names, when it can be read and plans a
439    /// change: read through the same builder a print's index is, holding no
440    /// spool, and kept no longer than the check.
441    async fn planned_index_of(&self, file_name: &FileName) -> Option<GcodeIndex> {
442        let mut builder = IndexBuilder::new();
443        self.read_gcode(file_name.clone(), &mut builder)
444            .await
445            .ok()?;
446        let index = builder.finish();
447        index.planned_change(0).is_some().then_some(index)
448    }
449
450    /// Check tool 0 against segment 0 alone, record every segment with the
451    /// spool meant for it, and check each later segment the manifest names a
452    /// spool for against that spool. Answers the refusal the first short or
453    /// doubted named spool makes.
454    async fn judge_segments(
455        &self,
456        preflight: &mut Preflight,
457        index: &GcodeIndex,
458        loaded: &[SpoolRecord],
459        named: &[SegmentSpool],
460    ) -> Result<Option<RejectionReason>, CoreError> {
461        let policy = self.config().spools;
462        let segments = index.planned_segments();
463        let first = spool_on_tool(loaded, CHECKED_TOOL);
464        if let (Some(spool), Some(segment)) = (first, segments.first()) {
465            let result = judged(spool, need_for(segment, spool, &policy));
466            match preflight
467                .tools
468                .iter_mut()
469                .find(|tool| tool.tool == CHECKED_TOOL)
470            {
471                Some(tool) => tool.result = result,
472                None => preflight.tools.insert(
473                    0,
474                    PreflightTool {
475                        tool: CHECKED_TOOL,
476                        result,
477                    },
478                ),
479            }
480        }
481        let mut refused = None;
482        let mut checked = Vec::with_capacity(segments.len());
483        for segment in &segments {
484            let spool = if segment.segment == 0 {
485                first.cloned()
486            } else {
487                match named.iter().find(|named| named.segment == segment.segment) {
488                    Some(named) => self.stores().filament.spool(named.spool_id).await?,
489                    None => None,
490                }
491            };
492            if let Some(spool) = spool.as_ref().filter(|_| segment.segment > 0) {
493                let result = judged(spool, need_for(segment, spool, &policy));
494                refused = refused.or_else(|| segment_refusal(segment.segment, &result));
495                checked.push(result.verdict());
496            }
497            preflight.segments.push(PreflightSegment {
498                segment: segment.segment,
499                color: segment.color.clone(),
500                filament_mm: segment.filament_mm,
501                required_g: spool
502                    .as_ref()
503                    .map(|spool| need_for(segment, spool, &policy).required_g),
504                spool_id: spool.as_ref().map(|spool| spool.id),
505            });
506        }
507        preflight.verdict = checked
508            .into_iter()
509            .chain(Some(worst(&preflight.tools)))
510            .min_by_key(|verdict| severity(*verdict))
511            .unwrap_or(PreflightVerdict::Unchecked);
512        Ok(refused)
513    }
514
515    /// Whether the file was sliced for the material of the spool on tool 0:
516    /// unchecked when no tracked spool is loaded there.
517    async fn judge_material(&self, file_name: &FileName, loaded: &[SpoolRecord]) -> MaterialResult {
518        let Some((spool, material)) = spool_on_tool(loaded, CHECKED_TOOL)
519            .and_then(|spool| Some((spool, material_of(spool)?)))
520        else {
521            return MaterialResult::Unchecked;
522        };
523        let read = self
524            .read_filament_types(file_name.clone())
525            .await
526            .map_err(|error| error.to_string());
527        judged_material(file_name, spool, material, read)
528    }
529
530    /// Whether the table allows the material of the spool on tool 0 on a
531    /// sheet: unchecked when no tracked spool is loaded there.
532    fn judge_sheet(&self, sheet: &SheetId, loaded: &[SpoolRecord]) -> SheetResult {
533        let Some(material) = spool_on_tool(loaded, CHECKED_TOOL).and_then(material_of) else {
534            return SheetResult::Unchecked;
535        };
536        let table = &self.config().sheets;
537        let sheet = sheet.clone();
538        let objection = if !table.lists(&sheet) {
539            SheetObjection::UnknownSheet {
540                sheet,
541                material,
542                known: table.sheets(),
543            }
544        } else if let Some(allowed) = table.allowed_for(&material) {
545            let compared = SheetComparison {
546                allowed: allowed.to_vec(),
547                sheet,
548                material,
549            };
550            if allowed.iter().any(|listed| listed.same(&compared.sheet)) {
551                return SheetResult::Passed(compared);
552            }
553            SheetObjection::NotAllowed(compared)
554        } else {
555            SheetObjection::UnlistedMaterial { sheet, material }
556        };
557        SheetResult::Refused { objection }
558    }
559
560    /// The check of one file's facts against the spools loaded.
561    fn judge(
562        &self,
563        file_name: &FileName,
564        facts: Option<&FileFacts>,
565        loaded: &[SpoolRecord],
566    ) -> Preflight {
567        let policy = &self.config().spools;
568        let on_tool = |tool: i64| {
569            loaded
570                .iter()
571                .find(|spool| spool.loaded_tool() == Some(tool))
572        };
573        let tools: Vec<PreflightTool> = match facts.and_then(|facts| facts.filament.as_deref()) {
574            Some(filament) => lengths_of(filament)
575                .into_iter()
576                .filter(|(_, length)| *length > NOTHING_MM)
577                .map(|(tool, length)| PreflightTool {
578                    tool,
579                    result: on_tool(tool).map_or(PreflightToolResult::Unchecked, |spool| {
580                        let required_g =
581                            grams_for_length(length, spool.diameter_mm, spool.density_g_cm3);
582                        judged(
583                            spool,
584                            PreflightNeed {
585                                required_g,
586                                buffer_g: buffer_g(required_g, policy),
587                            },
588                        )
589                    }),
590                })
591                .collect(),
592            None => loaded
593                .iter()
594                .filter_map(|spool| {
595                    Some(PreflightTool {
596                        tool: spool.loaded_tool()?,
597                        result: unanalysed(spool),
598                    })
599                })
600                .collect(),
601        };
602        Preflight {
603            file_name: file_name.as_str().to_owned(),
604            verdict: worst(&tools),
605            tools,
606            material: None,
607            sheet: None,
608            segments: Vec::new(),
609            checked_at: self.clock().now(),
610        }
611    }
612
613    /// Wait for `OctoPrint`'s analysis of a file a start names, when the
614    /// check will need one: a tool holds a tracked spool, the check is on, the
615    /// actor may start a print at all, and the file has none yet.
616    ///
617    /// Returns once the analysis appears or the configured wait has elapsed on
618    /// the injected clock, re-reading the file every [`ANALYSIS_POLL`].
619    ///
620    /// # Errors
621    ///
622    /// Returns the store's own error when the loaded spools could not be read.
623    pub(crate) async fn await_analysis(
624        &self,
625        file_name: &FileName,
626        actor: &Actor,
627    ) -> Result<(), CoreError> {
628        let policy = &self.config().spools;
629        let granted = self
630            .config()
631            .envelope
632            .actions
633            .get(&actor.class())
634            .is_some_and(|kinds| kinds.contains(&ActionKind::StartPrint));
635        if policy.preflight == PreflightMode::Off || policy.analysis_wait_s == 0 || !granted {
636            return Ok(());
637        }
638        if self.stores().filament.loaded_spools().await?.is_empty() {
639            return Ok(());
640        }
641        let wait = i64::try_from(policy.analysis_wait_s).unwrap_or(i64::MAX);
642        let started = self.clock().now();
643        loop {
644            let analysed = self
645                .read_file_facts(file_name.clone())
646                .await
647                .is_ok_and(|facts| facts.filament.is_some());
648            if analysed || seconds_between(started, self.clock().now()) >= wait {
649                return Ok(());
650            }
651            // A wait the system will not take a thread for ends the wait: the
652            // start is judged on what the file says now.
653            if Delay::new(ANALYSIS_POLL).await.is_err() {
654                return Ok(());
655            }
656        }
657    }
658
659    /// The check a start the decision accepted is held to, and the refusal it
660    /// turns the decision into when it makes one.
661    ///
662    /// A manifest declaring no sheet is refused whatever the mode and whoever
663    /// overrides. Otherwise mode `off` checks nothing and records `unchecked`,
664    /// and a short, unverified or still-unanalysed tool, a material mismatch
665    /// or a sheet the table does not allow refuses the start in mode `refuse`
666    /// — unless an operator overrode every check that refused, each by its own
667    /// flag, which proceeds as `overridden` — and proceeds as `warned` in mode
668    /// `warn`.
669    ///
670    /// # Errors
671    ///
672    /// Returns the store's own error when the loaded spools could not be read.
673    pub(crate) async fn check_start(
674        &self,
675        file_name: &FileName,
676        sheet: Option<&str>,
677        segment_spools: &[SegmentSpool],
678        actor: &Actor,
679        asked: Overrides,
680    ) -> Result<(Preflight, Option<RejectionReason>), CoreError> {
681        let policy = self.config().spools;
682        // A blank sheet names none, and is refused as declaring none.
683        let declared = sheet.and_then(|sheet| SheetId::try_from(sheet.to_owned()).ok());
684        let declared = declared.as_ref();
685        let (mut preflight, segment_refused) = if policy.preflight == PreflightMode::Off {
686            let unchecked = Preflight {
687                file_name: file_name.as_str().to_owned(),
688                tools: Vec::new(),
689                verdict: PreflightVerdict::Unchecked,
690                material: Some(MaterialResult::Unchecked),
691                sheet: Some(SheetResult::Unchecked),
692                segments: Vec::new(),
693                checked_at: self.clock().now(),
694            };
695            (unchecked, None)
696        } else {
697            self.preflight_for(file_name, declared, segment_spools)
698                .await?
699        };
700        if declared.is_none() {
701            preflight.sheet = Some(SheetResult::Undeclared);
702            return Ok((preflight, Some(RejectionReason::SheetNotDeclared)));
703        }
704        if policy.preflight == PreflightMode::Off {
705            return Ok((preflight, None));
706        }
707        let segment_let_through = segment_refused.is_some();
708        let refusals = [
709            (
710                refusal(&preflight, policy.analysis_wait_s).or(segment_refused),
711                asked.filament,
712            ),
713            (material_refusal(&preflight), asked.material),
714            (sheet_refusal(&preflight), asked.sheet),
715        ];
716        if refusals.iter().all(|(refused, _)| refused.is_none()) {
717            return Ok((preflight, None));
718        }
719        // A later segment's spool lets the start through as tool 0's would,
720        // and the verdict says so whatever tool 0 was found to hold.
721        let through = |preflight: Preflight, how: LetThrough| {
722            let mut preflight = let_all_through(preflight, how);
723            if segment_let_through {
724                let let_through = match how {
725                    LetThrough::Overridden => PreflightVerdict::Overridden,
726                    LetThrough::Warned => PreflightVerdict::Warned,
727                };
728                if severity(let_through) < severity(preflight.verdict) {
729                    preflight.verdict = let_through;
730                }
731            }
732            preflight
733        };
734        if policy.preflight == PreflightMode::Warn {
735            return Ok((through(preflight, LetThrough::Warned), None));
736        }
737        let operator = actor.class() == ActorClass::Operator;
738        let standing = refusals.into_iter().find_map(|(refused, asked)| {
739            refused.filter(|_| !(operator && asked == Override::Asked))
740        });
741        Ok(match standing {
742            Some(reason) => (preflight, Some(reason)),
743            None => (through(preflight, LetThrough::Overridden), None),
744        })
745    }
746}