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