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. A request
46/// is an alter emit over the request's input; only a request can be
47/// refused by a listener ([`HookError::Refuse`]) or declared fail-closed
48/// ([`PointSpec::fail_closed`]).
49#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
50#[non_exhaustive]
51pub enum PointKind {
52    /// A request (`<noun>.<verb>`): its listeners do the work in their
53    /// declared order; the value is what each did.
54    Request,
55    /// An event's listeners: each event delivered once, in journal order.
56    Event,
57    /// One value passed through the listeners in turn.
58    #[default]
59    Alter,
60    /// Each listener adds its own part.
61    Collect,
62}
63
64impl PointKind {
65    /// The kind as introspection writes it (`request`).
66    pub fn as_str(self) -> &'static str {
67        match self {
68            PointKind::Request => "request",
69            PointKind::Event => "event",
70            PointKind::Alter => "alter",
71            PointKind::Collect => "collect",
72        }
73    }
74}
75
76/// A point's declaration: its description and limits, for introspection.
77///
78/// New fields may be added in a minor release: build one with
79/// [`PointSpec::new`] and the builder methods.
80#[derive(Clone, Debug, Default, PartialEq, Eq)]
81#[non_exhaustive]
82pub struct PointSpec {
83    /// What the point builds, for people and agents reading
84    /// [`Bus::points`](crate::Bus::points).
85    pub description: String,
86    /// The deadline of the point's listeners that set none themselves;
87    /// `None` takes the kernel's default.
88    pub deadline: Option<Duration>,
89    /// On a [`PointKind::Request`] point, a listener that fails (an
90    /// error, a panic, a missed deadline) refuses the request instead of
91    /// having its contribution dropped: the emit stops there
92    /// ([`Refusal::failed`]). Ignored on the other kinds.
93    pub fail_closed: bool,
94}
95
96impl PointSpec {
97    /// A point described by `description`, with the kernel's deadline.
98    pub fn new(description: impl Into<String>) -> PointSpec {
99        PointSpec {
100            description: description.into(),
101            deadline: None,
102            fail_closed: false,
103        }
104    }
105
106    /// The deadline of the point's listeners that set none themselves.
107    pub fn deadline(mut self, deadline: Duration) -> PointSpec {
108        self.deadline = Some(deadline);
109        self
110    }
111
112    /// A listener failure refuses the request ([`PointSpec::fail_closed`]).
113    pub fn fail_closed(mut self) -> PointSpec {
114        self.fail_closed = true;
115        self
116    }
117}
118
119/// How a listener is placed and limited.
120#[derive(Clone, Debug, Default, PartialEq, Eq)]
121pub struct ListenOpts {
122    /// Listeners this one runs after.
123    pub after: Vec<String>,
124    /// Listeners this one runs before.
125    pub before: Vec<String>,
126    /// Among listeners `after`/`before` leave free, higher runs first;
127    /// ties run in registration order.
128    pub priority: i32,
129    /// Overrides the point's deadline.
130    pub deadline: Option<Duration>,
131    /// Who registered it (a module, a plugin), for [`Bus::forget`](crate::Bus::forget) and
132    /// introspection.
133    pub owner: Option<String>,
134    /// Runs on a thread of its own, so the emit stops waiting at the
135    /// deadline. An inline listener (the default) runs on the emitting
136    /// thread: it cannot be stopped, and only counts as late once it
137    /// returns. A local listener runs inline on its own thread: it is
138    /// refused with this set ([`Refused::Threaded`]).
139    pub threaded: bool,
140}
141
142impl ListenOpts {
143    /// No constraint, priority 0, the point's deadline, inline.
144    pub fn new() -> ListenOpts {
145        ListenOpts::default()
146    }
147
148    /// Runs after the listener `id` (a missing one is reported and
149    /// ignored).
150    pub fn after(mut self, id: impl Into<String>) -> ListenOpts {
151        self.after.push(id.into());
152        self
153    }
154
155    /// Runs before the listener `id` (a missing one is reported and
156    /// ignored).
157    pub fn before(mut self, id: impl Into<String>) -> ListenOpts {
158        self.before.push(id.into());
159        self
160    }
161
162    /// Runs after every other listener of its point, whatever they
163    /// declare: an invariants check, a listener that reads what all the
164    /// others left. One per point: a second one closes a cycle and is
165    /// refused ([`Refused::Cycle`]). Kept in [`ListenOpts::after`] as
166    /// [`LAST`].
167    pub fn last(mut self) -> ListenOpts {
168        if !self.after.iter().any(|a| a == LAST) {
169            self.after.push(LAST.to_owned());
170        }
171        self
172    }
173
174    /// Whether the listener runs after every other one of its point
175    /// ([`ListenOpts::last`]).
176    pub fn is_last(&self) -> bool {
177        self.after.iter().any(|a| a == LAST)
178    }
179
180    /// Higher runs first among listeners left free by `after`/`before`.
181    pub fn priority(mut self, priority: i32) -> ListenOpts {
182        self.priority = priority;
183        self
184    }
185
186    /// Overrides the point's deadline.
187    pub fn deadline(mut self, deadline: Duration) -> ListenOpts {
188        self.deadline = Some(deadline);
189        self
190    }
191
192    /// Who registered the listener.
193    pub fn owner(mut self, owner: impl Into<String>) -> ListenOpts {
194        self.owner = Some(owner.into());
195        self
196    }
197
198    /// Runs on a thread of its own, so a slow listener cannot hold the
199    /// emit past its deadline.
200    pub fn threaded(mut self) -> ListenOpts {
201        self.threaded = true;
202        self
203    }
204}
205
206/// What a listener returns instead of `Ok(())`: it failed, or it refuses
207/// the request.
208#[derive(Clone, Debug, PartialEq, Eq)]
209#[non_exhaustive]
210pub enum HookError {
211    /// The listener failed: its contribution is dropped and the other
212    /// listeners run, unless its point is fail-closed
213    /// ([`PointSpec::fail_closed`]).
214    Failed(String),
215    /// The listener refuses the request, with a reason. On a
216    /// [`PointKind::Request`] point the emit stops: no later listener
217    /// runs, and the result names the refusal ([`Refusal`]). On another
218    /// kind it counts as [`HookError::Failed`].
219    Refuse(String),
220}
221
222impl HookError {
223    /// A failure with `message`.
224    pub fn failed(message: impl Into<String>) -> HookError {
225        HookError::Failed(message.into())
226    }
227
228    /// A refusal of the request, with `reason`.
229    pub fn refuse(reason: impl Into<String>) -> HookError {
230        HookError::Refuse(reason.into())
231    }
232
233    /// The failure's message or the refusal's reason.
234    pub fn message(&self) -> &str {
235        match self {
236            HookError::Failed(m) | HookError::Refuse(m) => m,
237        }
238    }
239
240    /// Whether the listener refuses the request.
241    pub fn is_refusal(&self) -> bool {
242        matches!(self, HookError::Refuse(_))
243    }
244}
245
246impl fmt::Display for HookError {
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        match self {
249            HookError::Failed(m) => f.write_str(m),
250            HookError::Refuse(r) => write!(f, "refused: {r}"),
251        }
252    }
253}
254
255impl std::error::Error for HookError {}
256
257/// A failure with this message.
258impl From<String> for HookError {
259    fn from(message: String) -> HookError {
260        HookError::Failed(message)
261    }
262}
263
264/// A failure with this message.
265impl From<&str> for HookError {
266    fn from(message: &str) -> HookError {
267        HookError::Failed(message.to_owned())
268    }
269}
270
271/// What went wrong with one listener during an emit.
272#[derive(Clone, Debug, PartialEq, Eq)]
273#[non_exhaustive]
274pub enum FailureKind {
275    /// The listener returned an error.
276    Error(String),
277    /// The listener panicked; the panic's message.
278    Panic(String),
279    /// The listener missed its deadline. `took` is its time when it
280    /// returned late (inline); `None` when the emit stopped waiting
281    /// (threaded).
282    Late {
283        /// The deadline it had.
284        deadline: Duration,
285        /// How long it ran, when it returned.
286        took: Option<Duration>,
287    },
288    /// An `after` or `before` constraint names a listener that is not
289    /// registered. The listener still ran and its contribution counts;
290    /// only the constraint was ignored. Not sent to the failure sinks.
291    MissingTarget(String),
292    /// The point id is registered with another [`Point`] type; no
293    /// listener ran. `listener` is `*`.
294    TypeMismatch,
295}
296
297/// One listener's failure: its contribution was dropped (except for a
298/// [`FailureKind::MissingTarget`]); the other listeners ran, unless the
299/// point is fail-closed ([`PointSpec::fail_closed`]).
300#[derive(Clone, Debug, PartialEq, Eq)]
301#[non_exhaustive]
302pub struct Failure {
303    /// The point emitted.
304    pub point: &'static str,
305    /// The listener's id.
306    pub listener: String,
307    /// The listener's owner.
308    pub owner: Option<String>,
309    /// What went wrong.
310    pub kind: FailureKind,
311}
312
313impl Failure {
314    /// The failure of the listener `listener` of `point`.
315    pub fn new(
316        point: &'static str,
317        listener: impl Into<String>,
318        owner: Option<String>,
319        kind: FailureKind,
320    ) -> Failure {
321        Failure {
322            point,
323            listener: listener.into(),
324            owner,
325            kind,
326        }
327    }
328
329    /// Whether the failure dropped a contribution: everything but a
330    /// missing ordering target. Only these reach the failure sinks.
331    pub fn dropped(&self) -> bool {
332        !matches!(self.kind, FailureKind::MissingTarget(_))
333    }
334}
335
336impl fmt::Display for FailureKind {
337    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338        match self {
339            FailureKind::Error(m) => write!(f, "failed: {m}"),
340            FailureKind::Panic(m) => write!(f, "panicked: {m}"),
341            FailureKind::Late {
342                deadline,
343                took: Some(t),
344            } => write!(f, "took {t:?}, past its deadline of {deadline:?}"),
345            FailureKind::Late { deadline, .. } => {
346                write!(f, "no answer within its deadline of {deadline:?}")
347            }
348            FailureKind::MissingTarget(t) => {
349                write!(f, "orders itself against `{t}`, which is not there")
350            }
351            FailureKind::TypeMismatch => write!(f, "the point is registered with another type"),
352        }
353    }
354}
355
356impl fmt::Display for Failure {
357    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
358        write!(
359            f,
360            "hook `{}`, listener `{}`: {}",
361            self.point, self.listener, self.kind
362        )
363    }
364}
365
366/// Why a declaration or a listener was refused. Nothing was changed.
367#[derive(Clone, Debug, PartialEq, Eq)]
368#[non_exhaustive]
369pub enum Refused {
370    /// The point already has a listener with this id.
371    Duplicate {
372        /// The point.
373        point: &'static str,
374        /// The id taken.
375        listener: String,
376    },
377    /// The listener's `after`/`before` would close a cycle: these
378    /// listeners, each to run before the next, the first again at the
379    /// end.
380    Cycle {
381        /// The point.
382        point: &'static str,
383        /// The listeners in the cycle.
384        path: Vec<String>,
385    },
386    /// The point id is already registered with another [`Point`] type.
387    TypeMismatch {
388        /// The point.
389        point: &'static str,
390    },
391    /// The point was already declared.
392    AlreadyDeclared {
393        /// The point.
394        point: &'static str,
395    },
396    /// A local listener asked for a thread of its own
397    /// ([`ListenOpts::threaded`]); it runs on the thread that registered
398    /// it.
399    Threaded {
400        /// The point.
401        point: &'static str,
402        /// The listener.
403        listener: String,
404    },
405    /// The point needs a capability the bus does not offer
406    /// ([`PointDecl::needs`](crate::PointDecl::needs)); it was not
407    /// declared.
408    Unsupported {
409        /// The point.
410        point: &'static str,
411        /// The capability missing.
412        capability: Capability,
413    },
414}
415
416impl fmt::Display for Refused {
417    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
418        match self {
419            Refused::Duplicate { point, listener } => {
420                write!(f, "hook `{point}` already has a listener `{listener}`")
421            }
422            Refused::Cycle { point, path } => {
423                write!(
424                    f,
425                    "hook `{point}`: listeners order each other in a cycle: {}",
426                    path.join(" -> ")
427                )
428            }
429            Refused::TypeMismatch { point } => {
430                write!(f, "hook `{point}` is registered with another type")
431            }
432            Refused::AlreadyDeclared { point } => write!(f, "hook `{point}` is already declared"),
433            Refused::Threaded { point, listener } => write!(
434                f,
435                "hook `{point}`: the local listener `{listener}` runs on its own thread, not a new one"
436            ),
437            Refused::Unsupported { point, capability } => write!(
438                f,
439                "hook `{point}` needs the `{}` capability, which this bus does not offer",
440                capability.as_str()
441            ),
442        }
443    }
444}
445
446impl std::error::Error for Refused {}
447
448/// A capability a bus may offer beyond the core of [`Bus`](crate::Bus),
449/// found at run time ([`Bus::defer`](crate::Bus::defer)). A library names
450/// the ones its points need in its contract table
451/// ([`PointDecl::needs`](crate::PointDecl::needs)).
452#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
453#[non_exhaustive]
454pub enum Capability {
455    /// Requests asked now and heard at the bus's next drain on the same
456    /// thread ([`Defer`](crate::Defer)).
457    Defer,
458}
459
460impl Capability {
461    /// The capability as messages write it (`defer`).
462    pub fn as_str(self) -> &'static str {
463        match self {
464            Capability::Defer => "defer",
465        }
466    }
467}
468
469/// A request stopped by one of its listeners: the listener refused it
470/// ([`HookError::Refuse`]), or failed on a fail-closed point
471/// ([`PointSpec::fail_closed`]). The listeners after it did not run.
472#[derive(Clone, Debug, PartialEq, Eq)]
473#[non_exhaustive]
474pub struct Refusal {
475    /// The point emitted.
476    pub point: &'static str,
477    /// The listener that stopped the request.
478    pub listener: String,
479    /// Its owner.
480    pub owner: Option<String>,
481    /// The reason it gave, or its failure as text.
482    pub reason: String,
483    /// Whether the listener failed (its [`Failure`] is in the result's
484    /// failures) rather than refused.
485    pub failed: bool,
486}
487
488impl Refusal {
489    /// The refusal of `point` by the listener `listener`, for `reason`.
490    pub fn new(
491        point: &'static str,
492        listener: impl Into<String>,
493        owner: Option<String>,
494        reason: impl Into<String>,
495    ) -> Refusal {
496        Refusal {
497            point,
498            listener: listener.into(),
499            owner,
500            reason: reason.into(),
501            failed: false,
502        }
503    }
504
505    /// The refusal a listener's failure makes on a fail-closed point.
506    pub fn from_failure(failure: &Failure) -> Refusal {
507        let reason = match &failure.kind {
508            FailureKind::Error(m) | FailureKind::Panic(m) => m.clone(),
509            kind => kind.to_string(),
510        };
511        Refusal {
512            point: failure.point,
513            listener: failure.listener.clone(),
514            owner: failure.owner.clone(),
515            reason,
516            failed: true,
517        }
518    }
519}
520
521impl fmt::Display for Refusal {
522    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
523        if self.failed {
524            write!(
525                f,
526                "hook `{}`: refused, `{}` failed: {}",
527                self.point, self.listener, self.reason
528            )
529        } else {
530            write!(
531                f,
532                "hook `{}`: refused by `{}`: {}",
533                self.point, self.listener, self.reason
534            )
535        }
536    }
537}
538
539/// The result of an [`alter`](crate::Bus::alter_any) emit.
540#[derive(Debug)]
541#[non_exhaustive]
542pub struct Altered<V> {
543    /// The value after every listener that succeeded; when the request
544    /// was refused, as the listeners before the refusal left it.
545    pub value: V,
546    /// Every failure, in listener order.
547    pub failures: Vec<Failure>,
548    /// The local listeners bound to another thread, in order: queued for
549    /// that thread's [`run_pending`](crate::Bus::run_pending), not run
550    /// by this emit. Empty when the request was refused.
551    pub deferred: Vec<String>,
552    /// The listener that stopped the request, if one did.
553    pub refused: Option<Refusal>,
554}
555
556impl<V> Altered<V> {
557    /// An emit that left `value`, with no failure, nothing deferred and
558    /// no refusal.
559    pub fn new(value: V) -> Altered<V> {
560        Altered {
561            value,
562            failures: Vec::new(),
563            deferred: Vec::new(),
564            refused: None,
565        }
566    }
567}
568
569/// The result of a [`collect`](crate::Bus::collect_any) emit.
570#[derive(Debug)]
571#[non_exhaustive]
572pub struct Collected<V> {
573    /// Each successful listener's value, in listener order, with its id.
574    pub parts: Vec<(String, V)>,
575    /// Every failure, in listener order.
576    pub failures: Vec<Failure>,
577    /// The local listeners bound to another thread, in order: queued for
578    /// that thread's [`run_pending`](crate::Bus::run_pending), not run
579    /// by this emit. Empty when the request was refused.
580    pub deferred: Vec<String>,
581    /// The listener that stopped the request, if one did.
582    pub refused: Option<Refusal>,
583}
584
585impl<V> Collected<V> {
586    /// An emit with no part, no failure, nothing deferred and no
587    /// refusal.
588    pub fn new() -> Collected<V> {
589        Collected {
590            parts: Vec::new(),
591            failures: Vec::new(),
592            deferred: Vec::new(),
593            refused: None,
594        }
595    }
596}
597
598impl<V> Default for Collected<V> {
599    fn default() -> Collected<V> {
600        Collected::new()
601    }
602}
603
604/// What listeners run later did: one emit's local listeners queued for
605/// their thread ([`Bus::run_pending`](crate::Bus::run_pending)), or one
606/// deferred request ([`Defer::drain`](crate::Defer::drain)).
607#[derive(Clone, Debug, PartialEq, Eq)]
608#[non_exhaustive]
609pub struct PendingRun {
610    /// The point emitted.
611    pub point: &'static str,
612    /// The listeners that ran, in order (a listener removed since the
613    /// emit is not run).
614    pub ran: Vec<String>,
615    /// Their failures, in listener order.
616    pub failures: Vec<Failure>,
617    /// The listener that stopped the request, if one did.
618    pub refused: Option<Refusal>,
619    /// For a deferred request, the number [`Defer::ask_any`](crate::Defer::ask_any)
620    /// returned when it was asked; `None` for local listeners run by
621    /// [`Bus::run_pending`](crate::Bus::run_pending).
622    pub ask: Option<u64>,
623}
624
625impl PendingRun {
626    /// A run of `point` where nothing ran yet.
627    pub fn new(point: &'static str) -> PendingRun {
628        PendingRun {
629            point,
630            ran: Vec::new(),
631            failures: Vec::new(),
632            refused: None,
633            ask: None,
634        }
635    }
636}
637
638/// A listener as introspection shows it.
639#[derive(Clone, Debug, PartialEq, Eq)]
640#[non_exhaustive]
641pub struct ListenerInfo {
642    /// Its id.
643    pub id: String,
644    /// Its owner.
645    pub owner: Option<String>,
646    /// The listeners it runs after.
647    pub after: Vec<String>,
648    /// The listeners it runs before.
649    pub before: Vec<String>,
650    /// Its priority.
651    pub priority: i32,
652    /// The deadline it gets: its own, else its point's, else the kernel's.
653    pub deadline: Duration,
654    /// Whether it runs on a thread of its own.
655    pub threaded: bool,
656    /// Whether it is a local listener, bound to the thread that
657    /// registered it.
658    pub local: bool,
659    /// The `after`/`before` targets that are not registered.
660    pub missing: Vec<String>,
661    /// How many times it ran.
662    pub runs: u64,
663    /// How many of those runs failed (contribution dropped).
664    pub failures: u64,
665    /// The last failure, as text.
666    pub last_failure: Option<String>,
667}
668
669impl ListenerInfo {
670    /// The listener `id` with no owner, no constraint, priority 0, the
671    /// default deadline, inline, never run.
672    pub fn new(id: impl Into<String>) -> ListenerInfo {
673        ListenerInfo {
674            id: id.into(),
675            owner: None,
676            after: Vec::new(),
677            before: Vec::new(),
678            priority: 0,
679            deadline: DEFAULT_DEADLINE,
680            threaded: false,
681            local: false,
682            missing: Vec::new(),
683            runs: 0,
684            failures: 0,
685            last_failure: None,
686        }
687    }
688}
689
690/// A point as introspection shows it.
691#[derive(Clone, Debug, PartialEq, Eq)]
692#[non_exhaustive]
693pub struct PointInfo {
694    /// Its id.
695    pub id: &'static str,
696    /// What it is for.
697    pub kind: PointKind,
698    /// Its description; empty until declared.
699    pub description: String,
700    /// Whether its owner declared it ([`Bus::declare_point`](crate::Bus::declare_point)); a point
701    /// listened to before that is not.
702    pub declared: bool,
703    /// The deadline of its listeners that set none.
704    pub deadline: Duration,
705    /// Whether a listener failure refuses the request
706    /// ([`PointSpec::fail_closed`]).
707    pub fail_closed: bool,
708    /// Its listeners, in the order they run.
709    pub listeners: Vec<ListenerInfo>,
710}
711
712impl PointInfo {
713    /// The point `id` of `kind`, not declared, with the default deadline
714    /// and no listener.
715    pub fn new(id: &'static str, kind: PointKind) -> PointInfo {
716        PointInfo {
717            id,
718            kind,
719            description: String::new(),
720            declared: false,
721            deadline: DEFAULT_DEADLINE,
722            fail_closed: false,
723            listeners: Vec::new(),
724        }
725    }
726}