Skip to main content

printobserver_core/
spools.rs

1//! The spool ledger's commands and reads, through the one granted path.
2//!
3//! A spool command is an action of its own kind: the safety envelope grants it
4//! per actor class exactly as it grants a print action, an ungranted one is
5//! refused [`ActorMayNotRequest`](RejectionReason::ActorMayNotRequest), and
6//! one the ledger cannot carry out is refused
7//! [`SpoolRefused`](RejectionReason::SpoolRefused) naming why. Every refusal
8//! writes a `spool_command_rejected`, and every accepted command writes its
9//! spool events through one store write carrying who asked and why — so a
10//! remaining figure can be traced to every print and correction behind it.
11//!
12//! Every command is carried out under the supervisor's one spool lock, so two
13//! commands — or a command and a settlement — never compute from the same
14//! stale figure.
15//!
16//! # A load mid-print, and a load after an unconfirmed change
17//!
18//! A load or unload during a print first charges what the tool fed up to the
19//! position read now to the spool that was feeding it, and opens the next
20//! segment for the spool loaded; the close-out charges that spool only the
21//! remainder. After an unconfirmed filament change the open segment is not the
22//! outgoing spool's: a load of another spool takes every pending charge on the
23//! tool and the open post-signal segment to that point, and a load naming the
24//! spool already there confirms it was never swapped — taking the pending
25//! charges, clearing its filament-change marks and charging nothing for the
26//! open segment, which the close-out charges to it as the remainder.
27
28use printobserver_types::{EventRecord, EventSource, PrintId};
29
30use crate::accounting::{
31    AFTER_CHANGE, Figures, feed_to, holds_any_change_mark, holds_change_mark, spool_on_tool,
32};
33use crate::actions::source_of;
34use crate::error::CoreError;
35use crate::filament::{DEFAULT_DIAMETER_MM, MarkClearing, density_for, marks_cleared_by};
36use crate::kinds::{
37    SpoolAdjustedPayload, SpoolCommandRejectedPayload, SpoolLoadedPayload, SpoolRetiredPayload,
38    SpoolUnloadedPayload,
39};
40use crate::records::{
41    ClearedMark, PolicyDecision, RejectionReason, SpoolCommand, SpoolId, SpoolRecord, SpoolTrust,
42};
43use crate::store::{
44    Charge, EventDraft, NewSpool, SpoolChange, SpoolMutation, StoreError, TimelineQuery,
45};
46use crate::supervisor::Supervisor;
47
48/// What became of one spool command.
49#[derive(Debug, Clone, PartialEq)]
50pub struct SpoolCommandOutcome {
51    /// The decision taken on it.
52    pub decision: PolicyDecision,
53    /// The spool it was about, as the command left it, when there is one.
54    pub spool: Option<SpoolRecord>,
55    /// Every event it wrote, in the order they were written.
56    pub events: Vec<EventRecord>,
57}
58
59/// A refusal of a spool command, saying why and what to do instead.
60fn refused(detail: impl Into<String>) -> RejectionReason {
61    RejectionReason::SpoolRefused {
62        detail: detail.into(),
63    }
64}
65
66/// Whether a figure is a finite number at or above zero.
67fn non_negative(value: f64) -> bool {
68    value.is_finite() && value >= 0.0
69}
70
71/// Whether a figure is a finite number above zero.
72fn positive(value: f64) -> bool {
73    value.is_finite() && value > 0.0
74}
75
76/// The marks one spool loses to a clearing, named against it.
77fn cleared_on(spool: &SpoolRecord, clearing: MarkClearing) -> Vec<ClearedMark> {
78    let (_, removed) = spool.trust.clone().cleared(marks_cleared_by(clearing));
79    removed
80        .into_iter()
81        .map(|reason| ClearedMark {
82            spool_id: spool.id,
83            reason,
84        })
85        .collect()
86}
87
88/// The mutation clearing one spool's marks of one clearing's kinds.
89///
90/// It writes no event of its own — the command's own event names the marks it
91/// cleared — so it carries that event's draft, which the store does not write
92/// for it.
93fn clearing(spool_id: SpoolId, clearing: MarkClearing, command: &EventDraft) -> SpoolMutation {
94    SpoolMutation {
95        spool_id,
96        change: SpoolChange::ClearMarks {
97            kinds: marks_cleared_by(clearing).to_vec(),
98        },
99        at: command.received_at,
100        event: command.clone(),
101    }
102}
103
104/// What one accepted command asks the store to write.
105#[derive(Debug, Default)]
106struct Write {
107    /// The spool mutations, in order.
108    mutations: Vec<SpoolMutation>,
109    /// The charges, in order.
110    charges: Vec<Charge>,
111}
112
113impl Supervisor {
114    /// Carry out one spool command, through the same grant every action passes.
115    ///
116    /// # Errors
117    ///
118    /// Returns the store's own error when the command or its refusal could not
119    /// be written. A refusal is not an error: it is written down and answered
120    /// in [`SpoolCommandOutcome::decision`].
121    // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
122    pub async fn request_spool_command(
123        &self,
124        command: SpoolCommand,
125    ) -> Result<SpoolCommandOutcome, CoreError> {
126        let actor = command.actor().clone();
127        let class = actor.class();
128        let kind = command.kind();
129        let granted = self
130            .config()
131            .envelope
132            .actions
133            .get(&class)
134            .is_some_and(|kinds| kinds.contains(&kind));
135        if !granted {
136            let reason = RejectionReason::ActorMayNotRequest {
137                actor_class: class,
138                action: kind,
139            };
140            return self.refuse(command, reason).await;
141        }
142        let _writing = self.spool_writes().await;
143        let during = self.print_during().await?.map(|print| print.id);
144        let carried = match &command {
145            SpoolCommand::RegisterSpool { .. } => self.register(&command).await?,
146            SpoolCommand::LoadSpool { spool_id, tool, .. } => {
147                self.load(&command, *spool_id, *tool, during).await?
148            }
149            SpoolCommand::UnloadSpool { spool_id, .. } => {
150                self.unload(&command, *spool_id, during).await?
151            }
152            SpoolCommand::AdjustSpool {
153                spool_id,
154                remaining_g,
155                gross_g,
156                ..
157            } => {
158                self.adjust(&command, *spool_id, *remaining_g, *gross_g, during)
159                    .await?
160            }
161            SpoolCommand::RetireSpool { spool_id, .. } => {
162                self.retire(&command, *spool_id, during).await?
163            }
164        };
165        match carried {
166            Ok(outcome) => Ok(outcome),
167            Err(reason) => self.refuse(command, reason).await,
168        }
169    }
170
171    /// Every spool, retired ones only when asked for, most recently registered
172    /// first.
173    ///
174    /// # Errors
175    ///
176    /// Returns the store's own error when the spools could not be read.
177    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
178    pub async fn spools(&self, include_retired: bool) -> Result<Vec<SpoolRecord>, CoreError> {
179        Ok(self.stores().filament.spools(include_retired).await?)
180    }
181
182    /// One spool, retired or not.
183    ///
184    /// # Errors
185    ///
186    /// Returns the store's own error when the spool could not be read.
187    pub async fn spool(&self, spool_id: SpoolId) -> Result<Option<SpoolRecord>, CoreError> {
188        Ok(self.stores().filament.spool(spool_id).await?)
189    }
190
191    /// The printer timeline, newest first.
192    ///
193    /// # Errors
194    ///
195    /// Returns the store's own error when the timeline could not be read, a
196    /// kind outside the timeline or a limit above the maximum included.
197    pub async fn timeline(&self, query: TimelineQuery) -> Result<Vec<EventRecord>, CoreError> {
198        Ok(self.stores().timeline.timeline(query).await?)
199    }
200
201    /// Every charge held after an unconfirmed filament change — on one tool,
202    /// when one is named — oldest first.
203    ///
204    /// # Errors
205    ///
206    /// Returns the store's own error when the charges could not be read.
207    pub async fn pending_charges(
208        &self,
209        tool: Option<i64>,
210    ) -> Result<Vec<crate::records::PendingCharge>, CoreError> {
211        Ok(self.stores().filament.pending_charges(tool).await?)
212    }
213
214    /// Write a refused command down and answer the refusal.
215    async fn refuse(
216        &self,
217        command: SpoolCommand,
218        reason: RejectionReason,
219    ) -> Result<SpoolCommandOutcome, CoreError> {
220        let decision = PolicyDecision::Rejected(reason);
221        let source = source_of(command.actor());
222        let during = self.print_during().await?.map(|print| print.id);
223        let spool = match &command {
224            SpoolCommand::RegisterSpool { .. } => None,
225            SpoolCommand::LoadSpool { spool_id, .. }
226            | SpoolCommand::UnloadSpool { spool_id, .. }
227            | SpoolCommand::AdjustSpool { spool_id, .. }
228            | SpoolCommand::RetireSpool { spool_id, .. } => {
229                self.stores().filament.spool(*spool_id).await?
230            }
231        };
232        let draft = self.draft_of(
233            during,
234            source,
235            &SpoolCommandRejectedPayload {
236                command,
237                decision: decision.clone(),
238            },
239        )?;
240        let event = self.stores().events.append_event(draft).await?;
241        Ok(SpoolCommandOutcome {
242            decision,
243            spool,
244            events: vec![event],
245        })
246    }
247
248    /// One spool the command names, or the refusal that it cannot be acted on.
249    async fn live_spool(
250        &self,
251        spool_id: SpoolId,
252    ) -> Result<Result<SpoolRecord, RejectionReason>, CoreError> {
253        Ok(match self.stores().filament.spool(spool_id).await? {
254            None => Err(refused(format!(
255                "there is no spool {spool_id}; list the spools to find the one meant"
256            ))),
257            Some(spool) if spool.retired_at.is_some() => Err(refused(format!(
258                "spool {} is retired and takes no further command; register a new spool instead",
259                spool.name
260            ))),
261            Some(spool) => Ok(spool),
262        })
263    }
264
265    /// Write one accepted command's changes and answer them.
266    async fn written(
267        &self,
268        spool_id: SpoolId,
269        write: Write,
270    ) -> Result<Result<SpoolCommandOutcome, RejectionReason>, CoreError> {
271        let written = match self
272            .stores()
273            .filament
274            .apply_spool_changes(write.mutations, write.charges, Vec::new())
275            .await
276        {
277            Ok(written) => written,
278            Err(StoreError::ConstraintRefused { constraint }) => {
279                return Ok(Err(refused(format!(
280                    "the ledger refused the change on {constraint}"
281                ))));
282            }
283            Err(error) => return Err(error.into()),
284        };
285        let spool = written
286            .spools
287            .into_iter()
288            .find(|spool| spool.id == spool_id);
289        Ok(Ok(SpoolCommandOutcome {
290            decision: PolicyDecision::Accepted,
291            spool,
292            events: written.events,
293        }))
294    }
295
296    /// Register a spool.
297    async fn register(
298        &self,
299        command: &SpoolCommand,
300    ) -> Result<Result<SpoolCommandOutcome, RejectionReason>, CoreError> {
301        let SpoolCommand::RegisterSpool {
302            name,
303            material,
304            color,
305            diameter_mm,
306            density_g_cm3,
307            initial_g,
308            remaining_g,
309            tare_g,
310            reason,
311            actor,
312        } = command
313        else {
314            return Ok(Err(refused("not a registration")));
315        };
316        let name = name.trim();
317        let material = material.trim();
318        if name.is_empty() {
319            return Ok(Err(refused("a spool needs a name to be known by")));
320        }
321        if material.is_empty() {
322            return Ok(Err(refused("a spool needs its material, such as PLA")));
323        }
324        let diameter_mm = diameter_mm.unwrap_or(DEFAULT_DIAMETER_MM);
325        if !positive(diameter_mm) {
326            return Ok(Err(refused(format!(
327                "a diameter of {diameter_mm}mm is not one a filament has; give it in millimetres, \
328                 such as 1.75"
329            ))));
330        }
331        let Some(density_g_cm3) = density_g_cm3.or_else(|| density_for(material)) else {
332            return Ok(Err(refused(format!(
333                "{material} has no known density, so the spool needs one in grams per cubic \
334                 centimetre"
335            ))));
336        };
337        if !positive(density_g_cm3) {
338            return Ok(Err(refused(format!(
339                "a density of {density_g_cm3}g/cm3 is not one a material has"
340            ))));
341        }
342        if !positive(*initial_g) {
343            return Ok(Err(refused(format!(
344                "a full spool of {initial_g}g holds nothing; give the net filament it held full"
345            ))));
346        }
347        let remaining_g = remaining_g.unwrap_or(*initial_g);
348        if !remaining_g.is_finite() {
349            return Ok(Err(refused("the remaining figure is not a number")));
350        }
351        if tare_g.is_some_and(|tare| !non_negative(tare)) {
352            return Ok(Err(refused(
353                "an empty spool's weight is at least zero grams",
354            )));
355        }
356        let spool = NewSpool {
357            name: name.to_owned(),
358            material: material.to_owned(),
359            color: color.clone(),
360            diameter_mm,
361            density_g_cm3,
362            initial_g: *initial_g,
363            remaining_g,
364            tare_g: *tare_g,
365            loaded_on_tool: None,
366            trust: SpoolTrust::Verified,
367            registered_at: self.clock().now(),
368        };
369        let (record, event) = self
370            .stores()
371            .filament
372            .register_spool(spool, source_of(actor), actor.clone(), reason.clone())
373            .await?;
374        Ok(Ok(SpoolCommandOutcome {
375            decision: PolicyDecision::Accepted,
376            spool: Some(record),
377            events: vec![event],
378        }))
379    }
380
381    /// Load a spool onto a tool: a confirmation in place when it is already
382    /// there, a swap when another is, and either way taking what that tool
383    /// holds pending.
384    async fn load(
385        &self,
386        command: &SpoolCommand,
387        spool_id: SpoolId,
388        tool: i64,
389        during: Option<PrintId>,
390    ) -> Result<Result<SpoolCommandOutcome, RejectionReason>, CoreError> {
391        if tool < 0 {
392            return Ok(Err(refused(format!(
393                "there is no tool {tool}; tools are numbered from 0, as the printer numbers them"
394            ))));
395        }
396        let incoming = match self.live_spool(spool_id).await? {
397            Ok(spool) => spool,
398            Err(reason) => return Ok(Err(reason)),
399        };
400        let source = source_of(command.actor());
401        let pending = self.stores().filament.pending_charges(Some(tool)).await?;
402        let mut figures = Figures::default();
403        let already_there = incoming.loaded_on_tool == Some(tool);
404        if already_there && pending.is_empty() && !holds_any_change_mark(&incoming) {
405            return Ok(Err(refused(format!(
406                "spool {} is already on tool {tool}, and nothing is pending there to confirm",
407                incoming.name
408            ))));
409        }
410        let spools = self.stores().filament.spools(true).await?;
411        // The spool that was feeding the tool, retired or not — a spool retired
412        // while it was loaded is still charged for what it fed — and the one
413        // the load takes off it, which only an unretired spool can be.
414        let feeding = spool_on_tool(&spools, tool)
415            .filter(|spool| spool.id != incoming.id)
416            .cloned();
417        let outgoing = feeding.clone().filter(|spool| spool.retired_at.is_none());
418        let (mut charges, took_pending) =
419            self.take_pending(&pending, &incoming, &mut figures, &source)?;
420        if !already_there && let Some(print_id) = during {
421            charges.extend(
422                self.close_segment(
423                    print_id,
424                    tool,
425                    feeding.as_ref(),
426                    Some(&incoming),
427                    &mut figures,
428                    &source,
429                )
430                .await?,
431            );
432        }
433        let swapped = outgoing
434            .as_ref()
435            .map(|spool| cleared_on(spool, MarkClearing::SwappedOut))
436            .unwrap_or_default();
437        let confirmed = if already_there {
438            cleared_on(&incoming, MarkClearing::ConfirmedInPlace)
439        } else {
440            Vec::new()
441        };
442        let loaded = self.draft_of(
443            during,
444            source.clone(),
445            &SpoolLoadedPayload {
446                spool_id: incoming.id,
447                tool,
448                replaced: outgoing.as_ref().map(|spool| spool.id),
449                took_pending,
450                cleared_marks: swapped.iter().chain(&confirmed).cloned().collect(),
451                actor: command.actor().clone(),
452                reason: command.reason().to_owned(),
453            },
454        )?;
455        let mut write = Write {
456            mutations: Vec::new(),
457            charges,
458        };
459        if let Some(outgoing) = &outgoing {
460            if !swapped.is_empty() {
461                write
462                    .mutations
463                    .push(clearing(outgoing.id, MarkClearing::SwappedOut, &loaded));
464            }
465            write.mutations.push(self.mutation(
466                outgoing.id,
467                SpoolChange::Unload,
468                during,
469                &source,
470                &SpoolUnloadedPayload {
471                    spool_id: outgoing.id,
472                    tool,
473                    actor: command.actor().clone(),
474                    reason: command.reason().to_owned(),
475                },
476            )?);
477        }
478        if !confirmed.is_empty() {
479            write.mutations.push(clearing(
480                incoming.id,
481                MarkClearing::ConfirmedInPlace,
482                &loaded,
483            ));
484        }
485        write.mutations.push(SpoolMutation {
486            spool_id: incoming.id,
487            change: SpoolChange::Load { tool },
488            at: loaded.received_at,
489            event: loaded,
490        });
491        self.written(incoming.id, write).await
492    }
493
494    /// Unload a spool from its tool, charging it first for what it fed of a
495    /// print running now.
496    async fn unload(
497        &self,
498        command: &SpoolCommand,
499        spool_id: SpoolId,
500        during: Option<PrintId>,
501    ) -> Result<Result<SpoolCommandOutcome, RejectionReason>, CoreError> {
502        let spool = match self.live_spool(spool_id).await? {
503            Ok(spool) => spool,
504            Err(reason) => return Ok(Err(reason)),
505        };
506        let Some(tool) = spool.loaded_on_tool else {
507            return Ok(Err(refused(format!(
508                "spool {} is not loaded on any tool, so there is nothing to unload",
509                spool.name
510            ))));
511        };
512        let source = source_of(command.actor());
513        let mut figures = Figures::default();
514        let mut write = Write::default();
515        if let Some(print_id) = during {
516            write.charges = self
517                .close_segment(print_id, tool, Some(&spool), None, &mut figures, &source)
518                .await?;
519        }
520        write.mutations.push(self.mutation(
521            spool.id,
522            SpoolChange::Unload,
523            during,
524            &source,
525            &SpoolUnloadedPayload {
526                spool_id: spool.id,
527                tool,
528                actor: command.actor().clone(),
529                reason: command.reason().to_owned(),
530            },
531        )?);
532        self.written(spool.id, write).await
533    }
534
535    /// Correct a spool's figure, taking first what its tool holds pending.
536    async fn adjust(
537        &self,
538        command: &SpoolCommand,
539        spool_id: SpoolId,
540        remaining_g: Option<f64>,
541        gross_g: Option<f64>,
542        during: Option<PrintId>,
543    ) -> Result<Result<SpoolCommandOutcome, RejectionReason>, CoreError> {
544        let spool = match self.live_spool(spool_id).await? {
545            Ok(spool) => spool,
546            Err(reason) => return Ok(Err(reason)),
547        };
548        let target = match (remaining_g, gross_g) {
549            (Some(_), Some(_)) | (None, None) => {
550                return Ok(Err(refused(
551                    "a correction names exactly one of remaining_g and gross_g",
552                )));
553            }
554            (Some(remaining), None) => remaining,
555            (None, Some(gross)) => match spool.tare_g {
556                Some(tare) => gross - tare,
557                None => {
558                    return Ok(Err(refused(format!(
559                        "spool {} has no tare, so a scale reading cannot be turned into a \
560                         figure; give remaining_g instead",
561                        spool.name
562                    ))));
563                }
564            },
565        };
566        if !target.is_finite() || gross_g.is_some_and(|gross| !non_negative(gross)) {
567            return Ok(Err(refused("the figure given is not a weight in grams")));
568        }
569        let source = source_of(command.actor());
570        let pending = match spool.loaded_on_tool {
571            Some(tool) => self.stores().filament.pending_charges(Some(tool)).await?,
572            None => Vec::new(),
573        };
574        let mut figures = Figures::default();
575        let (charges, took_pending) = self.take_pending(&pending, &spool, &mut figures, &source)?;
576        let adjusted = SpoolAdjustedPayload {
577            spool_id: spool.id,
578            remaining_before_g: figures.now(&spool),
579            remaining_after_g: target,
580            gross_g,
581            took_pending,
582            cleared_marks: cleared_on(&spool, MarkClearing::Adjusted),
583            actor: command.actor().clone(),
584            reason: command.reason().to_owned(),
585        };
586        let mutation = self.mutation(
587            spool.id,
588            SpoolChange::SetRemaining {
589                remaining_g: target,
590            },
591            during,
592            &source,
593            &adjusted,
594        )?;
595        self.written(
596            spool.id,
597            Write {
598                mutations: vec![mutation],
599                charges,
600            },
601        )
602        .await
603    }
604
605    /// Retire a spool, which takes nothing it fed and refuses every later
606    /// command.
607    async fn retire(
608        &self,
609        command: &SpoolCommand,
610        spool_id: SpoolId,
611        during: Option<PrintId>,
612    ) -> Result<Result<SpoolCommandOutcome, RejectionReason>, CoreError> {
613        let spool = match self.live_spool(spool_id).await? {
614            Ok(spool) => spool,
615            Err(reason) => return Ok(Err(reason)),
616        };
617        let source = source_of(command.actor());
618        let mutation = self.mutation(
619            spool.id,
620            SpoolChange::Retire,
621            during,
622            &source,
623            &SpoolRetiredPayload {
624                spool_id: spool.id,
625                remaining_g: spool.remaining_g,
626                actor: command.actor().clone(),
627                reason: command.reason().to_owned(),
628            },
629        )?;
630        self.written(
631            spool.id,
632            Write {
633                mutations: vec![mutation],
634                charges: Vec::new(),
635            },
636        )
637        .await
638    }
639
640    /// One mutation of one spool, with the event that says it happened.
641    fn mutation<P: printobserver_types::EventPayload>(
642        &self,
643        spool_id: SpoolId,
644        change: SpoolChange,
645        during: Option<PrintId>,
646        source: &EventSource,
647        payload: &P,
648    ) -> Result<SpoolMutation, CoreError> {
649        let event = self.draft_of(during, source.clone(), payload)?;
650        Ok(SpoolMutation {
651            spool_id,
652            change,
653            at: event.received_at,
654            event,
655        })
656    }
657
658    /// Close a tool's open segment of a print for a spool loaded or unloaded
659    /// during it: what the tool fed up to the position read now is charged to
660    /// the spool that was feeding it — or, after an unconfirmed filament
661    /// change, to the spool now loaded, and to nobody when none is.
662    async fn close_segment(
663        &self,
664        print_id: PrintId,
665        tool: i64,
666        outgoing: Option<&SpoolRecord>,
667        incoming: Option<&SpoolRecord>,
668        figures: &mut Figures,
669        source: &EventSource,
670    ) -> Result<Vec<Charge>, CoreError> {
671        let Some(print) = self.stores().prints.print(print_id).await? else {
672            return Ok(Vec::new());
673        };
674        let Some((position, extrusion, analysis)) = self.extrusion_now(&print).await? else {
675            return Ok(Vec::new());
676        };
677        let ledger = self.print_ledger(print_id).await?;
678        let Some(mut feed) = feed_to(print_id, tool, &ledger, &extrusion, &position, &analysis)
679        else {
680            return Ok(Vec::new());
681        };
682        // The spool judged for the open segment: the one feeding the tool, or
683        // — a tool emptied since — the one its last segment was charged to.
684        let judged = match (outgoing, ledger.last_spool(tool)) {
685            (Some(spool), _) => Some(spool.clone()),
686            (None, Some(last)) => self.stores().filament.spool(last).await?,
687            (None, None) => None,
688        };
689        let charged = if judged
690            .as_ref()
691            .is_some_and(|spool| holds_change_mark(spool, print_id))
692        {
693            let Some(incoming) = incoming else {
694                // Unloading the spool an unconfirmed change left takes
695                // nothing: the open segment is still the next spool's.
696                return Ok(Vec::new());
697            };
698            feed.note = Some(match &feed.note {
699                Some(note) => format!("{AFTER_CHANGE}; {note}"),
700                None => AFTER_CHANGE.to_owned(),
701            });
702            Some(incoming)
703        } else {
704            outgoing
705        };
706        Ok(vec![self.charge_of(
707            feed,
708            charged,
709            figures,
710            source.clone(),
711        )?])
712    }
713}