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