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