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    // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
146    pub async fn account_unobserved_prints(&self) -> Result<Vec<EventRecord>, CoreError> {
147        let files = self
148            .read_printed_files()
149            .await
150            .map_err(CoreError::Printer)?;
151        let _writing = self.spool_writes().await;
152        let held = self.stores().filament.file_tallies().await?;
153        let now = self.clock().now();
154        if held.is_empty() {
155            let baseline = files
156                .iter()
157                .filter(|file| readable(file))
158                .map(|file| FileTally {
159                    file_name: file.file_name.clone(),
160                    origin: file.origin.clone(),
161                    generation: 0,
162                    successes: file.successes,
163                    failures: file.failures,
164                    observed_at: now,
165                })
166                .collect();
167            return Ok(self
168                .stores()
169                .filament
170                .account_tallies(baseline, Vec::new(), Vec::new(), Vec::new())
171                .await?);
172        }
173        let loaded = self.stores().filament.loaded_spools().await?;
174        let settlements = self.settlements_of(&files).await?;
175        let mut accounting = Accounting::default();
176        for file in files.iter().filter(|file| readable(file)) {
177            let previous = held
178                .iter()
179                .find(|tally| tally.file_name == file.file_name && tally.origin == file.origin);
180            self.account_file(file, previous, &settlements, &loaded, now, &mut accounting)?;
181        }
182        Ok(self
183            .stores()
184            .filament
185            .account_tallies(
186                accounting.tallies,
187                accounting.charges,
188                accounting.marks,
189                accounting.events,
190            )
191            .await?)
192    }
193
194    /// Every settlement this system made of a print of one of these files:
195    /// the file, when, and with which outcome.
196    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
197    async fn settlements_of(
198        &self,
199        files: &[FileFacts],
200    ) -> Result<Vec<(String, Timestamp, PrintOutcome)>, CoreError> {
201        let mut settlements = Vec::new();
202        for print in self.stores().prints.prints().await? {
203            let Some(file_name) = print
204                .file_name
205                .filter(|name| files.iter().any(|file| &file.file_name == name))
206            else {
207                continue;
208            };
209            if let Some((at, outcome)) = self.stores().filament.print_settlement(print.id).await? {
210                settlements.push((file_name, at, outcome));
211            }
212        }
213        Ok(settlements)
214    }
215
216    /// Account one file's tally against the one last held for it.
217    fn account_file(
218        &self,
219        file: &FileFacts,
220        previous: Option<&FileTally>,
221        // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
222        settlements: &[(String, Timestamp, PrintOutcome)],
223        loaded: &[SpoolRecord],
224        now: Timestamp,
225        accounting: &mut Accounting,
226    ) -> Result<(), CoreError> {
227        let since = previous.map(|tally| tally.observed_at);
228        let settled = settled_since(settlements, &file.file_name, since);
229        let (generation, unseen) = match previous {
230            Some(held) if file.successes < held.successes || file.failures < held.failures => {
231                let generation = held.generation + 1;
232                let accounted = settled.total() == 0;
233                accounting.events.push(self.draft_of(
234                    None,
235                    system_source(),
236                    &FileTallyRebaselinedPayload {
237                        file_name: file.file_name.clone(),
238                        origin: file.origin.clone(),
239                        old_generation: held.generation,
240                        new_generation: generation,
241                        old_successes: held.successes,
242                        old_failures: held.failures,
243                        new_successes: file.successes,
244                        new_failures: file.failures,
245                        disposition: if accounted {
246                            RebaselineDisposition::Accounted
247                        } else {
248                            RebaselineDisposition::Unverified
249                        },
250                    },
251                )?);
252                if accounted {
253                    let unseen =
254                        unseen_between((0, 0), (file.successes, file.failures), Settled::default());
255                    (generation, unseen)
256                } else {
257                    for spool in spools_for(file, loaded) {
258                        accounting.marks.push(self.mark_of(
259                            spool.id,
260                            UnverifiedReason::TallyReset {
261                                file_name: file.file_name.clone(),
262                                origin: file.origin.clone(),
263                            },
264                            None,
265                        )?);
266                    }
267                    (generation, Vec::new())
268                }
269            }
270            Some(held) => (
271                held.generation,
272                unseen_between(
273                    (held.successes, held.failures),
274                    (file.successes, file.failures),
275                    settled,
276                ),
277            ),
278            None => (
279                0,
280                unseen_between((0, 0), (file.successes, file.failures), settled),
281            ),
282        };
283        for print in unseen {
284            self.account_unseen(file, generation, print, loaded, accounting)?;
285        }
286        accounting.tallies.push(FileTally {
287            file_name: file.file_name.clone(),
288            origin: file.origin.clone(),
289            generation,
290            successes: file.successes,
291            failures: file.failures,
292            observed_at: now,
293        });
294        Ok(())
295    }
296
297    /// Account one unseen print: charge a completed one its analysed length,
298    /// mark the spools of any other.
299    fn account_unseen(
300        &self,
301        file: &FileFacts,
302        generation: u32,
303        print: Unseen,
304        loaded: &[SpoolRecord],
305        accounting: &mut Accounting,
306    ) -> Result<(), CoreError> {
307        let printed_at = file.last_print.as_ref().map(|last| last.at);
308        let analysed: Option<BTreeMap<i64, f64>> = file.filament.as_deref().map(lengths_of);
309        let mut charged = false;
310        match (&analysed, print.outcome) {
311            (Some(lengths), PrintOutcome::Completed) => {
312                for (tool, length) in lengths {
313                    if *length <= NOTHING_MM {
314                        continue;
315                    }
316                    let spool = loaded
317                        .iter()
318                        .find(|spool| spool.loaded_on_tool == Some(*tool));
319                    charged |= spool.is_some();
320                    accounting.charges.push(self.charge_of(
321                        Feed {
322                            key: ChargeKey::Unobserved {
323                                origin: file.origin.clone(),
324                                file_name: file.file_name.clone(),
325                                generation,
326                                print_number: print.print_number,
327                                tool: *tool,
328                            },
329                            method: ChargeMethod::UnobservedEstimate,
330                            length_mm: *length,
331                            analysed_length_mm: Some(*length),
332                            position: None,
333                            note: None,
334                        },
335                        spool,
336                        &mut accounting.figures,
337                        system_source(),
338                    )?);
339                }
340            }
341            _ => {
342                for spool in spools_for(file, loaded) {
343                    accounting.marks.push(self.mark_of(
344                        spool.id,
345                        UnverifiedReason::UnaccountedPrint {
346                            file_name: file.file_name.clone(),
347                            printed_at: printed_at.unwrap_or_else(|| self.clock().now()),
348                        },
349                        None,
350                    )?);
351                }
352            }
353        }
354        accounting.events.push(self.draft_of(
355            None,
356            system_source(),
357            &UnaccountedPrintPayload {
358                file_name: file.file_name.clone(),
359                printed_at,
360                success: print.outcome == PrintOutcome::Completed,
361                charged,
362            },
363        )?);
364        Ok(())
365    }
366}
367
368/// Whether a file's tally is one the printer can have: no count below zero,
369/// and a total that does not overflow. One that is not is read at this
370/// boundary as no tally at all — neither stored as a baseline nor accounted on
371/// — so the file stays as last held until the printer reports a real one.
372fn readable(file: &FileFacts) -> bool {
373    file.successes >= 0 && file.failures >= 0 && file.successes.checked_add(file.failures).is_some()
374}
375
376/// The loaded spools a file's prints would have fed: those on the tools its
377/// analysis names, or every loaded spool when it has none.
378fn spools_for<'a>(file: &FileFacts, loaded: &'a [SpoolRecord]) -> Vec<&'a SpoolRecord> {
379    match file.filament.as_deref().map(lengths_of) {
380        Some(lengths) => loaded
381            .iter()
382            .filter(|spool| {
383                spool
384                    .loaded_on_tool
385                    .is_some_and(|tool| lengths.get(&tool).is_some_and(|l| *l > NOTHING_MM))
386            })
387            .collect(),
388        None => loaded.iter().collect(),
389    }
390}