Skip to main content

printobserver_store_api/
lib.rs

1//! `printobserver-store-api`.
2//!
3//! Owns: the port durable state speaks through: the trait for recording and
4//! replaying observations, decisions and job history, the shapes its methods
5//! carry, the two constants and the one resolution the history read is
6//! specified by, plus that port's own error type.
7//!
8//! May depend on: `printobserver-types` only. A port that named an
9//! implementation would stop being a port.
10//!
11//! # The history read has four behavioural facts, and they are settled here
12//!
13//! A signature carries none of them, and a trait that is structurally exact
14//! with all four unstated is an incomplete port, so this crate leaves an
15//! implementation exactly one answer to take for each rather than leaving them
16//! to whoever implements the trait:
17//!
18//! 1. The **default history window** is [`DEFAULT_HISTORY_WINDOW`].
19//! 2. The **maximum history limit** is [`MAX_HISTORY_LIMIT`], and it is above
20//!    the default.
21//! 3. [`StorePort::history`] answers **newest first**.
22//! 4. An **empty `kinds`** in a [`HistoryQuery`] means **every kind**, not no
23//!    kinds.
24//!
25//! The limit rule has one implementation here too — [`resolve_history_limit`] —
26//! so that refusing rather than clamping is a property of this contract and not
27//! of whoever implemented the trait. There is exactly one exported constant of
28//! each kind and exactly one exported resolution, so a consumer has one thing
29//! to import and no choice to make.
30//!
31//! Whether an implementation obeys the four is proven where the
32//! implementations are, by one conformance suite driving both of them.
33//!
34//! # Minting an identifier
35//!
36//! [`StorePort::record_action`] is the only method that takes an
37//! [`ActionRequest`] or a [`PolicyDecision`] at all, and it takes them only
38//! together, so this surface offers no way to *ask* for a fresh [`ActionId`]
39//! for a request whose decision was not recorded beside it. Other methods
40//! answer records that may carry an identifier an earlier `record_action`
41//! minted — [`StorePort::append_event`] answers an
42//! [`EventRecord`](printobserver_types::EventRecord) whose action-event
43//! payloads carry one — and that is stated rather than forbidden. That no
44//! method but `record_action` *mints* one is a property of an implementation's
45//! bodies rather than of a signature, and is established by the store
46//! implementation's own conformance suite.
47//!
48//! # Why the methods answer a boxed future
49//!
50//! Every method is asynchronous, and the trait is dyn-compatible and shareable
51//! across threads, because the supervision core holds all four ports behind
52//! `Arc<dyn Port>`. An `async fn` in a trait is not dyn-compatible, so each
53//! method answers a [`BoxFuture`] instead.
54
55use core::future::Future;
56use core::pin::Pin;
57use std::path::PathBuf;
58
59use printobserver_types::schemars::JsonSchema;
60use printobserver_types::serde::{Deserialize, Serialize};
61use printobserver_types::{
62    ActionId, ActionRecord, ActionRequest, Adjustable, EventId, EventKind, EventRecord,
63    EventSource, ExecutionOutcome, ImageId, ImageRecord, Intervention, InterventionId,
64    InterventionOutcome, JobManifest, ManifestNarrowing, PolicyDecision, PrintId, PrintRecord,
65    PrinterState, RawBytes, SupervisionSession, Timestamp,
66};
67
68/// A future this port's methods answer with, in the one shape a trait object
69/// can carry.
70pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
71
72/// How many events a history read answers when the caller asks for no limit.
73///
74/// The one default window this port declares, and it is below
75/// [`MAX_HISTORY_LIMIT`].
76pub const DEFAULT_HISTORY_WINDOW: u32 = 100;
77
78/// The most events a history read will answer, however many are asked for.
79///
80/// The one maximum this port declares. A read asking for more is refused
81/// naming this maximum rather than quietly clamped, because a caller that
82/// asked for more and was given fewer cannot tell a short page from the end of
83/// the history.
84pub const MAX_HISTORY_LIMIT: u32 = 1_000;
85
86/// Resolve the limit a history read asks for, refusing one above the maximum.
87///
88/// The one resolution of the limit rule this port declares: an implementation
89/// calls this rather than deciding for itself. An absent limit takes
90/// [`DEFAULT_HISTORY_WINDOW`]; a limit at or below [`MAX_HISTORY_LIMIT`] is
91/// taken as asked for; one above it is refused.
92///
93/// # Errors
94///
95/// Returns [`StoreError::LimitRefused`], naming the maximum and what was asked
96/// for, when the limit asked for is above [`MAX_HISTORY_LIMIT`].
97pub fn resolve_history_limit(limit: Option<u32>) -> Result<u32, StoreError> {
98    match limit {
99        None => Ok(DEFAULT_HISTORY_WINDOW),
100        Some(asked_for) if asked_for <= MAX_HISTORY_LIMIT => Ok(asked_for),
101        Some(asked_for) => Err(StoreError::LimitRefused {
102            limit: MAX_HISTORY_LIMIT,
103            asked_for,
104        }),
105    }
106}
107
108/// One event on its way into the store, before the store mints its identifier.
109#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
110#[serde(crate = "printobserver_types::serde")]
111#[schemars(crate = "printobserver_types::schemars")]
112pub struct EventDraft {
113    /// The print it belongs to, when it belongs to one.
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub print_id: Option<PrintId>,
116    /// Where it came from.
117    pub source: EventSource,
118    /// When it was received.
119    pub received_at: Timestamp,
120    /// The kind and the payload, which are one closed pair.
121    #[serde(flatten)]
122    pub payload: printobserver_types::EventPayload,
123    /// The bytes exactly as received, for an externally sourced event.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub raw: Option<RawBytes>,
126}
127
128impl EventDraft {
129    /// Which event this is, read off the payload it carries.
130    #[must_use]
131    pub const fn kind(&self) -> EventKind {
132        self.payload.kind()
133    }
134}
135
136/// Which of a print's events to read.
137///
138/// An empty `kinds` means every kind rather than no kinds, and an absent
139/// `limit` means [`DEFAULT_HISTORY_WINDOW`].
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
141#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
142#[schemars(crate = "printobserver_types::schemars")]
143pub struct HistoryQuery {
144    /// The print to read the history of.
145    pub print_id: PrintId,
146    /// The kinds to read; empty means every kind.
147    pub kinds: Vec<EventKind>,
148    /// The earliest instant to read from, inclusive.
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub since: Option<Timestamp>,
151    /// The latest instant to read to, inclusive.
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub until: Option<Timestamp>,
154    /// How many events to answer; absent means [`DEFAULT_HISTORY_WINDOW`].
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub limit: Option<u32>,
157}
158
159impl HistoryQuery {
160    /// The limit this query resolves to.
161    ///
162    /// # Errors
163    ///
164    /// Returns [`StoreError::LimitRefused`] when the limit asked for is above
165    /// [`MAX_HISTORY_LIMIT`].
166    pub fn resolved_limit(&self) -> Result<u32, StoreError> {
167        resolve_history_limit(self.limit)
168    }
169}
170
171/// What the store found when asked for an image.
172///
173/// The record and the bytes are two facts rather than one: a record whose file
174/// has gone is a distinguishable answer rather than an error, because it is
175/// the answer that tells a caller the history is intact and the file is not.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub enum ImageLookup {
178    /// The record, and the absolute path its bytes are at.
179    Found {
180        /// The record.
181        record: ImageRecord,
182        /// Where its bytes are, resolved against the state directory.
183        path: PathBuf,
184    },
185    /// The record, whose file is not where the record says it is.
186    FileMissing {
187        /// The record.
188        record: ImageRecord,
189    },
190}
191
192/// What settling an intervention did.
193#[derive(Debug, Clone, PartialEq)]
194pub enum SettleOutcome {
195    /// This call settled it, and here it is.
196    Settled {
197        /// The intervention as it now stands.
198        intervention: Intervention,
199    },
200    /// It was already settled, and this is the outcome that won.
201    AlreadySettled {
202        /// The outcome that was already recorded.
203        outcome: InterventionOutcome,
204    },
205}
206
207/// One page of a print's whole history, and the cursor that follows it.
208///
209/// The exhaustive read of a print's history is [`StorePort::audit_page`]
210/// walked to exhaustion; there is no method that answers a whole history in one
211/// response, which is what makes an unbounded answer something a caller cannot
212/// ask for by accident.
213#[derive(Debug, Clone, PartialEq)]
214pub struct AuditPage {
215    /// This page's events.
216    pub events: Vec<EventRecord>,
217    /// The cursor the next page follows, or absent at the end of the history.
218    pub next: Option<EventId>,
219}
220
221/// Why the store did not do what it was asked.
222#[derive(Debug, Clone, PartialEq, Eq)]
223pub enum StoreError {
224    /// A constraint refused the write.
225    ConstraintRefused {
226        /// The constraint that refused it.
227        constraint: String,
228    },
229    /// There is no such record.
230    NotFound {
231        /// What was looked for.
232        what: String,
233    },
234    /// More was asked for than a limit allows.
235    LimitRefused {
236        /// The limit.
237        limit: u32,
238        /// What was asked for.
239        asked_for: u32,
240    },
241    /// The database failed.
242    Database {
243        /// What went wrong.
244        detail: String,
245    },
246    /// Reading or writing a file failed.
247    Io {
248        /// What went wrong.
249        detail: String,
250    },
251}
252
253impl core::fmt::Display for StoreError {
254    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
255        match self {
256            Self::ConstraintRefused { constraint } => {
257                write!(formatter, "the constraint {constraint} refused the write")
258            }
259            Self::NotFound { what } => write!(formatter, "there is no {what}"),
260            Self::LimitRefused { limit, asked_for } => {
261                write!(
262                    formatter,
263                    "{asked_for} was asked for, and the limit is {limit}"
264                )
265            }
266            Self::Database { detail } => write!(formatter, "the database failed: {detail}"),
267            Self::Io { detail } => write!(formatter, "reading or writing failed: {detail}"),
268        }
269    }
270}
271
272impl core::error::Error for StoreError {}
273
274/// The port durable state speaks through.
275///
276/// Every method is asynchronous, the trait is dyn-compatible, and it is
277/// shareable across threads, because the supervision core holds it behind
278/// `Arc<dyn StorePort>`.
279pub trait StorePort: Send + Sync {
280    /// Open a print, minting its identifier.
281    fn open_print(
282        &self,
283        obico_print_id: Option<i64>,
284        file_name: Option<String>,
285    ) -> BoxFuture<'_, Result<PrintRecord, StoreError>>;
286
287    /// Read one print by its identifier.
288    fn print(&self, print_id: PrintId) -> BoxFuture<'_, Result<Option<PrintRecord>, StoreError>>;
289
290    /// Read every print with no end recorded, most recently opened first.
291    ///
292    /// This is what a supervisor adopts on start: the port already binds an
293    /// action to the most recently opened print with no end recorded, and
294    /// without this method nothing above the port could name that print in
295    /// order to say it had adopted it.
296    fn open_prints(&self) -> BoxFuture<'_, Result<Vec<PrintRecord>, StoreError>>;
297
298    /// Read one print by Obico's own identifier for it.
299    fn print_by_obico_id(
300        &self,
301        obico_print_id: i64,
302    ) -> BoxFuture<'_, Result<Option<PrintRecord>, StoreError>>;
303
304    /// End a print, in a terminal state, at an instant, for a reason.
305    fn end_print(
306        &self,
307        print_id: PrintId,
308        state: PrinterState,
309        ended_at: Timestamp,
310        reason: String,
311    ) -> BoxFuture<'_, Result<PrintRecord, StoreError>>;
312
313    /// Record that a manifest range was narrowed to the envelope's.
314    fn record_narrowing(
315        &self,
316        print_id: PrintId,
317        narrowing: ManifestNarrowing,
318    ) -> BoxFuture<'_, Result<PrintRecord, StoreError>>;
319
320    /// Append one event, minting its identifier.
321    fn append_event(&self, draft: EventDraft) -> BoxFuture<'_, Result<EventRecord, StoreError>>;
322
323    /// Store one image's bytes, minting its identifier.
324    fn put_image(
325        &self,
326        print_id: PrintId,
327        event_id: EventId,
328        source_url: Option<String>,
329        content_type: String,
330        bytes: RawBytes,
331    ) -> BoxFuture<'_, Result<ImageRecord, StoreError>>;
332
333    /// Read one image by its identifier.
334    fn image(&self, image_id: ImageId) -> BoxFuture<'_, Result<ImageLookup, StoreError>>;
335
336    /// Record one request together with the decision taken on it.
337    ///
338    /// This is the only method that takes either half, and it takes them only
339    /// together; the [`ActionId`] it answers is minted for the pair.
340    fn record_action(
341        &self,
342        request: ActionRequest,
343        decision: PolicyDecision,
344    ) -> BoxFuture<'_, Result<ActionRecord, StoreError>>;
345
346    /// Record what the printer made of an action that reached it.
347    fn record_execution(
348        &self,
349        action_id: ActionId,
350        outcome: ExecutionOutcome,
351    ) -> BoxFuture<'_, Result<ActionRecord, StoreError>>;
352
353    /// Open a bounded intervention, minting its identifier.
354    ///
355    /// The print is the one the action was recorded against, so that a caller
356    /// cannot name a print the action does not belong to.
357    fn open_intervention(
358        &self,
359        action_id: ActionId,
360        adjustable: Adjustable,
361        prior_value: Option<f64>,
362        applied_value: f64,
363        applied_at: Timestamp,
364        expires_at: Timestamp,
365    ) -> BoxFuture<'_, Result<Intervention, StoreError>>;
366
367    /// Settle one intervention, or report the outcome that already won.
368    fn settle_intervention(
369        &self,
370        intervention_id: InterventionId,
371        outcome: InterventionOutcome,
372    ) -> BoxFuture<'_, Result<SettleOutcome, StoreError>>;
373
374    /// Read every intervention due to expire at or before an instant.
375    fn due_interventions(
376        &self,
377        at: Timestamp,
378    ) -> BoxFuture<'_, Result<Vec<Intervention>, StoreError>>;
379
380    /// Read every intervention still active on one print.
381    fn active_interventions(
382        &self,
383        print_id: PrintId,
384    ) -> BoxFuture<'_, Result<Vec<Intervention>, StoreError>>;
385
386    /// Store one print's manifest.
387    fn put_manifest(
388        &self,
389        print_id: PrintId,
390        manifest: JobManifest,
391    ) -> BoxFuture<'_, Result<(), StoreError>>;
392
393    /// Read one print's manifest.
394    fn manifest(&self, print_id: PrintId)
395    -> BoxFuture<'_, Result<Option<JobManifest>, StoreError>>;
396
397    /// Read a print's events, newest first.
398    ///
399    /// Answers **newest first**. An empty `kinds` means **every kind** rather
400    /// than no kinds. An absent `limit` takes [`DEFAULT_HISTORY_WINDOW`], and a
401    /// limit above [`MAX_HISTORY_LIMIT`] is refused rather than clamped —
402    /// [`resolve_history_limit`] is the one resolution of that rule.
403    fn history(&self, query: HistoryQuery) -> BoxFuture<'_, Result<Vec<EventRecord>, StoreError>>;
404
405    /// Read one page of a print's whole history, oldest first.
406    ///
407    /// `after` is the identifier of the last event of the previous page, and is
408    /// absent for the first page. The page size is resolved by
409    /// [`resolve_history_limit`] like a history read's limit, so a page above
410    /// [`MAX_HISTORY_LIMIT`] is refused rather than clamped.
411    fn audit_page(
412        &self,
413        print_id: PrintId,
414        after: Option<EventId>,
415        page_size: u32,
416    ) -> BoxFuture<'_, Result<AuditPage, StoreError>>;
417
418    /// Store one print's supervision session.
419    fn put_session(&self, session: SupervisionSession) -> BoxFuture<'_, Result<(), StoreError>>;
420
421    /// Read one print's supervision session.
422    fn session(
423        &self,
424        print_id: PrintId,
425    ) -> BoxFuture<'_, Result<Option<SupervisionSession>, StoreError>>;
426}