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