Skip to main content

printobserver_core/
accounting.rs

1//! The printer timeline, and what every print takes from the spools that fed it.
2//!
3//! # A print is opened, charged in segments, and settled once
4//!
5//! Every print this system opens after spool tracking was installed — by a
6//! start through it, by a read adopting a job somebody started at the printer,
7//! or by an alert about a print it had not seen — gets a `print_started`
8//! naming the spool on each tool. A print without one was already open when
9//! tracking was installed, is never charged, and its close-out says so with one
10//! `print_untracked`.
11//!
12//! A tool's filament is charged in **segments**, each under its own
13//! [`ChargeKey`]: segment 0 opens at the start, and a spool loaded or unloaded
14//! mid-print, or a filament-change signal, charges the open segment up to the
15//! position read then and opens the next. Which segment is open is read back
16//! from the store — one past the highest the print has charged or held on that
17//! tool — and the closing segment is charged the tool's total less every
18//! length already charged or held for that print and tool. Both are read from
19//! what the store holds, never from memory, so a supervisor built after a
20//! restart charges exactly what is left.
21//!
22//! Close-out works the print's remaining charges out, then settles it through
23//! [`FilamentStore::settle_print`](crate::store::FilamentStore::settle_print)
24//! — its charges, pends, marks, `print_ended` and settlement in one write —
25//! and only then ends the print record. A close-out that finds the print
26//! settled only ends it, so whatever is replayed after a crash debits nothing
27//! twice.
28//!
29//! # After an unconfirmed filament change, the remainder is held
30//!
31//! A filament-change signal charges the loaded spool up to the stop point and
32//! marks it as one whose change nobody confirmed. From then until a spool is
33//! loaded onto that tool or that spool is confirmed in place, what the tool
34//! feeds is not charged to the spool still recorded there: the open segment is
35//! **pended**. Whether a segment is post-signal is read from the marks alone —
36//! the spool judged for the tool still carries that print's filament-change
37//! mark — so a restart between a confirmation and the close-out changes
38//! nothing.
39
40use std::collections::{BTreeMap, BTreeSet};
41
42use printobserver_printer_api::{FileFacts, JobSnapshot, PrinterState, ToolFilament};
43use printobserver_types::{
44    EventBody, EventKind, EventPayload, EventSource, FileName, PrintId, Timestamp,
45};
46use printobserver_vision_api::PrinterSignal;
47
48use crate::error::CoreError;
49use crate::filament::grams_for_length;
50use crate::kinds::{
51    ActionExecutedPayload, ActionRequestedPayload, ChargePendedPayload,
52    FilamentChangeSignalledPayload, FilamentConsumedPayload, PositionFreshness, PrintEndedPayload,
53    PrintStartedPayload, PrintUntrackedPayload, SignalPosition, SpoolUnverifiedPayload,
54    system_source,
55};
56use crate::records::{
57    ActionId, ChargeKey, ChargeMethod, ChargedFilament, FilePosition, LoadedSpool, PendingCharge,
58    PendingTaken, Preflight, PrintAction, PrintOutcome, PrintRecord, SpoolId, SpoolRecord,
59    SpoolTrust, UnverifiedReason,
60};
61use crate::store::{
62    Charge, ChargeIdentity, ChargeRecord, EventDraft, HistoryQuery, MAX_HISTORY_LIMIT, Pend,
63    SpoolChange, SpoolMutation,
64};
65use crate::supervisor::Supervisor;
66
67/// Below this many millimetres a length is nothing, and no charge is written
68/// for it: a zero-length charge would be a record of nothing having happened.
69pub(crate) const NOTHING_MM: f64 = 1e-6;
70
71/// Why a print that predates spool tracking carries no charge.
72pub const UNTRACKED_REASON: &str =
73    "the print was already open when spool tracking was installed, so it is not charged";
74
75/// The note a charge taken from a pending charge carries.
76const TAKEN_NOTE: &str = "fed after a filament change nobody confirmed, and taken by this spool";
77
78/// The note a post-signal segment charged to the spool loaded after it carries.
79pub(crate) const AFTER_CHANGE: &str =
80    "fed after a filament change nobody confirmed, and charged to the spool loaded after it";
81
82/// What one print has had charged and held so far, as the store holds it.
83#[derive(Debug, Clone, Default)]
84pub(crate) struct PrintLedger {
85    /// Every charge recorded against the print.
86    charges: Vec<ChargeRecord>,
87    /// Every charge still held for the print.
88    pending: Vec<PendingCharge>,
89}
90
91/// The segment a print key names, when it is one.
92const fn segment_of(key: &ChargeKey) -> Option<u32> {
93    match key {
94        ChargeKey::Print { segment, .. } => Some(*segment),
95        ChargeKey::Unobserved { .. } => None,
96    }
97}
98
99impl PrintLedger {
100    /// Every length charged or held for the print on one tool, in millimetres.
101    pub(crate) fn already_mm(&self, tool: i64) -> f64 {
102        let charged: f64 = self
103            .charges
104            .iter()
105            .filter(|charge| charge.identity.tool() == tool)
106            .map(|charge| charge.length_mm)
107            .sum();
108        let held: f64 = self
109            .pending
110            .iter()
111            .filter(|pending| pending.tool() == tool)
112            .map(|pending| pending.length_mm)
113            .sum();
114        charged + held
115    }
116
117    /// The segment open on one tool: one past the highest charged or held.
118    pub(crate) fn open_segment(&self, tool: i64) -> u32 {
119        let charged = self
120            .charges
121            .iter()
122            .filter(|charge| charge.identity.tool() == tool)
123            .filter_map(|charge| segment_of(charge.identity.key()));
124        let held = self
125            .pending
126            .iter()
127            .filter(|pending| pending.tool() == tool)
128            .map(|pending| pending.charge_key.segment);
129        charged.chain(held).max().map_or(0, |highest| highest + 1)
130    }
131
132    /// The spool the latest charged segment on one tool was charged to.
133    pub(crate) fn last_spool(&self, tool: i64) -> Option<SpoolId> {
134        self.charges
135            .iter()
136            .filter(|charge| charge.identity.tool() == tool)
137            .max_by_key(|charge| segment_of(charge.identity.key()))
138            .and_then(ChargeRecord::spool_id)
139    }
140
141    /// Every tool the print has charged or held anything on.
142    fn tools(&self) -> BTreeSet<i64> {
143        self.charges
144            .iter()
145            .map(|charge| charge.identity.tool())
146            .chain(self.pending.iter().map(PendingCharge::tool))
147            .collect()
148    }
149}
150
151/// The figure each spool stands at as one write's charges are worked out, so
152/// that two charges against one spool in one write chain rather than both
153/// starting from the figure read.
154#[derive(Debug, Default)]
155pub(crate) struct Figures {
156    /// Each spool's figure so far, once it has been charged in this write.
157    remaining: BTreeMap<SpoolId, f64>,
158}
159
160impl Figures {
161    /// One spool's figure before and after a debit of so many grams.
162    fn debit(&mut self, spool: &SpoolRecord, grams: f64) -> (f64, f64) {
163        let before = *self.remaining.get(&spool.id).unwrap_or(&spool.remaining_g);
164        let after = before - grams;
165        self.remaining.insert(spool.id, after);
166        (before, after)
167    }
168
169    /// One spool's figure once every debit so far has been taken.
170    pub(crate) fn now(&self, spool: &SpoolRecord) -> f64 {
171        *self.remaining.get(&spool.id).unwrap_or(&spool.remaining_g)
172    }
173}
174
175/// One stretch of filament a tool fed, before it is charged or held.
176#[derive(Debug, Clone)]
177pub(crate) struct Feed {
178    /// The durable identity of the debit, which names the tool that fed it
179    /// and, for a print this system watched, the print.
180    pub(crate) key: ChargeKey,
181    /// How the length was worked out.
182    pub(crate) method: ChargeMethod,
183    /// The length fed, in millimetres.
184    pub(crate) length_mm: f64,
185    /// The file's analysed length for the tool, when it had one.
186    pub(crate) analysed_length_mm: Option<f64>,
187    /// How far into the file the stretch runs, when that was read.
188    pub(crate) position: Option<FilePosition>,
189    /// Anything a reader needs to make sense of the figure.
190    pub(crate) note: Option<String>,
191}
192
193/// Where a print is, and how that is known.
194#[derive(Debug, Clone, PartialEq, Eq)]
195pub(crate) enum Whereabouts {
196    /// Read from the job just now.
197    ReadNow(FilePosition),
198    /// The last position recorded, the job reporting none now.
199    Recorded(FilePosition),
200    /// No position has been read for it at all.
201    Unknown,
202}
203
204impl Whereabouts {
205    /// The position, however it is known.
206    const fn position(&self) -> Option<&FilePosition> {
207        match self {
208            Self::ReadNow(position) | Self::Recorded(position) => Some(position),
209            Self::Unknown => None,
210        }
211    }
212}
213
214/// The filament each tool fed up to a position, and how that was worked out.
215#[derive(Debug, Clone)]
216pub(crate) struct Extrusion {
217    /// The length per tool, in millimetres.
218    pub(crate) lengths: BTreeMap<i64, f64>,
219    /// How the lengths were worked out.
220    pub(crate) method: ChargeMethod,
221    /// Why, when the lengths are a fallback.
222    pub(crate) note: Option<String>,
223}
224
225/// What the printer says of a print's file: its facts and its analysis.
226#[derive(Debug, Clone, Default)]
227pub(crate) struct FileAnalysis {
228    /// The file's facts, when they could be read.
229    pub(crate) facts: Option<FileFacts>,
230    /// The analysed length per tool, when the file has an analysis.
231    pub(crate) lengths: Option<BTreeMap<i64, f64>>,
232}
233
234impl FileAnalysis {
235    /// The analysed length for one tool, when the file has an analysis.
236    pub(crate) fn length(&self, tool: i64) -> Option<f64> {
237        self.lengths
238            .as_ref()
239            .map(|lengths| lengths.get(&tool).copied().unwrap_or(0.0))
240    }
241
242    /// The file's size in bytes, when it is known.
243    fn size_bytes(&self) -> Option<i64> {
244        self.facts.as_ref().and_then(|facts| facts.size_bytes)
245    }
246}
247
248/// The lengths per tool one list of tool filament adds up to.
249///
250/// A printer's answer is read at this boundary: a tool numbered below zero, or
251/// a length that is negative or not a number, is no filament any tool fed, and
252/// is left out rather than charged.
253pub(crate) fn lengths_of(filament: &[ToolFilament]) -> BTreeMap<i64, f64> {
254    let mut lengths = BTreeMap::new();
255    for each in filament
256        .iter()
257        .filter(|each| each.tool >= 0 && each.length_mm.is_finite() && each.length_mm >= 0.0)
258    {
259        *lengths.entry(each.tool).or_insert(0.0) += each.length_mm;
260    }
261    // Lengths that are each finite can still sum past what a figure holds;
262    // such a tool's total is no length either.
263    lengths.retain(|_, total| total.is_finite());
264    lengths
265}
266
267/// What a tool fed of a print's open segment, up to a position, when it fed
268/// anything since what the print has already charged or held on it.
269pub(crate) fn feed_to(
270    print_id: PrintId,
271    tool: i64,
272    ledger: &PrintLedger,
273    extrusion: &Extrusion,
274    position: &FilePosition,
275    analysis: &FileAnalysis,
276) -> Option<Feed> {
277    let length = extrusion.lengths.get(&tool).copied().unwrap_or(0.0) - ledger.already_mm(tool);
278    (length > NOTHING_MM).then(|| Feed {
279        key: ChargeKey::Print {
280            print_id,
281            tool,
282            segment: ledger.open_segment(tool),
283        },
284        method: extrusion.method,
285        length_mm: length,
286        analysed_length_mm: analysis.length(tool),
287        position: Some(position.clone()),
288        note: extrusion.note.clone(),
289    })
290}
291
292/// A print's file, as a name a file API takes, when it has one.
293fn file_of(print: &PrintRecord) -> Option<FileName> {
294    print
295        .file_name
296        .as_deref()
297        .and_then(|name| FileName::new(name).ok())
298}
299
300/// Whether a spool holds one print's filament-change mark, of either kind.
301pub(crate) fn holds_change_mark(spool: &SpoolRecord, print_id: PrintId) -> bool {
302    marks_of(spool).iter().any(|reason| {
303        matches!(
304            reason,
305            UnverifiedReason::FilamentChangeUnconfirmed { print_id: held }
306            | UnverifiedReason::FilamentChangeUnconfirmedPosition { print_id: held }
307            if *held == print_id
308        )
309    })
310}
311
312/// Whether a spool holds any filament-change mark at all.
313pub(crate) fn holds_any_change_mark(spool: &SpoolRecord) -> bool {
314    marks_of(spool).iter().any(|reason| {
315        matches!(
316            reason,
317            UnverifiedReason::FilamentChangeUnconfirmed { .. }
318                | UnverifiedReason::FilamentChangeUnconfirmedPosition { .. }
319        )
320    })
321}
322
323/// Every reason a spool's figure is in doubt, oldest first.
324pub(crate) fn marks_of(spool: &SpoolRecord) -> Vec<UnverifiedReason> {
325    match &spool.trust {
326        SpoolTrust::Verified => Vec::new(),
327        SpoolTrust::Unverified { marks } => marks.iter().map(|mark| mark.reason.clone()).collect(),
328    }
329}
330
331/// The spool loaded on one tool, when one is. A retired spool is on no tool:
332/// retiring one loaded mid-print charged it for what it fed up to then.
333pub(crate) fn spool_on_tool(spools: &[SpoolRecord], tool: i64) -> Option<&SpoolRecord> {
334    spools
335        .iter()
336        .find(|spool| spool.loaded_tool() == Some(tool))
337}
338
339/// The open position a job read reports for a print, when it reports one.
340pub(crate) fn position_from(
341    job: &JobSnapshot,
342    print: &PrintRecord,
343    observed_at: Timestamp,
344) -> Option<FilePosition> {
345    let active = matches!(job.state, PrinterState::Printing | PrinterState::Paused);
346    let same_file = print.file_name.is_none() || job.file_name == print.file_name;
347    if !active || !same_file {
348        return None;
349    }
350    // A position before the file's start is no position, and a size of
351    // nothing is no size: neither is kept.
352    job.file_position_bytes
353        .filter(|bytes| *bytes >= 0)
354        .map(|bytes| FilePosition {
355            bytes,
356            size_bytes: job.size_bytes.filter(|size| *size > 0),
357            observed_at,
358        })
359}
360
361/// What a tracked print's close-out writes: its charges, its pends and its
362/// marks, in that order.
363type ClosingWrites = (Vec<Charge>, Vec<Pend>, Vec<SpoolMutation>);
364
365/// What a tracked print's close-out read.
366#[derive(Debug, Clone)]
367struct Closing {
368    /// How the print ended.
369    outcome: PrintOutcome,
370    /// Whether anything was watching as it ended: unfinished and unwatched,
371    /// what it fed after the last position recorded is unknown.
372    watch: Watch,
373    /// What each tool fed by the outcome's rule, when that could be worked out.
374    totals: Option<Extrusion>,
375    /// What the printer says of the print's file.
376    analysis: FileAnalysis,
377    /// The last position recorded.
378    position: Option<FilePosition>,
379}
380
381/// How a print ended, from everything its close-out read.
382#[derive(Debug, Clone, Copy)]
383struct Ending<'a> {
384    /// The state the printer was in as it ended.
385    state: &'a PrinterState,
386    /// The last job read, when one was made.
387    job: Option<&'a JobSnapshot>,
388    /// The print's file, when it is known as a name a file API takes.
389    file_name: Option<&'a FileName>,
390    /// The last position recorded.
391    position: Option<&'a FilePosition>,
392    /// The file's size, when it is known.
393    size_bytes: Option<i64>,
394    /// What the file's tally says of a print since this one was opened.
395    tally: Tally,
396    /// Who cancelled it, as far as this system knows.
397    cancelled_by: Canceller,
398}
399
400/// How a print's closing charge is worked out, by the outcome it ended with.
401#[derive(Debug, Clone, Copy, PartialEq, Eq)]
402pub enum ChargeRule {
403    /// The length the file's analysis gives: the print ran to its end.
404    SlicerEstimate,
405    /// What the file's moves extruded up to the last file position seen.
406    ExtrudedToLastPosition,
407}
408
409/// The rule one outcome's closing charge is worked out by.
410///
411/// Only a completed print is charged its whole analysed length. Every other
412/// outcome stopped somewhere short of the end, so it is charged what the file
413/// extruded up to where it was last seen — an interrupted print exactly as a
414/// failed one.
415#[must_use]
416pub const fn charge_rule(outcome: PrintOutcome) -> ChargeRule {
417    match outcome {
418        PrintOutcome::Completed => ChargeRule::SlicerEstimate,
419        PrintOutcome::Cancelled | PrintOutcome::Failed | PrintOutcome::Interrupted => {
420            ChargeRule::ExtrudedToLastPosition
421        }
422    }
423}
424
425/// Whether a print was watched to its end.
426#[derive(Debug, Clone, Copy, PartialEq, Eq)]
427enum Watch {
428    /// This supervisor saw it running, or it completed: what it fed is known.
429    Watched,
430    /// It ended unfinished while nothing was watching.
431    Unwatched,
432}
433
434/// What a file's tally says of a print since one was opened.
435#[derive(Debug, Clone, Copy, PartialEq, Eq)]
436enum Tally {
437    /// A successful print of the file was recorded since.
438    CompletedSince,
439    /// Nothing the tally says shows this print completed.
440    NoCompletion,
441}
442
443/// Who cancelled a print, as far as this system knows.
444#[derive(Debug, Clone, Copy, PartialEq, Eq)]
445enum Canceller {
446    /// This system's own cancel was executed for it.
447    Here,
448    /// No cancel of this system's was executed for it.
449    NotHere,
450}
451
452impl Ending<'_> {
453    /// The outcome these say the print ended with.
454    fn outcome(&self) -> PrintOutcome {
455        let reached_the_end = self.position.is_some_and(|position| {
456            let size = position.size_bytes.or(self.size_bytes);
457            size.is_some_and(|size| size > 0 && position.bytes >= size)
458        });
459        let reported_complete = self.job.is_some_and(|job| {
460            self.file_name
461                .is_none_or(|file| job.file_name.as_deref() == Some(file.as_str()))
462                && job
463                    .completion
464                    .is_some_and(|completion| completion.value() >= 1.0)
465        });
466        if reached_the_end || reported_complete || self.tally == Tally::CompletedSince {
467            return PrintOutcome::Completed;
468        }
469        if self.cancelled_by == Canceller::Here || *self.state == PrinterState::Cancelling {
470            return PrintOutcome::Cancelled;
471        }
472        match self.state {
473            PrinterState::Error | PrinterState::Offline => PrintOutcome::Failed,
474            _ => PrintOutcome::Cancelled,
475        }
476    }
477}
478
479impl Supervisor {
480    /// One event draft this system writes now, about a print or about none.
481    pub(crate) fn draft_of<P: EventPayload>(
482        &self,
483        print_id: Option<PrintId>,
484        source: EventSource,
485        payload: &P,
486    ) -> Result<EventDraft, CoreError> {
487        Ok(EventDraft {
488            print_id,
489            source,
490            received_at: self.clock().now(),
491            body: EventBody::of(payload)?,
492            raw: None,
493        })
494    }
495
496    /// The charge one feed makes against a spool, or records uncharged with no
497    /// spool, carrying its `filament_consumed` event.
498    pub(crate) fn charge_of(
499        &self,
500        feed: Feed,
501        spool: Option<&SpoolRecord>,
502        figures: &mut Figures,
503        source: EventSource,
504    ) -> Result<Charge, CoreError> {
505        let charged = spool.map(|spool| {
506            let grams = grams_for_length(feed.length_mm, spool.diameter_mm, spool.density_g_cm3);
507            let (remaining_before_g, remaining_after_g) = figures.debit(spool, grams);
508            ChargedFilament {
509                spool_id: spool.id,
510                grams,
511                diameter_mm: spool.diameter_mm,
512                density_g_cm3: spool.density_g_cm3,
513                remaining_before_g,
514                remaining_after_g,
515            }
516        });
517        let payload = FilamentConsumedPayload {
518            charge_key: feed.key.clone(),
519            tool: feed.key.tool(),
520            method: feed.method,
521            length_mm: feed.length_mm,
522            charged: charged.clone(),
523            analysed_length_mm: feed.analysed_length_mm,
524            position: feed.position.clone(),
525            note: feed.note.clone(),
526        };
527        let event = self.draft_of(feed.key.watched_print(), source, &payload)?;
528        Ok(Charge {
529            identity: ChargeIdentity::of(feed.key),
530            length_mm: feed.length_mm,
531            charged,
532            at: event.received_at,
533            event,
534        })
535    }
536
537    /// The pend one feed makes, held for the next spool loaded onto its tool,
538    /// carrying its `charge_pended` event.
539    pub(crate) fn pend_of(&self, feed: Feed) -> Result<Pend, CoreError> {
540        let Some(charge_key) = feed.key.print_segment() else {
541            return Err(CoreError::Unrepresentable {
542                detail: format!(
543                    "{} is no print segment, and only a watched print's filament is held",
544                    feed.key.canonical()
545                ),
546            });
547        };
548        let print_id = charge_key.print_id;
549        let pending = PendingCharge {
550            charge_key,
551            length_mm: feed.length_mm,
552            method: feed.method,
553            analysed_length_mm: feed.analysed_length_mm,
554            position: feed.position,
555            note: feed.note,
556            pended_at: self.clock().now(),
557        };
558        let event = self.draft_of(
559            Some(print_id),
560            system_source(),
561            &ChargePendedPayload {
562                pending: pending.clone(),
563            },
564        )?;
565        Ok(Pend { pending, event })
566    }
567
568    /// The mutation that marks one spool's figure as in doubt, with its
569    /// `spool_unverified` event.
570    pub(crate) fn mark_of(
571        &self,
572        spool_id: SpoolId,
573        reason: UnverifiedReason,
574        print_id: Option<PrintId>,
575    ) -> Result<SpoolMutation, CoreError> {
576        let event = self.draft_of(
577            print_id,
578            system_source(),
579            &SpoolUnverifiedPayload {
580                spool_id,
581                reason: reason.clone(),
582            },
583        )?;
584        Ok(SpoolMutation {
585            spool_id,
586            at: event.received_at,
587            change: SpoolChange::MarkUnverified { reason, event },
588        })
589    }
590
591    /// Every pending charge a spool takes, each charged to it under its own
592    /// key and named for the command's own event.
593    pub(crate) fn take_pending(
594        &self,
595        pending: &[PendingCharge],
596        spool: &SpoolRecord,
597        figures: &mut Figures,
598        source: &EventSource,
599    ) -> Result<(Vec<Charge>, Vec<PendingTaken>), CoreError> {
600        let mut charges = Vec::new();
601        let mut taken = Vec::new();
602        for held in pending {
603            let note = match &held.note {
604                Some(note) => format!("{TAKEN_NOTE}; {note}"),
605                None => TAKEN_NOTE.to_owned(),
606            };
607            charges.push(self.charge_of(
608                Feed {
609                    key: held.charge_key.charge_key(),
610                    method: held.method,
611                    length_mm: held.length_mm,
612                    analysed_length_mm: held.analysed_length_mm,
613                    position: held.position.clone(),
614                    note: Some(note),
615                },
616                Some(spool),
617                figures,
618                source.clone(),
619            )?);
620            taken.push(PendingTaken {
621                charge_key: held.charge_key.charge_key(),
622                print_id: held.print_id(),
623            });
624        }
625        Ok((charges, taken))
626    }
627
628    /// What one print has had charged and held so far.
629    pub(crate) async fn print_ledger(&self, print_id: PrintId) -> Result<PrintLedger, CoreError> {
630        let charges = self.stores().filament.charges(print_id).await?;
631        let pending = self
632            .stores()
633            .filament
634            .pending_charges(None)
635            .await?
636            .into_iter()
637            .filter(|held| held.print_id() == print_id)
638            .collect();
639        Ok(PrintLedger { charges, pending })
640    }
641
642    /// The `print_started` a print was opened with, when it has one.
643    pub(crate) async fn print_started_of(
644        &self,
645        print_id: PrintId,
646    ) -> Result<Option<PrintStartedPayload>, CoreError> {
647        let found = self
648            .stores()
649            .events
650            .history(HistoryQuery {
651                print_id,
652                kinds: vec![PrintStartedPayload::kind()],
653                since: None,
654                until: None,
655                limit: Some(1),
656            })
657            .await?;
658        Ok(found
659            .first()
660            .and_then(printobserver_types::EventRecord::payload_as::<PrintStartedPayload>)
661            .transpose()?)
662    }
663
664    /// Write a print's `print_started`, naming the spool on each tool now.
665    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
666    pub(crate) async fn record_print_started(
667        &self,
668        print_id: PrintId,
669        file_name: Option<String>,
670        started_by: Option<ActionId>,
671        preflight: Option<Preflight>,
672    ) -> Result<(), CoreError> {
673        let loaded = self
674            .stores()
675            .filament
676            .loaded_spools()
677            .await?
678            .into_iter()
679            .filter_map(|spool| {
680                spool.loaded_tool().map(|tool| LoadedSpool {
681                    tool,
682                    spool_id: spool.id,
683                })
684            })
685            .collect();
686        let draft = self.draft_of(
687            Some(print_id),
688            system_source(),
689            &PrintStartedPayload {
690                file_name,
691                started_by,
692                loaded,
693                preflight,
694            },
695        )?;
696        self.stores().events.append_event(draft).await?;
697        Ok(())
698    }
699
700    /// Record how far into its file a print had got, from one job read.
701    pub(crate) async fn record_position_from(
702        &self,
703        print: &PrintRecord,
704        job: &JobSnapshot,
705        observed_at: Timestamp,
706    ) -> Result<Option<FilePosition>, CoreError> {
707        let Some(position) = position_from(job, print, observed_at) else {
708            return Ok(None);
709        };
710        self.stores()
711            .filament
712            .record_file_position(print.id, position.clone())
713            .await?;
714        Ok(Some(position))
715    }
716
717    /// What the printer says of one file: its facts, and the analysed length
718    /// per tool from the job read when it carries one, otherwise from the
719    /// file's own facts.
720    pub(crate) async fn analysis_of(
721        &self,
722        file_name: &FileName,
723        job: Option<&JobSnapshot>,
724    ) -> FileAnalysis {
725        let facts = self.read_file_facts(file_name.clone()).await.ok();
726        let from_job = job
727            .filter(|job| {
728                job.file_name.as_deref() == Some(file_name.as_str()) && !job.filament.is_empty()
729            })
730            .map(|job| lengths_of(&job.filament));
731        let lengths = from_job.or_else(|| {
732            facts
733                .as_ref()
734                .and_then(|facts| facts.filament.as_deref().map(lengths_of))
735        });
736        FileAnalysis { facts, lengths }
737    }
738
739    /// The filament each tool fed up to a position: summed from the file's own
740    /// moves, or — when the file could not be read — the analysed length
741    /// scaled by how far into the file the position is, with a note saying
742    /// why. Nothing when neither can be worked out.
743    pub(crate) async fn extrusion_to(
744        &self,
745        file_name: &FileName,
746        position: &FilePosition,
747        analysis: &FileAnalysis,
748    ) -> Option<Extrusion> {
749        let refusal = match self
750            .read_extruded_to(file_name.clone(), position.bytes)
751            .await
752        {
753            Ok(filament) => {
754                return Some(Extrusion {
755                    lengths: lengths_of(&filament),
756                    method: ChargeMethod::GcodeExtrusion,
757                    note: None,
758                });
759            }
760            Err(error) => error.to_string(),
761        };
762        let analysed = analysis.lengths.as_ref()?;
763        let size = position
764            .size_bytes
765            .or_else(|| analysis.size_bytes())
766            .filter(|size| *size > 0)?;
767        #[expect(clippy::cast_precision_loss)]
768        let fraction = (position.bytes as f64 / size as f64).clamp(0.0, 1.0);
769        Some(Extrusion {
770            lengths: analysed
771                .iter()
772                .map(|(tool, length)| (*tool, length * fraction))
773                .collect(),
774            method: ChargeMethod::FileFraction,
775            note: Some(format!(
776                "the file could not be read ({refusal}), so the analysed length was scaled by \
777                 how far into the file the print got"
778            )),
779        })
780    }
781
782    /// Whether this system's own cancel was executed for a print.
783    async fn cancelled_here(&self, print_id: PrintId) -> Result<bool, CoreError> {
784        let events = self
785            .stores()
786            .events
787            .history(HistoryQuery {
788                print_id,
789                kinds: vec![
790                    ActionRequestedPayload::kind(),
791                    ActionExecutedPayload::kind(),
792                ],
793                since: None,
794                until: None,
795                limit: Some(MAX_HISTORY_LIMIT),
796            })
797            .await?;
798        let executed: BTreeSet<ActionId> = events
799            .iter()
800            .filter_map(printobserver_types::EventRecord::payload_as::<ActionExecutedPayload>)
801            .filter_map(Result::ok)
802            .map(|payload| payload.action_id)
803            .collect();
804        Ok(events
805            .iter()
806            .filter_map(printobserver_types::EventRecord::payload_as::<ActionRequestedPayload>)
807            .filter_map(Result::ok)
808            .any(|payload| {
809                matches!(payload.action, PrintAction::Cancel { .. })
810                    && executed.contains(&payload.action_id)
811            }))
812    }
813
814    /// Settle one print's filament as it is closed out, unless it is settled
815    /// already.
816    ///
817    /// A print with no `print_started` predates spool tracking: it is settled
818    /// with no charge and one `print_untracked` — when a job was ever seen for
819    /// it at all; a print a refused start opened and nothing ever ran is not
820    /// a print of the timeline. Any other print is charged by the rule of its
821    /// outcome, as this module states.
822    pub(crate) async fn settle_filament(
823        &self,
824        print: &PrintRecord,
825        state: &PrinterState,
826        reason: &str,
827        closing_job: Option<&JobSnapshot>,
828    ) -> Result<(), CoreError> {
829        if self
830            .stores()
831            .filament
832            .print_settlement(print.id)
833            .await?
834            .is_some()
835        {
836            return Ok(());
837        }
838        let Some(started) = self.print_started_of(print.id).await? else {
839            return self
840                .settle_untracked(print, state, reason, closing_job)
841                .await;
842        };
843        let closing = self.closing(print, &started, state, closing_job).await?;
844        let ended = self.draft_of(
845            Some(print.id),
846            system_source(),
847            &PrintEndedPayload {
848                outcome: closing.outcome,
849                state: state.clone(),
850                reason: reason.to_owned(),
851                last_position: closing.position.clone(),
852            },
853        )?;
854        let _writing = self.spool_writes().await;
855        let spools = self.stores().filament.spools(true).await?;
856        let ledger = self.print_ledger(print.id).await?;
857        let mut used: BTreeSet<i64> = ledger.tools();
858        used.extend(started.loaded.iter().map(|loaded| loaded.tool));
859        let (charges, pends, marks) =
860            self.closing_writes(print.id, used, &closing, &spools, &ledger)?;
861        self.stores()
862            .filament
863            .settle_print(print.id, closing.outcome, ended, charges, pends, marks)
864            .await?;
865        Ok(())
866    }
867
868    /// Everything a tracked print's close-out reads before it works out what
869    /// to charge: how it ended, and what each tool fed by that outcome's rule.
870    async fn closing(
871        &self,
872        print: &PrintRecord,
873        started: &PrintStartedPayload,
874        state: &PrinterState,
875        closing_job: Option<&JobSnapshot>,
876    ) -> Result<Closing, CoreError> {
877        let read = if closing_job.is_none() {
878            self.read_job().await.ok()
879        } else {
880            None
881        };
882        let job = closing_job.or(read.as_ref());
883        let file_name = print
884            .file_name
885            .as_deref()
886            .or(started.file_name.as_deref())
887            .and_then(|name| FileName::new(name).ok());
888        let analysis = match &file_name {
889            Some(file) => self.analysis_of(file, job).await,
890            None => FileAnalysis::default(),
891        };
892        let position = self.stores().filament.file_position(print.id).await?;
893        // A print completes after it was opened, whoever opened it; the job's
894        // own start, as a read puts it, can lie before that, and a success
895        // recorded between the two is an earlier print's.
896        let began = print.opened_at;
897        let tally = if analysis
898            .facts
899            .as_ref()
900            .and_then(|facts| facts.last_print.as_ref())
901            .is_some_and(|last| last.success && last.at >= began)
902        {
903            Tally::CompletedSince
904        } else {
905            Tally::NoCompletion
906        };
907        let cancelled_by = if self.cancelled_here(print.id).await? {
908            Canceller::Here
909        } else {
910            Canceller::NotHere
911        };
912        let outcome = Ending {
913            state,
914            job,
915            file_name: file_name.as_ref(),
916            position: position.as_ref(),
917            size_bytes: analysis.size_bytes(),
918            tally,
919            cancelled_by,
920        }
921        .outcome();
922        let rule = charge_rule(outcome);
923        let totals = match (rule, &file_name, &position) {
924            (ChargeRule::SlicerEstimate, _, _) => {
925                analysis.lengths.clone().map(|lengths| Extrusion {
926                    lengths,
927                    method: ChargeMethod::SlicerEstimate,
928                    note: None,
929                })
930            }
931            (ChargeRule::ExtrudedToLastPosition, Some(file), Some(position)) => {
932                self.extrusion_to(file, position, &analysis).await
933            }
934            (ChargeRule::ExtrudedToLastPosition, _, _) => None,
935        };
936        Ok(Closing {
937            outcome,
938            watch: if self.was_seen_running(print.id) || rule == ChargeRule::SlicerEstimate {
939                Watch::Watched
940            } else {
941                Watch::Unwatched
942            },
943            totals,
944            analysis,
945            position,
946        })
947    }
948
949    /// What a tracked print's close-out writes: each tool's remainder charged
950    /// to the spool on it, or held when the tool's last change is unconfirmed,
951    /// and every spool whose figure the print leaves in doubt marked.
952    fn closing_writes(
953        &self,
954        print_id: PrintId,
955        mut used: BTreeSet<i64>,
956        closing: &Closing,
957        spools: &[SpoolRecord],
958        ledger: &PrintLedger,
959    ) -> Result<ClosingWrites, CoreError> {
960        let mut figures = Figures::default();
961        let mut charges = Vec::new();
962        let mut pends = Vec::new();
963        let mut marks = Vec::new();
964        let uncharged = UnverifiedReason::UnchargedPrint { print_id };
965        let Some(totals) = &closing.totals else {
966            for tool in used {
967                if let Some(spool) = spool_on_tool(spools, tool) {
968                    marks.push(self.mark_of(spool.id, uncharged.clone(), Some(print_id))?);
969                }
970            }
971            return Ok((charges, pends, marks));
972        };
973        used.extend(totals.lengths.keys().copied());
974        for tool in used {
975            let on_tool = spool_on_tool(spools, tool);
976            if closing.watch == Watch::Unwatched
977                && let Some(spool) = on_tool
978            {
979                marks.push(self.mark_of(spool.id, uncharged.clone(), Some(print_id))?);
980            }
981            let total = totals.lengths.get(&tool).copied().unwrap_or(0.0);
982            let remainder = total - ledger.already_mm(tool);
983            if remainder <= NOTHING_MM {
984                continue;
985            }
986            let feed = Feed {
987                key: ChargeKey::Print {
988                    print_id,
989                    tool,
990                    segment: ledger.open_segment(tool),
991                },
992                method: totals.method,
993                length_mm: remainder,
994                analysed_length_mm: closing.analysis.length(tool),
995                position: closing.position.clone(),
996                note: totals.note.clone(),
997            };
998            let judged = on_tool.or_else(|| {
999                ledger
1000                    .last_spool(tool)
1001                    .and_then(|id| spools.iter().find(|spool| spool.id == id))
1002            });
1003            if judged.is_some_and(|spool| holds_change_mark(spool, print_id)) {
1004                pends.push(self.pend_of(feed)?);
1005            } else {
1006                charges.push(self.charge_of(feed, on_tool, &mut figures, system_source())?);
1007            }
1008        }
1009        Ok((charges, pends, marks))
1010    }
1011
1012    /// Settle a print with no `print_started`: no charge, one `print_untracked`
1013    /// and one `print_ended`, when a job was ever seen for it.
1014    async fn settle_untracked(
1015        &self,
1016        print: &PrintRecord,
1017        state: &PrinterState,
1018        reason: &str,
1019        closing_job: Option<&JobSnapshot>,
1020    ) -> Result<(), CoreError> {
1021        let ran = print.provider_print_id.is_some()
1022            || print.job_started_at.is_some()
1023            || print.job_print_time_s.is_some();
1024        if !ran {
1025            return Ok(());
1026        }
1027        let named = print
1028            .file_name
1029            .as_deref()
1030            .and_then(|name| FileName::new(name).ok());
1031        let outcome = Ending {
1032            state,
1033            job: closing_job,
1034            file_name: named.as_ref(),
1035            position: None,
1036            size_bytes: None,
1037            tally: Tally::NoCompletion,
1038            cancelled_by: Canceller::NotHere,
1039        }
1040        .outcome();
1041        // The `print_untracked` goes first, once: a close-out replayed after
1042        // it — the settlement refused, or committed with its answer lost —
1043        // finds it written and writes no second, and one replayed after the
1044        // settlement finds that and writes nothing at all.
1045        let written = self
1046            .stores()
1047            .events
1048            .history(HistoryQuery {
1049                print_id: print.id,
1050                kinds: vec![PrintUntrackedPayload::kind()],
1051                since: None,
1052                until: None,
1053                limit: Some(1),
1054            })
1055            .await?;
1056        if written.is_empty() {
1057            let draft = self.draft_of(
1058                Some(print.id),
1059                system_source(),
1060                &PrintUntrackedPayload {
1061                    reason: UNTRACKED_REASON.to_owned(),
1062                },
1063            )?;
1064            self.stores().events.append_event(draft).await?;
1065        }
1066        let ended = self.draft_of(
1067            Some(print.id),
1068            system_source(),
1069            &PrintEndedPayload {
1070                outcome,
1071                state: state.clone(),
1072                reason: reason.to_owned(),
1073                last_position: None,
1074            },
1075        )?;
1076        self.stores()
1077            .filament
1078            .settle_print(print.id, outcome, ended, Vec::new(), Vec::new(), Vec::new())
1079            .await?;
1080        Ok(())
1081    }
1082
1083    /// The print a spool command made now happens during, when one is: the
1084    /// most recently opened open print that is tracked and not yet settled.
1085    pub(crate) async fn print_during(&self) -> Result<Option<PrintRecord>, CoreError> {
1086        for print in self.stores().prints.open_prints().await? {
1087            if self
1088                .stores()
1089                .filament
1090                .print_settlement(print.id)
1091                .await?
1092                .is_none()
1093                && self.print_started_of(print.id).await?.is_some()
1094            {
1095                return Ok(Some(print));
1096            }
1097        }
1098        Ok(None)
1099    }
1100
1101    /// Where a print is now: read afresh from the job when it reports one,
1102    /// recorded as it is read, and otherwise the last position recorded —
1103    /// with the job the read found, when it found one.
1104    pub(crate) async fn position_now(
1105        &self,
1106        print: &PrintRecord,
1107    ) -> Result<(Whereabouts, Option<JobSnapshot>), CoreError> {
1108        let job = self.read_job().await.ok();
1109        let observed_at = self.clock().now();
1110        if let Some(job) = &job
1111            && let Some(position) = self.record_position_from(print, job, observed_at).await?
1112        {
1113            self.note_seen_running(print.id);
1114            return Ok((Whereabouts::ReadNow(position), Some(job.clone())));
1115        }
1116        let whereabouts = match self.stores().filament.file_position(print.id).await? {
1117            Some(recorded) => Whereabouts::Recorded(recorded),
1118            None => Whereabouts::Unknown,
1119        };
1120        Ok((whereabouts, job))
1121    }
1122
1123    /// The filament each tool fed up to where a print is now, and that
1124    /// position — what a spool command made during it charges against.
1125    pub(crate) async fn extrusion_now(
1126        &self,
1127        print: &PrintRecord,
1128    ) -> Result<Option<(FilePosition, Extrusion, FileAnalysis)>, CoreError> {
1129        let Some(file_name) = file_of(print) else {
1130            return Ok(None);
1131        };
1132        let (whereabouts, job) = self.position_now(print).await?;
1133        let Some(position) = whereabouts.position().cloned() else {
1134            return Ok(None);
1135        };
1136        let analysis = self.analysis_of(&file_name, job.as_ref()).await;
1137        Ok(self
1138            .extrusion_to(&file_name, &position, &analysis)
1139            .await
1140            .map(|extrusion| (position, extrusion, analysis)))
1141    }
1142
1143    /// Handle what the printer itself signalled, as an alert relayed it.
1144    ///
1145    /// A filament change reads the job afresh — the printer is paused at the
1146    /// change, so that is where the spool stopped feeding — charges the spool
1147    /// on each tool up to it, writes `filament_change_signalled`, and marks
1148    /// the spool as one whose change nobody has confirmed. When no fresh
1149    /// position can be read it charges up to the last position recorded and
1150    /// says so, with the mark that says its figure may be overstated. A spool
1151    /// already holding the print's mark — a second signal before any load —
1152    /// has its open segment pended instead, and is marked again.
1153    pub(crate) async fn handle_signal(
1154        &self,
1155        print: &PrintRecord,
1156        signal: PrinterSignal,
1157        source_kind: &EventKind,
1158    ) -> Result<(), CoreError> {
1159        let PrinterSignal::FilamentChange = signal;
1160        if print.ended_at.is_some()
1161            || self
1162                .stores()
1163                .filament
1164                .print_settlement(print.id)
1165                .await?
1166                .is_some()
1167            || self.print_started_of(print.id).await?.is_none()
1168        {
1169            return Ok(());
1170        }
1171        let (whereabouts, job) = self.position_now(print).await?;
1172        let read_now = matches!(whereabouts, Whereabouts::ReadNow(_));
1173        let position = whereabouts.position().cloned();
1174        let signal_position = position.clone().map(|position| SignalPosition {
1175            position,
1176            freshness: if read_now {
1177                PositionFreshness::ReadAtSignal
1178            } else {
1179                PositionFreshness::LastRecorded
1180            },
1181        });
1182        let file_name = file_of(print);
1183        let analysis = match &file_name {
1184            Some(file) => self.analysis_of(file, job.as_ref()).await,
1185            None => FileAnalysis::default(),
1186        };
1187        let extrusion = match (&file_name, &position) {
1188            (Some(file), Some(position)) => self.extrusion_to(file, position, &analysis).await,
1189            _ => None,
1190        };
1191        let signalled = |tool: Option<i64>, spool_id: Option<SpoolId>| {
1192            self.draft_of(
1193                Some(print.id),
1194                system_source(),
1195                &FilamentChangeSignalledPayload {
1196                    tool,
1197                    spool_id,
1198                    source_kind: source_kind.clone(),
1199                    position: signal_position.clone(),
1200                },
1201            )
1202        };
1203        let reason = if read_now {
1204            UnverifiedReason::FilamentChangeUnconfirmed { print_id: print.id }
1205        } else {
1206            UnverifiedReason::FilamentChangeUnconfirmedPosition { print_id: print.id }
1207        };
1208
1209        let _writing = self.spool_writes().await;
1210        let loaded = self.stores().filament.loaded_spools().await?;
1211        if loaded.is_empty() {
1212            self.stores()
1213                .events
1214                .append_event(signalled(None, None)?)
1215                .await?;
1216            return Ok(());
1217        }
1218        let ledger = self.print_ledger(print.id).await?;
1219        let mut figures = Figures::default();
1220        let mut charges = Vec::new();
1221        let mut pends = Vec::new();
1222        let mut marks = Vec::new();
1223        for spool in &loaded {
1224            let Some(tool) = spool.loaded_tool() else {
1225                continue;
1226            };
1227            self.stores()
1228                .events
1229                .append_event(signalled(Some(tool), Some(spool.id))?)
1230                .await?;
1231            let feed = match (&extrusion, &position) {
1232                (Some(extrusion), Some(position)) => {
1233                    feed_to(print.id, tool, &ledger, extrusion, position, &analysis)
1234                }
1235                _ => None,
1236            };
1237            match feed {
1238                Some(feed) if holds_change_mark(spool, print.id) => {
1239                    pends.push(self.pend_of(feed)?);
1240                }
1241                Some(feed) => {
1242                    charges.push(self.charge_of(
1243                        feed,
1244                        Some(spool),
1245                        &mut figures,
1246                        system_source(),
1247                    )?);
1248                }
1249                None => {}
1250            }
1251            marks.push(self.mark_of(spool.id, reason.clone(), Some(print.id))?);
1252        }
1253        self.stores()
1254            .filament
1255            .apply_spool_changes(marks, charges, pends)
1256            .await?;
1257        Ok(())
1258    }
1259}