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; requests
3//! answered on the other side of a process boundary (crossing).
4
5use std::any::{Any, type_name};
6use std::fmt;
7use std::sync::atomic::{AtomicU64, Ordering};
8use std::sync::{Arc, OnceLock};
9use std::time::{Duration, Instant};
10
11use crate::{
12    AnyInput, AnyListener, CloneFn, FreshFn, HookError, Point, PointKey, Refused, clone_value,
13    fresh_value,
14};
15
16/// Writes an event's input as text, its type erased; `None` when the
17/// input is not of the point's type.
18pub type EncodeFn = fn(&(dyn Any + Send + Sync)) -> Option<String>;
19
20/// Reads an event's input back from text, its type erased.
21pub type DecodeFn = fn(&str) -> Result<AnyInput, String>;
22
23/// Writes a request's value as text, its type erased; `None` when the
24/// value is not of the point's type.
25pub type EncodeValueFn = fn(&(dyn Any + Send)) -> Option<String>;
26
27/// Reads a request's value back from text into a value of the point's
28/// type, its type erased, replacing it.
29pub type DecodeValueFn = fn(&str, &mut (dyn Any + Send)) -> Result<(), String>;
30
31/// An event point whose input can cross a process: written as text by
32/// one bus, read back by another ([`Relay`]).
33///
34/// The format is the application's (JSON, most often), the same on both
35/// ends. Two processes of different versions read each other: a decoder
36/// should accept fields it does not know and fill the ones it misses,
37/// and fail only on a payload it cannot use.
38pub trait Relayed: Point {
39    /// The input as text.
40    fn encode(input: &Self::Input) -> String;
41    /// The input read back from text, or why it cannot be.
42    fn decode(text: &str) -> Result<Self::Input, String>;
43}
44
45/// A request point that can be answered by another process
46/// ([`Relay::answer`]): its value, as well as its input, written as text
47/// and read back.
48///
49/// The value goes out with the ask (what the asking side's listeners
50/// left before the far side's turn) and comes back with the answer
51/// (what the far side's listeners left). The same rules as
52/// [`Relayed`] hold for versions: accept unknown fields, fail only on a
53/// value that cannot be used.
54pub trait RelayedRequest: Relayed {
55    /// The value as text.
56    fn encode_value(value: &Self::Value) -> String;
57    /// The value read back from text, or why it cannot be.
58    fn decode_value(text: &str) -> Result<Self::Value, String>;
59}
60
61/// How a relayable point's input is written and read
62/// ([`Relayed`]), and a relayable request's value ([`RelayedRequest`]),
63/// its types erased, for a contract table
64/// ([`PointDecl::relayable`](crate::PointDecl::relayable)). Two codecs
65/// are equal when they are for the same point.
66///
67/// Build one with [`Codec::of`] (an event) or [`Codec::request`] (a
68/// request).
69#[derive(Clone, Copy, Debug)]
70#[non_exhaustive]
71pub struct Codec {
72    /// The point it is for ([`Point::ID`]): [`declare_all`](crate::declare_all)
73    /// refuses a codec on another point ([`Refused::TypeMismatch`]).
74    pub point: &'static str,
75    /// Writes an input.
76    pub encode: EncodeFn,
77    /// Reads one back.
78    pub decode: DecodeFn,
79    /// Makes the value each listener fills when an event relayed in is
80    /// delivered ([`Relay::ingest`]), and the value a request answered
81    /// here starts from before its text is read into it.
82    pub fresh: FreshFn,
83    /// On a request's codec, writes its value; `None` on an event's.
84    pub encode_value: Option<EncodeValueFn>,
85    /// On a request's codec, reads its value back; `None` on an event's.
86    pub decode_value: Option<DecodeValueFn>,
87    /// On a request's codec, copies its value (the far side runs an
88    /// alter emit, [`Bus::alter_any`](crate::Bus::alter_any)); `None` on
89    /// an event's.
90    pub clone_value: Option<CloneFn>,
91}
92
93impl Codec {
94    /// The codec of the event point `P`.
95    pub const fn of<P: Relayed>() -> Codec
96    where
97        P::Value: Default,
98    {
99        Codec {
100            point: P::ID,
101            encode: encode_erased::<P>,
102            decode: decode_erased::<P>,
103            fresh: fresh_value::<P::Value>,
104            encode_value: None,
105            decode_value: None,
106            clone_value: None,
107        }
108    }
109
110    /// The codec of the request point `P`: its input and its value.
111    pub const fn request<P: RelayedRequest>() -> Codec
112    where
113        P::Value: Default + Clone,
114    {
115        Codec {
116            point: P::ID,
117            encode: encode_erased::<P>,
118            decode: decode_erased::<P>,
119            fresh: fresh_value::<P::Value>,
120            encode_value: Some(encode_value_erased::<P>),
121            decode_value: Some(decode_value_erased::<P>),
122            clone_value: Some(clone_value::<P::Value>),
123        }
124    }
125
126    /// Whether it writes and reads a value too ([`Codec::request`]): a
127    /// request point needs one to cross.
128    pub const fn answers(&self) -> bool {
129        self.encode_value.is_some() && self.decode_value.is_some() && self.clone_value.is_some()
130    }
131}
132
133impl PartialEq for Codec {
134    fn eq(&self, other: &Codec) -> bool {
135        self.point == other.point
136    }
137}
138
139impl Eq for Codec {}
140
141fn encode_erased<P: Relayed>(input: &(dyn Any + Send + Sync)) -> Option<String> {
142    input.downcast_ref::<P::Input>().map(P::encode)
143}
144
145fn decode_erased<P: Relayed>(text: &str) -> Result<AnyInput, String> {
146    P::decode(text).map(|input| Arc::new(input) as AnyInput)
147}
148
149fn encode_value_erased<P: RelayedRequest>(value: &(dyn Any + Send)) -> Option<String> {
150    value.downcast_ref::<P::Value>().map(P::encode_value)
151}
152
153fn decode_value_erased<P: RelayedRequest>(
154    text: &str,
155    into: &mut (dyn Any + Send),
156) -> Result<(), String> {
157    let Some(slot) = into.downcast_mut::<P::Value>() else {
158        return Err(format!("the value is not a `{}`", type_name::<P::Value>()));
159    };
160    *slot = P::decode_value(text)?;
161    Ok(())
162}
163
164/// Who sent what crosses a process boundary: the far side of a link, as
165/// the receiving side knows it.
166///
167/// The receiving side sets it from the link it read the entry or the ask
168/// on (the link's own identity: a process, or an agent's session), never
169/// from what the sender wrote: a sender cannot claim another origin.
170/// Every entry taken in carries one ([`JournalEntry::origin`]); every ask
171/// answered is checked against one ([`Relay::answer`]).
172#[derive(Clone, Debug, PartialEq, Eq, Hash)]
173#[non_exhaustive]
174pub struct Origin {
175    /// The process on the far side of the link (`node`, `plugin:geo`).
176    pub process: String,
177    /// The agent the link speaks for, when the link is an agent's
178    /// session (the agent socket, an MCP client); `None` for a process.
179    pub agent: Option<String>,
180}
181
182impl Origin {
183    /// The process `name`, no agent.
184    pub fn process(name: impl Into<String>) -> Origin {
185        Origin {
186            process: name.into(),
187            agent: None,
188        }
189    }
190
191    /// The same origin, speaking for the agent `name`.
192    pub fn agent(mut self, name: impl Into<String>) -> Origin {
193        self.agent = Some(name.into());
194        self
195    }
196}
197
198impl fmt::Display for Origin {
199    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200        match &self.agent {
201            Some(agent) => write!(f, "{} (agent {agent})", self.process),
202            None => f.write_str(&self.process),
203        }
204    }
205}
206
207/// Whether the event kind `kind` matches `pattern`: the same id, or a
208/// prefix ending in `.*` (`vault.*` matches `vault.changed`), or `*` for
209/// every kind. Every implementation reads patterns this way.
210pub fn kind_matches(pattern: &str, kind: &str) -> bool {
211    if pattern == "*" || pattern == kind {
212        return true;
213    }
214    match pattern.strip_suffix(".*") {
215        Some(prefix) => kind
216            .strip_prefix(prefix)
217            .is_some_and(|rest| rest.starts_with('.')),
218        None => false,
219    }
220}
221
222/// One event of a journal: what happened, its number, what caused it.
223#[derive(Clone)]
224#[non_exhaustive]
225pub struct JournalEntry {
226    /// Its number in this journal: from 1, increasing by one, never
227    /// reused while the process runs.
228    pub seq: u64,
229    /// Its kind: the event point's id, or a kind the journal keeps with
230    /// no point (a fact recorded by the implementation, an event relayed
231    /// from a process whose point this one does not declare).
232    pub kind: String,
233    /// The entry that caused it, if one did: a number in this journal,
234    /// or, for an entry relayed in ([`JournalEntry::origin`] set), in
235    /// its origin's.
236    pub cause: Option<u64>,
237    /// Where it was published: `None` here, else the origin
238    /// [`Relay::ingest`] was given (another process, an agent's
239    /// session). Every entry taken in has one.
240    pub origin: Option<Origin>,
241    /// Its input, typed, when this process holds it: published here, or
242    /// relayed and decoded with its point's codec.
243    pub input: Option<AnyInput>,
244    /// Its input as text, when it has one: relayed in, or written by a
245    /// codec.
246    pub text: Option<String>,
247}
248
249impl JournalEntry {
250    /// The entry `seq` of `kind`, with no cause, no origin and no input.
251    pub fn new(seq: u64, kind: impl Into<String>) -> JournalEntry {
252        JournalEntry {
253            seq,
254            kind: kind.into(),
255            cause: None,
256            origin: None,
257            input: None,
258            text: None,
259        }
260    }
261
262    /// The input of the event point `P`, when the entry is one of its
263    /// events and holds it typed.
264    pub fn read<P: Point>(&self) -> Option<&P::Input> {
265        if self.kind != P::ID {
266            return None;
267        }
268        self.input.as_deref()?.downcast_ref::<P::Input>()
269    }
270}
271
272impl fmt::Debug for JournalEntry {
273    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274        f.debug_struct("JournalEntry")
275            .field("seq", &self.seq)
276            .field("kind", &self.kind)
277            .field("cause", &self.cause)
278            .field("origin", &self.origin)
279            .field("input", &self.input.as_ref().map(|_| ".."))
280            .field("text", &self.text)
281            .finish()
282    }
283}
284
285/// What a read of a journal after a number found ([`Journal::since`]).
286#[derive(Clone, Debug)]
287#[non_exhaustive]
288pub struct Since {
289    /// The entries after the number asked, oldest first.
290    pub entries: Vec<JournalEntry>,
291    /// Entries after the number asked were dropped before this read (a
292    /// journal keeps a window): the reader missed them, and rebuilds
293    /// what it follows from the current state.
294    pub gap: bool,
295    /// The journal's last number when it was read.
296    pub last_seq: u64,
297}
298
299impl Since {
300    /// A read that found `entries`, with no gap, the journal at
301    /// `last_seq`.
302    pub fn new(entries: Vec<JournalEntry>, last_seq: u64) -> Since {
303        Since {
304            entries,
305            gap: false,
306            last_seq,
307        }
308    }
309}
310
311/// A capability of a bus ([`Bus::journal`](crate::Bus::journal)): events
312/// kept in order with a number, read again from a number, and delivered
313/// to their point's listeners after the publisher has moved on.
314///
315/// An event point is journaled when its declaration says so
316/// ([`PointDecl::journaled`](crate::PointDecl::journaled),
317/// [`PointSpec::journaled`](crate::PointSpec::journaled)). Its events are
318/// published through the journal ([`Journal::publish_any`], typed
319/// `publish::<P>`), not emitted.
320///
321/// What an implementation promises:
322///
323/// - Numbers start at 1 and increase by one with each entry; the
324///   journal is ordered by them. An implementation may keep entries
325///   that are not events of a point (its own facts, events relayed in
326///   from a kind not declared here).
327/// - Publishing never runs a listener and never waits on one: it
328///   records the entry and returns its number.
329/// - Each entry of a journaled point is delivered to the point's
330///   listeners once, entries in number order, each as a collect emit of
331///   the point with the entry's input (every rule of
332///   [`Bus`](crate::Bus) holds: order, deadlines, failures, local
333///   listeners queued for their thread). Delivery runs on a thread of
334///   the implementation's (a pump), so a slow listener delays the
335///   following entries, never the publisher; deadlines bound it.
336/// - The journal keeps a window: [`Journal::since`] reports a gap when
337///   entries after the number asked were dropped.
338pub trait Journal: Send + Sync {
339    /// The number of the last entry; 0 before the first.
340    fn last_seq(&self) -> u64;
341
342    /// The entries after `seq`, oldest first, at most `limit`; a gap when
343    /// some were dropped before this read.
344    fn since(&self, seq: u64, limit: usize) -> Since;
345
346    /// The first entry after `seq` whose kind matches one of `patterns`
347    /// ([`kind_matches`]; empty matches every kind), waiting for it up
348    /// to `timeout`; `None` when none came. An entry already in the
349    /// journal is returned at once.
350    fn wait(&self, patterns: &[&str], seq: u64, timeout: Duration) -> Option<JournalEntry>;
351
352    /// Records an event of the journaled point `point`, caused by the
353    /// entry `cause`; its number. `fresh` makes the value each listener
354    /// fills at delivery. Refused, with nothing recorded, when the point
355    /// is not declared journaled on this bus ([`Refused::NotJournaled`])
356    /// or is declared with another type ([`Refused::TypeMismatch`]).
357    fn publish_any(
358        &self,
359        point: PointKey,
360        input: AnyInput,
361        fresh: FreshFn,
362        cause: Option<u64>,
363    ) -> Result<u64, Refused>;
364
365    /// Waits until every entry recorded before the call has been
366    /// delivered to its listeners, up to `timeout`; whether it was. For
367    /// a host before it exits and for tests.
368    fn flush(&self, timeout: Duration) -> bool;
369}
370
371impl<'a> dyn Journal + 'a {
372    /// Publishes an event of the journaled point `P`: recorded now,
373    /// delivered to its listeners later, in journal order. Its number.
374    pub fn publish<P: Point>(&self, input: P::Input) -> Result<u64, Refused>
375    where
376        P::Value: Default,
377    {
378        self.publish_any(
379            PointKey::of::<P>(),
380            Arc::new(input),
381            fresh_value::<P::Value>,
382            None,
383        )
384    }
385
386    /// Publishes an event of `P` caused by the entry `cause`.
387    pub fn publish_caused<P: Point>(&self, input: P::Input, cause: u64) -> Result<u64, Refused>
388    where
389        P::Value: Default,
390    {
391        self.publish_any(
392            PointKey::of::<P>(),
393            Arc::new(input),
394            fresh_value::<P::Value>,
395            Some(cause),
396        )
397    }
398
399    /// The next event of `P` after `seq`, typed, waiting up to
400    /// `timeout`.
401    pub fn wait_for<P: Point>(&self, seq: u64, timeout: Duration) -> Option<(u64, P::Input)>
402    where
403        P::Input: Clone,
404    {
405        let entry = self.wait(&[P::ID], seq, timeout)?;
406        let input = entry.read::<P>().cloned().unwrap_or_else(|| {
407            panic!(
408                "the journal returned a `{}` entry with no `{}` input",
409                P::ID,
410                type_name::<P::Input>()
411            )
412        });
413        Some((entry.seq, input))
414    }
415}
416
417/// Where a reader of a relay stands: the journal run it read and the
418/// last number it took.
419#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
420pub struct Cursor {
421    /// The journal's run ([`Relay::cursor`]); it changes when the
422    /// journal starts again (the process restarted) and numbers restart
423    /// with it. 0: the reader has read nothing yet.
424    pub run: u64,
425    /// The last number taken in that run.
426    pub seq: u64,
427}
428
429impl Cursor {
430    /// A reader that has read nothing: [`Relay::resume`] from it returns
431    /// what the journal still keeps, with nothing lost.
432    pub const START: Cursor = Cursor { run: 0, seq: 0 };
433}
434
435/// An event as it crosses a process ([`Relay`]): its input as text.
436#[derive(Clone, Debug, PartialEq, Eq)]
437#[non_exhaustive]
438pub struct RelayedEntry {
439    /// Its number in the journal it was read from.
440    pub seq: u64,
441    /// Its point's id.
442    pub kind: String,
443    /// The entry that caused it, in the journal it was read from.
444    pub cause: Option<u64>,
445    /// Its point's version on the sending side
446    /// ([`PointDecl::version`](crate::PointDecl::version)): a receiver
447    /// that declares the point with another version refuses it
448    /// ([`IngestError::Version`]).
449    pub version: u32,
450    /// Its input, written by its point's codec.
451    pub text: String,
452}
453
454impl RelayedEntry {
455    /// The entry `seq` of `kind`, its input `text`, with no cause, at
456    /// version 1.
457    pub fn new(seq: u64, kind: impl Into<String>, text: impl Into<String>) -> RelayedEntry {
458        RelayedEntry {
459            seq,
460            kind: kind.into(),
461            cause: None,
462            version: 1,
463            text: text.into(),
464        }
465    }
466}
467
468/// Why a reader of a relay missed entries ([`Resumed::lost`]).
469#[derive(Clone, Copy, Debug, PartialEq, Eq)]
470#[non_exhaustive]
471pub enum Lost {
472    /// Entries after the reader's number were dropped from the journal's
473    /// window.
474    Gap,
475    /// The journal started again (another run): the reader's number
476    /// means nothing in it.
477    Restarted,
478}
479
480/// What a relay read found ([`Relay::resume`]).
481#[derive(Clone, Debug, PartialEq, Eq)]
482#[non_exhaustive]
483pub struct Resumed {
484    /// The relayable entries after the reader's cursor, oldest first.
485    pub entries: Vec<RelayedEntry>,
486    /// Whether the reader missed entries before these: it rebuilds what
487    /// it follows from the current state (a resync), then applies them.
488    pub lost: Option<Lost>,
489    /// Where the reader resumes next time.
490    pub next: Cursor,
491}
492
493impl Resumed {
494    /// A read that found `entries`, nothing lost, resuming at `next`.
495    pub fn new(entries: Vec<RelayedEntry>, next: Cursor) -> Resumed {
496        Resumed {
497            entries,
498            lost: None,
499            next,
500        }
501    }
502}
503
504/// Why an entry relayed in was not taken ([`Relay::ingest`]).
505#[derive(Clone, Debug, PartialEq, Eq)]
506#[non_exhaustive]
507pub enum IngestError {
508    /// Its point is declared here and its codec could not read the text
509    /// (a sender of another version, a broken payload). Nothing was
510    /// recorded.
511    Decode {
512        /// The point.
513        kind: String,
514        /// What the codec said.
515        reason: String,
516    },
517    /// Its point is declared here but not relayable: a process may not
518    /// publish it on this one. Nothing was recorded.
519    NotRelayable {
520        /// The point.
521        kind: String,
522    },
523    /// An authority of this bus refused it ([`Relay::add_authority`]).
524    /// Nothing was recorded.
525    Refused {
526        /// The point.
527        kind: String,
528        /// What the authority said.
529        reason: String,
530    },
531    /// Its point is declared here with another version: the sender and
532    /// this process do not mean the same payload by it. Nothing was
533    /// recorded.
534    Version {
535        /// The point.
536        kind: String,
537        /// The sender's version.
538        sent: u32,
539        /// This process's version.
540        here: u32,
541    },
542}
543
544impl fmt::Display for IngestError {
545    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
546        match self {
547            IngestError::Decode { kind, reason } => {
548                write!(f, "relayed `{kind}`: cannot read its input: {reason}")
549            }
550            IngestError::NotRelayable { kind } => {
551                write!(f, "relayed `{kind}`: the point is not relayable here")
552            }
553            IngestError::Refused { kind, reason } => {
554                write!(f, "relayed `{kind}`: refused: {reason}")
555            }
556            IngestError::Version { kind, sent, here } => write!(
557                f,
558                "relayed `{kind}`: sent at version {sent}, declared here at version {here}"
559            ),
560        }
561    }
562}
563
564impl std::error::Error for IngestError {}
565
566/// What an authority of a bus is shown of something crossing in
567/// ([`Relay::add_authority`]), before anything is decoded or recorded.
568#[derive(Clone, Copy, Debug)]
569#[non_exhaustive]
570pub struct Crossing<'a> {
571    /// Who sent it: the link it came on.
572    pub origin: &'a Origin,
573    /// Its point's id (or a kind this process does not declare).
574    pub kind: &'a str,
575    /// Its point's version on the sending side.
576    pub version: u32,
577    /// An ask to answer ([`Relay::answer`]) rather than an event taken in
578    /// ([`Relay::ingest`]).
579    pub ask: bool,
580}
581
582impl<'a> Crossing<'a> {
583    /// An event of `kind` at `version` from `origin`, or an ask when
584    /// `ask` is set.
585    pub fn new(origin: &'a Origin, kind: &'a str, version: u32, ask: bool) -> Crossing<'a> {
586        Crossing {
587            origin,
588            kind,
589            version,
590            ask,
591        }
592    }
593}
594
595/// Decides whether what crosses in may be taken ([`Relay::add_authority`]):
596/// `Err(reason)` refuses it.
597pub type Authority = Arc<dyn Fn(&Crossing<'_>) -> Result<(), String> + Send + Sync>;
598
599/// A request asked of another process ([`Relay::answer`]): its input and
600/// the value so far, as text, with the time the asker waits.
601#[derive(Clone, Debug, PartialEq, Eq)]
602#[non_exhaustive]
603pub struct RelayedAsk {
604    /// The asking process's run: it changes when that process starts
605    /// again. With [`RelayedAsk::id`], names the ask.
606    pub run: u64,
607    /// The ask's number in its run; never reused while the run lasts.
608    pub id: u64,
609    /// Its point's id.
610    pub kind: String,
611    /// Its point's version on the asking side.
612    pub version: u32,
613    /// How long the asker waits for the answer, counted from when it
614    /// sent the ask: the far side counts it from when it got the ask
615    /// (clocks of two machines are not compared). Past it, both sides
616    /// hold the ask refused.
617    pub deadline: Duration,
618    /// Its input, written by its point's codec.
619    pub input: String,
620    /// The value the asking side's listeners left before the far side's
621    /// turn, written by its point's codec.
622    pub value: String,
623}
624
625impl RelayedAsk {
626    /// The ask `id` of the run `run` on `kind`, at version 1.
627    pub fn new(
628        run: u64,
629        id: u64,
630        kind: impl Into<String>,
631        deadline: Duration,
632        input: impl Into<String>,
633        value: impl Into<String>,
634    ) -> RelayedAsk {
635        RelayedAsk {
636            run,
637            id,
638            kind: kind.into(),
639            version: 1,
640            deadline,
641            input: input.into(),
642            value: value.into(),
643        }
644    }
645}
646
647/// How an ask was answered ([`RelayedAnswer::answer`]).
648#[derive(Clone, Debug, PartialEq, Eq)]
649#[non_exhaustive]
650pub enum Answer {
651    /// The far side's listeners ran and none refused: the value they
652    /// left, as text.
653    Done {
654        /// The value, written by the point's codec.
655        value: String,
656    },
657    /// The ask was refused: by a listener of the far side (a veto, or a
658    /// failure: the point is fail-closed), or by the far bus itself (an
659    /// authority, a point it does not declare, relayable or at this
660    /// version, an input it cannot read, the deadline gone).
661    Refused {
662        /// The far listener that refused it; `None` when the far bus
663        /// refused it before any listener ran.
664        listener: Option<String>,
665        /// That listener's owner.
666        owner: Option<String>,
667        /// Why: the listener's reason, or the bus's.
668        reason: String,
669        /// Whether a listener failed rather than refused
670        /// ([`Refusal::failed`](crate::Refusal::failed)).
671        failed: bool,
672    },
673}
674
675impl Answer {
676    /// A refusal by the far bus itself, before any listener ran.
677    pub fn refused(reason: impl Into<String>) -> Answer {
678        Answer::Refused {
679            listener: None,
680            owner: None,
681            reason: reason.into(),
682            failed: false,
683        }
684    }
685}
686
687/// The answer to one ask ([`Relay::answer`]), naming it.
688#[derive(Clone, Debug, PartialEq, Eq)]
689#[non_exhaustive]
690pub struct RelayedAnswer {
691    /// The ask's run ([`RelayedAsk::run`]).
692    pub run: u64,
693    /// The ask's number ([`RelayedAsk::id`]).
694    pub id: u64,
695    /// What it got.
696    pub answer: Answer,
697}
698
699impl RelayedAnswer {
700    /// The answer `answer` to `ask`.
701    pub fn to(ask: &RelayedAsk, answer: Answer) -> RelayedAnswer {
702        RelayedAnswer {
703            run: ask.run,
704            id: ask.id,
705            answer,
706        }
707    }
708}
709
710/// A capability of a bus ([`Bus::relay`](crate::Bus::relay)), on top of
711/// its [`Journal`]: what crosses a process boundary. The events of
712/// relayable points served to another process from a cursor and taken
713/// in from one as if published here; the asks of relayable request
714/// points answered here for another process.
715///
716/// A point is relayable when its declaration gives it a codec
717/// ([`PointDecl::relayable`](crate::PointDecl::relayable)); only events
718/// and requests cross. The transport (a socket, a pipe, an RPC, a
719/// channel in the same process) is not part of the contract: a relay
720/// reads, takes in and answers; something else moves the text. Whatever
721/// moves it, the meaning is the one written here, so a listener cannot
722/// tell whether the far side is in this process or another.
723///
724/// What an implementation promises:
725///
726/// - A bus that offers `Relay` offers [`Journal`].
727/// - [`Relay::resume`] returns the relayable entries after the cursor,
728///   in number order, each written by its point's codec with its point's
729///   version, and the cursor to resume from. A cursor of another run
730///   returns the run's entries from its start with [`Lost::Restarted`];
731///   a cursor whose next entries left the window returns the kept ones
732///   with [`Lost::Gap`]. [`Cursor::START`] loses nothing.
733/// - Authority first: whatever comes in ([`Relay::ingest`],
734///   [`Relay::answer`]) is shown to every authority added
735///   ([`Relay::add_authority`]), in the order they were added, before
736///   anything is decoded, recorded or run. One refusal refuses it. With
737///   no authority added, everything relayable is taken.
738/// - [`Relay::ingest`] records a relayed entry in this journal with its
739///   origin: a point declared here is decoded with its codec and
740///   delivered to its listeners like an entry published here; a kind
741///   not declared here is kept with its text only and delivered to no
742///   one. The cause is the sender's number, kept as it came. A point
743///   declared here but not relayable, or at another version, is refused.
744/// - Entries taken in are not served again by [`Relay::resume`]: two
745///   processes relaying to each other do not echo.
746/// - [`Relay::answer`] runs a relayable request's listeners here, as an
747///   alter emit of the point with the ask's input and value read by its
748///   codec, and answers with the value they left or the refusal. Every
749///   rule of [`Bus`](crate::Bus) holds; a relayable request point is
750///   fail-closed. It refuses, running no listener, an ask on a point not
751///   declared here, not relayable, at another version, whose input or
752///   value it cannot read, or whose deadline has passed when it would
753///   run. When the listeners end past the ask's deadline, the answer is
754///   a refusal (failed) whatever they did: the asker has stopped
755///   waiting and holds it refused, and both sides record the same.
756/// - Each ask is answered once: an ask whose run and number this bus has
757///   already answered for the same origin process runs no listener; it
758///   gets the first answer again while the bus still keeps it (at least
759///   as long as the ask's deadline), else a refusal.
760pub trait Relay: Send + Sync {
761    /// Where a reader that starts now stands: this journal's run and its
762    /// last number.
763    fn cursor(&self) -> Cursor;
764
765    /// The relayable entries after `from`, at most `limit`.
766    fn resume(&self, from: Cursor, limit: usize) -> Resumed;
767
768    /// Takes in an entry relayed from `origin`; its number in this
769    /// journal.
770    fn ingest(&self, origin: &Origin, entry: RelayedEntry) -> Result<u64, IngestError>;
771
772    /// Answers an ask relayed from `origin`: runs the request's listeners
773    /// here and says what they did. Blocks while they run.
774    fn answer(&self, origin: &Origin, ask: RelayedAsk) -> RelayedAnswer;
775
776    /// Adds an authority shown everything that crosses in before it is
777    /// taken: an event to ingest, an ask to answer. An authority that
778    /// panics refuses.
779    fn add_authority(&self, authority: Authority);
780}
781
782impl<'a> dyn Relay + 'a {
783    /// Adds an authority ([`Relay::add_authority`]): `Err(reason)`
784    /// refuses what crosses in.
785    pub fn authorize(
786        &self,
787        authority: impl Fn(&Crossing<'_>) -> Result<(), String> + Send + Sync + 'static,
788    ) {
789        self.add_authority(Arc::new(authority));
790    }
791}
792
793/// This process's run, for the asks it sends ([`RelayedAsk::run`]):
794/// fixed while the process runs, another one after a restart.
795pub fn ask_run() -> u64 {
796    static RUN: OnceLock<u64> = OnceLock::new();
797    *RUN.get_or_init(|| {
798        let nanos = std::time::SystemTime::now()
799            .duration_since(std::time::UNIX_EPOCH)
800            .map_or(0, |d| d.as_nanos() as u64);
801        (nanos ^ (u64::from(std::process::id()) << 32)).max(1)
802    })
803}
804
805/// The next ask number of this process ([`RelayedAsk::id`]).
806fn next_ask_id() -> u64 {
807    static NEXT: AtomicU64 = AtomicU64::new(1);
808    NEXT.fetch_add(1, Ordering::Relaxed)
809}
810
811/// The listener that stands, on the asking side, for the far side of a
812/// relayable request point: register it on the point here (with the
813/// point's deadline and threaded, so the emit stops waiting at the
814/// deadline), and the far side's listeners take their turn in this
815/// side's order, at its place.
816///
817/// When it runs, it writes the input and the value so far with `codec`
818/// ([`Codec::request`]), numbers the ask ([`ask_run`], a number of this
819/// process), and hands it to `send`, which moves it to the far side's
820/// [`Relay::answer`] and returns the answer, or `None` when none came
821/// within [`RelayedAsk::deadline`] (a link down, a far side gone, too
822/// slow). Then:
823///
824/// - an answer [`Answer::Done`] in time replaces the value with the far
825///   side's;
826/// - no answer, an answer after `deadline`, an answer to another ask, or
827///   a value it cannot read refuses the request ("no answer is a no");
828/// - an [`Answer::Refused`] refuses the request with the far side's
829///   reason, naming the far listener.
830///
831/// `send` is the transport's part; this listener is the contract's, so
832/// every transport gives a crossing request the same meaning.
833pub fn far_listener(
834    codec: Codec,
835    deadline: Duration,
836    version: u32,
837    send: impl Fn(RelayedAsk) -> Option<RelayedAnswer> + Send + Sync + 'static,
838) -> AnyListener {
839    Arc::new(move |input, value| {
840        let kind = codec.point;
841        let (Some(encode_value), Some(decode_value)) = (codec.encode_value, codec.decode_value)
842        else {
843            return Err(HookError::refuse(format!(
844                "`{kind}` has no request codec: it cannot cross"
845            )));
846        };
847        let Some(input) = (codec.encode)(input) else {
848            return Err(HookError::refuse(format!(
849                "`{kind}`: the input is not the point's"
850            )));
851        };
852        let Some(text) = encode_value(&*value) else {
853            return Err(HookError::refuse(format!(
854                "`{kind}`: the value is not the point's"
855            )));
856        };
857        let mut ask = RelayedAsk::new(ask_run(), next_ask_id(), kind, deadline, input, text);
858        ask.version = version;
859        let (run, id) = (ask.run, ask.id);
860        let sent = Instant::now();
861        let Some(answer) = send(ask) else {
862            return Err(HookError::refuse(format!(
863                "`{kind}`: no answer within {deadline:?}"
864            )));
865        };
866        if sent.elapsed() > deadline {
867            return Err(HookError::refuse(format!(
868                "`{kind}`: the answer came after {deadline:?}"
869            )));
870        }
871        if (answer.run, answer.id) != (run, id) {
872            return Err(HookError::refuse(format!(
873                "`{kind}`: the answer is to another ask"
874            )));
875        }
876        match answer.answer {
877            // The value is replaced only when the answer reads.
878            Answer::Done { value: text } => decode_value(&text, value).map_err(|reason| {
879                HookError::refuse(format!("`{kind}`: cannot read the answer: {reason}"))
880            }),
881            Answer::Refused {
882                listener, reason, ..
883            } => Err(HookError::refuse(match listener {
884                Some(l) => format!("refused on the far side by `{l}`: {reason}"),
885                None => format!("refused on the far side: {reason}"),
886            })),
887        }
888    })
889}