Skip to main content

printobserver_core/
store.rs

1//! The persistence interfaces the supervision domain needs, one per aggregate.
2//!
3//! Durable state is this domain's own concern: what it persists — prints,
4//! events, images, actions with the interventions they open, and sessions —
5//! are its own records, so the interfaces it persists them through are
6//! declared here, beside the records, rather than in a crate every consumer of
7//! the store would have to depend on. There is one trait per aggregate rather
8//! than one trait for everything, so that a caller names only the aggregates
9//! it touches and a column one aggregate gains is a change nothing else
10//! rebuilds against:
11//!
12//! * [`PrintStore`] — the print record, its manifest and its narrowings.
13//! * [`EventStore`] — the event log.
14//! * [`ImageStore`] — the images stored beside events.
15//! * [`ActionStore`] — actions, and the bounded interventions they open.
16//! * [`SessionStore`] — the supervision session of a print.
17//! * [`FilamentStore`] — the filament ledger: spools, the charges against them,
18//!   the charges held for a spool not yet named, each print's settlement and
19//!   last file position, and the printer's per-file print tallies.
20//! * [`TimelineStore`] — the printer-wide reading of the event log.
21//!
22//! An implementation implements all seven over one backing, and the composition
23//! root hands each consumer the trait it names: [`Stores`] is one
24//! implementation coerced once per trait, which is what lets a consumer take
25//! `Arc<dyn EventStore>` without knowing which store is behind it.
26//!
27//! # The history read has four behavioural facts, and they are settled here
28//!
29//! A signature carries none of them, and a trait that is structurally exact
30//! with all four unstated is an incomplete interface, so this module leaves an
31//! implementation exactly one answer to take for each rather than leaving them
32//! to whoever implements the trait:
33//!
34//! 1. The **default history window** is [`DEFAULT_HISTORY_WINDOW`].
35//! 2. The **maximum history limit** is [`MAX_HISTORY_LIMIT`], and it is above
36//!    the default.
37//! 3. [`EventStore::history`] answers **newest first**.
38//! 4. An **empty `kinds`** in a [`HistoryQuery`] means **every kind**, not no
39//!    kinds.
40//!
41//! The limit rule has one implementation here too — [`resolve_history_limit`] —
42//! so that refusing rather than clamping is a property of this contract and not
43//! of whoever implemented the trait. There is exactly one exported constant of
44//! each kind and exactly one exported resolution, so a consumer has one thing
45//! to import and no choice to make.
46//!
47//! Whether an implementation obeys the four is proven where the
48//! implementations are, by one conformance suite driving both of them.
49//!
50//! # Minting an identifier
51//!
52//! [`ActionStore::record_action`] is the only method that takes an
53//! [`ActionRequest`] or a [`PolicyDecision`] at all, and it takes them only
54//! together, so this surface offers no way to *ask* for a fresh [`ActionId`]
55//! for a request whose decision was not recorded beside it. Other methods
56//! answer records that may carry an identifier an earlier `record_action`
57//! minted — [`EventStore::append_event`] answers an [`EventRecord`] whose
58//! action-event payloads carry one — and that is stated rather than forbidden.
59//! That no method but `record_action` *mints* one is a property of an
60//! implementation's bodies rather than of a signature, and is established by
61//! the store implementation's own conformance suite.
62//!
63//! # Why the methods answer a boxed future
64//!
65//! Every method is asynchronous, and each trait is dyn-compatible and
66//! shareable across threads, because the supervisor holds every port behind
67//! `Arc<dyn Port>`. An `async fn` in a trait is not dyn-compatible, so each
68//! method answers a [`BoxFuture`] instead.
69
70use core::future::Future;
71use core::pin::Pin;
72use std::path::PathBuf;
73use std::sync::Arc;
74
75use crate::records::{
76    ActionId, ActionRecord, ActionRequest, Actor, ChargeKey, ChargedFilament, ExecutionOutcome,
77    FilePosition, ImageRecord, Intervention, InterventionId, InterventionOutcome, JobManifest,
78    ManifestNarrowing, PendingCharge, PolicyDecision, PrintOutcome, PrintRecord, SpoolId,
79    SpoolRecord, SpoolTrust, UnverifiedReason, UnverifiedReasonKind,
80};
81use printobserver_printer_api::{Adjustable, PrinterState};
82use printobserver_supervisor_api::SupervisionSession;
83use printobserver_types::schemars::JsonSchema;
84use printobserver_types::serde::{Deserialize, Serialize};
85use printobserver_types::{
86    EventBody, EventId, EventKind, EventRecord, EventSource, ImageId, PrintId, RawBytes, Timestamp,
87};
88
89/// A future these traits' methods answer with, in the one shape a trait object
90/// can carry.
91pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
92
93/// How many events a history read answers when the caller asks for no limit.
94///
95/// The one default window this domain declares, and it is below
96/// [`MAX_HISTORY_LIMIT`].
97pub const DEFAULT_HISTORY_WINDOW: u32 = 100;
98
99/// The most events a history read will answer, however many are asked for.
100///
101/// The one maximum this domain declares. A read asking for more is refused
102/// naming this maximum rather than quietly clamped, because a caller that
103/// asked for more and was given fewer cannot tell a short page from the end of
104/// the history.
105pub const MAX_HISTORY_LIMIT: u32 = 1_000;
106
107/// Resolve the limit a history read asks for, refusing one above the maximum.
108///
109/// The one resolution of the limit rule this domain declares: an
110/// implementation calls this rather than deciding for itself. An absent limit
111/// takes [`DEFAULT_HISTORY_WINDOW`]; a limit at or below [`MAX_HISTORY_LIMIT`]
112/// is taken as asked for; one above it is refused.
113///
114/// # Errors
115///
116/// Returns [`StoreError::LimitRefused`], naming the maximum and what was asked
117/// for, when the limit asked for is above [`MAX_HISTORY_LIMIT`].
118pub fn resolve_history_limit(limit: Option<u32>) -> Result<u32, StoreError> {
119    match limit {
120        None => Ok(DEFAULT_HISTORY_WINDOW),
121        Some(asked_for) if asked_for <= MAX_HISTORY_LIMIT => Ok(asked_for),
122        Some(asked_for) => Err(StoreError::LimitRefused {
123            limit: MAX_HISTORY_LIMIT,
124            asked_for,
125        }),
126    }
127}
128
129/// One event on its way into the store, before the store mints its identifier.
130#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
131#[serde(crate = "printobserver_types::serde")]
132#[schemars(crate = "printobserver_types::schemars")]
133pub struct EventDraft {
134    /// The print it belongs to, when it belongs to one.
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub print_id: Option<PrintId>,
137    /// Where it came from.
138    pub source: EventSource,
139    /// When it was received.
140    pub received_at: Timestamp,
141    /// The kind and the payload, flattened into the draft's own fields.
142    #[serde(flatten)]
143    pub body: EventBody,
144    /// The bytes exactly as received, for an externally sourced event.
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub raw: Option<RawBytes>,
147}
148
149impl EventDraft {
150    /// Which event this is.
151    #[must_use]
152    pub const fn kind(&self) -> &EventKind {
153        &self.body.kind
154    }
155}
156
157/// Which of a print's events to read.
158///
159/// An empty `kinds` means every kind rather than no kinds, and an absent
160/// `limit` means [`DEFAULT_HISTORY_WINDOW`].
161#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
162#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
163#[schemars(crate = "printobserver_types::schemars")]
164pub struct HistoryQuery {
165    /// The print to read the history of.
166    pub print_id: PrintId,
167    /// The kinds to read; empty means every kind.
168    pub kinds: Vec<EventKind>,
169    /// The earliest instant to read from, inclusive.
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    pub since: Option<Timestamp>,
172    /// The latest instant to read to, inclusive.
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub until: Option<Timestamp>,
175    /// How many events to answer; absent means [`DEFAULT_HISTORY_WINDOW`].
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub limit: Option<u32>,
178}
179
180impl HistoryQuery {
181    /// The limit this query resolves to.
182    ///
183    /// # Errors
184    ///
185    /// Returns [`StoreError::LimitRefused`] when the limit asked for is above
186    /// [`MAX_HISTORY_LIMIT`].
187    pub fn resolved_limit(&self) -> Result<u32, StoreError> {
188        resolve_history_limit(self.limit)
189    }
190}
191
192/// One read of the event log in the order the store stored it.
193///
194/// The order is the store's own sequence rather than any field of the
195/// record: `received_at` is the instant its producer stamped, which a late
196/// arrival can carry from before an event stored ahead of it, so a reader
197/// following the log by it would skip what arrived late. Identifiers are not
198/// that order either, because they are minted by whoever appended them.
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct StoredQuery {
201    /// The event to read after, exclusive. Absent with a print, the read
202    /// starts at that print's first event; absent without one, at the first
203    /// event stored.
204    pub after: Option<EventId>,
205    /// The print to scope to: its own events and every event that belongs to
206    /// no print. Absent, every event.
207    pub print_id: Option<PrintId>,
208    /// How many events to answer; absent means [`DEFAULT_HISTORY_WINDOW`].
209    pub limit: Option<u32>,
210}
211
212impl StoredQuery {
213    /// The limit this query resolves to.
214    ///
215    /// # Errors
216    ///
217    /// Returns [`StoreError::LimitRefused`] when the limit asked for is above
218    /// [`MAX_HISTORY_LIMIT`].
219    pub fn resolved_limit(&self) -> Result<u32, StoreError> {
220        resolve_history_limit(self.limit)
221    }
222}
223
224/// What a store calls after every write that stored an event has committed.
225///
226/// Raised after the commit rather than before it, so a reader woken by it reads
227/// what woke it; and raised for every write that stored one, whichever
228/// aggregate's method made it. It carries nothing: what was stored is read
229/// back through [`EventStore::stored_after`].
230pub type StoredSignal = Arc<dyn Fn() + Send + Sync>;
231
232/// What the store found when asked for an image.
233///
234/// The record and the bytes are two facts rather than one: a record whose file
235/// has gone is a distinguishable answer rather than an error, because it is
236/// the answer that tells a caller the history is intact and the file is not.
237#[derive(Debug, Clone, PartialEq, Eq)]
238pub enum ImageLookup {
239    /// The record, and the absolute path its bytes are at.
240    Found {
241        /// The record.
242        record: ImageRecord,
243        /// Where its bytes are, resolved against the state directory.
244        path: PathBuf,
245    },
246    /// The record, whose file is not where the record says it is.
247    FileMissing {
248        /// The record.
249        record: ImageRecord,
250    },
251}
252
253/// What settling an intervention did.
254#[derive(Debug, Clone, PartialEq)]
255pub enum SettleOutcome {
256    /// This call settled it, and here it is.
257    Settled {
258        /// The intervention as it now stands.
259        intervention: Intervention,
260    },
261    /// It was already settled, and this is the outcome that won.
262    AlreadySettled {
263        /// The outcome that was already recorded.
264        outcome: InterventionOutcome,
265    },
266}
267
268/// One page of a print's whole history, and the cursor that follows it.
269///
270/// The exhaustive read of a print's history is [`EventStore::audit_page`]
271/// walked to exhaustion; there is no method that answers a whole history in one
272/// response, which is what makes an unbounded answer something a caller cannot
273/// ask for by accident.
274#[derive(Debug, Clone, PartialEq)]
275pub struct AuditPage {
276    /// This page's events.
277    pub events: Vec<EventRecord>,
278    /// The cursor the next page follows, or absent at the end of the history.
279    pub next: Option<EventId>,
280}
281
282/// Why the store did not do what it was asked.
283#[derive(Debug, Clone, PartialEq, Eq)]
284pub enum StoreError {
285    /// A constraint refused the write.
286    ConstraintRefused {
287        /// The constraint that refused it.
288        constraint: String,
289    },
290    /// There is no such record.
291    NotFound {
292        /// What was looked for.
293        what: String,
294    },
295    /// More was asked for than a limit allows.
296    LimitRefused {
297        /// The limit.
298        limit: u32,
299        /// What was asked for.
300        asked_for: u32,
301    },
302    /// The database failed.
303    Database {
304        /// What went wrong.
305        detail: String,
306    },
307    /// Reading or writing a file failed.
308    Io {
309        /// What went wrong.
310        detail: String,
311    },
312}
313
314impl core::fmt::Display for StoreError {
315    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
316        match self {
317            Self::ConstraintRefused { constraint } => {
318                write!(formatter, "the constraint {constraint} refused the write")
319            }
320            Self::NotFound { what } => write!(formatter, "there is no {what}"),
321            Self::LimitRefused { limit, asked_for } => {
322                write!(
323                    formatter,
324                    "{asked_for} was asked for, and the limit is {limit}"
325                )
326            }
327            Self::Database { detail } => write!(formatter, "the database failed: {detail}"),
328            Self::Io { detail } => write!(formatter, "reading or writing failed: {detail}"),
329        }
330    }
331}
332
333impl core::error::Error for StoreError {}
334
335/// The print record, with its manifest and the narrowings recorded on it.
336///
337/// Every method is asynchronous, the trait is dyn-compatible, and it is
338/// shareable across threads, because its consumers hold it behind
339/// `Arc<dyn PrintStore>`.
340pub trait PrintStore: Send + Sync {
341    /// Open a print, minting its identifier.
342    fn open_print(
343        &self,
344        provider_print_id: Option<i64>,
345        file_name: Option<String>,
346    ) -> BoxFuture<'_, Result<PrintRecord, StoreError>>;
347
348    /// Read one print by its identifier.
349    fn print(&self, print_id: PrintId) -> BoxFuture<'_, Result<Option<PrintRecord>, StoreError>>;
350
351    /// Read every print with no end recorded, most recently opened first.
352    ///
353    /// This is what a supervisor adopts on start: the store already binds an
354    /// action to the most recently opened print with no end recorded, and
355    /// without this method nothing above the store could name that print in
356    /// order to say it had adopted it.
357    fn open_prints(&self) -> BoxFuture<'_, Result<Vec<PrintRecord>, StoreError>>;
358
359    /// Read every print, ended or not, most recently opened first.
360    ///
361    /// This is what a caller finds a print's identifier in: the identifier is
362    /// minted here, and nothing outside the store could otherwise name it.
363    fn prints(&self) -> BoxFuture<'_, Result<Vec<PrintRecord>, StoreError>>;
364
365    /// Record `Obico`'s own identifier on a print that carries none.
366    ///
367    /// A print is opened before `Obico` reports on it when a caller finds the
368    /// job the printer is running, and this is how the first alert about that
369    /// job joins the print already open for it rather than opening a second.
370    /// Recording the identifier a print already carries answers the print
371    /// unchanged.
372    ///
373    /// # Errors
374    ///
375    /// Refuses a print that does not exist with [`StoreError::NotFound`], and a
376    /// print already carrying a different identifier with
377    /// [`StoreError::ConstraintRefused`] naming `prints.provider_print_id`: a
378    /// correlation, once recorded, is never moved to another of the provider's
379    /// prints.
380    fn attach_obico_print(
381        &self,
382        print_id: PrintId,
383        obico_print_id: i64,
384    ) -> BoxFuture<'_, Result<PrintRecord, StoreError>>;
385
386    /// Record what one read of the printer saw of a print's job.
387    ///
388    /// The job's start is set to `job_started_at` whatever it was, since a
389    /// pause moves it ([`PrintRecord::job_started_at`]); the print's running
390    /// time is raised to `job_print_time_s` when that is longer than the one it
391    /// carries and left alone otherwise, so that the longest the job was ever
392    /// seen printing is what it carries. Absent `job_print_time_s` — a read
393    /// that found the job paused — leaves the running time as it is.
394    ///
395    /// # Errors
396    ///
397    /// Refuses a print that does not exist with [`StoreError::NotFound`].
398    fn record_job_sighting(
399        &self,
400        print_id: PrintId,
401        job_started_at: Timestamp,
402        job_print_time_s: Option<i64>,
403    ) -> BoxFuture<'_, Result<PrintRecord, StoreError>>;
404
405    /// Read one print by the provider's own identifier for it.
406    fn print_by_provider_id(
407        &self,
408        provider_print_id: i64,
409    ) -> BoxFuture<'_, Result<Option<PrintRecord>, StoreError>>;
410
411    /// End a print, in a terminal state, at an instant, for a reason.
412    fn end_print(
413        &self,
414        print_id: PrintId,
415        state: PrinterState,
416        ended_at: Timestamp,
417        reason: String,
418    ) -> BoxFuture<'_, Result<PrintRecord, StoreError>>;
419
420    /// Record that a manifest range was narrowed to the envelope's.
421    fn record_narrowing(
422        &self,
423        print_id: PrintId,
424        narrowing: ManifestNarrowing,
425    ) -> BoxFuture<'_, Result<PrintRecord, StoreError>>;
426
427    /// Store one print's manifest.
428    fn put_manifest(
429        &self,
430        print_id: PrintId,
431        manifest: JobManifest,
432    ) -> BoxFuture<'_, Result<(), StoreError>>;
433
434    /// Read one print's manifest.
435    fn manifest(&self, print_id: PrintId)
436    -> BoxFuture<'_, Result<Option<JobManifest>, StoreError>>;
437}
438
439/// The event log.
440///
441/// Every method is asynchronous, the trait is dyn-compatible, and it is
442/// shareable across threads, because its consumers hold it behind
443/// `Arc<dyn EventStore>`.
444pub trait EventStore: Send + Sync {
445    /// Append one event, minting its identifier.
446    fn append_event(&self, draft: EventDraft) -> BoxFuture<'_, Result<EventRecord, StoreError>>;
447
448    /// Read a print's events, newest first.
449    ///
450    /// Answers **newest first**. An empty `kinds` means **every kind** rather
451    /// than no kinds. An absent `limit` takes [`DEFAULT_HISTORY_WINDOW`], and a
452    /// limit above [`MAX_HISTORY_LIMIT`] is refused rather than clamped —
453    /// [`resolve_history_limit`] is the one resolution of that rule.
454    fn history(&self, query: HistoryQuery) -> BoxFuture<'_, Result<Vec<EventRecord>, StoreError>>;
455
456    /// Read one page of a print's whole history, oldest first.
457    ///
458    /// `after` is the identifier of the last event of the previous page, and is
459    /// absent for the first page. The page size is resolved by
460    /// [`resolve_history_limit`] like a history read's limit, so a page above
461    /// [`MAX_HISTORY_LIMIT`] is refused rather than clamped.
462    fn audit_page(
463        &self,
464        print_id: PrintId,
465        after: Option<EventId>,
466        page_size: u32,
467    ) -> BoxFuture<'_, Result<AuditPage, StoreError>>;
468
469    /// Read the events stored after a point, in the order they were stored.
470    ///
471    /// Answers **oldest first by the store's own sequence** — the order the
472    /// events were appended in, whatever their `received_at` — scoped as
473    /// [`StoredQuery`] says. A print with no event yet starts after the newest
474    /// event stored. The limit is resolved by [`resolve_history_limit`].
475    ///
476    /// # Errors
477    ///
478    /// Refuses a cursor naming no event with [`StoreError::NotFound`], and a
479    /// limit above [`MAX_HISTORY_LIMIT`] with [`StoreError::LimitRefused`].
480    fn stored_after(
481        &self,
482        query: StoredQuery,
483    ) -> BoxFuture<'_, Result<Vec<EventRecord>, StoreError>>;
484
485    /// The newest event stored, by the store's own sequence, when there is one.
486    fn newest_stored(&self) -> BoxFuture<'_, Result<Option<EventId>, StoreError>>;
487
488    /// Raise this signal after every write that stores an event has committed,
489    /// from now on.
490    fn on_stored(&self, signal: StoredSignal);
491}
492
493/// The images stored beside events.
494///
495/// Every method is asynchronous, the trait is dyn-compatible, and it is
496/// shareable across threads, because its consumers hold it behind
497/// `Arc<dyn ImageStore>`.
498pub trait ImageStore: Send + Sync {
499    /// Store one image's bytes, minting its identifier.
500    fn put_image(
501        &self,
502        print_id: PrintId,
503        event_id: EventId,
504        source_url: Option<String>,
505        content_type: String,
506        bytes: RawBytes,
507    ) -> BoxFuture<'_, Result<ImageRecord, StoreError>>;
508
509    /// Read one image by its identifier.
510    fn image(&self, image_id: ImageId) -> BoxFuture<'_, Result<ImageLookup, StoreError>>;
511}
512
513/// Actions, and the bounded interventions they open.
514///
515/// Every method is asynchronous, the trait is dyn-compatible, and it is
516/// shareable across threads, because its consumers hold it behind
517/// `Arc<dyn ActionStore>`.
518pub trait ActionStore: Send + Sync {
519    /// Record one request together with the decision taken on it.
520    ///
521    /// This is the only method that takes either half, and it takes them only
522    /// together; the [`ActionId`] it answers is minted for the pair.
523    fn record_action(
524        &self,
525        request: ActionRequest,
526        decision: PolicyDecision,
527    ) -> BoxFuture<'_, Result<ActionRecord, StoreError>>;
528
529    /// Record what the printer made of an action that reached it.
530    fn record_execution(
531        &self,
532        action_id: ActionId,
533        outcome: ExecutionOutcome,
534    ) -> BoxFuture<'_, Result<ActionRecord, StoreError>>;
535
536    /// Open a bounded intervention, minting its identifier.
537    ///
538    /// The print is the one the action was recorded against, so that a caller
539    /// cannot name a print the action does not belong to.
540    fn open_intervention(
541        &self,
542        action_id: ActionId,
543        adjustable: Adjustable,
544        prior_value: Option<f64>,
545        applied_value: f64,
546        applied_at: Timestamp,
547        expires_at: Timestamp,
548    ) -> BoxFuture<'_, Result<Intervention, StoreError>>;
549
550    /// Settle one intervention, or report the outcome that already won.
551    fn settle_intervention(
552        &self,
553        intervention_id: InterventionId,
554        outcome: InterventionOutcome,
555    ) -> BoxFuture<'_, Result<SettleOutcome, StoreError>>;
556
557    /// Read every intervention due to expire at or before an instant.
558    fn due_interventions(
559        &self,
560        at: Timestamp,
561    ) -> BoxFuture<'_, Result<Vec<Intervention>, StoreError>>;
562
563    /// Read every intervention still active on one print.
564    fn active_interventions(
565        &self,
566        print_id: PrintId,
567    ) -> BoxFuture<'_, Result<Vec<Intervention>, StoreError>>;
568}
569
570/// The supervision session of a print.
571///
572/// Every method is asynchronous, the trait is dyn-compatible, and it is
573/// shareable across threads, because its consumers hold it behind
574/// `Arc<dyn SessionStore>`.
575pub trait SessionStore: Send + Sync {
576    /// Store one print's supervision session.
577    fn put_session(&self, session: SupervisionSession) -> BoxFuture<'_, Result<(), StoreError>>;
578
579    /// Read one print's supervision session.
580    fn session(
581        &self,
582        print_id: PrintId,
583    ) -> BoxFuture<'_, Result<Option<SupervisionSession>, StoreError>>;
584}
585
586/// A spool on its way into the store, before the store mints its identifier.
587///
588/// A [`SpoolRecord`] without what the store sets itself: its `id`, minted; and
589/// its `updated_at`, which is `registered_at`. It is shelved, or loaded on a
590/// tool, and never retired.
591#[derive(Debug, Clone, PartialEq)]
592pub struct NewSpool {
593    /// The operator's own label for the spool.
594    pub name: String,
595    /// The material, such as `PLA`.
596    pub material: String,
597    /// The filament's colour, when the operator gave one.
598    pub color: Option<String>,
599    /// The filament's diameter, in millimetres.
600    pub diameter_mm: f64,
601    /// The material's density, in grams per cubic centimetre.
602    pub density_g_cm3: f64,
603    /// The net filament on the spool when it was full, in grams.
604    pub initial_g: f64,
605    /// The filament left, in grams.
606    pub remaining_g: f64,
607    /// The empty spool's own weight, in grams, when the operator gave it.
608    pub tare_g: Option<f64>,
609    /// The tool the spool is loaded on, when it is registered loaded.
610    pub loaded_on_tool: Option<i64>,
611    /// How far the remaining figure can be trusted.
612    pub trust: SpoolTrust,
613    /// When the spool was registered.
614    pub registered_at: Timestamp,
615}
616
617/// Whose debit a charge is: its key, which names the tool and — for a print
618/// this system watched — the print, and for a print it never saw, the print
619/// it recorded that one as, when one is linked.
620///
621/// The fields are private, so a watched print's charge cannot carry a second
622/// print beside the one its key names.
623#[derive(Debug, Clone, PartialEq, Eq)]
624pub struct ChargeIdentity {
625    /// The durable identity of the debit.
626    key: ChargeKey,
627    /// For an unobserved print only, the print this system recorded it as.
628    linked_print: Option<PrintId>,
629}
630
631impl ChargeIdentity {
632    /// The identity a key alone gives: a watched print's own, or an unobserved
633    /// print linked to none.
634    #[must_use]
635    pub const fn of(key: ChargeKey) -> Self {
636        Self {
637            key,
638            linked_print: None,
639        }
640    }
641
642    /// An unobserved print's identity, linked to the print this system
643    /// recorded it as.
644    ///
645    /// # Errors
646    ///
647    /// Answers the key back for a watched print's key, whose print is the one
648    /// it names and no other.
649    pub const fn linked(key: ChargeKey, print_id: PrintId) -> Result<Self, ChargeKey> {
650        match key {
651            ChargeKey::Print { .. } => Err(key),
652            ChargeKey::Unobserved { .. } => Ok(Self {
653                key,
654                linked_print: Some(print_id),
655            }),
656        }
657    }
658
659    /// The durable identity of the debit.
660    #[must_use]
661    pub const fn key(&self) -> &ChargeKey {
662        &self.key
663    }
664
665    /// The tool that fed the filament, as the key names it.
666    #[must_use]
667    pub const fn tool(&self) -> i64 {
668        self.key.tool()
669    }
670
671    /// The print the filament was fed in, when it was one this system
672    /// recorded: the one a watched key names, or the one an unobserved print
673    /// is linked to.
674    #[must_use]
675    pub const fn print_id(&self) -> Option<PrintId> {
676        match self.key.watched_print() {
677            Some(print_id) => Some(print_id),
678            None => self.linked_print,
679        }
680    }
681}
682
683/// One debit on its way into the store.
684#[derive(Debug, Clone, PartialEq)]
685pub struct Charge {
686    /// Whose debit it is, from which its tool and print are read.
687    pub identity: ChargeIdentity,
688    /// How much was fed, in millimetres.
689    pub length_mm: f64,
690    /// The spool charged and the whole calculation of what is subtracted from
691    /// it; absent when nothing was tracked on the tool, and the filament is
692    /// recorded uncharged.
693    pub charged: Option<ChargedFilament>,
694    /// When the charge was taken.
695    pub at: Timestamp,
696    /// Its `filament_consumed` event.
697    pub event: EventDraft,
698}
699
700/// What the store holds of one debit.
701#[derive(Debug, Clone, PartialEq)]
702pub struct ChargeRecord {
703    /// Whose debit it is, from which its tool and print are read.
704    pub identity: ChargeIdentity,
705    /// How much was fed, in millimetres.
706    pub length_mm: f64,
707    /// The spool charged and the whole calculation of what was subtracted;
708    /// absent when the filament was recorded uncharged.
709    pub charged: Option<ChargedFilament>,
710    /// When the charge was taken.
711    pub at: Timestamp,
712    /// Its `filament_consumed` event.
713    pub event_id: EventId,
714}
715
716impl ChargeRecord {
717    /// The spool charged, when one was.
718    #[must_use]
719    pub fn spool_id(&self) -> Option<SpoolId> {
720        self.charged.as_ref().map(|charged| charged.spool_id)
721    }
722}
723
724/// A charge held for a spool not yet named, on its way into the store.
725#[derive(Debug, Clone, PartialEq)]
726pub struct Pend {
727    /// What is held.
728    pub pending: PendingCharge,
729    /// Its `charge_pended` event.
730    pub event: EventDraft,
731}
732
733/// One change to one spool, on its way into the store.
734#[derive(Debug, Clone, PartialEq)]
735pub struct SpoolMutation {
736    /// The spool changed.
737    pub spool_id: SpoolId,
738    /// What changes, carrying the event it writes when it writes one.
739    pub change: SpoolChange,
740    /// When it changed; the spool's `updated_at` once it has.
741    pub at: Timestamp,
742}
743
744/// What one [`SpoolMutation`] changes, each change that writes an event
745/// carrying it and the one that writes none carrying none.
746#[derive(Debug, Clone, PartialEq)]
747pub enum SpoolChange {
748    /// Put the spool on a tool.
749    Load {
750        /// The tool, in the printer's own numbering.
751        tool: i64,
752        /// Its `spool_loaded` event.
753        event: EventDraft,
754    },
755    /// Take the spool off its tool.
756    Unload {
757        /// Its `spool_unloaded` event.
758        event: EventDraft,
759    },
760    /// Set the spool's remaining figure, which clears every mark: the spool
761    /// reads `verified` after it.
762    SetRemaining {
763        /// The filament left, in grams.
764        remaining_g: f64,
765        /// Its `spool_adjusted` event.
766        event: EventDraft,
767    },
768    /// Add one mark, by [`SpoolTrust::marked`], at the mutation's instant.
769    ///
770    /// A reason the spool already holds changes nothing, so it is a no-op: the
771    /// spool is not written and its `event` is not appended, which is how a
772    /// second signal of one change writes no second `spool_unverified`.
773    MarkUnverified {
774        /// Why the figure is in doubt.
775        reason: UnverifiedReason,
776        /// Its `spool_unverified` event, appended only when the mark is new.
777        event: EventDraft,
778    },
779    /// Remove every mark of these kinds, by [`SpoolTrust::cleared`]. The
780    /// domain chooses the kinds through
781    /// [`marks_cleared_by`](crate::filament::marks_cleared_by), and the marks
782    /// cleared are named in the command's own event, so this change carries
783    /// and writes no event of its own.
784    ClearMarks {
785        /// The kinds of mark removed.
786        kinds: Vec<UnverifiedReasonKind>,
787    },
788    /// Retire the spool, which takes it off any tool it is loaded on.
789    Retire {
790        /// Its `spool_retired` event.
791        event: EventDraft,
792    },
793}
794
795/// What one [`FilamentStore::apply_spool_changes`] wrote.
796#[derive(Debug, Clone, PartialEq)]
797pub struct SpoolWrite {
798    /// Every spool a charge or a mutation named, as the write left it, once
799    /// each, in the order it was first named.
800    pub spools: Vec<SpoolRecord>,
801    /// Every event the write appended, in the order it appended them.
802    pub events: Vec<EventRecord>,
803    /// One record per charge submitted, in the order submitted: the one this
804    /// write recorded, or, for a replay, the one already recorded.
805    pub charges: Vec<ChargeRecord>,
806    /// Every charge this write held; a replayed pend is not among them.
807    pub pending: Vec<PendingCharge>,
808}
809
810/// What settling a print did.
811#[derive(Debug, Clone, PartialEq)]
812pub enum Settlement {
813    /// This call settled it.
814    Settled {
815        /// When it was settled: its `print_ended` event's instant.
816        at: Timestamp,
817        /// Every event the settlement appended, in the order it appended them,
818        /// its `print_ended` event last.
819        events: Vec<EventRecord>,
820    },
821    /// It was already settled, and this call wrote nothing.
822    AlreadySettled {
823        /// When it was settled.
824        at: Timestamp,
825        /// The outcome it was settled with.
826        outcome: PrintOutcome,
827    },
828}
829
830/// The printer's own count of the prints of one file, as last accounted.
831#[derive(Debug, Clone, PartialEq, Eq)]
832pub struct FileTally {
833    /// The file.
834    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
835    pub file_name: String,
836    /// Where the file lives, in the printer's own vocabulary.
837    pub origin: String,
838    /// The tally generation, which starts at 0 and only ever advances: it
839    /// advances each time the printer's tally for the file is reset.
840    pub generation: u32,
841    /// The completed prints the tally counts.
842    pub successes: i64,
843    /// The failed prints the tally counts.
844    pub failures: i64,
845    /// When the tally was read.
846    pub observed_at: Timestamp,
847}
848
849/// Which timeline events to read.
850///
851/// An empty `kinds` means every kind of
852/// [`TIMELINE_KINDS`](crate::kinds::TIMELINE_KINDS), and an absent `limit`
853/// means [`DEFAULT_HISTORY_WINDOW`].
854#[derive(Debug, Clone, PartialEq, Eq)]
855pub struct TimelineQuery {
856    /// The kinds to read; empty means every timeline kind, and a kind outside
857    /// the timeline is refused.
858    pub kinds: Vec<EventKind>,
859    /// The earliest instant to read from, inclusive.
860    pub since: Option<Timestamp>,
861    /// The latest instant to read to, inclusive.
862    pub until: Option<Timestamp>,
863    /// Only events whose payload names this spool.
864    pub spool_id: Option<SpoolId>,
865    /// The cursor: only events strictly older than this one.
866    pub before: Option<EventId>,
867    /// How many events to answer; absent means [`DEFAULT_HISTORY_WINDOW`].
868    pub limit: Option<u32>,
869}
870
871impl TimelineQuery {
872    /// The limit this query resolves to.
873    ///
874    /// # Errors
875    ///
876    /// Returns [`StoreError::LimitRefused`] when the limit asked for is above
877    /// [`MAX_HISTORY_LIMIT`].
878    pub fn resolved_limit(&self) -> Result<u32, StoreError> {
879        resolve_history_limit(self.limit)
880    }
881
882    /// The kinds this query reads: those asked for, or every timeline kind.
883    ///
884    /// # Errors
885    ///
886    /// Returns [`StoreError::ConstraintRefused`] naming `timeline.kinds` when a
887    /// kind asked for is not one of
888    /// [`TIMELINE_KINDS`](crate::kinds::TIMELINE_KINDS).
889    pub fn resolved_kinds(&self) -> Result<Vec<EventKind>, StoreError> {
890        let refused = || StoreError::ConstraintRefused {
891            constraint: "timeline.kinds".to_owned(),
892        };
893        if self.kinds.is_empty() {
894            return crate::kinds::TIMELINE_KINDS
895                .iter()
896                .map(|kind| EventKind::new(*kind).map_err(|_| refused()))
897                .collect();
898        }
899        if self
900            .kinds
901            .iter()
902            .any(|kind| !crate::kinds::TIMELINE_KINDS.contains(&kind.as_str()))
903        {
904            return Err(refused());
905        }
906        Ok(self.kinds.clone())
907    }
908}
909
910/// The filament ledger: spools, the charges against them, the charges held for
911/// a spool not yet named, each print's settlement and last file position, and
912/// the printer's per-file print tallies.
913///
914/// # Every write is one transaction
915///
916/// Each writing method writes everything it was given and every event that
917/// goes with it, or — when any part is refused — none of it: a crash or a
918/// refusal halfway leaves the ledger as it was before the call.
919///
920/// # A charge is debited exactly once
921///
922/// A charge is keyed by its [`ChargeKey`], stored under
923/// [`ChargeKey::canonical`]. Wherever a charge is submitted —
924/// [`apply_spool_changes`](Self::apply_spool_changes),
925/// [`settle_print`](Self::settle_print) or
926/// [`account_tallies`](Self::account_tallies) — the same rules hold:
927///
928/// * A charge whose key is **not yet recorded** subtracts its charged grams
929///   from its spool — a retired spool included, since retirement refuses later commands
930///   rather than the settlement of earlier prints, and below zero included,
931///   since a charge is never refused or clamped — records the charge, and
932///   appends its event. The spool's `updated_at` becomes the later of its own
933///   and the charge's instant. A charge naming no spool subtracts nothing and
934///   is still recorded.
935/// * A charge whose key is **already recorded** is a replay: it subtracts
936///   nothing and appends no event.
937/// * A charge whose key is **pending** takes it: the pending charge is removed
938///   in the same transaction that records the charge, so it is debited once.
939///
940/// A pend is held the same way: one whose key is already pending or already
941/// charged is a replay and writes nothing; otherwise it is held and its event
942/// appended.
943///
944/// Within one call, the charges are applied first, in the order given, then
945/// the pends, then the mutations — so a correction sets its figure after any
946/// pending charge the same command took.
947///
948/// # A spool change, and what refuses one
949///
950/// A mutation applies its [`SpoolChange`], sets the spool's `updated_at` to its
951/// instant, and appends the event the change carries — a `clear_marks` carries
952/// none, and a `mark_unverified` the spool already holds is a no-op that
953/// appends nothing. The trust functions are the contract's,
954/// [`SpoolTrust::marked`] and [`SpoolTrust::cleared`], and no implementation
955/// restates them. Every refusal is the whole call's:
956///
957/// * [`StoreError::NotFound`] for a spool that does not exist.
958/// * [`StoreError::ConstraintRefused`] naming `spools.loaded_on_tool` for a
959///   load onto a tool another unretired spool holds. A swap is two mutations
960///   in one call, the unload and then the load.
961/// * [`StoreError::ConstraintRefused`] naming `spools.retired_at` for a load,
962///   an unload, a `set_remaining`, a `clear_marks` or a `retire` of a retired
963///   spool. A `mark_unverified` still applies to one, because a settlement
964///   marks the spool that fed the print whatever has happened to it since.
965///
966/// Every method is asynchronous, the trait is dyn-compatible, and it is
967/// shareable across threads, because its consumers hold it behind
968/// `Arc<dyn FilamentStore>`.
969pub trait FilamentStore: Send + Sync {
970    /// Register a spool, minting its identifier.
971    ///
972    /// In one transaction, writes the spool and a `spool_registered` event —
973    /// with no print, from `source`, received at the spool's `registered_at` —
974    /// whose payload carries the record as written, `actor` and `reason`.
975    ///
976    /// # Errors
977    ///
978    /// Refuses a spool registered loaded onto a tool another unretired spool
979    /// holds with [`StoreError::ConstraintRefused`] naming
980    /// `spools.loaded_on_tool`.
981    fn register_spool(
982        &self,
983        spool: NewSpool,
984        source: EventSource,
985        actor: Actor,
986        reason: String,
987    ) -> BoxFuture<'_, Result<(SpoolRecord, EventRecord), StoreError>>;
988
989    /// Apply spool mutations, charges and pends, with their events, in one
990    /// transaction — all of them or none.
991    ///
992    /// # Errors
993    ///
994    /// Refuses the whole call as the trait's own documentation states.
995    fn apply_spool_changes(
996        &self,
997        changes: Vec<SpoolMutation>,
998        charges: Vec<Charge>,
999        pends: Vec<Pend>,
1000    ) -> BoxFuture<'_, Result<SpoolWrite, StoreError>>;
1001
1002    /// Settle a print, once.
1003    ///
1004    /// In one transaction: the print's remaining charges and its pends, under
1005    /// the replay rules, with their events; the `mark_unverified` mutations in
1006    /// `marks`, applied by the rules every mutation is, with their events; the
1007    /// `ended` event, which is the print's `print_ended`; and the print's
1008    /// settlement, at that event's instant, with `outcome`. A print already
1009    /// settled is answered [`Settlement::AlreadySettled`] and nothing is
1010    /// written.
1011    ///
1012    /// It does not end the print record: the domain calls
1013    /// [`PrintStore::end_print`] after it, so a crash between the two leaves a
1014    /// settled, open print that the next close-out only ends.
1015    ///
1016    /// # Errors
1017    ///
1018    /// Refuses a print that does not exist with [`StoreError::NotFound`], and
1019    /// otherwise as the trait's own documentation states.
1020    fn settle_print(
1021        &self,
1022        print_id: PrintId,
1023        outcome: PrintOutcome,
1024        ended: EventDraft,
1025        charges: Vec<Charge>,
1026        pends: Vec<Pend>,
1027        marks: Vec<SpoolMutation>,
1028    ) -> BoxFuture<'_, Result<Settlement, StoreError>>;
1029
1030    /// When a print was settled, and with which outcome, when it has been.
1031    fn print_settlement(
1032        &self,
1033        print_id: PrintId,
1034    ) -> BoxFuture<'_, Result<Option<(Timestamp, PrintOutcome)>, StoreError>>;
1035
1036    /// Every charge recorded against a print, by tool and then by segment.
1037    ///
1038    /// This is how a later segment is charged only the remainder after a
1039    /// restart.
1040    fn charges(&self, print_id: PrintId) -> BoxFuture<'_, Result<Vec<ChargeRecord>, StoreError>>;
1041
1042    /// Every charge still pending — on one tool, when one is named — oldest
1043    /// first.
1044    fn pending_charges(
1045        &self,
1046        tool: Option<i64>,
1047    ) -> BoxFuture<'_, Result<Vec<PendingCharge>, StoreError>>;
1048
1049    /// Read one spool.
1050    fn spool(&self, id: SpoolId) -> BoxFuture<'_, Result<Option<SpoolRecord>, StoreError>>;
1051
1052    /// Read every spool — retired ones only when asked for — most recently
1053    /// registered first.
1054    fn spools(&self, include_retired: bool) -> BoxFuture<'_, Result<Vec<SpoolRecord>, StoreError>>;
1055
1056    /// Read every unretired spool loaded on a tool, by tool.
1057    fn loaded_spools(&self) -> BoxFuture<'_, Result<Vec<SpoolRecord>, StoreError>>;
1058
1059    /// Record how far into its file a print had got.
1060    ///
1061    /// Keeps the latest by `observed_at`: a position observed before the one
1062    /// held is not recorded.
1063    ///
1064    /// # Errors
1065    ///
1066    /// Refuses a print that does not exist with [`StoreError::NotFound`].
1067    fn record_file_position(
1068        &self,
1069        print_id: PrintId,
1070        position: FilePosition,
1071    ) -> BoxFuture<'_, Result<(), StoreError>>;
1072
1073    /// The latest file position recorded for a print.
1074    fn file_position(
1075        &self,
1076        print_id: PrintId,
1077    ) -> BoxFuture<'_, Result<Option<FilePosition>, StoreError>>;
1078
1079    /// Every file's tally as last accounted, by file name and then origin.
1080    fn file_tallies(&self) -> BoxFuture<'_, Result<Vec<FileTally>, StoreError>>;
1081
1082    /// Account the prints the printer's tallies counted and this system never
1083    /// saw, in one transaction.
1084    ///
1085    /// Their charges, under the replay rules; their `mark_unverified`
1086    /// mutations, applied by the rules every mutation is; their
1087    /// `unaccounted_print` and `file_tally_rebaselined` events; and the
1088    /// advanced tallies, each stored by file name and origin over whatever was
1089    /// held — so a crash leaves either none of it or all of it. Answers every
1090    /// event it appended, in the order it appended them.
1091    ///
1092    /// # Errors
1093    ///
1094    /// Refuses a tally whose generation is below the one held for its file
1095    /// with [`StoreError::ConstraintRefused`] naming `file_tallies.generation`,
1096    /// and otherwise as the trait's own documentation states.
1097    fn account_tallies(
1098        &self,
1099        tallies: Vec<FileTally>,
1100        charges: Vec<Charge>,
1101        marks: Vec<SpoolMutation>,
1102        events: Vec<EventDraft>,
1103    ) -> BoxFuture<'_, Result<Vec<EventRecord>, StoreError>>;
1104}
1105
1106/// The printer-wide reading of the event log.
1107///
1108/// Every method is asynchronous, the trait is dyn-compatible, and it is
1109/// shareable across threads, because its consumers hold it behind
1110/// `Arc<dyn TimelineStore>`.
1111pub trait TimelineStore: Send + Sync {
1112    /// Read the events of the printer timeline, across every print and none.
1113    ///
1114    /// Answers only events of [`TIMELINE_KINDS`](crate::kinds::TIMELINE_KINDS),
1115    /// **newest first** by `(received_at, id)`. An empty `kinds` means every
1116    /// timeline kind; `since` and `until` are inclusive; `spool_id` keeps only
1117    /// events whose payload names that spool — carries its identifier as a
1118    /// string value anywhere in it; and `before` keeps only events strictly
1119    /// older than that event. The limit is resolved by
1120    /// [`resolve_history_limit`].
1121    ///
1122    /// # Errors
1123    ///
1124    /// Refuses a kind outside the timeline with
1125    /// [`StoreError::ConstraintRefused`] naming `timeline.kinds`, a limit above
1126    /// [`MAX_HISTORY_LIMIT`] with [`StoreError::LimitRefused`], and a cursor
1127    /// naming no event with [`StoreError::NotFound`].
1128    fn timeline(&self, query: TimelineQuery)
1129    -> BoxFuture<'_, Result<Vec<EventRecord>, StoreError>>;
1130}
1131
1132/// One store implementation, held once per aggregate it persists.
1133///
1134/// The composition root builds this from the one implementation it chose, by
1135/// [`Stores::of`], and each consumer takes the handle for the aggregate it
1136/// names: seven shared handles to one backing rather than seven backings. A
1137/// consumer that needs several aggregates holds the bundle; one that needs one
1138/// clones that handle out of it.
1139#[derive(Clone)]
1140pub struct Stores {
1141    /// The print record, its manifest and its narrowings.
1142    pub prints: Arc<dyn PrintStore>,
1143    /// The event log.
1144    pub events: Arc<dyn EventStore>,
1145    /// The images stored beside events.
1146    pub images: Arc<dyn ImageStore>,
1147    /// Actions, and the bounded interventions they open.
1148    pub actions: Arc<dyn ActionStore>,
1149    /// The supervision session of a print.
1150    pub sessions: Arc<dyn SessionStore>,
1151    /// The filament ledger.
1152    pub filament: Arc<dyn FilamentStore>,
1153    /// The printer-wide reading of the event log.
1154    pub timeline: Arc<dyn TimelineStore>,
1155}
1156
1157impl Stores {
1158    /// Every aggregate's handle onto one implementation.
1159    pub fn of<S>(store: Arc<S>) -> Self
1160    where
1161        S: PrintStore
1162            + EventStore
1163            + ImageStore
1164            + ActionStore
1165            + SessionStore
1166            + FilamentStore
1167            + TimelineStore
1168            + 'static,
1169    {
1170        Self {
1171            prints: Arc::clone(&store) as Arc<dyn PrintStore>,
1172            events: Arc::clone(&store) as Arc<dyn EventStore>,
1173            images: Arc::clone(&store) as Arc<dyn ImageStore>,
1174            actions: Arc::clone(&store) as Arc<dyn ActionStore>,
1175            sessions: Arc::clone(&store) as Arc<dyn SessionStore>,
1176            filament: Arc::clone(&store) as Arc<dyn FilamentStore>,
1177            timeline: store as Arc<dyn TimelineStore>,
1178        }
1179    }
1180}