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/// The name a host gives the fact it publishes for each [`OverBudget`]
25/// its budget sinks receive
26/// ([`Timings::add_budget_sink`](crate::Timings::add_budget_sink)).
27pub const OVER_BUDGET_FACT: &str = "bus.overBudget";
28
29/// A hook point: one type per point, so its input and value are checked
30/// at compile time. Declared by the crate that owns the result.
31///
32/// Every listener of a point has the same shape: it reads the emit's
33/// [`Input`](Point::Input) and edits a [`Value`](Point::Value). An
34/// [`alter`](crate::Bus::alter_any) emit passes one value through the listeners
35/// in order; a [`collect`](crate::Bus::collect_any) emit gives each listener a
36/// fresh value and gathers them in a list.
37pub trait Point: 'static {
38    /// The point's id, dotted by convention (`health.report`).
39    const ID: &'static str;
40    /// What every listener reads: shared, never changed by a listener.
41    type Input: Send + Sync + 'static;
42    /// What a listener edits: the value altered in turn, or one
43    /// listener's contribution to a collect.
44    type Value: Send + 'static;
45    /// What the point is for ([`PointKind`]); [`PointKind::Alter`] unless
46    /// the point says otherwise.
47    const KIND: PointKind = PointKind::Alter;
48}
49
50/// What a point is for, declared for introspection and review. A request
51/// is an alter emit over the request's input; only a request can be
52/// refused by a listener ([`HookError::Refuse`]) or declared fail-closed
53/// ([`PointSpec::fail_closed`]).
54#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
55#[non_exhaustive]
56pub enum PointKind {
57    /// A request (`<noun>.<verb>`): its listeners do the work in their
58    /// declared order; the value is what each did.
59    Request,
60    /// An event's listeners: each event delivered once, in journal order.
61    Event,
62    /// One value passed through the listeners in turn.
63    #[default]
64    Alter,
65    /// Each listener adds its own part.
66    Collect,
67}
68
69impl PointKind {
70    /// The kind as introspection writes it (`request`).
71    pub fn as_str(self) -> &'static str {
72        match self {
73            PointKind::Request => "request",
74            PointKind::Event => "event",
75            PointKind::Alter => "alter",
76            PointKind::Collect => "collect",
77        }
78    }
79}
80
81/// A point's declaration: its description and limits, for introspection.
82///
83/// New fields may be added in a minor release: build one with
84/// [`PointSpec::new`] and the builder methods.
85#[derive(Clone, Debug, Default, PartialEq, Eq)]
86#[non_exhaustive]
87pub struct PointSpec {
88    /// What the point builds, for people and agents reading
89    /// [`Bus::points`](crate::Bus::points).
90    pub description: String,
91    /// The deadline of the point's listeners that set none themselves;
92    /// `None` takes the kernel's default.
93    pub deadline: Option<Duration>,
94    /// On a [`PointKind::Request`] point, a listener that fails (an
95    /// error, a panic, a missed deadline) refuses the request instead of
96    /// having its contribution dropped: the emit stops there
97    /// ([`Refusal::failed`]). Ignored on the other kinds.
98    pub fail_closed: bool,
99    /// The time one pass of the point's listeners should take on a
100    /// thread ([`Timings`](crate::Timings)): a pass over it is reported
101    /// ([`OverBudget`]), never failed. `None`: no budget.
102    pub budget: Option<Duration>,
103    /// On a [`PointKind::Event`] point, its events go through the bus's
104    /// journal ([`Journal`](crate::Journal)): published with a number,
105    /// delivered to the listeners in journal order after the publisher
106    /// has moved on.
107    pub journaled: bool,
108    /// How the point crosses a process ([`Relay`](crate::Relay)): on a
109    /// journaled event point, how its input is written; on a request
110    /// point, its input and value ([`Codec::request`](crate::Codec::request)),
111    /// so another process may ask it ([`Relay::answer`](crate::Relay::answer)).
112    /// `None`: it stays in this one.
113    pub relay: Option<crate::Codec>,
114    /// The point's version, from 1: raised when its payload changes in a
115    /// way an older reader cannot use (a field it may ignore is not such
116    /// a change). Two processes cross a point only at the same version
117    /// ([`IngestError::Version`](crate::IngestError::Version)).
118    pub version: u32,
119}
120
121impl PointSpec {
122    /// A point described by `description`, with the kernel's deadline.
123    pub fn new(description: impl Into<String>) -> PointSpec {
124        PointSpec {
125            description: description.into(),
126            deadline: None,
127            fail_closed: false,
128            budget: None,
129            journaled: false,
130            relay: None,
131            version: 1,
132        }
133    }
134
135    /// The deadline of the point's listeners that set none themselves.
136    pub fn deadline(mut self, deadline: Duration) -> PointSpec {
137        self.deadline = Some(deadline);
138        self
139    }
140
141    /// A listener failure refuses the request ([`PointSpec::fail_closed`]).
142    pub fn fail_closed(mut self) -> PointSpec {
143        self.fail_closed = true;
144        self
145    }
146
147    /// The time one pass of the point's listeners should take
148    /// ([`PointSpec::budget`]).
149    pub fn budget(mut self, budget: Duration) -> PointSpec {
150        self.budget = Some(budget);
151        self
152    }
153
154    /// Its events go through the journal ([`PointSpec::journaled`]).
155    pub fn journaled(mut self) -> PointSpec {
156        self.journaled = true;
157        self
158    }
159
160    /// Its events cross processes with `codec`; journaled too
161    /// ([`PointSpec::relay`]). For an event point: a request uses
162    /// [`PointSpec::relayable_request`].
163    pub fn relayable(mut self, codec: crate::Codec) -> PointSpec {
164        self.journaled = true;
165        self.relay = Some(codec);
166        self
167    }
168
169    /// Another process may ask this request, its input and value written
170    /// by `codec` ([`Codec::request`](crate::Codec::request)); fail-closed
171    /// too, so no answer in time is a refusal ([`PointSpec::relay`]).
172    pub fn relayable_request(mut self, codec: crate::Codec) -> PointSpec {
173        self.fail_closed = true;
174        self.relay = Some(codec);
175        self
176    }
177
178    /// The point's version ([`PointSpec::version`]).
179    pub fn version(mut self, version: u32) -> PointSpec {
180        self.version = version;
181        self
182    }
183}
184
185/// How a listener is placed and limited.
186#[derive(Clone, Debug, Default, PartialEq, Eq)]
187pub struct ListenOpts {
188    /// Listeners this one runs after.
189    pub after: Vec<String>,
190    /// Listeners this one runs before.
191    pub before: Vec<String>,
192    /// Among listeners `after`/`before` leave free, higher runs first;
193    /// ties run in registration order.
194    pub priority: i32,
195    /// Overrides the point's deadline.
196    pub deadline: Option<Duration>,
197    /// Who registered it (a module, a plugin), for [`Bus::forget`](crate::Bus::forget) and
198    /// introspection.
199    pub owner: Option<String>,
200    /// Runs on a thread of its own, so the emit stops waiting at the
201    /// deadline. An inline listener (the default) runs on the emitting
202    /// thread: it cannot be stopped, and only counts as late once it
203    /// returns. A local listener runs inline on its own thread: it is
204    /// refused with this set ([`Refused::Threaded`]).
205    pub threaded: bool,
206}
207
208impl ListenOpts {
209    /// No constraint, priority 0, the point's deadline, inline.
210    pub fn new() -> ListenOpts {
211        ListenOpts::default()
212    }
213
214    /// Runs after the listener `id` (a missing one is reported and
215    /// ignored).
216    pub fn after(mut self, id: impl Into<String>) -> ListenOpts {
217        self.after.push(id.into());
218        self
219    }
220
221    /// Runs before the listener `id` (a missing one is reported and
222    /// ignored).
223    pub fn before(mut self, id: impl Into<String>) -> ListenOpts {
224        self.before.push(id.into());
225        self
226    }
227
228    /// Runs after every other listener of its point, whatever they
229    /// declare: an invariants check, a listener that reads what all the
230    /// others left. One per point: a second one closes a cycle and is
231    /// refused ([`Refused::Cycle`]). Kept in [`ListenOpts::after`] as
232    /// [`LAST`].
233    pub fn last(mut self) -> ListenOpts {
234        if !self.after.iter().any(|a| a == LAST) {
235            self.after.push(LAST.to_owned());
236        }
237        self
238    }
239
240    /// Whether the listener runs after every other one of its point
241    /// ([`ListenOpts::last`]).
242    pub fn is_last(&self) -> bool {
243        self.after.iter().any(|a| a == LAST)
244    }
245
246    /// Higher runs first among listeners left free by `after`/`before`.
247    pub fn priority(mut self, priority: i32) -> ListenOpts {
248        self.priority = priority;
249        self
250    }
251
252    /// Overrides the point's deadline.
253    pub fn deadline(mut self, deadline: Duration) -> ListenOpts {
254        self.deadline = Some(deadline);
255        self
256    }
257
258    /// Who registered the listener.
259    pub fn owner(mut self, owner: impl Into<String>) -> ListenOpts {
260        self.owner = Some(owner.into());
261        self
262    }
263
264    /// Runs on a thread of its own, so a slow listener cannot hold the
265    /// emit past its deadline.
266    pub fn threaded(mut self) -> ListenOpts {
267        self.threaded = true;
268        self
269    }
270}
271
272/// What a listener returns instead of `Ok(())`: it failed, or it refuses
273/// the request.
274#[derive(Clone, Debug, PartialEq, Eq)]
275#[non_exhaustive]
276pub enum HookError {
277    /// The listener failed: its contribution is dropped and the other
278    /// listeners run, unless its point is fail-closed
279    /// ([`PointSpec::fail_closed`]).
280    Failed(String),
281    /// The listener refuses the request, with a reason. On a
282    /// [`PointKind::Request`] point the emit stops: no later listener
283    /// runs, and the result names the refusal ([`Refusal`]). On another
284    /// kind it counts as [`HookError::Failed`].
285    Refuse(String),
286}
287
288impl HookError {
289    /// A failure with `message`.
290    pub fn failed(message: impl Into<String>) -> HookError {
291        HookError::Failed(message.into())
292    }
293
294    /// A refusal of the request, with `reason`.
295    pub fn refuse(reason: impl Into<String>) -> HookError {
296        HookError::Refuse(reason.into())
297    }
298
299    /// The failure's message or the refusal's reason.
300    pub fn message(&self) -> &str {
301        match self {
302            HookError::Failed(m) | HookError::Refuse(m) => m,
303        }
304    }
305
306    /// Whether the listener refuses the request.
307    pub fn is_refusal(&self) -> bool {
308        matches!(self, HookError::Refuse(_))
309    }
310}
311
312impl fmt::Display for HookError {
313    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
314        match self {
315            HookError::Failed(m) => f.write_str(m),
316            HookError::Refuse(r) => write!(f, "refused: {r}"),
317        }
318    }
319}
320
321impl std::error::Error for HookError {}
322
323/// A failure with this message.
324impl From<String> for HookError {
325    fn from(message: String) -> HookError {
326        HookError::Failed(message)
327    }
328}
329
330/// A failure with this message.
331impl From<&str> for HookError {
332    fn from(message: &str) -> HookError {
333        HookError::Failed(message.to_owned())
334    }
335}
336
337/// What went wrong with one listener during an emit.
338#[derive(Clone, Debug, PartialEq, Eq)]
339#[non_exhaustive]
340pub enum FailureKind {
341    /// The listener returned an error.
342    Error(String),
343    /// The listener panicked; the panic's message.
344    Panic(String),
345    /// The listener missed its deadline. `took` is its time when it
346    /// returned late (inline); `None` when the emit stopped waiting
347    /// (threaded).
348    Late {
349        /// The deadline it had.
350        deadline: Duration,
351        /// How long it ran, when it returned.
352        took: Option<Duration>,
353    },
354    /// An `after` or `before` constraint names a listener that is not
355    /// registered. The listener still ran and its contribution counts;
356    /// only the constraint was ignored. Not sent to the failure sinks.
357    MissingTarget(String),
358    /// The point id is registered with another [`Point`] type; no
359    /// listener ran. `listener` is `*`.
360    TypeMismatch,
361}
362
363/// One listener's failure: its contribution was dropped (except for a
364/// [`FailureKind::MissingTarget`]); the other listeners ran, unless the
365/// point is fail-closed ([`PointSpec::fail_closed`]).
366#[derive(Clone, Debug, PartialEq, Eq)]
367#[non_exhaustive]
368pub struct Failure {
369    /// The point emitted.
370    pub point: &'static str,
371    /// The listener's id.
372    pub listener: String,
373    /// The listener's owner.
374    pub owner: Option<String>,
375    /// What went wrong.
376    pub kind: FailureKind,
377}
378
379impl Failure {
380    /// The failure of the listener `listener` of `point`.
381    pub fn new(
382        point: &'static str,
383        listener: impl Into<String>,
384        owner: Option<String>,
385        kind: FailureKind,
386    ) -> Failure {
387        Failure {
388            point,
389            listener: listener.into(),
390            owner,
391            kind,
392        }
393    }
394
395    /// Whether the failure dropped a contribution: everything but a
396    /// missing ordering target. Only these reach the failure sinks.
397    pub fn dropped(&self) -> bool {
398        !matches!(self.kind, FailureKind::MissingTarget(_))
399    }
400}
401
402impl fmt::Display for FailureKind {
403    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404        match self {
405            FailureKind::Error(m) => write!(f, "failed: {m}"),
406            FailureKind::Panic(m) => write!(f, "panicked: {m}"),
407            FailureKind::Late {
408                deadline,
409                took: Some(t),
410            } => write!(f, "took {t:?}, past its deadline of {deadline:?}"),
411            FailureKind::Late { deadline, .. } => {
412                write!(f, "no answer within its deadline of {deadline:?}")
413            }
414            FailureKind::MissingTarget(t) => {
415                write!(f, "orders itself against `{t}`, which is not there")
416            }
417            FailureKind::TypeMismatch => write!(f, "the point is registered with another type"),
418        }
419    }
420}
421
422impl fmt::Display for Failure {
423    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
424        write!(
425            f,
426            "hook `{}`, listener `{}`: {}",
427            self.point, self.listener, self.kind
428        )
429    }
430}
431
432/// Why a declaration or a listener was refused. Nothing was changed.
433#[derive(Clone, Debug, PartialEq, Eq)]
434#[non_exhaustive]
435pub enum Refused {
436    /// The point already has a listener with this id.
437    Duplicate {
438        /// The point.
439        point: &'static str,
440        /// The id taken.
441        listener: String,
442    },
443    /// The listener's `after`/`before` would close a cycle: these
444    /// listeners, each to run before the next, the first again at the
445    /// end.
446    Cycle {
447        /// The point.
448        point: &'static str,
449        /// The listeners in the cycle.
450        path: Vec<String>,
451    },
452    /// The point id is already registered with another [`Point`] type.
453    TypeMismatch {
454        /// The point.
455        point: &'static str,
456    },
457    /// The point was already declared.
458    AlreadyDeclared {
459        /// The point.
460        point: &'static str,
461    },
462    /// A local listener asked for a thread of its own
463    /// ([`ListenOpts::threaded`]); it runs on the thread that registered
464    /// it.
465    Threaded {
466        /// The point.
467        point: &'static str,
468        /// The listener.
469        listener: String,
470    },
471    /// The point needs a capability the bus does not offer
472    /// ([`PointDecl::needs`](crate::PointDecl::needs)); it was not
473    /// declared.
474    Unsupported {
475        /// The point.
476        point: &'static str,
477        /// The capability missing.
478        capability: Capability,
479    },
480    /// Only an event point is journaled or relayed
481    /// ([`PointSpec::journaled`]); it was not declared.
482    NotEvent {
483        /// The point.
484        point: &'static str,
485    },
486    /// An event was published through the journal on a point not
487    /// declared journaled on this bus; nothing was recorded.
488    NotJournaled {
489        /// The point.
490        point: &'static str,
491    },
492    /// The point is relayable but cannot cross: only an event point, or
493    /// a request point whose codec writes its value too
494    /// ([`Codec::request`](crate::Codec::request)), crosses a process. It
495    /// was not declared.
496    NotCrossable {
497        /// The point.
498        point: &'static str,
499    },
500}
501
502impl fmt::Display for Refused {
503    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504        match self {
505            Refused::Duplicate { point, listener } => {
506                write!(f, "hook `{point}` already has a listener `{listener}`")
507            }
508            Refused::Cycle { point, path } => {
509                write!(
510                    f,
511                    "hook `{point}`: listeners order each other in a cycle: {}",
512                    path.join(" -> ")
513                )
514            }
515            Refused::TypeMismatch { point } => {
516                write!(f, "hook `{point}` is registered with another type")
517            }
518            Refused::AlreadyDeclared { point } => write!(f, "hook `{point}` is already declared"),
519            Refused::Threaded { point, listener } => write!(
520                f,
521                "hook `{point}`: the local listener `{listener}` runs on its own thread, not a new one"
522            ),
523            Refused::Unsupported { point, capability } => write!(
524                f,
525                "hook `{point}` needs the `{}` capability, which this bus does not offer",
526                capability.as_str()
527            ),
528            Refused::NotEvent { point } => write!(
529                f,
530                "hook `{point}` is journaled or relayable but is not an event point"
531            ),
532            Refused::NotJournaled { point } => {
533                write!(f, "hook `{point}` is not declared journaled on this bus")
534            }
535            Refused::NotCrossable { point } => write!(
536                f,
537                "hook `{point}` is relayable but cannot cross: only an event, or a request with a value codec, crosses"
538            ),
539        }
540    }
541}
542
543impl std::error::Error for Refused {}
544
545/// A capability a bus may offer beyond the core of [`Bus`](crate::Bus),
546/// found at run time ([`Bus::defer`](crate::Bus::defer)). A library names
547/// the ones its points need in its contract table
548/// ([`PointDecl::needs`](crate::PointDecl::needs)).
549#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
550#[non_exhaustive]
551pub enum Capability {
552    /// Requests asked now and heard at the bus's next drain on the same
553    /// thread ([`Defer`](crate::Defer)).
554    Defer,
555    /// How long listeners take, per point and listener, and passes over
556    /// a point's budget reported ([`Timings`](crate::Timings)).
557    Timings,
558    /// Events kept with a number, read again from one, delivered after
559    /// the publisher has moved on ([`Journal`](crate::Journal)).
560    Journal,
561    /// Events of relayable points served to another process and taken
562    /// in from one, asks of relayable requests answered for one
563    /// ([`Relay`](crate::Relay)); implies `Journal`.
564    Relay,
565}
566
567impl Capability {
568    /// The capability as messages write it (`defer`).
569    pub fn as_str(self) -> &'static str {
570        match self {
571            Capability::Defer => "defer",
572            Capability::Timings => "timings",
573            Capability::Journal => "journal",
574            Capability::Relay => "relay",
575        }
576    }
577}
578
579/// A request stopped by one of its listeners: the listener refused it
580/// ([`HookError::Refuse`]), or failed on a fail-closed point
581/// ([`PointSpec::fail_closed`]). The listeners after it did not run.
582#[derive(Clone, Debug, PartialEq, Eq)]
583#[non_exhaustive]
584pub struct Refusal {
585    /// The point emitted.
586    pub point: &'static str,
587    /// The listener that stopped the request.
588    pub listener: String,
589    /// Its owner.
590    pub owner: Option<String>,
591    /// The reason it gave, or its failure as text.
592    pub reason: String,
593    /// Whether the listener failed (its [`Failure`] is in the result's
594    /// failures) rather than refused.
595    pub failed: bool,
596}
597
598impl Refusal {
599    /// The refusal of `point` by the listener `listener`, for `reason`.
600    pub fn new(
601        point: &'static str,
602        listener: impl Into<String>,
603        owner: Option<String>,
604        reason: impl Into<String>,
605    ) -> Refusal {
606        Refusal {
607            point,
608            listener: listener.into(),
609            owner,
610            reason: reason.into(),
611            failed: false,
612        }
613    }
614
615    /// The refusal a listener's failure makes on a fail-closed point.
616    pub fn from_failure(failure: &Failure) -> Refusal {
617        let reason = match &failure.kind {
618            FailureKind::Error(m) | FailureKind::Panic(m) => m.clone(),
619            kind => kind.to_string(),
620        };
621        Refusal {
622            point: failure.point,
623            listener: failure.listener.clone(),
624            owner: failure.owner.clone(),
625            reason,
626            failed: true,
627        }
628    }
629}
630
631impl fmt::Display for Refusal {
632    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
633        if self.failed {
634            write!(
635                f,
636                "hook `{}`: refused, `{}` failed: {}",
637                self.point, self.listener, self.reason
638            )
639        } else {
640            write!(
641                f,
642                "hook `{}`: refused by `{}`: {}",
643                self.point, self.listener, self.reason
644            )
645        }
646    }
647}
648
649/// The result of an [`alter`](crate::Bus::alter_any) emit.
650#[derive(Debug)]
651#[non_exhaustive]
652pub struct Altered<V> {
653    /// The value after every listener that succeeded; when the request
654    /// was refused, as the listeners before the refusal left it.
655    pub value: V,
656    /// Every failure, in listener order.
657    pub failures: Vec<Failure>,
658    /// The local listeners bound to another thread, in order: queued for
659    /// that thread's [`run_pending`](crate::Bus::run_pending), not run
660    /// by this emit. Empty when the request was refused.
661    pub deferred: Vec<String>,
662    /// The listener that stopped the request, if one did.
663    pub refused: Option<Refusal>,
664}
665
666impl<V> Altered<V> {
667    /// An emit that left `value`, with no failure, nothing deferred and
668    /// no refusal.
669    pub fn new(value: V) -> Altered<V> {
670        Altered {
671            value,
672            failures: Vec::new(),
673            deferred: Vec::new(),
674            refused: None,
675        }
676    }
677}
678
679/// The result of a [`collect`](crate::Bus::collect_any) emit.
680#[derive(Debug)]
681#[non_exhaustive]
682pub struct Collected<V> {
683    /// Each successful listener's value, in listener order, with its id.
684    pub parts: Vec<(String, V)>,
685    /// Every failure, in listener order.
686    pub failures: Vec<Failure>,
687    /// The local listeners bound to another thread, in order: queued for
688    /// that thread's [`run_pending`](crate::Bus::run_pending), not run
689    /// by this emit. Empty when the request was refused.
690    pub deferred: Vec<String>,
691    /// The listener that stopped the request, if one did.
692    pub refused: Option<Refusal>,
693}
694
695impl<V> Collected<V> {
696    /// An emit with no part, no failure, nothing deferred and no
697    /// refusal.
698    pub fn new() -> Collected<V> {
699        Collected {
700            parts: Vec::new(),
701            failures: Vec::new(),
702            deferred: Vec::new(),
703            refused: None,
704        }
705    }
706}
707
708impl<V> Default for Collected<V> {
709    fn default() -> Collected<V> {
710        Collected::new()
711    }
712}
713
714/// What listeners run later did: one emit's local listeners queued for
715/// their thread ([`Bus::run_pending`](crate::Bus::run_pending)), or one
716/// deferred request ([`Defer::drain`](crate::Defer::drain)).
717#[derive(Clone, Debug, PartialEq, Eq)]
718#[non_exhaustive]
719pub struct PendingRun {
720    /// The point emitted.
721    pub point: &'static str,
722    /// The listeners that ran, in order (a listener removed since the
723    /// emit is not run).
724    pub ran: Vec<String>,
725    /// Their failures, in listener order.
726    pub failures: Vec<Failure>,
727    /// The listener that stopped the request, if one did.
728    pub refused: Option<Refusal>,
729    /// For a deferred request, the number [`Defer::ask_any`](crate::Defer::ask_any)
730    /// returned when it was asked; `None` for local listeners run by
731    /// [`Bus::run_pending`](crate::Bus::run_pending).
732    pub ask: Option<u64>,
733}
734
735impl PendingRun {
736    /// A run of `point` where nothing ran yet.
737    pub fn new(point: &'static str) -> PendingRun {
738        PendingRun {
739            point,
740            ran: Vec::new(),
741            failures: Vec::new(),
742            refused: None,
743            ask: None,
744        }
745    }
746}
747
748/// A listener as introspection shows it.
749#[derive(Clone, Debug, PartialEq, Eq)]
750#[non_exhaustive]
751pub struct ListenerInfo {
752    /// Its id.
753    pub id: String,
754    /// Its owner.
755    pub owner: Option<String>,
756    /// The listeners it runs after.
757    pub after: Vec<String>,
758    /// The listeners it runs before.
759    pub before: Vec<String>,
760    /// Its priority.
761    pub priority: i32,
762    /// The deadline it gets: its own, else its point's, else the kernel's.
763    pub deadline: Duration,
764    /// Whether it runs on a thread of its own.
765    pub threaded: bool,
766    /// Whether it is a local listener, bound to the thread that
767    /// registered it.
768    pub local: bool,
769    /// The `after`/`before` targets that are not registered.
770    pub missing: Vec<String>,
771    /// How many times it ran.
772    pub runs: u64,
773    /// How many of those runs failed (contribution dropped).
774    pub failures: u64,
775    /// The last failure, as text.
776    pub last_failure: Option<String>,
777}
778
779impl ListenerInfo {
780    /// The listener `id` with no owner, no constraint, priority 0, the
781    /// default deadline, inline, never run.
782    pub fn new(id: impl Into<String>) -> ListenerInfo {
783        ListenerInfo {
784            id: id.into(),
785            owner: None,
786            after: Vec::new(),
787            before: Vec::new(),
788            priority: 0,
789            deadline: DEFAULT_DEADLINE,
790            threaded: false,
791            local: false,
792            missing: Vec::new(),
793            runs: 0,
794            failures: 0,
795            last_failure: None,
796        }
797    }
798}
799
800/// A point as introspection shows it.
801#[derive(Clone, Debug, PartialEq, Eq)]
802#[non_exhaustive]
803pub struct PointInfo {
804    /// Its id.
805    pub id: &'static str,
806    /// What it is for.
807    pub kind: PointKind,
808    /// Its description; empty until declared.
809    pub description: String,
810    /// Whether its owner declared it ([`Bus::declare_point`](crate::Bus::declare_point)); a point
811    /// listened to before that is not.
812    pub declared: bool,
813    /// The deadline of its listeners that set none.
814    pub deadline: Duration,
815    /// Whether a listener failure refuses the request
816    /// ([`PointSpec::fail_closed`]).
817    pub fail_closed: bool,
818    /// The time one pass of its listeners should take
819    /// ([`PointSpec::budget`]).
820    pub budget: Option<Duration>,
821    /// Whether its events go through the journal
822    /// ([`PointSpec::journaled`]).
823    pub journaled: bool,
824    /// Whether it crosses processes ([`PointSpec::relay`]): its events,
825    /// or, on a request, asks from another process.
826    pub relayable: bool,
827    /// Its version ([`PointSpec::version`]).
828    pub version: u32,
829    /// Its listeners, in the order they run.
830    pub listeners: Vec<ListenerInfo>,
831}
832
833impl PointInfo {
834    /// The point `id` of `kind`, not declared, with the default deadline
835    /// and no listener.
836    pub fn new(id: &'static str, kind: PointKind) -> PointInfo {
837        PointInfo {
838            id,
839            kind,
840            description: String::new(),
841            declared: false,
842            deadline: DEFAULT_DEADLINE,
843            fail_closed: false,
844            budget: None,
845            journaled: false,
846            relayable: false,
847            version: 1,
848            listeners: Vec::new(),
849        }
850    }
851}
852
853/// How long something took over a window of runs
854/// ([`Timings`](crate::Timings)): a listener's runs, or a point's passes.
855/// The quantiles may be approximate (an implementation may read them
856/// from a histogram); the count, total and max are exact.
857#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
858#[non_exhaustive]
859pub struct TimingStats {
860    /// How many runs.
861    pub count: u64,
862    /// Their time added up.
863    pub total: Duration,
864    /// The longest.
865    pub max: Duration,
866    /// The median.
867    pub p50: Duration,
868    /// The 95th percentile.
869    pub p95: Duration,
870}
871
872impl TimingStats {
873    /// No run.
874    pub fn new() -> TimingStats {
875        TimingStats::default()
876    }
877
878    /// The mean time of a run; zero with no run.
879    pub fn mean(&self) -> Duration {
880        match u32::try_from(self.count) {
881            Ok(0) => Duration::ZERO,
882            Ok(n) => self.total / n,
883            Err(_) => Duration::from_secs_f64(self.total.as_secs_f64() / self.count as f64),
884        }
885    }
886}
887
888/// One listener's time on a point ([`PointTimings::listeners`]).
889#[derive(Clone, Debug, Default, PartialEq, Eq)]
890#[non_exhaustive]
891pub struct ListenerTimings {
892    /// Its id.
893    pub id: String,
894    /// Its owner.
895    pub owner: Option<String>,
896    /// Its runs.
897    pub stats: TimingStats,
898}
899
900impl ListenerTimings {
901    /// The listener `id`, no run.
902    pub fn new(id: impl Into<String>) -> ListenerTimings {
903        ListenerTimings {
904            id: id.into(),
905            owner: None,
906            stats: TimingStats::new(),
907        }
908    }
909}
910
911/// A point's time ([`Timings::points`](crate::Timings::points)): its
912/// passes, its listeners, its budget and how often a pass went over.
913#[derive(Clone, Debug, PartialEq, Eq)]
914#[non_exhaustive]
915pub struct PointTimings {
916    /// The point.
917    pub point: &'static str,
918    /// Its budget ([`PointSpec::budget`]).
919    pub budget: Option<Duration>,
920    /// Its passes: each the time of the listeners one emit, queued run
921    /// or drained ask ran on one thread.
922    pub passes: TimingStats,
923    /// How many passes went over the budget.
924    pub over_budget: u64,
925    /// Its listeners that ran, in the order they run.
926    pub listeners: Vec<ListenerTimings>,
927}
928
929impl PointTimings {
930    /// The point `point`, no budget, no run.
931    pub fn new(point: &'static str) -> PointTimings {
932        PointTimings {
933            point,
934            budget: None,
935            passes: TimingStats::new(),
936            over_budget: 0,
937            listeners: Vec::new(),
938        }
939    }
940
941    /// Its listeners, the slowest first by their 95th percentile, then
942    /// by their max.
943    pub fn slowest(&self) -> Vec<&ListenerTimings> {
944        let mut out: Vec<&ListenerTimings> = self.listeners.iter().collect();
945        out.sort_by(|a, b| {
946            (b.stats.p95, b.stats.max)
947                .cmp(&(a.stats.p95, a.stats.max))
948                .then_with(|| a.id.cmp(&b.id))
949        });
950        out
951    }
952}
953
954/// A pass of a point's listeners that went over its budget
955/// ([`PointSpec::budget`]): reported to the budget sinks
956/// ([`Timings::add_budget_sink`](crate::Timings::add_budget_sink)). The
957/// pass's results were kept: a budget is not a deadline.
958#[derive(Clone, Debug, PartialEq, Eq)]
959#[non_exhaustive]
960pub struct OverBudget {
961    /// The point.
962    pub point: &'static str,
963    /// The pass's time: its listeners' times added up.
964    pub took: Duration,
965    /// The point's budget.
966    pub budget: Duration,
967    /// Each listener that ran in the pass, in order, with its time.
968    pub listeners: Vec<(String, Duration)>,
969}
970
971impl OverBudget {
972    /// A pass of `point` that took `took` against `budget`.
973    pub fn new(point: &'static str, took: Duration, budget: Duration) -> OverBudget {
974        OverBudget {
975            point,
976            took,
977            budget,
978            listeners: Vec::new(),
979        }
980    }
981
982    /// The listener that took longest in the pass, with its time.
983    pub fn slowest(&self) -> Option<(&str, Duration)> {
984        self.listeners
985            .iter()
986            .max_by_key(|(_, t)| *t)
987            .map(|(id, t)| (id.as_str(), *t))
988    }
989}
990
991impl fmt::Display for OverBudget {
992    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
993        write!(
994            f,
995            "hook `{}`: a pass took {:?}, over its budget of {:?}",
996            self.point, self.took, self.budget
997        )?;
998        if let Some((id, t)) = self.slowest() {
999            write!(f, " (slowest `{id}`: {t:?})")?;
1000        }
1001        Ok(())
1002    }
1003}