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