Skip to main content

bus_contract/
journal.rs

1//! The `Journal` and `Relay` capabilities: events kept with a sequence
2//! number, read again from one, and served to another process.
3
4use std::any::{Any, type_name};
5use std::fmt;
6use std::sync::Arc;
7use std::time::Duration;
8
9use crate::{AnyInput, FreshFn, Point, PointKey, Refused, fresh_value};
10
11/// Writes an event's input as text, its type erased; `None` when the
12/// input is not of the point's type.
13pub type EncodeFn = fn(&(dyn Any + Send + Sync)) -> Option<String>;
14
15/// Reads an event's input back from text, its type erased.
16pub type DecodeFn = fn(&str) -> Result<AnyInput, String>;
17
18/// An event point whose input can cross a process: written as text by
19/// one bus, read back by another ([`Relay`]).
20///
21/// The format is the application's (JSON, most often), the same on both
22/// ends. Two processes of different versions read each other: a decoder
23/// should accept fields it does not know and fill the ones it misses,
24/// and fail only on a payload it cannot use.
25pub trait Relayed: Point {
26    /// The input as text.
27    fn encode(input: &Self::Input) -> String;
28    /// The input read back from text, or why it cannot be.
29    fn decode(text: &str) -> Result<Self::Input, String>;
30}
31
32/// How a relayable point's input is written and read
33/// ([`Relayed`]), its types erased, for a contract table
34/// ([`PointDecl::relayable`](crate::PointDecl::relayable)). Two codecs
35/// are equal when they are for the same point.
36#[derive(Clone, Copy, Debug)]
37pub struct Codec {
38    /// The point it is for ([`Point::ID`]): [`declare_all`](crate::declare_all)
39    /// refuses a codec on another point ([`Refused::TypeMismatch`]).
40    pub point: &'static str,
41    /// Writes an input.
42    pub encode: EncodeFn,
43    /// Reads one back.
44    pub decode: DecodeFn,
45    /// Makes the value each listener fills when an event relayed in is
46    /// delivered ([`Relay::ingest`]).
47    pub fresh: FreshFn,
48}
49
50impl Codec {
51    /// The codec of the point `P`.
52    pub const fn of<P: Relayed>() -> Codec
53    where
54        P::Value: Default,
55    {
56        Codec {
57            point: P::ID,
58            encode: encode_erased::<P>,
59            decode: decode_erased::<P>,
60            fresh: fresh_value::<P::Value>,
61        }
62    }
63}
64
65impl PartialEq for Codec {
66    fn eq(&self, other: &Codec) -> bool {
67        self.point == other.point
68    }
69}
70
71impl Eq for Codec {}
72
73fn encode_erased<P: Relayed>(input: &(dyn Any + Send + Sync)) -> Option<String> {
74    input.downcast_ref::<P::Input>().map(P::encode)
75}
76
77fn decode_erased<P: Relayed>(text: &str) -> Result<AnyInput, String> {
78    P::decode(text).map(|input| Arc::new(input) as AnyInput)
79}
80
81/// Whether the event kind `kind` matches `pattern`: the same id, or a
82/// prefix ending in `.*` (`vault.*` matches `vault.changed`), or `*` for
83/// every kind. Every implementation reads patterns this way.
84pub fn kind_matches(pattern: &str, kind: &str) -> bool {
85    if pattern == "*" || pattern == kind {
86        return true;
87    }
88    match pattern.strip_suffix(".*") {
89        Some(prefix) => kind
90            .strip_prefix(prefix)
91            .is_some_and(|rest| rest.starts_with('.')),
92        None => false,
93    }
94}
95
96/// One event of a journal: what happened, its number, what caused it.
97#[derive(Clone)]
98#[non_exhaustive]
99pub struct JournalEntry {
100    /// Its number in this journal: from 1, increasing by one, never
101    /// reused while the process runs.
102    pub seq: u64,
103    /// Its kind: the event point's id, or a kind the journal keeps with
104    /// no point (a fact recorded by the implementation, an event relayed
105    /// from a process whose point this one does not declare).
106    pub kind: String,
107    /// The entry that caused it, if one did: a number in this journal,
108    /// or, for an entry relayed in ([`JournalEntry::source`] set), in
109    /// its source's.
110    pub cause: Option<u64>,
111    /// Where it was published: `None` here, else the source a
112    /// [`Relay::ingest`] named (another process).
113    pub source: Option<String>,
114    /// Its input, typed, when this process holds it: published here, or
115    /// relayed and decoded with its point's codec.
116    pub input: Option<AnyInput>,
117    /// Its input as text, when it has one: relayed in, or written by a
118    /// codec.
119    pub text: Option<String>,
120}
121
122impl JournalEntry {
123    /// The entry `seq` of `kind`, with no cause, no source and no input.
124    pub fn new(seq: u64, kind: impl Into<String>) -> JournalEntry {
125        JournalEntry {
126            seq,
127            kind: kind.into(),
128            cause: None,
129            source: None,
130            input: None,
131            text: None,
132        }
133    }
134
135    /// The input of the event point `P`, when the entry is one of its
136    /// events and holds it typed.
137    pub fn read<P: Point>(&self) -> Option<&P::Input> {
138        if self.kind != P::ID {
139            return None;
140        }
141        self.input.as_deref()?.downcast_ref::<P::Input>()
142    }
143}
144
145impl fmt::Debug for JournalEntry {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        f.debug_struct("JournalEntry")
148            .field("seq", &self.seq)
149            .field("kind", &self.kind)
150            .field("cause", &self.cause)
151            .field("source", &self.source)
152            .field("input", &self.input.as_ref().map(|_| ".."))
153            .field("text", &self.text)
154            .finish()
155    }
156}
157
158/// What a read of a journal after a number found ([`Journal::since`]).
159#[derive(Clone, Debug)]
160#[non_exhaustive]
161pub struct Since {
162    /// The entries after the number asked, oldest first.
163    pub entries: Vec<JournalEntry>,
164    /// Entries after the number asked were dropped before this read (a
165    /// journal keeps a window): the reader missed them, and rebuilds
166    /// what it follows from the current state.
167    pub gap: bool,
168    /// The journal's last number when it was read.
169    pub last_seq: u64,
170}
171
172impl Since {
173    /// A read that found `entries`, with no gap, the journal at
174    /// `last_seq`.
175    pub fn new(entries: Vec<JournalEntry>, last_seq: u64) -> Since {
176        Since {
177            entries,
178            gap: false,
179            last_seq,
180        }
181    }
182}
183
184/// A capability of a bus ([`Bus::journal`](crate::Bus::journal)): events
185/// kept in order with a number, read again from a number, and delivered
186/// to their point's listeners after the publisher has moved on.
187///
188/// An event point is journaled when its declaration says so
189/// ([`PointDecl::journaled`](crate::PointDecl::journaled),
190/// [`PointSpec::journaled`](crate::PointSpec::journaled)). Its events are
191/// published through the journal ([`Journal::publish_any`], typed
192/// `publish::<P>`), not emitted.
193///
194/// What an implementation promises:
195///
196/// - Numbers start at 1 and increase by one with each entry; the
197///   journal is ordered by them. An implementation may keep entries
198///   that are not events of a point (its own facts, events relayed in
199///   from a kind not declared here).
200/// - Publishing never runs a listener and never waits on one: it
201///   records the entry and returns its number.
202/// - Each entry of a journaled point is delivered to the point's
203///   listeners once, entries in number order, each as a collect emit of
204///   the point with the entry's input (every rule of
205///   [`Bus`](crate::Bus) holds: order, deadlines, failures, local
206///   listeners queued for their thread). Delivery runs on a thread of
207///   the implementation's (a pump), so a slow listener delays the
208///   following entries, never the publisher; deadlines bound it.
209/// - The journal keeps a window: [`Journal::since`] reports a gap when
210///   entries after the number asked were dropped.
211pub trait Journal: Send + Sync {
212    /// The number of the last entry; 0 before the first.
213    fn last_seq(&self) -> u64;
214
215    /// The entries after `seq`, oldest first, at most `limit`; a gap when
216    /// some were dropped before this read.
217    fn since(&self, seq: u64, limit: usize) -> Since;
218
219    /// The first entry after `seq` whose kind matches one of `patterns`
220    /// ([`kind_matches`]; empty matches every kind), waiting for it up
221    /// to `timeout`; `None` when none came. An entry already in the
222    /// journal is returned at once.
223    fn wait(&self, patterns: &[&str], seq: u64, timeout: Duration) -> Option<JournalEntry>;
224
225    /// Records an event of the journaled point `point`, caused by the
226    /// entry `cause`; its number. `fresh` makes the value each listener
227    /// fills at delivery. Refused, with nothing recorded, when the point
228    /// is not declared journaled on this bus ([`Refused::NotJournaled`])
229    /// or is declared with another type ([`Refused::TypeMismatch`]).
230    fn publish_any(
231        &self,
232        point: PointKey,
233        input: AnyInput,
234        fresh: FreshFn,
235        cause: Option<u64>,
236    ) -> Result<u64, Refused>;
237
238    /// Waits until every entry recorded before the call has been
239    /// delivered to its listeners, up to `timeout`; whether it was. For
240    /// a host before it exits and for tests.
241    fn flush(&self, timeout: Duration) -> bool;
242}
243
244impl<'a> dyn Journal + 'a {
245    /// Publishes an event of the journaled point `P`: recorded now,
246    /// delivered to its listeners later, in journal order. Its number.
247    pub fn publish<P: Point>(&self, input: P::Input) -> Result<u64, Refused>
248    where
249        P::Value: Default,
250    {
251        self.publish_any(
252            PointKey::of::<P>(),
253            Arc::new(input),
254            fresh_value::<P::Value>,
255            None,
256        )
257    }
258
259    /// Publishes an event of `P` caused by the entry `cause`.
260    pub fn publish_caused<P: Point>(&self, input: P::Input, cause: u64) -> Result<u64, Refused>
261    where
262        P::Value: Default,
263    {
264        self.publish_any(
265            PointKey::of::<P>(),
266            Arc::new(input),
267            fresh_value::<P::Value>,
268            Some(cause),
269        )
270    }
271
272    /// The next event of `P` after `seq`, typed, waiting up to
273    /// `timeout`.
274    pub fn wait_for<P: Point>(&self, seq: u64, timeout: Duration) -> Option<(u64, P::Input)>
275    where
276        P::Input: Clone,
277    {
278        let entry = self.wait(&[P::ID], seq, timeout)?;
279        let input = entry.read::<P>().cloned().unwrap_or_else(|| {
280            panic!(
281                "the journal returned a `{}` entry with no `{}` input",
282                P::ID,
283                type_name::<P::Input>()
284            )
285        });
286        Some((entry.seq, input))
287    }
288}
289
290/// Where a reader of a relay stands: the journal run it read and the
291/// last number it took.
292#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
293pub struct Cursor {
294    /// The journal's run ([`Relay::cursor`]); it changes when the
295    /// journal starts again (the process restarted) and numbers restart
296    /// with it. 0: the reader has read nothing yet.
297    pub run: u64,
298    /// The last number taken in that run.
299    pub seq: u64,
300}
301
302impl Cursor {
303    /// A reader that has read nothing: [`Relay::resume`] from it returns
304    /// what the journal still keeps, with nothing lost.
305    pub const START: Cursor = Cursor { run: 0, seq: 0 };
306}
307
308/// An event as it crosses a process ([`Relay`]): its input as text.
309#[derive(Clone, Debug, PartialEq, Eq)]
310#[non_exhaustive]
311pub struct RelayedEntry {
312    /// Its number in the journal it was read from.
313    pub seq: u64,
314    /// Its point's id.
315    pub kind: String,
316    /// The entry that caused it, in the journal it was read from.
317    pub cause: Option<u64>,
318    /// Its input, written by its point's codec.
319    pub text: String,
320}
321
322impl RelayedEntry {
323    /// The entry `seq` of `kind`, its input `text`, with no cause.
324    pub fn new(seq: u64, kind: impl Into<String>, text: impl Into<String>) -> RelayedEntry {
325        RelayedEntry {
326            seq,
327            kind: kind.into(),
328            cause: None,
329            text: text.into(),
330        }
331    }
332}
333
334/// Why a reader of a relay missed entries ([`Resumed::lost`]).
335#[derive(Clone, Copy, Debug, PartialEq, Eq)]
336#[non_exhaustive]
337pub enum Lost {
338    /// Entries after the reader's number were dropped from the journal's
339    /// window.
340    Gap,
341    /// The journal started again (another run): the reader's number
342    /// means nothing in it.
343    Restarted,
344}
345
346/// What a relay read found ([`Relay::resume`]).
347#[derive(Clone, Debug, PartialEq, Eq)]
348#[non_exhaustive]
349pub struct Resumed {
350    /// The relayable entries after the reader's cursor, oldest first.
351    pub entries: Vec<RelayedEntry>,
352    /// Whether the reader missed entries before these: it rebuilds what
353    /// it follows from the current state (a resync), then applies them.
354    pub lost: Option<Lost>,
355    /// Where the reader resumes next time.
356    pub next: Cursor,
357}
358
359impl Resumed {
360    /// A read that found `entries`, nothing lost, resuming at `next`.
361    pub fn new(entries: Vec<RelayedEntry>, next: Cursor) -> Resumed {
362        Resumed {
363            entries,
364            lost: None,
365            next,
366        }
367    }
368}
369
370/// Why an entry relayed in was not taken ([`Relay::ingest`]).
371#[derive(Clone, Debug, PartialEq, Eq)]
372#[non_exhaustive]
373pub enum IngestError {
374    /// Its point is declared here and its codec could not read the text
375    /// (a sender of another version, a broken payload). Nothing was
376    /// recorded.
377    Decode {
378        /// The point.
379        kind: String,
380        /// What the codec said.
381        reason: String,
382    },
383    /// Its point is declared here but not relayable: a process may not
384    /// publish it on this one. Nothing was recorded.
385    NotRelayable {
386        /// The point.
387        kind: String,
388    },
389}
390
391impl fmt::Display for IngestError {
392    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393        match self {
394            IngestError::Decode { kind, reason } => {
395                write!(f, "relayed `{kind}`: cannot read its input: {reason}")
396            }
397            IngestError::NotRelayable { kind } => {
398                write!(f, "relayed `{kind}`: the point is not relayable here")
399            }
400        }
401    }
402}
403
404impl std::error::Error for IngestError {}
405
406/// A capability of a bus ([`Bus::relay`](crate::Bus::relay)), on top of
407/// its [`Journal`]: the events of relayable points served to another
408/// process from a cursor, and the events another process serves taken
409/// in as if published here.
410///
411/// A point is relayable when its declaration gives it a codec
412/// ([`PointDecl::relayable`](crate::PointDecl::relayable)); only its
413/// events cross. The transport (a socket, a pipe, an RPC) is the
414/// application's: a relay reads and takes entries, it does not move
415/// them.
416///
417/// What an implementation promises:
418///
419/// - A bus that offers `Relay` offers [`Journal`].
420/// - [`Relay::resume`] returns the relayable entries after the cursor,
421///   in number order, each written by its point's codec, and the cursor
422///   to resume from. A cursor of another run returns the run's entries
423///   from its start with [`Lost::Restarted`]; a cursor whose next
424///   entries left the window returns the kept ones with [`Lost::Gap`].
425///   [`Cursor::START`] loses nothing.
426/// - [`Relay::ingest`] records a relayed entry in this journal with its
427///   source: a point declared here is decoded with its codec and
428///   delivered to its listeners like an entry published here; a kind
429///   not declared here is kept with its text only and delivered to no
430///   one. The cause is the sender's number, kept as it came.
431/// - Entries taken in are not served again by [`Relay::resume`]: two
432///   processes relaying to each other do not echo.
433pub trait Relay: Send + Sync {
434    /// Where a reader that starts now stands: this journal's run and its
435    /// last number.
436    fn cursor(&self) -> Cursor;
437
438    /// The relayable entries after `from`, at most `limit`.
439    fn resume(&self, from: Cursor, limit: usize) -> Resumed;
440
441    /// Takes in an entry relayed from `source`; its number in this
442    /// journal.
443    fn ingest(&self, source: &str, entry: RelayedEntry) -> Result<u64, IngestError>;
444}