Skip to main content

bus_contract/
types.rs

1//! The contract's types, shared by every implementation.
2
3use std::fmt;
4use std::time::Duration;
5
6/// The deadline of an in-process listener when neither the listener nor
7/// its point sets one.
8pub const DEFAULT_DEADLINE: Duration = Duration::from_secs(1);
9
10/// The deadline meant for listeners that answer from another process (a
11/// plugin over RPC): give it with [`ListenOpts::deadline`] or
12/// [`PointSpec::deadline`].
13pub const PLUGIN_DEADLINE: Duration = Duration::from_secs(5);
14
15/// The `after` target that places a listener after every other listener
16/// of its point ([`ListenOpts::last`]): one per point, a second is
17/// refused as a [`Refused::Cycle`] (each would run after the other).
18pub const LAST: &str = "*";
19
20/// The name a host gives the fact it publishes for each [`Failure`] its
21/// sinks receive ([`Bus::add_failure_sink`](crate::Bus::add_failure_sink)).
22pub const FAILED_FACT: &str = "hook.failed";
23
24/// A hook point: one type per point, so its input and value are checked
25/// at compile time. Declared by the crate that owns the result.
26///
27/// Every listener of a point has the same shape: it reads the emit's
28/// [`Input`](Point::Input) and edits a [`Value`](Point::Value). An
29/// [`alter`](crate::Bus::alter_any) emit passes one value through the listeners
30/// in order; a [`collect`](crate::Bus::collect_any) emit gives each listener a
31/// fresh value and gathers them in a list.
32pub trait Point: 'static {
33    /// The point's id, dotted by convention (`health.report`).
34    const ID: &'static str;
35    /// What every listener reads: shared, never changed by a listener.
36    type Input: Send + Sync + 'static;
37    /// What a listener edits: the value altered in turn, or one
38    /// listener's contribution to a collect.
39    type Value: Send + 'static;
40    /// What the point is for ([`PointKind`]); [`PointKind::Alter`] unless
41    /// the point says otherwise.
42    const KIND: PointKind = PointKind::Alter;
43}
44
45/// What a point is for: declared, for introspection and review, not
46/// enforced (a request is an alter emit over the request's input).
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
48#[non_exhaustive]
49pub enum PointKind {
50    /// A request (`<noun>.<verb>`): its listeners do the work in their
51    /// declared order; the value is what each did.
52    Request,
53    /// An event's listeners: each event delivered once, in journal order.
54    Event,
55    /// One value passed through the listeners in turn.
56    #[default]
57    Alter,
58    /// Each listener adds its own part.
59    Collect,
60}
61
62impl PointKind {
63    /// The kind as introspection writes it (`request`).
64    pub fn as_str(self) -> &'static str {
65        match self {
66            PointKind::Request => "request",
67            PointKind::Event => "event",
68            PointKind::Alter => "alter",
69            PointKind::Collect => "collect",
70        }
71    }
72}
73
74/// A point's declaration: its description and limits, for introspection.
75#[derive(Clone, Debug, Default, PartialEq, Eq)]
76pub struct PointSpec {
77    /// What the point builds, for people and agents reading
78    /// [`Bus::points`](crate::Bus::points).
79    pub description: String,
80    /// The deadline of the point's listeners that set none themselves;
81    /// `None` takes the kernel's default.
82    pub deadline: Option<Duration>,
83}
84
85impl PointSpec {
86    /// A point described by `description`, with the kernel's deadline.
87    pub fn new(description: impl Into<String>) -> PointSpec {
88        PointSpec {
89            description: description.into(),
90            deadline: None,
91        }
92    }
93
94    /// The deadline of the point's listeners that set none themselves.
95    pub fn deadline(mut self, deadline: Duration) -> PointSpec {
96        self.deadline = Some(deadline);
97        self
98    }
99}
100
101/// How a listener is placed and limited.
102#[derive(Clone, Debug, Default, PartialEq, Eq)]
103pub struct ListenOpts {
104    /// Listeners this one runs after.
105    pub after: Vec<String>,
106    /// Listeners this one runs before.
107    pub before: Vec<String>,
108    /// Among listeners `after`/`before` leave free, higher runs first;
109    /// ties run in registration order.
110    pub priority: i32,
111    /// Overrides the point's deadline.
112    pub deadline: Option<Duration>,
113    /// Who registered it (a module, a plugin), for [`Bus::forget`](crate::Bus::forget) and
114    /// introspection.
115    pub owner: Option<String>,
116    /// Runs on a thread of its own, so the emit stops waiting at the
117    /// deadline. An inline listener (the default) runs on the emitting
118    /// thread: it cannot be stopped, and only counts as late once it
119    /// returns.
120    pub threaded: bool,
121}
122
123impl ListenOpts {
124    /// No constraint, priority 0, the point's deadline, inline.
125    pub fn new() -> ListenOpts {
126        ListenOpts::default()
127    }
128
129    /// Runs after the listener `id` (a missing one is reported and
130    /// ignored).
131    pub fn after(mut self, id: impl Into<String>) -> ListenOpts {
132        self.after.push(id.into());
133        self
134    }
135
136    /// Runs before the listener `id` (a missing one is reported and
137    /// ignored).
138    pub fn before(mut self, id: impl Into<String>) -> ListenOpts {
139        self.before.push(id.into());
140        self
141    }
142
143    /// Runs after every other listener of its point, whatever they
144    /// declare: an invariants check, a listener that reads what all the
145    /// others left. One per point: a second one closes a cycle and is
146    /// refused ([`Refused::Cycle`]). Kept in [`ListenOpts::after`] as
147    /// [`LAST`].
148    pub fn last(mut self) -> ListenOpts {
149        if !self.after.iter().any(|a| a == LAST) {
150            self.after.push(LAST.to_owned());
151        }
152        self
153    }
154
155    /// Whether the listener runs after every other one of its point
156    /// ([`ListenOpts::last`]).
157    pub fn is_last(&self) -> bool {
158        self.after.iter().any(|a| a == LAST)
159    }
160
161    /// Higher runs first among listeners left free by `after`/`before`.
162    pub fn priority(mut self, priority: i32) -> ListenOpts {
163        self.priority = priority;
164        self
165    }
166
167    /// Overrides the point's deadline.
168    pub fn deadline(mut self, deadline: Duration) -> ListenOpts {
169        self.deadline = Some(deadline);
170        self
171    }
172
173    /// Who registered the listener.
174    pub fn owner(mut self, owner: impl Into<String>) -> ListenOpts {
175        self.owner = Some(owner.into());
176        self
177    }
178
179    /// Runs on a thread of its own, so a slow listener cannot hold the
180    /// emit past its deadline.
181    pub fn threaded(mut self) -> ListenOpts {
182        self.threaded = true;
183        self
184    }
185}
186
187/// The error a listener returns.
188#[derive(Clone, Debug, PartialEq, Eq)]
189pub struct HookError(pub String);
190
191impl fmt::Display for HookError {
192    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193        f.write_str(&self.0)
194    }
195}
196
197impl std::error::Error for HookError {}
198
199impl From<String> for HookError {
200    fn from(message: String) -> HookError {
201        HookError(message)
202    }
203}
204
205impl From<&str> for HookError {
206    fn from(message: &str) -> HookError {
207        HookError(message.to_owned())
208    }
209}
210
211/// What went wrong with one listener during an emit.
212#[derive(Clone, Debug, PartialEq, Eq)]
213pub enum FailureKind {
214    /// The listener returned an error.
215    Error(String),
216    /// The listener panicked; the panic's message.
217    Panic(String),
218    /// The listener missed its deadline. `took` is its time when it
219    /// returned late (inline); `None` when the emit stopped waiting
220    /// (threaded).
221    Late {
222        /// The deadline it had.
223        deadline: Duration,
224        /// How long it ran, when it returned.
225        took: Option<Duration>,
226    },
227    /// An `after` or `before` constraint names a listener that is not
228    /// registered. The listener still ran and its contribution counts;
229    /// only the constraint was ignored. Not sent to the failure sinks.
230    MissingTarget(String),
231    /// The point id is registered with another [`Point`] type; no
232    /// listener ran. `listener` is `*`.
233    TypeMismatch,
234}
235
236/// One listener's failure: its contribution was dropped (except for a
237/// [`FailureKind::MissingTarget`]), the other listeners ran.
238#[derive(Clone, Debug, PartialEq, Eq)]
239pub struct Failure {
240    /// The point emitted.
241    pub point: &'static str,
242    /// The listener's id.
243    pub listener: String,
244    /// The listener's owner.
245    pub owner: Option<String>,
246    /// What went wrong.
247    pub kind: FailureKind,
248}
249
250impl Failure {
251    /// Whether the failure dropped a contribution: everything but a
252    /// missing ordering target. Only these reach the failure sinks.
253    pub fn dropped(&self) -> bool {
254        !matches!(self.kind, FailureKind::MissingTarget(_))
255    }
256}
257
258impl fmt::Display for Failure {
259    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260        write!(f, "hook `{}`, listener `{}`: ", self.point, self.listener)?;
261        match &self.kind {
262            FailureKind::Error(m) => write!(f, "failed: {m}"),
263            FailureKind::Panic(m) => write!(f, "panicked: {m}"),
264            FailureKind::Late {
265                deadline,
266                took: Some(t),
267            } => write!(f, "took {t:?}, past its deadline of {deadline:?}"),
268            FailureKind::Late { deadline, .. } => {
269                write!(f, "no answer within its deadline of {deadline:?}")
270            }
271            FailureKind::MissingTarget(t) => {
272                write!(f, "orders itself against `{t}`, which is not there")
273            }
274            FailureKind::TypeMismatch => write!(f, "the point is registered with another type"),
275        }
276    }
277}
278
279/// Why a declaration or a listener was refused. Nothing was changed.
280#[derive(Clone, Debug, PartialEq, Eq)]
281pub enum Refused {
282    /// The point already has a listener with this id.
283    Duplicate {
284        /// The point.
285        point: &'static str,
286        /// The id taken.
287        listener: String,
288    },
289    /// The listener's `after`/`before` would close a cycle: these
290    /// listeners, each to run before the next, the first again at the
291    /// end.
292    Cycle {
293        /// The point.
294        point: &'static str,
295        /// The listeners in the cycle.
296        path: Vec<String>,
297    },
298    /// The point id is already registered with another [`Point`] type.
299    TypeMismatch {
300        /// The point.
301        point: &'static str,
302    },
303    /// The point was already declared.
304    AlreadyDeclared {
305        /// The point.
306        point: &'static str,
307    },
308}
309
310impl fmt::Display for Refused {
311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312        match self {
313            Refused::Duplicate { point, listener } => {
314                write!(f, "hook `{point}` already has a listener `{listener}`")
315            }
316            Refused::Cycle { point, path } => {
317                write!(
318                    f,
319                    "hook `{point}`: listeners order each other in a cycle: {}",
320                    path.join(" -> ")
321                )
322            }
323            Refused::TypeMismatch { point } => {
324                write!(f, "hook `{point}` is registered with another type")
325            }
326            Refused::AlreadyDeclared { point } => write!(f, "hook `{point}` is already declared"),
327        }
328    }
329}
330
331impl std::error::Error for Refused {}
332
333/// The result of an [`alter`](crate::Bus::alter_any) emit.
334#[derive(Debug)]
335pub struct Altered<V> {
336    /// The value after every listener that succeeded.
337    pub value: V,
338    /// Every failure, in listener order.
339    pub failures: Vec<Failure>,
340}
341
342/// The result of a [`collect`](crate::Bus::collect_any) emit.
343#[derive(Debug)]
344pub struct Collected<V> {
345    /// Each successful listener's value, in listener order, with its id.
346    pub parts: Vec<(String, V)>,
347    /// Every failure, in listener order.
348    pub failures: Vec<Failure>,
349}
350
351/// A listener as introspection shows it.
352#[derive(Clone, Debug, PartialEq, Eq)]
353pub struct ListenerInfo {
354    /// Its id.
355    pub id: String,
356    /// Its owner.
357    pub owner: Option<String>,
358    /// The listeners it runs after.
359    pub after: Vec<String>,
360    /// The listeners it runs before.
361    pub before: Vec<String>,
362    /// Its priority.
363    pub priority: i32,
364    /// The deadline it gets: its own, else its point's, else the kernel's.
365    pub deadline: Duration,
366    /// Whether it runs on a thread of its own.
367    pub threaded: bool,
368    /// The `after`/`before` targets that are not registered.
369    pub missing: Vec<String>,
370    /// How many times it ran.
371    pub runs: u64,
372    /// How many of those runs failed (contribution dropped).
373    pub failures: u64,
374    /// The last failure, as text.
375    pub last_failure: Option<String>,
376}
377
378/// A point as introspection shows it.
379#[derive(Clone, Debug, PartialEq, Eq)]
380pub struct PointInfo {
381    /// Its id.
382    pub id: &'static str,
383    /// What it is for.
384    pub kind: PointKind,
385    /// Its description; empty until declared.
386    pub description: String,
387    /// Whether its owner declared it ([`Bus::declare_point`](crate::Bus::declare_point)); a point
388    /// listened to before that is not.
389    pub declared: bool,
390    /// The deadline of its listeners that set none.
391    pub deadline: Duration,
392    /// Its listeners, in the order they run.
393    pub listeners: Vec<ListenerInfo>,
394}