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, 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;
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    ) -> Result<(), CoreError> {
716        self.forget_pushes();
717        let loaded = self
718            .stores()
719            .filament
720            .loaded_spools()
721            .await?
722            .into_iter()
723            .filter_map(|spool| {
724                spool.loaded_tool().map(|tool| LoadedSpool {
725                    tool,
726                    spool_id: spool.id,
727                })
728            })
729            .collect();
730        let draft = self.draft_of(
731            Some(print_id),
732            system_source(),
733            &PrintStartedPayload {
734                file_name,
735                started_by,
736                loaded,
737                preflight,
738            },
739        )?;
740        self.stores().events.append_event(draft).await?;
741        Ok(())
742    }
743
744    /// Record how far into its file a print had got, from one job read.
745    pub(crate) async fn record_position_from(
746        &self,
747        print: &PrintRecord,
748        job: &JobSnapshot,
749        observed_at: Timestamp,
750    ) -> Result<Option<FilePosition>, CoreError> {
751        let Some(position) = position_from(job, print, observed_at) else {
752            return Ok(None);
753        };
754        self.stores()
755            .filament
756            .record_file_position(print.id, position.clone())
757            .await?;
758        Ok(Some(position))
759    }
760
761    /// What the printer says of one file: its facts, and the analysed length
762    /// per tool from the job read when it carries one, otherwise from the
763    /// file's own facts.
764    pub(crate) async fn analysis_of(
765        &self,
766        file_name: &FileName,
767        job: Option<&JobSnapshot>,
768    ) -> FileAnalysis {
769        let facts = self.read_file_facts(file_name.clone()).await.ok();
770        let from_job = job
771            .filter(|job| {
772                job.file_name.as_deref() == Some(file_name.as_str()) && !job.filament.is_empty()
773            })
774            .map(|job| lengths_of(&job.filament));
775        let lengths = from_job.or_else(|| {
776            facts
777                .as_ref()
778                .and_then(|facts| facts.filament.as_deref().map(lengths_of))
779        });
780        FileAnalysis { facts, lengths }
781    }
782
783    /// The filament each tool fed up to a position: summed from the file's own
784    /// moves, or — when the file could not be read — the analysed length
785    /// scaled by how far into the file the position is, with a note saying
786    /// why. Nothing when neither can be worked out.
787    pub(crate) async fn extrusion_to(
788        &self,
789        file_name: &FileName,
790        position: &FilePosition,
791        analysis: &FileAnalysis,
792    ) -> Option<Extrusion> {
793        let refusal = match self
794            .read_extruded_to(file_name.clone(), position.bytes)
795            .await
796        {
797            Ok(filament) => {
798                return Some(Extrusion {
799                    lengths: lengths_of(&filament),
800                    method: ChargeMethod::GcodeExtrusion,
801                    note: None,
802                });
803            }
804            Err(error) => error.to_string(),
805        };
806        let analysed = analysis.lengths.as_ref()?;
807        let size = position
808            .size_bytes
809            .or_else(|| analysis.size_bytes())
810            .filter(|size| *size > 0)?;
811        #[expect(clippy::cast_precision_loss)]
812        let fraction = (position.bytes as f64 / size as f64).clamp(0.0, 1.0);
813        Some(Extrusion {
814            lengths: analysed
815                .iter()
816                .map(|(tool, length)| (*tool, length * fraction))
817                .collect(),
818            method: ChargeMethod::FileFraction,
819            note: Some(format!(
820                "the file could not be read ({refusal}), so the analysed length was scaled by \
821                 how far into the file the print got"
822            )),
823        })
824    }
825
826    /// Whether this system's own cancel was executed for a print.
827    async fn cancelled_here(&self, print_id: PrintId) -> Result<bool, CoreError> {
828        let events = self
829            .stores()
830            .events
831            .history(HistoryQuery {
832                print_id,
833                kinds: vec![
834                    ActionRequestedPayload::kind(),
835                    ActionExecutedPayload::kind(),
836                ],
837                since: None,
838                until: None,
839                limit: Some(MAX_HISTORY_LIMIT),
840            })
841            .await?;
842        let executed: BTreeSet<ActionId> = events
843            .iter()
844            .filter_map(printobserver_types::EventRecord::payload_as::<ActionExecutedPayload>)
845            .filter_map(Result::ok)
846            .map(|payload| payload.action_id)
847            .collect();
848        Ok(events
849            .iter()
850            .filter_map(printobserver_types::EventRecord::payload_as::<ActionRequestedPayload>)
851            .filter_map(Result::ok)
852            .any(|payload| {
853                matches!(payload.action, PrintAction::Cancel { .. })
854                    && executed.contains(&payload.action_id)
855            }))
856    }
857
858    /// Settle one print's filament as it is closed out, unless it is settled
859    /// already.
860    ///
861    /// A print with no `print_started` predates spool tracking: it is settled
862    /// with no charge and one `print_untracked` — when a job was ever seen for
863    /// it at all; a print a refused start opened and nothing ever ran is not
864    /// a print of the timeline. Any other print is charged by the rule of its
865    /// outcome, as this module states.
866    pub(crate) async fn settle_filament(
867        &self,
868        print: &PrintRecord,
869        state: &PrinterState,
870        reason: &str,
871        closing_job: Option<&JobSnapshot>,
872    ) -> Result<(), CoreError> {
873        if self
874            .stores()
875            .filament
876            .print_settlement(print.id)
877            .await?
878            .is_some()
879        {
880            return Ok(());
881        }
882        let Some(started) = self.print_started_of(print.id).await? else {
883            return self
884                .settle_untracked(print, state, reason, closing_job)
885                .await;
886        };
887        let closing = self.closing(print, &started, state, closing_job).await?;
888        let ended = self.draft_of(
889            Some(print.id),
890            system_source(),
891            &PrintEndedPayload {
892                outcome: closing.outcome,
893                state: state.clone(),
894                reason: reason.to_owned(),
895                last_position: closing.position.clone(),
896            },
897        )?;
898        let _writing = self.spool_writes().await;
899        let spools = self.stores().filament.spools(true).await?;
900        let ledger = self.print_ledger(print.id).await?;
901        let mut used: BTreeSet<i64> = ledger.tools();
902        used.extend(started.loaded.iter().map(|loaded| loaded.tool));
903        let (charges, pends, marks) =
904            self.closing_writes(print.id, used, &closing, &spools, &ledger)?;
905        self.stores()
906            .filament
907            .settle_print(print.id, closing.outcome, ended, charges, pends, marks)
908            .await?;
909        Ok(())
910    }
911
912    /// Everything a tracked print's close-out reads before it works out what
913    /// to charge: how it ended, and what each tool fed by that outcome's rule.
914    async fn closing(
915        &self,
916        print: &PrintRecord,
917        started: &PrintStartedPayload,
918        state: &PrinterState,
919        closing_job: Option<&JobSnapshot>,
920    ) -> Result<Closing, CoreError> {
921        let read = if closing_job.is_none() {
922            self.read_job().await.ok()
923        } else {
924            None
925        };
926        let job = closing_job.or(read.as_ref());
927        let file_name = print
928            .file_name
929            .as_deref()
930            .or(started.file_name.as_deref())
931            .and_then(|name| FileName::new(name).ok());
932        let analysis = match &file_name {
933            Some(file) => self.analysis_of(file, job).await,
934            None => FileAnalysis::default(),
935        };
936        let position = self.stores().filament.file_position(print.id).await?;
937        // A print completes after it was opened, whoever opened it; the job's
938        // own start, as a read puts it, can lie before that, and a success
939        // recorded between the two is an earlier print's.
940        //
941        // That record is read only for a stop this supervisor did not observe
942        // — it was not running when the print ended, so no job read of the
943        // finish was made. A stop it watched is completed by its job reads
944        // alone.
945        let began = print.opened_at;
946        let unobserved = !self.was_seen_running(print.id);
947        let tally = if unobserved
948            && analysis
949                .facts
950                .as_ref()
951                .and_then(|facts| facts.last_print.as_ref())
952                .is_some_and(|last| last.success && last.at >= began)
953        {
954            Tally::CompletedSince
955        } else {
956            Tally::NoCompletion
957        };
958        let cancelled_by = if self.cancelled_here(print.id).await? {
959            Canceller::Here
960        } else {
961            Canceller::NotHere
962        };
963        let ending = |pushes| {
964            Ending {
965                state,
966                job,
967                file_name: file_name.as_ref(),
968                size_bytes: analysis.size_bytes(),
969                tally,
970                cancelled_by,
971                pushes,
972            }
973            .outcome()
974        };
975        let mut outcome = ending(self.push_facts());
976        if outcome == PrintOutcome::Cancelled && cancelled_by == Canceller::NotHere {
977            outcome = ending(self.pushes_after_a_reset_could_arrive().await);
978        }
979        let rule = charge_rule(outcome);
980        let totals = match (rule, &file_name, &position) {
981            (ChargeRule::SlicerEstimate, _, _) => {
982                analysis.lengths.clone().map(|lengths| Extrusion {
983                    lengths,
984                    method: ChargeMethod::SlicerEstimate,
985                    note: None,
986                })
987            }
988            (ChargeRule::ExtrudedToLastPosition, Some(file), Some(position)) => {
989                self.extrusion_to(file, position, &analysis).await
990            }
991            (ChargeRule::ExtrudedToLastPosition, _, _) => None,
992        };
993        Ok(Closing {
994            outcome,
995            watch: if self.was_seen_running(print.id) || rule == ChargeRule::SlicerEstimate {
996                Watch::Watched
997            } else {
998                Watch::Unwatched
999            },
1000            totals,
1001            analysis,
1002            position,
1003        })
1004    }
1005
1006    /// What a tracked print's close-out writes: each tool's remainder charged
1007    /// to the spool on it, or held when the tool's last change is unconfirmed,
1008    /// and every spool whose figure the print leaves in doubt marked.
1009    fn closing_writes(
1010        &self,
1011        print_id: PrintId,
1012        mut used: BTreeSet<i64>,
1013        closing: &Closing,
1014        spools: &[SpoolRecord],
1015        ledger: &PrintLedger,
1016    ) -> Result<ClosingWrites, CoreError> {
1017        let mut figures = Figures::default();
1018        let mut charges = Vec::new();
1019        let mut pends = Vec::new();
1020        let mut marks = Vec::new();
1021        let uncharged = UnverifiedReason::UnchargedPrint { print_id };
1022        let Some(totals) = &closing.totals else {
1023            for tool in used {
1024                if let Some(spool) = spool_on_tool(spools, tool) {
1025                    marks.push(self.mark_of(spool.id, uncharged.clone(), Some(print_id))?);
1026                }
1027            }
1028            return Ok((charges, pends, marks));
1029        };
1030        used.extend(totals.lengths.keys().copied());
1031        for tool in used {
1032            let on_tool = spool_on_tool(spools, tool);
1033            if closing.watch == Watch::Unwatched
1034                && let Some(spool) = on_tool
1035            {
1036                marks.push(self.mark_of(spool.id, uncharged.clone(), Some(print_id))?);
1037            }
1038            let total = totals.lengths.get(&tool).copied().unwrap_or(0.0);
1039            let remainder = total - ledger.already_mm(tool);
1040            if remainder <= NOTHING_MM {
1041                continue;
1042            }
1043            let feed = Feed {
1044                key: ChargeKey::Print {
1045                    print_id,
1046                    tool,
1047                    segment: ledger.open_segment(tool),
1048                },
1049                method: totals.method,
1050                length_mm: remainder,
1051                analysed_length_mm: closing.analysis.length(tool),
1052                position: closing.position.clone(),
1053                note: totals.note.clone(),
1054            };
1055            let judged = on_tool.or_else(|| {
1056                ledger
1057                    .last_spool(tool)
1058                    .and_then(|id| spools.iter().find(|spool| spool.id == id))
1059            });
1060            if judged.is_some_and(|spool| holds_change_mark(spool, print_id)) {
1061                pends.push(self.pend_of(feed)?);
1062            } else {
1063                charges.push(self.charge_of(feed, on_tool, &mut figures, system_source())?);
1064            }
1065        }
1066        Ok((charges, pends, marks))
1067    }
1068
1069    /// Settle a print with no `print_started`: no charge, one `print_untracked`
1070    /// and one `print_ended`, when a job was ever seen for it.
1071    async fn settle_untracked(
1072        &self,
1073        print: &PrintRecord,
1074        state: &PrinterState,
1075        reason: &str,
1076        closing_job: Option<&JobSnapshot>,
1077    ) -> Result<(), CoreError> {
1078        let ran = print.provider_print_id.is_some()
1079            || print.job_started_at.is_some()
1080            || print.job_print_time_s.is_some();
1081        if !ran {
1082            return Ok(());
1083        }
1084        let named = print
1085            .file_name
1086            .as_deref()
1087            .and_then(|name| FileName::new(name).ok());
1088        let ending = |pushes| {
1089            Ending {
1090                state,
1091                job: closing_job,
1092                file_name: named.as_ref(),
1093                size_bytes: None,
1094                tally: Tally::NoCompletion,
1095                cancelled_by: Canceller::NotHere,
1096                pushes,
1097            }
1098            .outcome()
1099        };
1100        let mut outcome = ending(self.push_facts());
1101        if outcome == PrintOutcome::Cancelled {
1102            outcome = ending(self.pushes_after_a_reset_could_arrive().await);
1103        }
1104        // The `print_untracked` goes first, once: a close-out replayed after
1105        // it — the settlement refused, or committed with its answer lost —
1106        // finds it written and writes no second, and one replayed after the
1107        // settlement finds that and writes nothing at all.
1108        let written = self
1109            .stores()
1110            .events
1111            .history(HistoryQuery {
1112                print_id: print.id,
1113                kinds: vec![PrintUntrackedPayload::kind()],
1114                since: None,
1115                until: None,
1116                limit: Some(1),
1117            })
1118            .await?;
1119        if written.is_empty() {
1120            let draft = self.draft_of(
1121                Some(print.id),
1122                system_source(),
1123                &PrintUntrackedPayload {
1124                    reason: UNTRACKED_REASON.to_owned(),
1125                },
1126            )?;
1127            self.stores().events.append_event(draft).await?;
1128        }
1129        let ended = self.draft_of(
1130            Some(print.id),
1131            system_source(),
1132            &PrintEndedPayload {
1133                outcome,
1134                state: state.clone(),
1135                reason: reason.to_owned(),
1136                last_position: None,
1137            },
1138        )?;
1139        self.stores()
1140            .filament
1141            .settle_print(print.id, outcome, ended, Vec::new(), Vec::new(), Vec::new())
1142            .await?;
1143        Ok(())
1144    }
1145
1146    /// The print a spool command made now happens during, when one is: the
1147    /// most recently opened open print that is tracked and not yet settled.
1148    pub(crate) async fn print_during(&self) -> Result<Option<PrintRecord>, CoreError> {
1149        for print in self.stores().prints.open_prints().await? {
1150            if self
1151                .stores()
1152                .filament
1153                .print_settlement(print.id)
1154                .await?
1155                .is_none()
1156                && self.print_started_of(print.id).await?.is_some()
1157            {
1158                return Ok(Some(print));
1159            }
1160        }
1161        Ok(None)
1162    }
1163
1164    /// Where a print is now: read afresh from the job when it reports one,
1165    /// recorded as it is read, and otherwise the last position recorded —
1166    /// with the job the read found, when it found one.
1167    pub(crate) async fn position_now(
1168        &self,
1169        print: &PrintRecord,
1170    ) -> Result<(Whereabouts, Option<JobSnapshot>), CoreError> {
1171        let job = self.read_job().await.ok();
1172        let observed_at = self.clock().now();
1173        if let Some(job) = &job
1174            && let Some(position) = self.record_position_from(print, job, observed_at).await?
1175        {
1176            self.note_seen_running(print.id);
1177            return Ok((Whereabouts::ReadNow(position), Some(job.clone())));
1178        }
1179        let whereabouts = match self.stores().filament.file_position(print.id).await? {
1180            Some(recorded) => Whereabouts::Recorded(recorded),
1181            None => Whereabouts::Unknown,
1182        };
1183        Ok((whereabouts, job))
1184    }
1185
1186    /// The filament each tool fed up to where a print is now, and that
1187    /// position — what a spool command made during it charges against.
1188    pub(crate) async fn extrusion_now(
1189        &self,
1190        print: &PrintRecord,
1191    ) -> Result<Option<(FilePosition, Extrusion, FileAnalysis)>, CoreError> {
1192        let Some(file_name) = file_of(print) else {
1193            return Ok(None);
1194        };
1195        let (whereabouts, job) = self.position_now(print).await?;
1196        let Some(position) = whereabouts.position().cloned() else {
1197            return Ok(None);
1198        };
1199        let analysis = self.analysis_of(&file_name, job.as_ref()).await;
1200        Ok(self
1201            .extrusion_to(&file_name, &position, &analysis)
1202            .await
1203            .map(|extrusion| (position, extrusion, analysis)))
1204    }
1205
1206    /// Handle what the printer itself signalled, as an alert relayed it.
1207    ///
1208    /// A filament change at a change the print's G-code plans is that change
1209    /// reached ([`crate::planned`]), and one repeated while the print waits
1210    /// there is nothing more. Any other reads the job afresh — the printer is
1211    /// paused at the change, so that is where the spool stopped feeding —
1212    /// charges the spool on each tool up to it, writes
1213    /// `filament_change_signalled`, and marks the spool as one whose change
1214    /// nobody has confirmed. When no fresh position can be read it charges up
1215    /// to the last position recorded and says so, with the mark that says its
1216    /// figure may be overstated. A spool already holding the print's mark — a
1217    /// second signal before any load — has its open segment pended instead,
1218    /// and is marked again.
1219    pub(crate) async fn handle_signal(
1220        &self,
1221        print: &PrintRecord,
1222        signal: PrinterSignal,
1223        source_kind: &EventKind,
1224    ) -> Result<(), CoreError> {
1225        let PrinterSignal::FilamentChange = signal;
1226        if print.ended_at.is_some() || self.signal_at_planned_change(print, source_kind).await? {
1227            return Ok(());
1228        }
1229        if !self.charges_changes(print).await? {
1230            return Ok(());
1231        }
1232        let (whereabouts, job) = self.position_now(print).await?;
1233        self.charge_filament_change(print, source_kind, whereabouts, job, None)
1234            .await
1235    }
1236
1237    /// Whether a filament change during a print is charged: the print is open,
1238    /// tracked and not yet settled.
1239    async fn charges_changes(&self, print: &PrintRecord) -> Result<bool, CoreError> {
1240        Ok(print.ended_at.is_none()
1241            && self
1242                .stores()
1243                .filament
1244                .print_settlement(print.id)
1245                .await?
1246                .is_none()
1247            && self.print_started_of(print.id).await?.is_some())
1248    }
1249
1250    /// Charge the spool on each tool up to where a filament change stopped it,
1251    /// write `filament_change_signalled` — naming the planned change it was,
1252    /// when it was one — and mark the spool as one whose change nobody has
1253    /// confirmed.
1254    pub(crate) async fn charge_filament_change(
1255        &self,
1256        print: &PrintRecord,
1257        source_kind: &EventKind,
1258        whereabouts: Whereabouts,
1259        job: Option<JobSnapshot>,
1260        planned_change: Option<u32>,
1261    ) -> Result<(), CoreError> {
1262        if planned_change.is_some() && !self.charges_changes(print).await? {
1263            return Ok(());
1264        }
1265        let read_now = matches!(whereabouts, Whereabouts::ReadNow(_));
1266        let position = whereabouts.position().cloned();
1267        let signal_position = position.clone().map(|position| SignalPosition {
1268            position,
1269            freshness: if read_now {
1270                PositionFreshness::ReadAtSignal
1271            } else {
1272                PositionFreshness::LastRecorded
1273            },
1274        });
1275        let file_name = file_of(print);
1276        let analysis = match &file_name {
1277            Some(file) => self.analysis_of(file, job.as_ref()).await,
1278            None => FileAnalysis::default(),
1279        };
1280        let extrusion = match (&file_name, &position) {
1281            (Some(file), Some(position)) => self.extrusion_to(file, position, &analysis).await,
1282            _ => None,
1283        };
1284        let signalled = |tool: Option<i64>, spool_id: Option<SpoolId>| {
1285            self.draft_of(
1286                Some(print.id),
1287                system_source(),
1288                &FilamentChangeSignalledPayload {
1289                    tool,
1290                    spool_id,
1291                    source_kind: source_kind.clone(),
1292                    position: signal_position.clone(),
1293                    planned_change,
1294                },
1295            )
1296        };
1297        let reason = if read_now {
1298            UnverifiedReason::FilamentChangeUnconfirmed { print_id: print.id }
1299        } else {
1300            UnverifiedReason::FilamentChangeUnconfirmedPosition { print_id: print.id }
1301        };
1302
1303        let _writing = self.spool_writes().await;
1304        let loaded = self.stores().filament.loaded_spools().await?;
1305        if loaded.is_empty() {
1306            self.stores()
1307                .events
1308                .append_event(signalled(None, None)?)
1309                .await?;
1310            return Ok(());
1311        }
1312        let ledger = self.print_ledger(print.id).await?;
1313        let mut figures = Figures::default();
1314        let mut charges = Vec::new();
1315        let mut pends = Vec::new();
1316        let mut marks = Vec::new();
1317        for spool in &loaded {
1318            let Some(tool) = spool.loaded_tool() else {
1319                continue;
1320            };
1321            self.stores()
1322                .events
1323                .append_event(signalled(Some(tool), Some(spool.id))?)
1324                .await?;
1325            let feed = match (&extrusion, &position) {
1326                (Some(extrusion), Some(position)) => {
1327                    feed_to(print.id, tool, &ledger, extrusion, position, &analysis)
1328                }
1329                _ => None,
1330            };
1331            match feed {
1332                Some(feed) if holds_change_mark(spool, print.id) => {
1333                    pends.push(self.pend_of(feed)?);
1334                }
1335                Some(feed) => {
1336                    charges.push(self.charge_of(
1337                        feed,
1338                        Some(spool),
1339                        &mut figures,
1340                        system_source(),
1341                    )?);
1342                }
1343                None => {}
1344            }
1345            marks.push(self.mark_of(spool.id, reason.clone(), Some(print.id))?);
1346        }
1347        self.stores()
1348            .filament
1349            .apply_spool_changes(marks, charges, pends)
1350            .await?;
1351        Ok(())
1352    }
1353}