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//!
18//! An implementation implements all five over one backing, and the composition
19//! root hands each consumer the trait it names: [`Stores`] is one
20//! implementation coerced once per trait, which is what lets a consumer take
21//! `Arc<dyn EventStore>` without knowing which store is behind it.
22//!
23//! # The history read has four behavioural facts, and they are settled here
24//!
25//! A signature carries none of them, and a trait that is structurally exact
26//! with all four unstated is an incomplete interface, so this module leaves an
27//! implementation exactly one answer to take for each rather than leaving them
28//! to whoever implements the trait:
29//!
30//! 1. The **default history window** is [`DEFAULT_HISTORY_WINDOW`].
31//! 2. The **maximum history limit** is [`MAX_HISTORY_LIMIT`], and it is above
32//! the default.
33//! 3. [`EventStore::history`] answers **newest first**.
34//! 4. An **empty `kinds`** in a [`HistoryQuery`] means **every kind**, not no
35//! kinds.
36//!
37//! The limit rule has one implementation here too — [`resolve_history_limit`] —
38//! so that refusing rather than clamping is a property of this contract and not
39//! of whoever implemented the trait. There is exactly one exported constant of
40//! each kind and exactly one exported resolution, so a consumer has one thing
41//! to import and no choice to make.
42//!
43//! Whether an implementation obeys the four is proven where the
44//! implementations are, by one conformance suite driving both of them.
45//!
46//! # Minting an identifier
47//!
48//! [`ActionStore::record_action`] is the only method that takes an
49//! [`ActionRequest`] or a [`PolicyDecision`] at all, and it takes them only
50//! together, so this surface offers no way to *ask* for a fresh [`ActionId`]
51//! for a request whose decision was not recorded beside it. Other methods
52//! answer records that may carry an identifier an earlier `record_action`
53//! minted — [`EventStore::append_event`] answers an [`EventRecord`] whose
54//! action-event payloads carry one — and that is stated rather than forbidden.
55//! That no method but `record_action` *mints* one is a property of an
56//! implementation's bodies rather than of a signature, and is established by
57//! the store implementation's own conformance suite.
58//!
59//! # Why the methods answer a boxed future
60//!
61//! Every method is asynchronous, and each trait is dyn-compatible and
62//! shareable across threads, because the supervisor holds every port behind
63//! `Arc<dyn Port>`. An `async fn` in a trait is not dyn-compatible, so each
64//! method answers a [`BoxFuture`] instead.
65
66use core::future::Future;
67use core::pin::Pin;
68use std::path::PathBuf;
69use std::sync::Arc;
70
71use crate::records::{
72 ActionId, ActionRecord, ActionRequest, ExecutionOutcome, ImageRecord, Intervention,
73 InterventionId, InterventionOutcome, JobManifest, ManifestNarrowing, PolicyDecision,
74 PrintRecord,
75};
76use printobserver_printer_api::{Adjustable, PrinterState};
77use printobserver_supervisor_api::SupervisionSession;
78use printobserver_types::schemars::JsonSchema;
79use printobserver_types::serde::{Deserialize, Serialize};
80use printobserver_types::{
81 EventBody, EventId, EventKind, EventRecord, EventSource, ImageId, PrintId, RawBytes, Timestamp,
82};
83
84/// A future these traits' methods answer with, in the one shape a trait object
85/// can carry.
86pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
87
88/// How many events a history read answers when the caller asks for no limit.
89///
90/// The one default window this domain declares, and it is below
91/// [`MAX_HISTORY_LIMIT`].
92pub const DEFAULT_HISTORY_WINDOW: u32 = 100;
93
94/// The most events a history read will answer, however many are asked for.
95///
96/// The one maximum this domain declares. A read asking for more is refused
97/// naming this maximum rather than quietly clamped, because a caller that
98/// asked for more and was given fewer cannot tell a short page from the end of
99/// the history.
100pub const MAX_HISTORY_LIMIT: u32 = 1_000;
101
102/// Resolve the limit a history read asks for, refusing one above the maximum.
103///
104/// The one resolution of the limit rule this domain declares: an
105/// implementation calls this rather than deciding for itself. An absent limit
106/// takes [`DEFAULT_HISTORY_WINDOW`]; a limit at or below [`MAX_HISTORY_LIMIT`]
107/// is taken as asked for; one above it is refused.
108///
109/// # Errors
110///
111/// Returns [`StoreError::LimitRefused`], naming the maximum and what was asked
112/// for, when the limit asked for is above [`MAX_HISTORY_LIMIT`].
113pub fn resolve_history_limit(limit: Option<u32>) -> Result<u32, StoreError> {
114 match limit {
115 None => Ok(DEFAULT_HISTORY_WINDOW),
116 Some(asked_for) if asked_for <= MAX_HISTORY_LIMIT => Ok(asked_for),
117 Some(asked_for) => Err(StoreError::LimitRefused {
118 limit: MAX_HISTORY_LIMIT,
119 asked_for,
120 }),
121 }
122}
123
124/// One event on its way into the store, before the store mints its identifier.
125#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
126#[serde(crate = "printobserver_types::serde")]
127#[schemars(crate = "printobserver_types::schemars")]
128pub struct EventDraft {
129 /// The print it belongs to, when it belongs to one.
130 #[serde(default, skip_serializing_if = "Option::is_none")]
131 pub print_id: Option<PrintId>,
132 /// Where it came from.
133 pub source: EventSource,
134 /// When it was received.
135 pub received_at: Timestamp,
136 /// The kind and the payload, flattened into the draft's own fields.
137 #[serde(flatten)]
138 pub body: EventBody,
139 /// The bytes exactly as received, for an externally sourced event.
140 #[serde(default, skip_serializing_if = "Option::is_none")]
141 pub raw: Option<RawBytes>,
142}
143
144impl EventDraft {
145 /// Which event this is.
146 #[must_use]
147 pub const fn kind(&self) -> &EventKind {
148 &self.body.kind
149 }
150}
151
152/// Which of a print's events to read.
153///
154/// An empty `kinds` means every kind rather than no kinds, and an absent
155/// `limit` means [`DEFAULT_HISTORY_WINDOW`].
156#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
157#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
158#[schemars(crate = "printobserver_types::schemars")]
159pub struct HistoryQuery {
160 /// The print to read the history of.
161 pub print_id: PrintId,
162 /// The kinds to read; empty means every kind.
163 pub kinds: Vec<EventKind>,
164 /// The earliest instant to read from, inclusive.
165 #[serde(default, skip_serializing_if = "Option::is_none")]
166 pub since: Option<Timestamp>,
167 /// The latest instant to read to, inclusive.
168 #[serde(default, skip_serializing_if = "Option::is_none")]
169 pub until: Option<Timestamp>,
170 /// How many events to answer; absent means [`DEFAULT_HISTORY_WINDOW`].
171 #[serde(default, skip_serializing_if = "Option::is_none")]
172 pub limit: Option<u32>,
173}
174
175impl HistoryQuery {
176 /// The limit this query resolves to.
177 ///
178 /// # Errors
179 ///
180 /// Returns [`StoreError::LimitRefused`] when the limit asked for is above
181 /// [`MAX_HISTORY_LIMIT`].
182 pub fn resolved_limit(&self) -> Result<u32, StoreError> {
183 resolve_history_limit(self.limit)
184 }
185}
186
187/// What the store found when asked for an image.
188///
189/// The record and the bytes are two facts rather than one: a record whose file
190/// has gone is a distinguishable answer rather than an error, because it is
191/// the answer that tells a caller the history is intact and the file is not.
192#[derive(Debug, Clone, PartialEq, Eq)]
193pub enum ImageLookup {
194 /// The record, and the absolute path its bytes are at.
195 Found {
196 /// The record.
197 record: ImageRecord,
198 /// Where its bytes are, resolved against the state directory.
199 path: PathBuf,
200 },
201 /// The record, whose file is not where the record says it is.
202 FileMissing {
203 /// The record.
204 record: ImageRecord,
205 },
206}
207
208/// What settling an intervention did.
209#[derive(Debug, Clone, PartialEq)]
210pub enum SettleOutcome {
211 /// This call settled it, and here it is.
212 Settled {
213 /// The intervention as it now stands.
214 intervention: Intervention,
215 },
216 /// It was already settled, and this is the outcome that won.
217 AlreadySettled {
218 /// The outcome that was already recorded.
219 outcome: InterventionOutcome,
220 },
221}
222
223/// One page of a print's whole history, and the cursor that follows it.
224///
225/// The exhaustive read of a print's history is [`EventStore::audit_page`]
226/// walked to exhaustion; there is no method that answers a whole history in one
227/// response, which is what makes an unbounded answer something a caller cannot
228/// ask for by accident.
229#[derive(Debug, Clone, PartialEq)]
230pub struct AuditPage {
231 /// This page's events.
232 pub events: Vec<EventRecord>,
233 /// The cursor the next page follows, or absent at the end of the history.
234 pub next: Option<EventId>,
235}
236
237/// Why the store did not do what it was asked.
238#[derive(Debug, Clone, PartialEq, Eq)]
239pub enum StoreError {
240 /// A constraint refused the write.
241 ConstraintRefused {
242 /// The constraint that refused it.
243 constraint: String,
244 },
245 /// There is no such record.
246 NotFound {
247 /// What was looked for.
248 what: String,
249 },
250 /// More was asked for than a limit allows.
251 LimitRefused {
252 /// The limit.
253 limit: u32,
254 /// What was asked for.
255 asked_for: u32,
256 },
257 /// The database failed.
258 Database {
259 /// What went wrong.
260 detail: String,
261 },
262 /// Reading or writing a file failed.
263 Io {
264 /// What went wrong.
265 detail: String,
266 },
267}
268
269impl core::fmt::Display for StoreError {
270 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
271 match self {
272 Self::ConstraintRefused { constraint } => {
273 write!(formatter, "the constraint {constraint} refused the write")
274 }
275 Self::NotFound { what } => write!(formatter, "there is no {what}"),
276 Self::LimitRefused { limit, asked_for } => {
277 write!(
278 formatter,
279 "{asked_for} was asked for, and the limit is {limit}"
280 )
281 }
282 Self::Database { detail } => write!(formatter, "the database failed: {detail}"),
283 Self::Io { detail } => write!(formatter, "reading or writing failed: {detail}"),
284 }
285 }
286}
287
288impl core::error::Error for StoreError {}
289
290/// The print record, with its manifest and the narrowings recorded on it.
291///
292/// Every method is asynchronous, the trait is dyn-compatible, and it is
293/// shareable across threads, because its consumers hold it behind
294/// `Arc<dyn PrintStore>`.
295pub trait PrintStore: Send + Sync {
296 /// Open a print, minting its identifier.
297 fn open_print(
298 &self,
299 provider_print_id: Option<i64>,
300 file_name: Option<String>,
301 ) -> BoxFuture<'_, Result<PrintRecord, StoreError>>;
302
303 /// Read one print by its identifier.
304 fn print(&self, print_id: PrintId) -> BoxFuture<'_, Result<Option<PrintRecord>, StoreError>>;
305
306 /// Read every print with no end recorded, most recently opened first.
307 ///
308 /// This is what a supervisor adopts on start: the store already binds an
309 /// action to the most recently opened print with no end recorded, and
310 /// without this method nothing above the store could name that print in
311 /// order to say it had adopted it.
312 fn open_prints(&self) -> BoxFuture<'_, Result<Vec<PrintRecord>, StoreError>>;
313
314 /// Read every print, ended or not, most recently opened first.
315 ///
316 /// This is what a caller finds a print's identifier in: the identifier is
317 /// minted here, and nothing outside the store could otherwise name it.
318 fn prints(&self) -> BoxFuture<'_, Result<Vec<PrintRecord>, StoreError>>;
319
320 /// Record `Obico`'s own identifier on a print that carries none.
321 ///
322 /// A print is opened before `Obico` reports on it when a caller finds the
323 /// job the printer is running, and this is how the first alert about that
324 /// job joins the print already open for it rather than opening a second.
325 /// Recording the identifier a print already carries answers the print
326 /// unchanged.
327 ///
328 /// # Errors
329 ///
330 /// Refuses a print that does not exist with [`StoreError::NotFound`], and a
331 /// print already carrying a different identifier with
332 /// [`StoreError::ConstraintRefused`] naming `prints.provider_print_id`: a
333 /// correlation, once recorded, is never moved to another of the provider's
334 /// prints.
335 fn attach_obico_print(
336 &self,
337 print_id: PrintId,
338 obico_print_id: i64,
339 ) -> BoxFuture<'_, Result<PrintRecord, StoreError>>;
340
341 /// Read one print by the provider's own identifier for it.
342 fn print_by_provider_id(
343 &self,
344 provider_print_id: i64,
345 ) -> BoxFuture<'_, Result<Option<PrintRecord>, StoreError>>;
346
347 /// End a print, in a terminal state, at an instant, for a reason.
348 fn end_print(
349 &self,
350 print_id: PrintId,
351 state: PrinterState,
352 ended_at: Timestamp,
353 reason: String,
354 ) -> BoxFuture<'_, Result<PrintRecord, StoreError>>;
355
356 /// Record that a manifest range was narrowed to the envelope's.
357 fn record_narrowing(
358 &self,
359 print_id: PrintId,
360 narrowing: ManifestNarrowing,
361 ) -> BoxFuture<'_, Result<PrintRecord, StoreError>>;
362
363 /// Store one print's manifest.
364 fn put_manifest(
365 &self,
366 print_id: PrintId,
367 manifest: JobManifest,
368 ) -> BoxFuture<'_, Result<(), StoreError>>;
369
370 /// Read one print's manifest.
371 fn manifest(&self, print_id: PrintId)
372 -> BoxFuture<'_, Result<Option<JobManifest>, StoreError>>;
373}
374
375/// The event log.
376///
377/// Every method is asynchronous, the trait is dyn-compatible, and it is
378/// shareable across threads, because its consumers hold it behind
379/// `Arc<dyn EventStore>`.
380pub trait EventStore: Send + Sync {
381 /// Append one event, minting its identifier.
382 fn append_event(&self, draft: EventDraft) -> BoxFuture<'_, Result<EventRecord, StoreError>>;
383
384 /// Read a print's events, newest first.
385 ///
386 /// Answers **newest first**. An empty `kinds` means **every kind** rather
387 /// than no kinds. An absent `limit` takes [`DEFAULT_HISTORY_WINDOW`], and a
388 /// limit above [`MAX_HISTORY_LIMIT`] is refused rather than clamped —
389 /// [`resolve_history_limit`] is the one resolution of that rule.
390 fn history(&self, query: HistoryQuery) -> BoxFuture<'_, Result<Vec<EventRecord>, StoreError>>;
391
392 /// Read one page of a print's whole history, oldest first.
393 ///
394 /// `after` is the identifier of the last event of the previous page, and is
395 /// absent for the first page. The page size is resolved by
396 /// [`resolve_history_limit`] like a history read's limit, so a page above
397 /// [`MAX_HISTORY_LIMIT`] is refused rather than clamped.
398 fn audit_page(
399 &self,
400 print_id: PrintId,
401 after: Option<EventId>,
402 page_size: u32,
403 ) -> BoxFuture<'_, Result<AuditPage, StoreError>>;
404}
405
406/// The images stored beside events.
407///
408/// Every method is asynchronous, the trait is dyn-compatible, and it is
409/// shareable across threads, because its consumers hold it behind
410/// `Arc<dyn ImageStore>`.
411pub trait ImageStore: Send + Sync {
412 /// Store one image's bytes, minting its identifier.
413 fn put_image(
414 &self,
415 print_id: PrintId,
416 event_id: EventId,
417 source_url: Option<String>,
418 content_type: String,
419 bytes: RawBytes,
420 ) -> BoxFuture<'_, Result<ImageRecord, StoreError>>;
421
422 /// Read one image by its identifier.
423 fn image(&self, image_id: ImageId) -> BoxFuture<'_, Result<ImageLookup, StoreError>>;
424}
425
426/// Actions, and the bounded interventions they open.
427///
428/// Every method is asynchronous, the trait is dyn-compatible, and it is
429/// shareable across threads, because its consumers hold it behind
430/// `Arc<dyn ActionStore>`.
431pub trait ActionStore: Send + Sync {
432 /// Record one request together with the decision taken on it.
433 ///
434 /// This is the only method that takes either half, and it takes them only
435 /// together; the [`ActionId`] it answers is minted for the pair.
436 fn record_action(
437 &self,
438 request: ActionRequest,
439 decision: PolicyDecision,
440 ) -> BoxFuture<'_, Result<ActionRecord, StoreError>>;
441
442 /// Record what the printer made of an action that reached it.
443 fn record_execution(
444 &self,
445 action_id: ActionId,
446 outcome: ExecutionOutcome,
447 ) -> BoxFuture<'_, Result<ActionRecord, StoreError>>;
448
449 /// Open a bounded intervention, minting its identifier.
450 ///
451 /// The print is the one the action was recorded against, so that a caller
452 /// cannot name a print the action does not belong to.
453 fn open_intervention(
454 &self,
455 action_id: ActionId,
456 adjustable: Adjustable,
457 prior_value: Option<f64>,
458 applied_value: f64,
459 applied_at: Timestamp,
460 expires_at: Timestamp,
461 ) -> BoxFuture<'_, Result<Intervention, StoreError>>;
462
463 /// Settle one intervention, or report the outcome that already won.
464 fn settle_intervention(
465 &self,
466 intervention_id: InterventionId,
467 outcome: InterventionOutcome,
468 ) -> BoxFuture<'_, Result<SettleOutcome, StoreError>>;
469
470 /// Read every intervention due to expire at or before an instant.
471 fn due_interventions(
472 &self,
473 at: Timestamp,
474 ) -> BoxFuture<'_, Result<Vec<Intervention>, StoreError>>;
475
476 /// Read every intervention still active on one print.
477 fn active_interventions(
478 &self,
479 print_id: PrintId,
480 ) -> BoxFuture<'_, Result<Vec<Intervention>, StoreError>>;
481}
482
483/// The supervision session of a print.
484///
485/// Every method is asynchronous, the trait is dyn-compatible, and it is
486/// shareable across threads, because its consumers hold it behind
487/// `Arc<dyn SessionStore>`.
488pub trait SessionStore: Send + Sync {
489 /// Store one print's supervision session.
490 fn put_session(&self, session: SupervisionSession) -> BoxFuture<'_, Result<(), StoreError>>;
491
492 /// Read one print's supervision session.
493 fn session(
494 &self,
495 print_id: PrintId,
496 ) -> BoxFuture<'_, Result<Option<SupervisionSession>, StoreError>>;
497}
498
499/// One store implementation, held once per aggregate it persists.
500///
501/// The composition root builds this from the one implementation it chose, by
502/// [`Stores::of`], and each consumer takes the handle for the aggregate it
503/// names: five shared handles to one backing rather than five backings. A
504/// consumer that needs several aggregates holds the bundle; one that needs one
505/// clones that handle out of it.
506#[derive(Clone)]
507pub struct Stores {
508 /// The print record, its manifest and its narrowings.
509 pub prints: Arc<dyn PrintStore>,
510 /// The event log.
511 pub events: Arc<dyn EventStore>,
512 /// The images stored beside events.
513 pub images: Arc<dyn ImageStore>,
514 /// Actions, and the bounded interventions they open.
515 pub actions: Arc<dyn ActionStore>,
516 /// The supervision session of a print.
517 pub sessions: Arc<dyn SessionStore>,
518}
519
520impl Stores {
521 /// Every aggregate's handle onto one implementation.
522 pub fn of<S>(store: Arc<S>) -> Self
523 where
524 S: PrintStore + EventStore + ImageStore + ActionStore + SessionStore + 'static,
525 {
526 Self {
527 prints: Arc::clone(&store) as Arc<dyn PrintStore>,
528 events: Arc::clone(&store) as Arc<dyn EventStore>,
529 images: Arc::clone(&store) as Arc<dyn ImageStore>,
530 actions: Arc::clone(&store) as Arc<dyn ActionStore>,
531 sessions: store as Arc<dyn SessionStore>,
532 }
533 }
534}