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