Skip to main content

printobserver_core/
unobserved.rs

1//! The prints the printer's own tallies counted and this system never saw.
2//!
3//! `OctoPrint` counts every print of every file it holds, by outcome. A print
4//! made while this system was down, or one it otherwise never watched, shows up
5//! there and nowhere else, so [`Supervisor::account_unobserved_prints`] —
6//! which the server calls as it starts — compares each file's tallies with the
7//! ones last accounted, less the prints of that file this system itself settled
8//! since then, counted print by print.
9//!
10//! Each print left over is written down as an `unaccounted_print` and keyed by
11//! its ordinal in the file's tally: a successful one charges the spool on each
12//! tool its analysed length, and any other marks that spool as one whose figure
13//! is in doubt. A tally that went **down** — the file deleted and uploaded
14//! again — advances that file's generation, so an ordinal reused after it is a
15//! new key: its count is the new generation's growth from zero, accounted like
16//! any other when no print of the file was settled in the window, and otherwise
17//! answered by marking the loaded spools rather than charging on a guess.
18//!
19//! Everything one run finds is written by one
20//! [`account_tallies`](crate::store::FilamentStore::account_tallies), so a run
21//! interrupted before it commits leaves nothing and one repeated after it
22//! commits finds nothing new. The first run, with no tallies held, stores the
23//! baseline and flags nothing.
24
25use std::collections::BTreeMap;
26
27use printobserver_printer_api::FileFacts;
28use printobserver_types::{EventRecord, Timestamp};
29
30use crate::accounting::{Feed, Figures, NOTHING_MM, lengths_of};
31use crate::error::CoreError;
32use crate::kinds::{
33    FileTallyRebaselinedPayload, RebaselineDisposition, UnaccountedPrintPayload, system_source,
34};
35use crate::records::{ChargeKey, ChargeMethod, PrintOutcome, SpoolRecord, UnverifiedReason};
36use crate::store::{Charge, EventDraft, FileTally, SpoolMutation};
37use crate::supervisor::Supervisor;
38
39/// One print the tallies counted and nobody accounted for.
40#[derive(Debug, Clone, Copy)]
41struct Unseen {
42    /// Its ordinal in the file's tally, within the generation.
43    print_number: i64,
44    /// How it ended, by the tally: completed, or not.
45    outcome: PrintOutcome,
46}
47
48/// The prints of one file this system settled in a window, by outcome.
49#[derive(Debug, Clone, Copy, Default)]
50struct Settled {
51    /// The ones it settled completed.
52    successes: i64,
53    /// The ones it settled any other way.
54    failures: i64,
55}
56
57impl Settled {
58    /// Every print it settled.
59    const fn total(self) -> i64 {
60        self.successes + self.failures
61    }
62}
63
64/// The unseen prints between two tallies of one generation: the highest
65/// ordinals of the growth, completed ones first. A tally whose counts overflow
66/// when added is no tally, and has none.
67fn unseen_between(from: (i64, i64), to: (i64, i64), settled: Settled) -> Vec<Unseen> {
68    let grown = |now: i64, before: i64, seen: i64| {
69        now.checked_sub(before)
70            .and_then(|growth| growth.checked_sub(seen))
71            .map(|unseen| unseen.max(0))
72    };
73    let (Some(successes), Some(failures), Some(total)) = (
74        grown(to.0, from.0, settled.successes),
75        grown(to.1, from.1, settled.failures),
76        to.0.checked_add(to.1),
77    ) else {
78        return Vec::new();
79    };
80    let Some(first) = successes
81        .checked_add(failures)
82        .and_then(|unseen| total.checked_sub(unseen))
83        .and_then(|before| before.checked_add(1))
84    else {
85        return Vec::new();
86    };
87    (0..successes.saturating_add(failures))
88        .map(|offset| Unseen {
89            print_number: first.saturating_add(offset),
90            outcome: if offset < successes {
91                PrintOutcome::Completed
92            } else {
93                PrintOutcome::Failed
94            },
95        })
96        .collect()
97}
98
99/// The prints of one file this system settled at or after an instant, or ever
100/// when there is none, by outcome.
101// llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
102fn settled_since(
103    settlements: &[(String, Timestamp, PrintOutcome)],
104    file_name: &str,
105    since: Option<Timestamp>,
106) -> Settled {
107    let mut settled = Settled::default();
108    for (_, _, outcome) in settlements
109        .iter()
110        .filter(|(file, at, _)| file == file_name && since.is_none_or(|since| *at >= since))
111    {
112        if *outcome == PrintOutcome::Completed {
113            settled.successes += 1;
114        } else {
115            settled.failures += 1;
116        }
117    }
118    settled
119}
120
121/// What one run of the accounting writes.
122#[derive(Debug, Default)]
123struct Accounting {
124    /// The advanced tallies.
125    tallies: Vec<FileTally>,
126    /// The charges of unseen prints that completed.
127    charges: Vec<Charge>,
128    /// The marks on spools nothing could be charged to.
129    marks: Vec<SpoolMutation>,
130    /// The `file_tally_rebaselined` and `unaccounted_print` events.
131    events: Vec<EventDraft>,
132    /// Each spool's figure as the charges are worked out.
133    figures: Figures,
134}
135
136impl Supervisor {
137    /// Account the prints the printer's tallies counted that this system never
138    /// saw, and answer what that recorded.
139    ///
140    /// # Errors
141    ///
142    /// Returns the printer's own error when its tallies could not be read, and
143    /// the store's own when the accounting could not be written — in which case
144    /// nothing of this run was.
145    pub async fn account_unobserved_prints(&self) -> Result<Vec<EventRecord>, CoreError> {
146        let files = self
147            .read_printed_files()
148            .await
149            .map_err(CoreError::Printer)?;
150        let _writing = self.spool_writes().await;
151        let held = self.stores().filament.file_tallies().await?;
152        let now = self.clock().now();
153        if held.is_empty() {
154            let baseline = files
155                .iter()
156                .filter(|file| readable(file))
157                .map(|file| FileTally {
158                    file_name: file.file_name.clone(),
159                    origin: file.origin.clone(),
160                    generation: 0,
161                    successes: file.successes,
162                    failures: file.failures,
163                    observed_at: now,
164                })
165                .collect();
166            return Ok(self
167                .stores()
168                .filament
169                .account_tallies(baseline, Vec::new(), Vec::new(), Vec::new())
170                .await?);
171        }
172        let loaded = self.stores().filament.loaded_spools().await?;
173        let settlements = self.settlements_of(&files).await?;
174        let mut accounting = Accounting::default();
175        for file in files.iter().filter(|file| readable(file)) {
176            let previous = held
177                .iter()
178                .find(|tally| tally.file_name == file.file_name && tally.origin == file.origin);
179            self.account_file(file, previous, &settlements, &loaded, now, &mut accounting)?;
180        }
181        Ok(self
182            .stores()
183            .filament
184            .account_tallies(
185                accounting.tallies,
186                accounting.charges,
187                accounting.marks,
188                accounting.events,
189            )
190            .await?)
191    }
192
193    /// Every settlement this system made of a print of one of these files:
194    /// the file, when, and with which outcome.
195    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
196    async fn settlements_of(
197        &self,
198        files: &[FileFacts],
199    ) -> Result<Vec<(String, Timestamp, PrintOutcome)>, CoreError> {
200        let mut settlements = Vec::new();
201        for print in self.stores().prints.prints().await? {
202            let Some(file_name) = print
203                .file_name
204                .filter(|name| files.iter().any(|file| &file.file_name == name))
205            else {
206                continue;
207            };
208            if let Some((at, outcome)) = self.stores().filament.print_settlement(print.id).await? {
209                settlements.push((file_name, at, outcome));
210            }
211        }
212        Ok(settlements)
213    }
214
215    /// Account one file's tally against the one last held for it.
216    fn account_file(
217        &self,
218        file: &FileFacts,
219        previous: Option<&FileTally>,
220        // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
221        settlements: &[(String, Timestamp, PrintOutcome)],
222        loaded: &[SpoolRecord],
223        now: Timestamp,
224        accounting: &mut Accounting,
225    ) -> Result<(), CoreError> {
226        let since = previous.map(|tally| tally.observed_at);
227        let settled = settled_since(settlements, &file.file_name, since);
228        let (generation, unseen) = match previous {
229            Some(held) if file.successes < held.successes || file.failures < held.failures => {
230                let generation = held.generation + 1;
231                let accounted = settled.total() == 0;
232                accounting.events.push(self.draft_of(
233                    None,
234                    system_source(),
235                    &FileTallyRebaselinedPayload {
236                        file_name: file.file_name.clone(),
237                        origin: file.origin.clone(),
238                        old_generation: held.generation,
239                        new_generation: generation,
240                        old_successes: held.successes,
241                        old_failures: held.failures,
242                        new_successes: file.successes,
243                        new_failures: file.failures,
244                        disposition: if accounted {
245                            RebaselineDisposition::Accounted
246                        } else {
247                            RebaselineDisposition::Unverified
248                        },
249                    },
250                )?);
251                if accounted {
252                    let unseen =
253                        unseen_between((0, 0), (file.successes, file.failures), Settled::default());
254                    (generation, unseen)
255                } else {
256                    for spool in spools_for(file, loaded) {
257                        accounting.marks.push(self.mark_of(
258                            spool.id,
259                            UnverifiedReason::TallyReset {
260                                file_name: file.file_name.clone(),
261                                origin: file.origin.clone(),
262                            },
263                            None,
264                        )?);
265                    }
266                    (generation, Vec::new())
267                }
268            }
269            Some(held) => (
270                held.generation,
271                unseen_between(
272                    (held.successes, held.failures),
273                    (file.successes, file.failures),
274                    settled,
275                ),
276            ),
277            None => (
278                0,
279                unseen_between((0, 0), (file.successes, file.failures), settled),
280            ),
281        };
282        for print in unseen {
283            self.account_unseen(file, generation, print, loaded, accounting)?;
284        }
285        accounting.tallies.push(FileTally {
286            file_name: file.file_name.clone(),
287            origin: file.origin.clone(),
288            generation,
289            successes: file.successes,
290            failures: file.failures,
291            observed_at: now,
292        });
293        Ok(())
294    }
295
296    /// Account one unseen print: charge a completed one its analysed length,
297    /// mark the spools of any other.
298    fn account_unseen(
299        &self,
300        file: &FileFacts,
301        generation: u32,
302        print: Unseen,
303        loaded: &[SpoolRecord],
304        accounting: &mut Accounting,
305    ) -> Result<(), CoreError> {
306        let printed_at = file.last_print.as_ref().map(|last| last.at);
307        let analysed: Option<BTreeMap<i64, f64>> = file.filament.as_deref().map(lengths_of);
308        let mut charged = false;
309        match (&analysed, print.outcome) {
310            (Some(lengths), PrintOutcome::Completed) => {
311                for (tool, length) in lengths {
312                    if *length <= NOTHING_MM {
313                        continue;
314                    }
315                    let spool = loaded
316                        .iter()
317                        .find(|spool| spool.loaded_tool() == Some(*tool));
318                    charged |= spool.is_some();
319                    accounting.charges.push(self.charge_of(
320                        Feed {
321                            key: ChargeKey::Unobserved {
322                                origin: file.origin.clone(),
323                                file_name: file.file_name.clone(),
324                                generation,
325                                print_number: print.print_number,
326                                tool: *tool,
327                            },
328                            method: ChargeMethod::UnobservedEstimate,
329                            length_mm: *length,
330                            analysed_length_mm: Some(*length),
331                            position: None,
332                            note: None,
333                        },
334                        spool,
335                        &mut accounting.figures,
336                        system_source(),
337                    )?);
338                }
339            }
340            _ => {
341                for spool in spools_for(file, loaded) {
342                    accounting.marks.push(self.mark_of(
343                        spool.id,
344                        UnverifiedReason::UnaccountedPrint {
345                            file_name: file.file_name.clone(),
346                            printed_at: printed_at.unwrap_or_else(|| self.clock().now()),
347                        },
348                        None,
349                    )?);
350                }
351            }
352        }
353        accounting.events.push(self.draft_of(
354            None,
355            system_source(),
356            &UnaccountedPrintPayload {
357                file_name: file.file_name.clone(),
358                printed_at,
359                success: print.outcome == PrintOutcome::Completed,
360                charged,
361            },
362        )?);
363        Ok(())
364    }
365}
366
367/// Whether a file's tally is one the printer can have: no count below zero,
368/// and a total that does not overflow. One that is not is read at this
369/// boundary as no tally at all — neither stored as a baseline nor accounted on
370/// — so the file stays as last held until the printer reports a real one.
371fn readable(file: &FileFacts) -> bool {
372    file.successes >= 0 && file.failures >= 0 && file.successes.checked_add(file.failures).is_some()
373}
374
375/// The loaded spools a file's prints would have fed: those on the tools its
376/// analysis names, or every loaded spool when it has none.
377fn spools_for<'a>(file: &FileFacts, loaded: &'a [SpoolRecord]) -> Vec<&'a SpoolRecord> {
378    match file.filament.as_deref().map(lengths_of) {
379        Some(lengths) => loaded
380            .iter()
381            .filter(|spool| {
382                spool
383                    .loaded_tool()
384                    .is_some_and(|tool| lengths.get(&tool).is_some_and(|l| *l > NOTHING_MM))
385            })
386            .collect(),
387        None => loaded.iter().collect(),
388    }
389}