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 and [`ActionStore::record_action_against`] are the only methods
522 /// that take either half, and they take them only together; the
523 /// [`ActionId`] each answers is minted for the pair.
524 fn record_action(
525 &self,
526 request: ActionRequest,
527 decision: PolicyDecision,
528 ) -> BoxFuture<'_, Result<ActionRecord, StoreError>>;
529
530 /// Record one request together with the decision taken on it, against the
531 /// print it names rather than the one the store would bind it to.
532 ///
533 /// A close is asked of one record, which may have ended or may not be the
534 /// newest open one, so its request is recorded against that record or
535 /// refused as [`StoreError::NotFound`] when there is none.
536 fn record_action_against(
537 &self,
538 print_id: PrintId,
539 request: ActionRequest,
540 decision: PolicyDecision,
541 ) -> BoxFuture<'_, Result<ActionRecord, StoreError>>;
542
543 /// Record what the printer made of an action that reached it.
544 fn record_execution(
545 &self,
546 action_id: ActionId,
547 outcome: ExecutionOutcome,
548 ) -> BoxFuture<'_, Result<ActionRecord, StoreError>>;
549
550 /// Open a bounded intervention, minting its identifier.
551 ///
552 /// The print is the one the action was recorded against, so that a caller
553 /// cannot name a print the action does not belong to.
554 fn open_intervention(
555 &self,
556 action_id: ActionId,
557 adjustable: Adjustable,
558 prior_value: Option<f64>,
559 applied_value: f64,
560 applied_at: Timestamp,
561 expires_at: Timestamp,
562 ) -> BoxFuture<'_, Result<Intervention, StoreError>>;
563
564 /// Settle one intervention, or report the outcome that already won.
565 fn settle_intervention(
566 &self,
567 intervention_id: InterventionId,
568 outcome: InterventionOutcome,
569 ) -> BoxFuture<'_, Result<SettleOutcome, StoreError>>;
570
571 /// Read every intervention due to expire at or before an instant.
572 fn due_interventions(
573 &self,
574 at: Timestamp,
575 ) -> BoxFuture<'_, Result<Vec<Intervention>, StoreError>>;
576
577 /// Read every intervention still active on one print.
578 fn active_interventions(
579 &self,
580 print_id: PrintId,
581 ) -> BoxFuture<'_, Result<Vec<Intervention>, StoreError>>;
582}
583
584/// The supervision session of a print.
585///
586/// Every method is asynchronous, the trait is dyn-compatible, and it is
587/// shareable across threads, because its consumers hold it behind
588/// `Arc<dyn SessionStore>`.
589pub trait SessionStore: Send + Sync {
590 /// Store one print's supervision session.
591 fn put_session(&self, session: SupervisionSession) -> BoxFuture<'_, Result<(), StoreError>>;
592
593 /// Read one print's supervision session.
594 fn session(
595 &self,
596 print_id: PrintId,
597 ) -> BoxFuture<'_, Result<Option<SupervisionSession>, StoreError>>;
598}
599
600/// A spool on its way into the store, before the store mints its identifier.
601///
602/// A [`SpoolRecord`] without what the store sets itself: its `id`, minted; and
603/// its `updated_at`, which is `registered_at`. It is shelved, or loaded on a
604/// tool, and never retired.
605#[derive(Debug, Clone, PartialEq)]
606pub struct NewSpool {
607 /// The operator's own label for the spool.
608 pub name: String,
609 /// The material, such as `PLA`.
610 pub material: String,
611 /// The filament's colour, when the operator gave one.
612 pub color: Option<String>,
613 /// The filament's diameter, in millimetres.
614 pub diameter_mm: f64,
615 /// The material's density, in grams per cubic centimetre.
616 pub density_g_cm3: f64,
617 /// The net filament on the spool when it was full, in grams.
618 pub initial_g: f64,
619 /// The filament left, in grams.
620 pub remaining_g: f64,
621 /// The empty spool's own weight, in grams, when the operator gave it.
622 pub tare_g: Option<f64>,
623 /// The tool the spool is loaded on, when it is registered loaded.
624 pub loaded_on_tool: Option<i64>,
625 /// How far the remaining figure can be trusted.
626 pub trust: SpoolTrust,
627 /// When the spool was registered.
628 pub registered_at: Timestamp,
629}
630
631/// Whose debit a charge is: its key, which names the tool and — for a print
632/// this system watched — the print, and for a print it never saw, the print
633/// it recorded that one as, when one is linked.
634///
635/// The fields are private, so a watched print's charge cannot carry a second
636/// print beside the one its key names.
637#[derive(Debug, Clone, PartialEq, Eq)]
638pub struct ChargeIdentity {
639 /// The durable identity of the debit.
640 key: ChargeKey,
641 /// For an unobserved print only, the print this system recorded it as.
642 linked_print: Option<PrintId>,
643}
644
645impl ChargeIdentity {
646 /// The identity a key alone gives: a watched print's own, or an unobserved
647 /// print linked to none.
648 #[must_use]
649 pub const fn of(key: ChargeKey) -> Self {
650 Self {
651 key,
652 linked_print: None,
653 }
654 }
655
656 /// An unobserved print's identity, linked to the print this system
657 /// recorded it as.
658 ///
659 /// # Errors
660 ///
661 /// Answers the key back for a watched print's key, whose print is the one
662 /// it names and no other.
663 pub const fn linked(key: ChargeKey, print_id: PrintId) -> Result<Self, ChargeKey> {
664 match key {
665 ChargeKey::Print { .. } => Err(key),
666 ChargeKey::Unobserved { .. } => Ok(Self {
667 key,
668 linked_print: Some(print_id),
669 }),
670 }
671 }
672
673 /// The durable identity of the debit.
674 #[must_use]
675 pub const fn key(&self) -> &ChargeKey {
676 &self.key
677 }
678
679 /// The tool that fed the filament, as the key names it.
680 #[must_use]
681 pub const fn tool(&self) -> i64 {
682 self.key.tool()
683 }
684
685 /// The print the filament was fed in, when it was one this system
686 /// recorded: the one a watched key names, or the one an unobserved print
687 /// is linked to.
688 #[must_use]
689 pub const fn print_id(&self) -> Option<PrintId> {
690 match self.key.watched_print() {
691 Some(print_id) => Some(print_id),
692 None => self.linked_print,
693 }
694 }
695}
696
697/// One debit on its way into the store.
698#[derive(Debug, Clone, PartialEq)]
699pub struct Charge {
700 /// Whose debit it is, from which its tool and print are read.
701 pub identity: ChargeIdentity,
702 /// How much was fed, in millimetres.
703 pub length_mm: f64,
704 /// The spool charged and the whole calculation of what is subtracted from
705 /// it; absent when nothing was tracked on the tool, and the filament is
706 /// recorded uncharged.
707 pub charged: Option<ChargedFilament>,
708 /// When the charge was taken.
709 pub at: Timestamp,
710 /// Its `filament_consumed` event.
711 pub event: EventDraft,
712}
713
714/// What the store holds of one debit.
715#[derive(Debug, Clone, PartialEq)]
716pub struct ChargeRecord {
717 /// Whose debit it is, from which its tool and print are read.
718 pub identity: ChargeIdentity,
719 /// How much was fed, in millimetres.
720 pub length_mm: f64,
721 /// The spool charged and the whole calculation of what was subtracted;
722 /// absent when the filament was recorded uncharged.
723 pub charged: Option<ChargedFilament>,
724 /// When the charge was taken.
725 pub at: Timestamp,
726 /// Its `filament_consumed` event.
727 pub event_id: EventId,
728}
729
730impl ChargeRecord {
731 /// The spool charged, when one was.
732 #[must_use]
733 pub fn spool_id(&self) -> Option<SpoolId> {
734 self.charged.as_ref().map(|charged| charged.spool_id)
735 }
736}
737
738/// A charge held for a spool not yet named, on its way into the store.
739#[derive(Debug, Clone, PartialEq)]
740pub struct Pend {
741 /// What is held.
742 pub pending: PendingCharge,
743 /// Its `charge_pended` event.
744 pub event: EventDraft,
745}
746
747/// One change to one spool, on its way into the store.
748#[derive(Debug, Clone, PartialEq)]
749pub struct SpoolMutation {
750 /// The spool changed.
751 pub spool_id: SpoolId,
752 /// What changes, carrying the event it writes when it writes one.
753 pub change: SpoolChange,
754 /// When it changed; the spool's `updated_at` once it has.
755 pub at: Timestamp,
756}
757
758/// What one [`SpoolMutation`] changes, each change that writes an event
759/// carrying it and the one that writes none carrying none.
760#[derive(Debug, Clone, PartialEq)]
761pub enum SpoolChange {
762 /// Put the spool on a tool.
763 Load {
764 /// The tool, in the printer's own numbering.
765 tool: i64,
766 /// Its `spool_loaded` event.
767 event: EventDraft,
768 },
769 /// Take the spool off its tool.
770 Unload {
771 /// Its `spool_unloaded` event.
772 event: EventDraft,
773 },
774 /// Set the spool's remaining figure, which clears every mark: the spool
775 /// reads `verified` after it.
776 SetRemaining {
777 /// The filament left, in grams.
778 remaining_g: f64,
779 /// Its `spool_adjusted` event.
780 event: EventDraft,
781 },
782 /// Add one mark, by [`SpoolTrust::marked`], at the mutation's instant.
783 ///
784 /// A reason the spool already holds changes nothing, so it is a no-op: the
785 /// spool is not written and its `event` is not appended, which is how a
786 /// second signal of one change writes no second `spool_unverified`.
787 MarkUnverified {
788 /// Why the figure is in doubt.
789 reason: UnverifiedReason,
790 /// Its `spool_unverified` event, appended only when the mark is new.
791 event: EventDraft,
792 },
793 /// Remove every mark of these kinds, by [`SpoolTrust::cleared`]. The
794 /// domain chooses the kinds through
795 /// [`marks_cleared_by`](crate::filament::marks_cleared_by), and the marks
796 /// cleared are named in the command's own event, so this change carries
797 /// and writes no event of its own.
798 ClearMarks {
799 /// The kinds of mark removed.
800 kinds: Vec<UnverifiedReasonKind>,
801 },
802 /// Retire the spool, which takes it off any tool it is loaded on.
803 Retire {
804 /// Its `spool_retired` event.
805 event: EventDraft,
806 },
807}
808
809/// What one [`FilamentStore::apply_spool_changes`] wrote.
810#[derive(Debug, Clone, PartialEq)]
811pub struct SpoolWrite {
812 /// Every spool a charge or a mutation named, as the write left it, once
813 /// each, in the order it was first named.
814 pub spools: Vec<SpoolRecord>,
815 /// Every event the write appended, in the order it appended them.
816 pub events: Vec<EventRecord>,
817 /// One record per charge submitted, in the order submitted: the one this
818 /// write recorded, or, for a replay, the one already recorded.
819 pub charges: Vec<ChargeRecord>,
820 /// Every charge this write held; a replayed pend is not among them.
821 pub pending: Vec<PendingCharge>,
822}
823
824/// What settling a print did.
825#[derive(Debug, Clone, PartialEq)]
826pub enum Settlement {
827 /// This call settled it.
828 Settled {
829 /// When it was settled: its `print_ended` event's instant.
830 at: Timestamp,
831 /// Every event the settlement appended, in the order it appended them,
832 /// its `print_ended` event last.
833 events: Vec<EventRecord>,
834 },
835 /// It was already settled, and this call wrote nothing.
836 AlreadySettled {
837 /// When it was settled.
838 at: Timestamp,
839 /// The outcome it was settled with.
840 outcome: PrintOutcome,
841 },
842}
843
844/// The printer's own count of the prints of one file, as last accounted.
845#[derive(Debug, Clone, PartialEq, Eq)]
846pub struct FileTally {
847 /// The file.
848 // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
849 pub file_name: String,
850 /// Where the file lives, in the printer's own vocabulary.
851 pub origin: String,
852 /// The tally generation, which starts at 0 and only ever advances: it
853 /// advances each time the printer's tally for the file is reset.
854 pub generation: u32,
855 /// The completed prints the tally counts.
856 pub successes: i64,
857 /// The failed prints the tally counts.
858 pub failures: i64,
859 /// When the tally was read.
860 pub observed_at: Timestamp,
861}
862
863/// Which timeline events to read.
864///
865/// An empty `kinds` means every kind of
866/// [`TIMELINE_KINDS`](crate::kinds::TIMELINE_KINDS), and an absent `limit`
867/// means [`DEFAULT_HISTORY_WINDOW`].
868#[derive(Debug, Clone, PartialEq, Eq)]
869pub struct TimelineQuery {
870 /// The kinds to read; empty means every timeline kind, and a kind outside
871 /// the timeline is refused.
872 pub kinds: Vec<EventKind>,
873 /// The earliest instant to read from, inclusive.
874 pub since: Option<Timestamp>,
875 /// The latest instant to read to, inclusive.
876 pub until: Option<Timestamp>,
877 /// Only events whose payload names this spool.
878 pub spool_id: Option<SpoolId>,
879 /// The cursor: only events strictly older than this one.
880 pub before: Option<EventId>,
881 /// How many events to answer; absent means [`DEFAULT_HISTORY_WINDOW`].
882 pub limit: Option<u32>,
883}
884
885impl TimelineQuery {
886 /// The limit this query resolves to.
887 ///
888 /// # Errors
889 ///
890 /// Returns [`StoreError::LimitRefused`] when the limit asked for is above
891 /// [`MAX_HISTORY_LIMIT`].
892 pub fn resolved_limit(&self) -> Result<u32, StoreError> {
893 resolve_history_limit(self.limit)
894 }
895
896 /// The kinds this query reads: those asked for, or every timeline kind.
897 ///
898 /// # Errors
899 ///
900 /// Returns [`StoreError::ConstraintRefused`] naming `timeline.kinds` when a
901 /// kind asked for is not one of
902 /// [`TIMELINE_KINDS`](crate::kinds::TIMELINE_KINDS).
903 pub fn resolved_kinds(&self) -> Result<Vec<EventKind>, StoreError> {
904 let refused = || StoreError::ConstraintRefused {
905 constraint: "timeline.kinds".to_owned(),
906 };
907 if self.kinds.is_empty() {
908 return crate::kinds::TIMELINE_KINDS
909 .iter()
910 .map(|kind| EventKind::new(*kind).map_err(|_| refused()))
911 .collect();
912 }
913 if self
914 .kinds
915 .iter()
916 .any(|kind| !crate::kinds::TIMELINE_KINDS.contains(&kind.as_str()))
917 {
918 return Err(refused());
919 }
920 Ok(self.kinds.clone())
921 }
922}
923
924/// The filament ledger: spools, the charges against them, the charges held for
925/// a spool not yet named, each print's settlement and last file position, and
926/// the printer's per-file print tallies.
927///
928/// # Every write is one transaction
929///
930/// Each writing method writes everything it was given and every event that
931/// goes with it, or — when any part is refused — none of it: a crash or a
932/// refusal halfway leaves the ledger as it was before the call.
933///
934/// # A charge is debited exactly once
935///
936/// A charge is keyed by its [`ChargeKey`], stored under
937/// [`ChargeKey::canonical`]. Wherever a charge is submitted —
938/// [`apply_spool_changes`](Self::apply_spool_changes),
939/// [`settle_print`](Self::settle_print) or
940/// [`account_tallies`](Self::account_tallies) — the same rules hold:
941///
942/// * A charge whose key is **not yet recorded** subtracts its charged grams
943/// from its spool — a retired spool included, since retirement refuses later commands
944/// rather than the settlement of earlier prints, and below zero included,
945/// since a charge is never refused or clamped — records the charge, and
946/// appends its event. The spool's `updated_at` becomes the later of its own
947/// and the charge's instant. A charge naming no spool subtracts nothing and
948/// is still recorded.
949/// * A charge whose key is **already recorded** is a replay: it subtracts
950/// nothing and appends no event.
951/// * A charge whose key is **pending** takes it: the pending charge is removed
952/// in the same transaction that records the charge, so it is debited once.
953///
954/// A pend is held the same way: one whose key is already pending or already
955/// charged is a replay and writes nothing; otherwise it is held and its event
956/// appended.
957///
958/// Within one call, the charges are applied first, in the order given, then
959/// the pends, then the mutations — so a correction sets its figure after any
960/// pending charge the same command took.
961///
962/// # A spool change, and what refuses one
963///
964/// A mutation applies its [`SpoolChange`], sets the spool's `updated_at` to its
965/// instant, and appends the event the change carries — a `clear_marks` carries
966/// none, and a `mark_unverified` the spool already holds is a no-op that
967/// appends nothing. The trust functions are the contract's,
968/// [`SpoolTrust::marked`] and [`SpoolTrust::cleared`], and no implementation
969/// restates them. Every refusal is the whole call's:
970///
971/// * [`StoreError::NotFound`] for a spool that does not exist.
972/// * [`StoreError::ConstraintRefused`] naming `spools.loaded_on_tool` for a
973/// load onto a tool another unretired spool holds. A swap is two mutations
974/// in one call, the unload and then the load.
975/// * [`StoreError::ConstraintRefused`] naming `spools.retired_at` for a load,
976/// an unload, a `set_remaining`, a `clear_marks` or a `retire` of a retired
977/// spool. A `mark_unverified` still applies to one, because a settlement
978/// marks the spool that fed the print whatever has happened to it since.
979///
980/// Every method is asynchronous, the trait is dyn-compatible, and it is
981/// shareable across threads, because its consumers hold it behind
982/// `Arc<dyn FilamentStore>`.
983pub trait FilamentStore: Send + Sync {
984 /// Register a spool, minting its identifier.
985 ///
986 /// In one transaction, writes the spool and a `spool_registered` event —
987 /// with no print, from `source`, received at the spool's `registered_at` —
988 /// whose payload carries the record as written, `actor` and `reason`.
989 ///
990 /// # Errors
991 ///
992 /// Refuses a spool registered loaded onto a tool another unretired spool
993 /// holds with [`StoreError::ConstraintRefused`] naming
994 /// `spools.loaded_on_tool`.
995 fn register_spool(
996 &self,
997 spool: NewSpool,
998 source: EventSource,
999 actor: Actor,
1000 reason: String,
1001 ) -> BoxFuture<'_, Result<(SpoolRecord, EventRecord), StoreError>>;
1002
1003 /// Apply spool mutations, charges and pends, with their events, in one
1004 /// transaction — all of them or none.
1005 ///
1006 /// # Errors
1007 ///
1008 /// Refuses the whole call as the trait's own documentation states.
1009 fn apply_spool_changes(
1010 &self,
1011 changes: Vec<SpoolMutation>,
1012 charges: Vec<Charge>,
1013 pends: Vec<Pend>,
1014 ) -> BoxFuture<'_, Result<SpoolWrite, StoreError>>;
1015
1016 /// Settle a print, once.
1017 ///
1018 /// In one transaction: the print's remaining charges and its pends, under
1019 /// the replay rules, with their events; the `mark_unverified` mutations in
1020 /// `marks`, applied by the rules every mutation is, with their events; the
1021 /// `ended` event, which is the print's `print_ended`; and the print's
1022 /// settlement, at that event's instant, with `outcome`. A print already
1023 /// settled is answered [`Settlement::AlreadySettled`] and nothing is
1024 /// written.
1025 ///
1026 /// It does not end the print record: the domain calls
1027 /// [`PrintStore::end_print`] after it, so a crash between the two leaves a
1028 /// settled, open print that the next close-out only ends.
1029 ///
1030 /// # Errors
1031 ///
1032 /// Refuses a print that does not exist with [`StoreError::NotFound`], and
1033 /// otherwise as the trait's own documentation states.
1034 fn settle_print(
1035 &self,
1036 print_id: PrintId,
1037 outcome: PrintOutcome,
1038 ended: EventDraft,
1039 charges: Vec<Charge>,
1040 pends: Vec<Pend>,
1041 marks: Vec<SpoolMutation>,
1042 ) -> BoxFuture<'_, Result<Settlement, StoreError>>;
1043
1044 /// When a print was settled, and with which outcome, when it has been.
1045 fn print_settlement(
1046 &self,
1047 print_id: PrintId,
1048 ) -> BoxFuture<'_, Result<Option<(Timestamp, PrintOutcome)>, StoreError>>;
1049
1050 /// Every charge recorded against a print, by tool and then by segment.
1051 ///
1052 /// This is how a later segment is charged only the remainder after a
1053 /// restart.
1054 fn charges(&self, print_id: PrintId) -> BoxFuture<'_, Result<Vec<ChargeRecord>, StoreError>>;
1055
1056 /// Every charge still pending — on one tool, when one is named — oldest
1057 /// first.
1058 fn pending_charges(
1059 &self,
1060 tool: Option<i64>,
1061 ) -> BoxFuture<'_, Result<Vec<PendingCharge>, StoreError>>;
1062
1063 /// Read one spool.
1064 fn spool(&self, id: SpoolId) -> BoxFuture<'_, Result<Option<SpoolRecord>, StoreError>>;
1065
1066 /// Read every spool — retired ones only when asked for — most recently
1067 /// registered first.
1068 fn spools(&self, include_retired: bool) -> BoxFuture<'_, Result<Vec<SpoolRecord>, StoreError>>;
1069
1070 /// Read every unretired spool loaded on a tool, by tool.
1071 fn loaded_spools(&self) -> BoxFuture<'_, Result<Vec<SpoolRecord>, StoreError>>;
1072
1073 /// Record how far into its file a print had got.
1074 ///
1075 /// Keeps the latest by `observed_at`: a position observed before the one
1076 /// held is not recorded.
1077 ///
1078 /// # Errors
1079 ///
1080 /// Refuses a print that does not exist with [`StoreError::NotFound`].
1081 fn record_file_position(
1082 &self,
1083 print_id: PrintId,
1084 position: FilePosition,
1085 ) -> BoxFuture<'_, Result<(), StoreError>>;
1086
1087 /// The latest file position recorded for a print.
1088 fn file_position(
1089 &self,
1090 print_id: PrintId,
1091 ) -> BoxFuture<'_, Result<Option<FilePosition>, StoreError>>;
1092
1093 /// Every file's tally as last accounted, by file name and then origin.
1094 fn file_tallies(&self) -> BoxFuture<'_, Result<Vec<FileTally>, StoreError>>;
1095
1096 /// Account the prints the printer's tallies counted and this system never
1097 /// saw, in one transaction.
1098 ///
1099 /// Their charges, under the replay rules; their `mark_unverified`
1100 /// mutations, applied by the rules every mutation is; their
1101 /// `unaccounted_print` and `file_tally_rebaselined` events; and the
1102 /// advanced tallies, each stored by file name and origin over whatever was
1103 /// held — so a crash leaves either none of it or all of it. Answers every
1104 /// event it appended, in the order it appended them.
1105 ///
1106 /// # Errors
1107 ///
1108 /// Refuses a tally whose generation is below the one held for its file
1109 /// with [`StoreError::ConstraintRefused`] naming `file_tallies.generation`,
1110 /// and otherwise as the trait's own documentation states.
1111 fn account_tallies(
1112 &self,
1113 tallies: Vec<FileTally>,
1114 charges: Vec<Charge>,
1115 marks: Vec<SpoolMutation>,
1116 events: Vec<EventDraft>,
1117 ) -> BoxFuture<'_, Result<Vec<EventRecord>, StoreError>>;
1118}
1119
1120/// The printer-wide reading of the event log.
1121///
1122/// Every method is asynchronous, the trait is dyn-compatible, and it is
1123/// shareable across threads, because its consumers hold it behind
1124/// `Arc<dyn TimelineStore>`.
1125pub trait TimelineStore: Send + Sync {
1126 /// Read the events of the printer timeline, across every print and none.
1127 ///
1128 /// Answers only events of [`TIMELINE_KINDS`](crate::kinds::TIMELINE_KINDS),
1129 /// **newest first** by `(received_at, id)`. An empty `kinds` means every
1130 /// timeline kind; `since` and `until` are inclusive; `spool_id` keeps only
1131 /// events whose payload names that spool — carries its identifier as a
1132 /// string value anywhere in it; and `before` keeps only events strictly
1133 /// older than that event. The limit is resolved by
1134 /// [`resolve_history_limit`].
1135 ///
1136 /// # Errors
1137 ///
1138 /// Refuses a kind outside the timeline with
1139 /// [`StoreError::ConstraintRefused`] naming `timeline.kinds`, a limit above
1140 /// [`MAX_HISTORY_LIMIT`] with [`StoreError::LimitRefused`], and a cursor
1141 /// naming no event with [`StoreError::NotFound`].
1142 fn timeline(&self, query: TimelineQuery)
1143 -> BoxFuture<'_, Result<Vec<EventRecord>, StoreError>>;
1144}
1145
1146/// One store implementation, held once per aggregate it persists.
1147///
1148/// The composition root builds this from the one implementation it chose, by
1149/// [`Stores::of`], and each consumer takes the handle for the aggregate it
1150/// names: seven shared handles to one backing rather than seven backings. A
1151/// consumer that needs several aggregates holds the bundle; one that needs one
1152/// clones that handle out of it.
1153#[derive(Clone)]
1154pub struct Stores {
1155 /// The print record, its manifest and its narrowings.
1156 pub prints: Arc<dyn PrintStore>,
1157 /// The event log.
1158 pub events: Arc<dyn EventStore>,
1159 /// The images stored beside events.
1160 pub images: Arc<dyn ImageStore>,
1161 /// Actions, and the bounded interventions they open.
1162 pub actions: Arc<dyn ActionStore>,
1163 /// The supervision session of a print.
1164 pub sessions: Arc<dyn SessionStore>,
1165 /// The filament ledger.
1166 pub filament: Arc<dyn FilamentStore>,
1167 /// The printer-wide reading of the event log.
1168 pub timeline: Arc<dyn TimelineStore>,
1169}
1170
1171impl Stores {
1172 /// Every aggregate's handle onto one implementation.
1173 pub fn of<S>(store: Arc<S>) -> Self
1174 where
1175 S: PrintStore
1176 + EventStore
1177 + ImageStore
1178 + ActionStore
1179 + SessionStore
1180 + FilamentStore
1181 + TimelineStore
1182 + 'static,
1183 {
1184 Self {
1185 prints: Arc::clone(&store) as Arc<dyn PrintStore>,
1186 events: Arc::clone(&store) as Arc<dyn EventStore>,
1187 images: Arc::clone(&store) as Arc<dyn ImageStore>,
1188 actions: Arc::clone(&store) as Arc<dyn ActionStore>,
1189 sessions: Arc::clone(&store) as Arc<dyn SessionStore>,
1190 filament: Arc::clone(&store) as Arc<dyn FilamentStore>,
1191 timeline: store as Arc<dyn TimelineStore>,
1192 }
1193 }
1194}