bus-contract 0.4.4

A contract for a hook bus: libraries declare typed hook points and listen with named order (after, before, last), owners and deadlines; the application supplies the implementation and decides on one bus or several. No dependencies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
//! The contract's types, shared by every implementation.

use std::fmt;
use std::time::Duration;

/// The deadline of an in-process listener when neither the listener nor
/// its point sets one.
pub const DEFAULT_DEADLINE: Duration = Duration::from_secs(1);

/// The deadline meant for listeners that answer from another process (a
/// plugin over RPC): give it with [`ListenOpts::deadline`] or
/// [`PointSpec::deadline`].
pub const PLUGIN_DEADLINE: Duration = Duration::from_secs(5);

/// The `after` target that places a listener after every other listener
/// of its point ([`ListenOpts::last`]): one per point, a second is
/// refused as a [`Refused::Cycle`] (each would run after the other).
pub const LAST: &str = "*";

/// The name a host gives the fact it publishes for each [`Failure`] its
/// sinks receive ([`Bus::add_failure_sink`](crate::Bus::add_failure_sink)).
pub const FAILED_FACT: &str = "hook.failed";

/// The name a host gives the fact it publishes for each [`OverBudget`]
/// its budget sinks receive
/// ([`Timings::add_budget_sink`](crate::Timings::add_budget_sink)).
pub const OVER_BUDGET_FACT: &str = "bus.overBudget";

/// A hook point: one type per point, so its input and value are checked
/// at compile time. Declared by the crate that owns the result.
///
/// Every listener of a point has the same shape: it reads the emit's
/// [`Input`](Point::Input) and edits a [`Value`](Point::Value). An
/// [`alter`](crate::Bus::alter_any) emit passes one value through the listeners
/// in order; a [`collect`](crate::Bus::collect_any) emit gives each listener a
/// fresh value and gathers them in a list.
pub trait Point: 'static {
    /// The point's id, dotted by convention (`health.report`).
    const ID: &'static str;
    /// What every listener reads: shared, never changed by a listener.
    type Input: Send + Sync + 'static;
    /// What a listener edits: the value altered in turn, or one
    /// listener's contribution to a collect.
    type Value: Send + 'static;
    /// What the point is for ([`PointKind`]); [`PointKind::Alter`] unless
    /// the point says otherwise.
    const KIND: PointKind = PointKind::Alter;
}

/// What a point is for, declared for introspection and review. A request
/// is an alter emit over the request's input; only a request can be
/// refused by a listener ([`HookError::Refuse`]) or declared fail-closed
/// ([`PointSpec::fail_closed`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PointKind {
    /// A request (`<noun>.<verb>`): its listeners do the work in their
    /// declared order; the value is what each did.
    Request,
    /// An event's listeners: each event delivered once, in journal order.
    Event,
    /// One value passed through the listeners in turn.
    #[default]
    Alter,
    /// Each listener adds its own part.
    Collect,
}

impl PointKind {
    /// The kind as introspection writes it (`request`).
    pub fn as_str(self) -> &'static str {
        match self {
            PointKind::Request => "request",
            PointKind::Event => "event",
            PointKind::Alter => "alter",
            PointKind::Collect => "collect",
        }
    }
}

/// A point's declaration: its description and limits, for introspection.
///
/// New fields may be added in a minor release: build one with
/// [`PointSpec::new`] and the builder methods.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PointSpec {
    /// What the point builds, for people and agents reading
    /// [`Bus::points`](crate::Bus::points).
    pub description: String,
    /// The deadline of the point's listeners that set none themselves;
    /// `None` takes the kernel's default.
    pub deadline: Option<Duration>,
    /// On a [`PointKind::Request`] point, a listener that fails (an
    /// error, a panic, a missed deadline) refuses the request instead of
    /// having its contribution dropped: the emit stops there
    /// ([`Refusal::failed`]). Ignored on the other kinds.
    pub fail_closed: bool,
    /// The time one pass of the point's listeners should take on a
    /// thread ([`Timings`](crate::Timings)): a pass over it is reported
    /// ([`OverBudget`]), never failed. `None`: no budget.
    pub budget: Option<Duration>,
    /// On a [`PointKind::Event`] point, its events go through the bus's
    /// journal ([`Journal`](crate::Journal)): published with a number,
    /// delivered to the listeners in journal order after the publisher
    /// has moved on.
    pub journaled: bool,
    /// How the point crosses a process ([`Relay`](crate::Relay)): on a
    /// journaled event point, how its input is written; on a request
    /// point, its input and value ([`Codec::request`](crate::Codec::request)),
    /// so another process may ask it ([`Relay::answer`](crate::Relay::answer)).
    /// `None`: it stays in this one.
    pub relay: Option<crate::Codec>,
    /// The point's version, from 1: raised when its payload changes in a
    /// way an older reader cannot use (a field it may ignore is not such
    /// a change). Two processes cross a point only at the same version
    /// ([`IngestError::Version`](crate::IngestError::Version)).
    pub version: u32,
}

impl PointSpec {
    /// A point described by `description`, with the kernel's deadline.
    pub fn new(description: impl Into<String>) -> PointSpec {
        PointSpec {
            description: description.into(),
            deadline: None,
            fail_closed: false,
            budget: None,
            journaled: false,
            relay: None,
            version: 1,
        }
    }

    /// The deadline of the point's listeners that set none themselves.
    pub fn deadline(mut self, deadline: Duration) -> PointSpec {
        self.deadline = Some(deadline);
        self
    }

    /// A listener failure refuses the request ([`PointSpec::fail_closed`]).
    pub fn fail_closed(mut self) -> PointSpec {
        self.fail_closed = true;
        self
    }

    /// The time one pass of the point's listeners should take
    /// ([`PointSpec::budget`]).
    pub fn budget(mut self, budget: Duration) -> PointSpec {
        self.budget = Some(budget);
        self
    }

    /// Its events go through the journal ([`PointSpec::journaled`]).
    pub fn journaled(mut self) -> PointSpec {
        self.journaled = true;
        self
    }

    /// Its events cross processes with `codec`; journaled too
    /// ([`PointSpec::relay`]). For an event point: a request uses
    /// [`PointSpec::relayable_request`].
    pub fn relayable(mut self, codec: crate::Codec) -> PointSpec {
        self.journaled = true;
        self.relay = Some(codec);
        self
    }

    /// Another process may ask this request, its input and value written
    /// by `codec` ([`Codec::request`](crate::Codec::request)); fail-closed
    /// too, so no answer in time is a refusal ([`PointSpec::relay`]).
    pub fn relayable_request(mut self, codec: crate::Codec) -> PointSpec {
        self.fail_closed = true;
        self.relay = Some(codec);
        self
    }

    /// The point's version ([`PointSpec::version`]).
    pub fn version(mut self, version: u32) -> PointSpec {
        self.version = version;
        self
    }
}

/// How a listener is placed and limited.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ListenOpts {
    /// Listeners this one runs after.
    pub after: Vec<String>,
    /// Listeners this one runs before.
    pub before: Vec<String>,
    /// Among listeners `after`/`before` leave free, higher runs first;
    /// ties run in registration order.
    pub priority: i32,
    /// Overrides the point's deadline.
    pub deadline: Option<Duration>,
    /// Who registered it (a module, a plugin), for [`Bus::forget`](crate::Bus::forget) and
    /// introspection.
    pub owner: Option<String>,
    /// Runs on a thread of its own, so the emit stops waiting at the
    /// deadline. An inline listener (the default) runs on the emitting
    /// thread: it cannot be stopped, and only counts as late once it
    /// returns. A local listener runs inline on its own thread: it is
    /// refused with this set ([`Refused::Threaded`]).
    pub threaded: bool,
}

impl ListenOpts {
    /// No constraint, priority 0, the point's deadline, inline.
    pub fn new() -> ListenOpts {
        ListenOpts::default()
    }

    /// Runs after the listener `id` (a missing one is reported and
    /// ignored).
    pub fn after(mut self, id: impl Into<String>) -> ListenOpts {
        self.after.push(id.into());
        self
    }

    /// Runs before the listener `id` (a missing one is reported and
    /// ignored).
    pub fn before(mut self, id: impl Into<String>) -> ListenOpts {
        self.before.push(id.into());
        self
    }

    /// Runs after every other listener of its point, whatever they
    /// declare: an invariants check, a listener that reads what all the
    /// others left. One per point: a second one closes a cycle and is
    /// refused ([`Refused::Cycle`]). Kept in [`ListenOpts::after`] as
    /// [`LAST`].
    pub fn last(mut self) -> ListenOpts {
        if !self.after.iter().any(|a| a == LAST) {
            self.after.push(LAST.to_owned());
        }
        self
    }

    /// Whether the listener runs after every other one of its point
    /// ([`ListenOpts::last`]).
    pub fn is_last(&self) -> bool {
        self.after.iter().any(|a| a == LAST)
    }

    /// Higher runs first among listeners left free by `after`/`before`.
    pub fn priority(mut self, priority: i32) -> ListenOpts {
        self.priority = priority;
        self
    }

    /// Overrides the point's deadline.
    pub fn deadline(mut self, deadline: Duration) -> ListenOpts {
        self.deadline = Some(deadline);
        self
    }

    /// Who registered the listener.
    pub fn owner(mut self, owner: impl Into<String>) -> ListenOpts {
        self.owner = Some(owner.into());
        self
    }

    /// Runs on a thread of its own, so a slow listener cannot hold the
    /// emit past its deadline.
    pub fn threaded(mut self) -> ListenOpts {
        self.threaded = true;
        self
    }
}

/// What a listener returns instead of `Ok(())`: it failed, or it refuses
/// the request.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum HookError {
    /// The listener failed: its contribution is dropped and the other
    /// listeners run, unless its point is fail-closed
    /// ([`PointSpec::fail_closed`]).
    Failed(String),
    /// The listener refuses the request, with a reason. On a
    /// [`PointKind::Request`] point the emit stops: no later listener
    /// runs, and the result names the refusal ([`Refusal`]). On another
    /// kind it counts as [`HookError::Failed`].
    Refuse(String),
}

impl HookError {
    /// A failure with `message`.
    pub fn failed(message: impl Into<String>) -> HookError {
        HookError::Failed(message.into())
    }

    /// A refusal of the request, with `reason`.
    pub fn refuse(reason: impl Into<String>) -> HookError {
        HookError::Refuse(reason.into())
    }

    /// The failure's message or the refusal's reason.
    pub fn message(&self) -> &str {
        match self {
            HookError::Failed(m) | HookError::Refuse(m) => m,
        }
    }

    /// Whether the listener refuses the request.
    pub fn is_refusal(&self) -> bool {
        matches!(self, HookError::Refuse(_))
    }
}

impl fmt::Display for HookError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HookError::Failed(m) => f.write_str(m),
            HookError::Refuse(r) => write!(f, "refused: {r}"),
        }
    }
}

impl std::error::Error for HookError {}

/// A failure with this message.
impl From<String> for HookError {
    fn from(message: String) -> HookError {
        HookError::Failed(message)
    }
}

/// A failure with this message.
impl From<&str> for HookError {
    fn from(message: &str) -> HookError {
        HookError::Failed(message.to_owned())
    }
}

/// What went wrong with one listener during an emit.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum FailureKind {
    /// The listener returned an error.
    Error(String),
    /// The listener panicked; the panic's message.
    Panic(String),
    /// The listener missed its deadline. `took` is its time when it
    /// returned late (inline); `None` when the emit stopped waiting
    /// (threaded).
    Late {
        /// The deadline it had.
        deadline: Duration,
        /// How long it ran, when it returned.
        took: Option<Duration>,
    },
    /// An `after` or `before` constraint names a listener that is not
    /// registered. The listener still ran and its contribution counts;
    /// only the constraint was ignored. Not sent to the failure sinks.
    MissingTarget(String),
    /// The point id is registered with another [`Point`] type; no
    /// listener ran. `listener` is `*`.
    TypeMismatch,
}

/// One listener's failure: its contribution was dropped (except for a
/// [`FailureKind::MissingTarget`]); the other listeners ran, unless the
/// point is fail-closed ([`PointSpec::fail_closed`]).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Failure {
    /// The point emitted.
    pub point: &'static str,
    /// The listener's id.
    pub listener: String,
    /// The listener's owner.
    pub owner: Option<String>,
    /// What went wrong.
    pub kind: FailureKind,
}

impl Failure {
    /// The failure of the listener `listener` of `point`.
    pub fn new(
        point: &'static str,
        listener: impl Into<String>,
        owner: Option<String>,
        kind: FailureKind,
    ) -> Failure {
        Failure {
            point,
            listener: listener.into(),
            owner,
            kind,
        }
    }

    /// Whether the failure dropped a contribution: everything but a
    /// missing ordering target. Only these reach the failure sinks.
    pub fn dropped(&self) -> bool {
        !matches!(self.kind, FailureKind::MissingTarget(_))
    }
}

impl fmt::Display for FailureKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FailureKind::Error(m) => write!(f, "failed: {m}"),
            FailureKind::Panic(m) => write!(f, "panicked: {m}"),
            FailureKind::Late {
                deadline,
                took: Some(t),
            } => write!(f, "took {t:?}, past its deadline of {deadline:?}"),
            FailureKind::Late { deadline, .. } => {
                write!(f, "no answer within its deadline of {deadline:?}")
            }
            FailureKind::MissingTarget(t) => {
                write!(f, "orders itself against `{t}`, which is not there")
            }
            FailureKind::TypeMismatch => write!(f, "the point is registered with another type"),
        }
    }
}

impl fmt::Display for Failure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "hook `{}`, listener `{}`: {}",
            self.point, self.listener, self.kind
        )
    }
}

/// Why a declaration or a listener was refused. Nothing was changed.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Refused {
    /// The point already has a listener with this id.
    Duplicate {
        /// The point.
        point: &'static str,
        /// The id taken.
        listener: String,
    },
    /// The listener's `after`/`before` would close a cycle: these
    /// listeners, each to run before the next, the first again at the
    /// end.
    Cycle {
        /// The point.
        point: &'static str,
        /// The listeners in the cycle.
        path: Vec<String>,
    },
    /// The point id is already registered with another [`Point`] type.
    TypeMismatch {
        /// The point.
        point: &'static str,
    },
    /// The point was already declared.
    AlreadyDeclared {
        /// The point.
        point: &'static str,
    },
    /// A local listener asked for a thread of its own
    /// ([`ListenOpts::threaded`]); it runs on the thread that registered
    /// it.
    Threaded {
        /// The point.
        point: &'static str,
        /// The listener.
        listener: String,
    },
    /// The point needs a capability the bus does not offer
    /// ([`PointDecl::needs`](crate::PointDecl::needs)); it was not
    /// declared.
    Unsupported {
        /// The point.
        point: &'static str,
        /// The capability missing.
        capability: Capability,
    },
    /// Only an event point is journaled or relayed
    /// ([`PointSpec::journaled`]); it was not declared.
    NotEvent {
        /// The point.
        point: &'static str,
    },
    /// An event was published through the journal on a point not
    /// declared journaled on this bus; nothing was recorded.
    NotJournaled {
        /// The point.
        point: &'static str,
    },
    /// The point is relayable but cannot cross: only an event point, or
    /// a request point whose codec writes its value too
    /// ([`Codec::request`](crate::Codec::request)), crosses a process. It
    /// was not declared.
    NotCrossable {
        /// The point.
        point: &'static str,
    },
}

impl fmt::Display for Refused {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Refused::Duplicate { point, listener } => {
                write!(f, "hook `{point}` already has a listener `{listener}`")
            }
            Refused::Cycle { point, path } => {
                write!(
                    f,
                    "hook `{point}`: listeners order each other in a cycle: {}",
                    path.join(" -> ")
                )
            }
            Refused::TypeMismatch { point } => {
                write!(f, "hook `{point}` is registered with another type")
            }
            Refused::AlreadyDeclared { point } => write!(f, "hook `{point}` is already declared"),
            Refused::Threaded { point, listener } => write!(
                f,
                "hook `{point}`: the local listener `{listener}` runs on its own thread, not a new one"
            ),
            Refused::Unsupported { point, capability } => write!(
                f,
                "hook `{point}` needs the `{}` capability, which this bus does not offer",
                capability.as_str()
            ),
            Refused::NotEvent { point } => write!(
                f,
                "hook `{point}` is journaled or relayable but is not an event point"
            ),
            Refused::NotJournaled { point } => {
                write!(f, "hook `{point}` is not declared journaled on this bus")
            }
            Refused::NotCrossable { point } => write!(
                f,
                "hook `{point}` is relayable but cannot cross: only an event, or a request with a value codec, crosses"
            ),
        }
    }
}

impl std::error::Error for Refused {}

/// A capability a bus may offer beyond the core of [`Bus`](crate::Bus),
/// found at run time ([`Bus::defer`](crate::Bus::defer)). A library names
/// the ones its points need in its contract table
/// ([`PointDecl::needs`](crate::PointDecl::needs)).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Capability {
    /// Requests asked now and heard at the bus's next drain on the same
    /// thread ([`Defer`](crate::Defer)).
    Defer,
    /// How long listeners take, per point and listener, and passes over
    /// a point's budget reported ([`Timings`](crate::Timings)).
    Timings,
    /// Events kept with a number, read again from one, delivered after
    /// the publisher has moved on ([`Journal`](crate::Journal)).
    Journal,
    /// Events of relayable points served to another process and taken
    /// in from one, asks of relayable requests answered for one
    /// ([`Relay`](crate::Relay)); implies `Journal`.
    Relay,
}

impl Capability {
    /// The capability as messages write it (`defer`).
    pub fn as_str(self) -> &'static str {
        match self {
            Capability::Defer => "defer",
            Capability::Timings => "timings",
            Capability::Journal => "journal",
            Capability::Relay => "relay",
        }
    }
}

/// A request stopped by one of its listeners: the listener refused it
/// ([`HookError::Refuse`]), or failed on a fail-closed point
/// ([`PointSpec::fail_closed`]). The listeners after it did not run.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Refusal {
    /// The point emitted.
    pub point: &'static str,
    /// The listener that stopped the request.
    pub listener: String,
    /// Its owner.
    pub owner: Option<String>,
    /// The reason it gave, or its failure as text.
    pub reason: String,
    /// Whether the listener failed (its [`Failure`] is in the result's
    /// failures) rather than refused.
    pub failed: bool,
}

impl Refusal {
    /// The refusal of `point` by the listener `listener`, for `reason`.
    pub fn new(
        point: &'static str,
        listener: impl Into<String>,
        owner: Option<String>,
        reason: impl Into<String>,
    ) -> Refusal {
        Refusal {
            point,
            listener: listener.into(),
            owner,
            reason: reason.into(),
            failed: false,
        }
    }

    /// The refusal a listener's failure makes on a fail-closed point.
    pub fn from_failure(failure: &Failure) -> Refusal {
        let reason = match &failure.kind {
            FailureKind::Error(m) | FailureKind::Panic(m) => m.clone(),
            kind => kind.to_string(),
        };
        Refusal {
            point: failure.point,
            listener: failure.listener.clone(),
            owner: failure.owner.clone(),
            reason,
            failed: true,
        }
    }
}

impl fmt::Display for Refusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.failed {
            write!(
                f,
                "hook `{}`: refused, `{}` failed: {}",
                self.point, self.listener, self.reason
            )
        } else {
            write!(
                f,
                "hook `{}`: refused by `{}`: {}",
                self.point, self.listener, self.reason
            )
        }
    }
}

/// The result of an [`alter`](crate::Bus::alter_any) emit.
#[derive(Debug)]
#[non_exhaustive]
pub struct Altered<V> {
    /// The value after every listener that succeeded; when the request
    /// was refused, as the listeners before the refusal left it.
    pub value: V,
    /// Every failure, in listener order.
    pub failures: Vec<Failure>,
    /// The local listeners bound to another thread, in order: queued for
    /// that thread's [`run_pending`](crate::Bus::run_pending), not run
    /// by this emit. Empty when the request was refused.
    pub deferred: Vec<String>,
    /// The listener that stopped the request, if one did.
    pub refused: Option<Refusal>,
}

impl<V> Altered<V> {
    /// An emit that left `value`, with no failure, nothing deferred and
    /// no refusal.
    pub fn new(value: V) -> Altered<V> {
        Altered {
            value,
            failures: Vec::new(),
            deferred: Vec::new(),
            refused: None,
        }
    }
}

/// The result of a [`collect`](crate::Bus::collect_any) emit.
#[derive(Debug)]
#[non_exhaustive]
pub struct Collected<V> {
    /// Each successful listener's value, in listener order, with its id.
    pub parts: Vec<(String, V)>,
    /// Every failure, in listener order.
    pub failures: Vec<Failure>,
    /// The local listeners bound to another thread, in order: queued for
    /// that thread's [`run_pending`](crate::Bus::run_pending), not run
    /// by this emit. Empty when the request was refused.
    pub deferred: Vec<String>,
    /// The listener that stopped the request, if one did.
    pub refused: Option<Refusal>,
}

impl<V> Collected<V> {
    /// An emit with no part, no failure, nothing deferred and no
    /// refusal.
    pub fn new() -> Collected<V> {
        Collected {
            parts: Vec::new(),
            failures: Vec::new(),
            deferred: Vec::new(),
            refused: None,
        }
    }
}

impl<V> Default for Collected<V> {
    fn default() -> Collected<V> {
        Collected::new()
    }
}

/// What listeners run later did: one emit's local listeners queued for
/// their thread ([`Bus::run_pending`](crate::Bus::run_pending)), or one
/// deferred request ([`Defer::drain`](crate::Defer::drain)).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PendingRun {
    /// The point emitted.
    pub point: &'static str,
    /// The listeners that ran, in order (a listener removed since the
    /// emit is not run).
    pub ran: Vec<String>,
    /// Their failures, in listener order.
    pub failures: Vec<Failure>,
    /// The listener that stopped the request, if one did.
    pub refused: Option<Refusal>,
    /// For a deferred request, the number [`Defer::ask_any`](crate::Defer::ask_any)
    /// returned when it was asked; `None` for local listeners run by
    /// [`Bus::run_pending`](crate::Bus::run_pending).
    pub ask: Option<u64>,
}

impl PendingRun {
    /// A run of `point` where nothing ran yet.
    pub fn new(point: &'static str) -> PendingRun {
        PendingRun {
            point,
            ran: Vec::new(),
            failures: Vec::new(),
            refused: None,
            ask: None,
        }
    }
}

/// A listener as introspection shows it.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ListenerInfo {
    /// Its id.
    pub id: String,
    /// Its owner.
    pub owner: Option<String>,
    /// The listeners it runs after.
    pub after: Vec<String>,
    /// The listeners it runs before.
    pub before: Vec<String>,
    /// Its priority.
    pub priority: i32,
    /// The deadline it gets: its own, else its point's, else the kernel's.
    pub deadline: Duration,
    /// Whether it runs on a thread of its own.
    pub threaded: bool,
    /// Whether it is a local listener, bound to the thread that
    /// registered it.
    pub local: bool,
    /// The `after`/`before` targets that are not registered.
    pub missing: Vec<String>,
    /// How many times it ran.
    pub runs: u64,
    /// How many of those runs failed (contribution dropped).
    pub failures: u64,
    /// The last failure, as text.
    pub last_failure: Option<String>,
}

impl ListenerInfo {
    /// The listener `id` with no owner, no constraint, priority 0, the
    /// default deadline, inline, never run.
    pub fn new(id: impl Into<String>) -> ListenerInfo {
        ListenerInfo {
            id: id.into(),
            owner: None,
            after: Vec::new(),
            before: Vec::new(),
            priority: 0,
            deadline: DEFAULT_DEADLINE,
            threaded: false,
            local: false,
            missing: Vec::new(),
            runs: 0,
            failures: 0,
            last_failure: None,
        }
    }
}

/// A point as introspection shows it.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PointInfo {
    /// Its id.
    pub id: &'static str,
    /// What it is for.
    pub kind: PointKind,
    /// Its description; empty until declared.
    pub description: String,
    /// Whether its owner declared it ([`Bus::declare_point`](crate::Bus::declare_point)); a point
    /// listened to before that is not.
    pub declared: bool,
    /// The deadline of its listeners that set none.
    pub deadline: Duration,
    /// Whether a listener failure refuses the request
    /// ([`PointSpec::fail_closed`]).
    pub fail_closed: bool,
    /// The time one pass of its listeners should take
    /// ([`PointSpec::budget`]).
    pub budget: Option<Duration>,
    /// Whether its events go through the journal
    /// ([`PointSpec::journaled`]).
    pub journaled: bool,
    /// Whether it crosses processes ([`PointSpec::relay`]): its events,
    /// or, on a request, asks from another process.
    pub relayable: bool,
    /// Its version ([`PointSpec::version`]).
    pub version: u32,
    /// Its listeners, in the order they run.
    pub listeners: Vec<ListenerInfo>,
}

impl PointInfo {
    /// The point `id` of `kind`, not declared, with the default deadline
    /// and no listener.
    pub fn new(id: &'static str, kind: PointKind) -> PointInfo {
        PointInfo {
            id,
            kind,
            description: String::new(),
            declared: false,
            deadline: DEFAULT_DEADLINE,
            fail_closed: false,
            budget: None,
            journaled: false,
            relayable: false,
            version: 1,
            listeners: Vec::new(),
        }
    }
}

/// How long something took over a window of runs
/// ([`Timings`](crate::Timings)): a listener's runs, or a point's passes.
/// The quantiles may be approximate (an implementation may read them
/// from a histogram); the count, total and max are exact.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct TimingStats {
    /// How many runs.
    pub count: u64,
    /// Their time added up.
    pub total: Duration,
    /// The longest.
    pub max: Duration,
    /// The median.
    pub p50: Duration,
    /// The 95th percentile.
    pub p95: Duration,
}

impl TimingStats {
    /// No run.
    pub fn new() -> TimingStats {
        TimingStats::default()
    }

    /// The mean time of a run; zero with no run.
    pub fn mean(&self) -> Duration {
        match u32::try_from(self.count) {
            Ok(0) => Duration::ZERO,
            Ok(n) => self.total / n,
            Err(_) => Duration::from_secs_f64(self.total.as_secs_f64() / self.count as f64),
        }
    }
}

/// One listener's time on a point ([`PointTimings::listeners`]).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ListenerTimings {
    /// Its id.
    pub id: String,
    /// Its owner.
    pub owner: Option<String>,
    /// Its runs.
    pub stats: TimingStats,
}

impl ListenerTimings {
    /// The listener `id`, no run.
    pub fn new(id: impl Into<String>) -> ListenerTimings {
        ListenerTimings {
            id: id.into(),
            owner: None,
            stats: TimingStats::new(),
        }
    }
}

/// A point's time ([`Timings::points`](crate::Timings::points)): its
/// passes, its listeners, its budget and how often a pass went over.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PointTimings {
    /// The point.
    pub point: &'static str,
    /// Its budget ([`PointSpec::budget`]).
    pub budget: Option<Duration>,
    /// Its passes: each the time of the listeners one emit, queued run
    /// or drained ask ran on one thread.
    pub passes: TimingStats,
    /// How many passes went over the budget.
    pub over_budget: u64,
    /// Its listeners that ran, in the order they run.
    pub listeners: Vec<ListenerTimings>,
}

impl PointTimings {
    /// The point `point`, no budget, no run.
    pub fn new(point: &'static str) -> PointTimings {
        PointTimings {
            point,
            budget: None,
            passes: TimingStats::new(),
            over_budget: 0,
            listeners: Vec::new(),
        }
    }

    /// Its listeners, the slowest first by their 95th percentile, then
    /// by their max.
    pub fn slowest(&self) -> Vec<&ListenerTimings> {
        let mut out: Vec<&ListenerTimings> = self.listeners.iter().collect();
        out.sort_by(|a, b| {
            (b.stats.p95, b.stats.max)
                .cmp(&(a.stats.p95, a.stats.max))
                .then_with(|| a.id.cmp(&b.id))
        });
        out
    }
}

/// A pass of a point's listeners that went over its budget
/// ([`PointSpec::budget`]): reported to the budget sinks
/// ([`Timings::add_budget_sink`](crate::Timings::add_budget_sink)). The
/// pass's results were kept: a budget is not a deadline.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct OverBudget {
    /// The point.
    pub point: &'static str,
    /// The pass's time: its listeners' times added up.
    pub took: Duration,
    /// The point's budget.
    pub budget: Duration,
    /// Each listener that ran in the pass, in order, with its time.
    pub listeners: Vec<(String, Duration)>,
}

impl OverBudget {
    /// A pass of `point` that took `took` against `budget`.
    pub fn new(point: &'static str, took: Duration, budget: Duration) -> OverBudget {
        OverBudget {
            point,
            took,
            budget,
            listeners: Vec::new(),
        }
    }

    /// The listener that took longest in the pass, with its time.
    pub fn slowest(&self) -> Option<(&str, Duration)> {
        self.listeners
            .iter()
            .max_by_key(|(_, t)| *t)
            .map(|(id, t)| (id.as_str(), *t))
    }
}

impl fmt::Display for OverBudget {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "hook `{}`: a pass took {:?}, over its budget of {:?}",
            self.point, self.took, self.budget
        )?;
        if let Some((id, t)) = self.slowest() {
            write!(f, " (slowest `{id}`: {t:?})")?;
        }
        Ok(())
    }
}