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