bus-contract 0.5.0

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
#![doc = include_str!("../README.md")]
#![forbid(unsafe_code)]
#![warn(missing_docs)]

mod contract;
mod ids;
mod tools;
mod types;

/// What an implementation guarantees and what it does not, contract by
/// contract, each property with a stable id and the conformance check
/// that proves it. Documentation only: this module has no items.
#[doc = include_str!("../GUARANTEES.md")]
pub mod guarantees {}

use std::any::{Any, TypeId, type_name};
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;

pub use contract::{Contract, Facet, offers};
pub use ids::{IdError, ListenerId, PointId, check_id};
pub use tools::{declare_all, missing_targets, order_dump};
pub use types::*;

/// A point as the erased methods of [`Bus`] name it: its id, its kind and
/// its type, so an implementation refuses one id registered with two
/// types.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PointKey {
    /// The point's id ([`Point::ID`]).
    pub id: &'static str,
    /// What it is for ([`Point::KIND`]).
    pub kind: PointKind,
    /// The point type's id.
    pub type_id: TypeId,
    /// The point type's name, for messages.
    pub type_name: &'static str,
}

impl PointKey {
    /// The key of the point `P`.
    pub fn of<P: Point>() -> PointKey {
        PointKey {
            id: P::ID.as_str(),
            kind: P::KIND,
            type_id: TypeId::of::<P>(),
            type_name: type_name::<P>(),
        }
    }
}

/// An emit's input, its type erased: a point's [`Point::Input`].
pub type AnyInput = Arc<dyn Any + Send + Sync>;

/// A value going through an emit, its type erased: a point's
/// [`Point::Value`].
pub type AnyValue = Box<dyn Any + Send>;

/// A listener, its types erased: it reads the input and edits the value
/// in place.
pub type AnyListener = Arc<
    dyn Fn(&(dyn Any + Send + Sync), &mut (dyn Any + Send)) -> Result<(), HookError> + Send + Sync,
>;

/// A local listener, its types erased: like [`AnyListener`], but neither
/// `Send` nor `Sync`. It is bound to the thread that registered it
/// ([`Bus::listen_local_any`]).
pub type AnyLocalListener =
    Rc<dyn Fn(&(dyn Any + Send + Sync), &mut (dyn Any + Send)) -> Result<(), HookError>>;

/// Called when local work is queued for a thread
/// ([`Bus::add_pending_waker`]), with that thread's id, on the emitting
/// thread.
pub type PendingWaker = Arc<dyn Fn(std::thread::ThreadId) + Send + Sync>;

/// Copies an erased value of a point's type (an alter keeps the value as
/// it was when a listener fails).
pub type CloneFn = fn(&(dyn Any + Send)) -> AnyValue;

/// Makes a fresh erased value of a point's type (each listener's part in
/// a collect).
pub type FreshFn = fn() -> AnyValue;

/// Receives each failure that dropped a contribution
/// ([`Failure::dropped`]).
pub type FailureSink = Arc<dyn Fn(&Failure) + Send + Sync>;

/// The bus contract: hook points, their listeners in a declared order,
/// emits and introspection. An application supplies one implementation
/// (its own, or one written for it, such as `bus-kernel`'s `Kernel`)
/// and hands it to each
/// library at construction; a library never constructs the bus it
/// publishes on.
///
/// The methods are object safe and their values erased, so a library
/// holds an `Arc<dyn Bus>`; the typed calls (`declare::<P>`,
/// `listen::<P>`, `alter::<P>`, `collect::<P>`, `on_failure`) are methods
/// of `dyn Bus`, written once here over these.
///
/// What an implementation promises:
///
/// - Listeners run ordered by `after` / `before` first (the target
///   [`LAST`] places one after every other of its point, one per point),
///   then by priority (higher first), then by registration. A cycle is
///   refused at registration ([`Refused::Cycle`]); a target not there is
///   reported ([`FailureKind::MissingTarget`]) and ignored.
/// - A listener's edit counts only when it returns `Ok` within its
///   deadline without panicking; otherwise it is dropped, the others
///   still run, and the failure is returned and sent to the sinks.
/// - The value an emit returns is of the point's type: the typed calls
///   panic otherwise, as a defect of the implementation.
/// - Listeners run with no lock held, so a listener may emit or listen.
///
/// Every property, with its stable id, what it does not guarantee and
/// the check that proves it: [`guarantees`].
///
/// Refusals, on a point declared [`PointKind::Request`]:
///
/// - A listener that returns [`HookError::Refuse`] stops the request: its
///   own edit is dropped, no later listener runs (on this thread or
///   another: nothing is queued), and the result names the refusal
///   ([`Altered::refused`], [`Collected::refused`]). It is not a failure
///   and does not reach the failure sinks.
/// - On a point declared fail-closed ([`PointSpec::fail_closed`]), a
///   listener that fails (error, panic, missed deadline) stops the
///   request the same way: the failure is reported as usual and the
///   result names a refusal with [`Refusal::failed`] set. A threaded
///   listener that misses its deadline stops it at once.
/// - On the other kinds, [`HookError::Refuse`] counts as a failure
///   ([`FailureKind::Error`] with the reason) and `fail_closed` is
///   ignored.
///
/// Capabilities: an implementation may offer more than this core, each
/// a contract of its own, defined in a crate of its own
/// (`bus-contract-defer`, `-timings`, `-journal`, `-crossing`) and found
/// at run time through [`Bus::capability`], which returns `None` by
/// default. Each contract crate adds the typed call on every bus
/// (`use bus_contract_journal::BusJournal;` then `bus.journal()`). A
/// library that needs one names its [`Contract`] in its table
/// ([`PointDecl::needs`]), or a [`Facet`] of it
/// ([`PointDecl::facets`]); [`declare_all`] then refuses the point on a
/// bus without it ([`Refused::Unsupported`]). A library that can do
/// without checks the call and falls back.
///
/// Ids: a point's id is a [`PointId`], checked when made; a listener's
/// id is checked by the bus when it registers ([`Refused::BadId`]), and
/// a point key whose id breaks the rule is refused at declaration
/// ([`check_id`]).
///
/// Local listeners ([`Bus::listen_local_any`]) are for state that is not
/// `Send` (`Rc`, `RefCell`), such as an interface's. Each is bound to the
/// thread that registered it:
///
/// - It takes its place in the same order as the other listeners of its
///   point (`after` / `before` / [`LAST`], priority, registration), keeps
///   its owner and deadline, and shows in introspection
///   ([`ListenerInfo::local`]).
/// - An emit on its thread runs it in that order, inline, with the
///   others.
/// - An emit on another thread runs every other listener in order and
///   queues the local ones for their thread; the result names them
///   ([`Altered::deferred`], [`Collected::deferred`]) and the wakers
///   ([`Bus::add_pending_waker`]) are called. The thread runs them when
///   it calls [`Bus::run_pending`], in their order, emits in the order
///   they were queued. A deferred alter's listeners edit a copy of the
///   value the emit returned; a deferred collect's listeners each fill a
///   fresh value. What they do is reported by [`Bus::run_pending`], not
///   to the emitter.
/// - A listener removed ([`Bus::unlisten`], [`Bus::forget`]), from any
///   thread, does not run again, queued or not.
pub trait Bus: Send + Sync {
    /// Declares a point: its description and deadline. Listeners may
    /// register before or after; declaring twice is refused.
    fn declare_point(&self, point: PointKey, spec: PointSpec) -> Result<(), Refused>;

    /// Registers a listener on a point under `id`. Refused, with nothing
    /// changed, when the id is taken on the point, when its constraints
    /// close a cycle, or when the point is registered with another type.
    fn listen_any(
        &self,
        point: PointKey,
        id: String,
        opts: ListenOpts,
        run: AnyListener,
    ) -> Result<(), Refused>;

    /// Registers a local listener on a point under `id`, bound to the
    /// calling thread: it runs only on that thread. Refused as
    /// [`Bus::listen_any`] is, and when `opts` asks for a thread of its
    /// own ([`Refused::Threaded`]).
    fn listen_local_any(
        &self,
        point: PointKey,
        id: String,
        opts: ListenOpts,
        run: AnyLocalListener,
    ) -> Result<(), Refused>;

    /// Runs the local listeners queued for the calling thread by emits
    /// on other threads, emit by emit in the order they were queued;
    /// what each emit's deferred part did. Empty when nothing waits.
    fn run_pending(&self) -> Vec<PendingRun>;

    /// Adds a waker called when an emit queues local listeners for a
    /// thread, with that thread's id: where the host asks that thread to
    /// call [`Bus::run_pending`] (a repaint request, a message to its
    /// loop). A waker that panics is ignored.
    fn add_pending_waker(&self, wake: PendingWaker);

    /// Removes the listener `id` of the point `point`; whether it was
    /// there.
    fn unlisten(&self, point: &str, id: &str) -> bool;

    /// Removes every listener of `owner`, on every point; how many.
    fn forget(&self, owner: &str) -> usize;

    /// Passes `value` through the point's listeners in order, each
    /// editing what the previous ones left; `clone` copies it so a
    /// failing listener leaves it as it found it.
    fn alter_any(
        &self,
        point: PointKey,
        input: AnyInput,
        value: AnyValue,
        clone: CloneFn,
    ) -> Altered<AnyValue>;

    /// Gives each of the point's listeners, in order, a value from
    /// `fresh` to fill, and gathers those that succeed.
    fn collect_any(&self, point: PointKey, input: AnyInput, fresh: FreshFn) -> Collected<AnyValue>;

    /// Adds a sink called with each failure that dropped a contribution,
    /// as it happens.
    fn add_failure_sink(&self, sink: FailureSink);

    /// Every point, in id order, with its listeners in the order they
    /// run.
    fn points(&self) -> Vec<PointInfo>;

    /// The listeners of the point `point`, in the order they run; `None`
    /// for a point nobody declared or listened to.
    fn listeners(&self, point: &str) -> Option<Vec<ListenerInfo>>;

    /// Looks a capability up by the `TypeId` of its trait object type
    /// (`TypeId::of::<dyn Journal>()`): the bus as [`Any`] and the cast
    /// to that trait ([`Provided`]), or `None` (the default) when the
    /// implementation does not offer it. The typed call is
    /// [`capability`] (`capability::<dyn Journal, _>(bus)`, or
    /// `bus.get::<dyn Journal>()` on a `dyn Bus`).
    ///
    /// This is how a bus offers a capability whose trait the core does
    /// not name: an extension contract defines its trait and its
    /// [`Contract`], a bus answers for its `TypeId`, and a library reaches
    /// it through [`capability`] or the contract crate's extension trait.
    ///
    /// ```
    /// use std::any::{Any, TypeId};
    /// use bus_contract::{Cast, Provided};
    /// # trait Journal {}
    /// # struct MyBus;
    /// # impl Journal for MyBus {}
    /// fn as_journal(bus: &dyn Any) -> Option<&(dyn Journal + 'static)> {
    ///     bus.downcast_ref::<MyBus>().map(|b| b as _)
    /// }
    /// static AS_JOURNAL: Cast<dyn Journal> = as_journal;
    ///
    /// // in `impl Bus for MyBus`:
    /// fn capability(bus: &MyBus, contract: TypeId) -> Option<Provided<'_>> {
    ///     (contract == TypeId::of::<dyn Journal>())
    ///         .then(|| Provided::new::<dyn Journal>(bus, &AS_JOURNAL))
    /// }
    /// # assert!(capability(&MyBus, TypeId::of::<dyn Journal>()).is_some());
    /// ```
    fn capability(&self, contract: TypeId) -> Option<Provided<'_>> {
        let _ = contract;
        None
    }
}

/// The cast a bus gives for the capability `C` ([`Provided::new`]): from
/// the bus as [`Any`] to `C`. A plain function, usually a `static`, that
/// downcasts to the implementation's type and coerces.
pub type Cast<C> = for<'x> fn(&'x dyn Any) -> Option<&'x C>;

/// A capability found on a bus ([`Bus::capability`]): the bus as [`Any`]
/// and the cast from it to the capability's trait. [`capability`] turns
/// it into `&C`.
///
/// The cast travels as `Any` because `C` is unsized (`dyn Journal`),
/// which `downcast_ref` cannot target, while a function pointer is
/// sized: the lookup checks the cast is a [`Cast<C>`] for the `C` asked,
/// so a bus that answers one `TypeId` with another capability's cast
/// gives `None`, never a wrong type.
#[derive(Clone, Copy)]
pub struct Provided<'a> {
    this: &'a dyn Any,
    cast: &'static (dyn Any + Send + Sync),
}

impl<'a> Provided<'a> {
    /// The capability `C` of the bus `this`, reached through `cast`.
    pub fn new<C: ?Sized + 'static>(this: &'a dyn Any, cast: &'static Cast<C>) -> Provided<'a> {
        Provided { this, cast }
    }
}

impl std::fmt::Debug for Provided<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Provided").finish_non_exhaustive()
    }
}

/// The capability `C` of `bus`, a trait object type such as
/// `dyn Journal`: what [`Bus::capability`] answers for
/// `TypeId::of::<C>()`, cast to `C`. `None` when the bus does not offer
/// it through the lookup.
///
/// ```ignore
/// let journal = bus_contract::capability::<dyn Journal, _>(&bus);
/// ```
pub fn capability<C: ?Sized + 'static, B: Bus + ?Sized>(bus: &B) -> Option<&C> {
    let provided = bus.capability(TypeId::of::<C>())?;
    let cast = provided.cast.downcast_ref::<Cast<C>>()?;
    cast(provided.this)
}

impl<'a> dyn Bus + 'a {
    /// The capability `C` of this bus, a trait object type such as
    /// `dyn Journal` ([`capability`]).
    pub fn get<C: ?Sized + 'static>(&self) -> Option<&C> {
        capability::<C, Self>(self)
    }
}

/// A shared bus is a bus: `&Arc<dyn Bus>` goes where `&dyn Bus` is
/// asked, and an application may hand out `Arc<MyBus>` as it is.
impl<B: Bus + ?Sized> Bus for Arc<B> {
    fn declare_point(&self, point: PointKey, spec: PointSpec) -> Result<(), Refused> {
        (**self).declare_point(point, spec)
    }

    fn listen_any(
        &self,
        point: PointKey,
        id: String,
        opts: ListenOpts,
        run: AnyListener,
    ) -> Result<(), Refused> {
        (**self).listen_any(point, id, opts, run)
    }

    fn listen_local_any(
        &self,
        point: PointKey,
        id: String,
        opts: ListenOpts,
        run: AnyLocalListener,
    ) -> Result<(), Refused> {
        (**self).listen_local_any(point, id, opts, run)
    }

    fn run_pending(&self) -> Vec<PendingRun> {
        (**self).run_pending()
    }

    fn add_pending_waker(&self, wake: PendingWaker) {
        (**self).add_pending_waker(wake);
    }

    fn unlisten(&self, point: &str, id: &str) -> bool {
        (**self).unlisten(point, id)
    }

    fn forget(&self, owner: &str) -> usize {
        (**self).forget(owner)
    }

    fn alter_any(
        &self,
        point: PointKey,
        input: AnyInput,
        value: AnyValue,
        clone: CloneFn,
    ) -> Altered<AnyValue> {
        (**self).alter_any(point, input, value, clone)
    }

    fn collect_any(&self, point: PointKey, input: AnyInput, fresh: FreshFn) -> Collected<AnyValue> {
        (**self).collect_any(point, input, fresh)
    }

    fn add_failure_sink(&self, sink: FailureSink) {
        (**self).add_failure_sink(sink);
    }

    fn points(&self) -> Vec<PointInfo> {
        (**self).points()
    }

    fn listeners(&self, point: &str) -> Option<Vec<ListenerInfo>> {
        (**self).listeners(point)
    }

    fn capability(&self, contract: TypeId) -> Option<Provided<'_>> {
        (**self).capability(contract)
    }
}

/// Copies an erased value of type `V`: the [`CloneFn`] of a point whose
/// value is `V`. Panics when the value is another type (a defect of the
/// implementation).
pub fn clone_value<V: Clone + Send + 'static>(value: &(dyn Any + Send)) -> AnyValue {
    match value.downcast_ref::<V>() {
        Some(v) => Box::new(v.clone()),
        None => panic!(
            "a bus implementation passed a value that is not a `{}`",
            type_name::<V>()
        ),
    }
}

/// A fresh erased value of type `V`: the [`FreshFn`] of a point whose
/// value is `V`.
pub fn fresh_value<V: Default + Send + 'static>() -> AnyValue {
    Box::new(V::default())
}

/// Takes the typed value back from what an implementation returned.
fn typed<P: Point>(value: AnyValue) -> P::Value {
    match value.downcast::<P::Value>() {
        Ok(v) => *v,
        Err(_) => panic!(
            "the bus returned a value of another type than `{}`'s ({})",
            P::ID,
            type_name::<P::Value>()
        ),
    }
}

impl<'a> dyn Bus + 'a {
    /// Declares the point `P`: its description and deadline. Listeners
    /// may register before or after; declaring twice is refused.
    pub fn declare<P: Point>(&self, spec: PointSpec) -> Result<(), Refused> {
        self.declare_point(PointKey::of::<P>(), spec)
    }

    /// Registers a listener on `P` under `id`. It reads the emit's input
    /// and edits the value; its edit counts only when it returns `Ok`
    /// within its deadline without panicking.
    ///
    /// Refused, with nothing changed, when the id is taken on the point
    /// or when its `after`/`before` close a cycle. A constraint naming a
    /// listener not (yet) registered is accepted, reported by each emit
    /// and by introspection, and ignored.
    pub fn listen<P: Point>(
        &self,
        id: impl Into<String>,
        opts: ListenOpts,
        run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + Send + Sync + 'static,
    ) -> Result<(), Refused> {
        self.listen_any(PointKey::of::<P>(), id.into(), opts, erase::<P>(run))
    }

    /// Registers a local listener on `P` under `id`, bound to the calling
    /// thread: it may hold state that is not `Send` (`Rc<RefCell<…>>`).
    /// It takes its place in the point's order with the other listeners;
    /// an emit from another thread queues it for this thread's next
    /// [`Bus::run_pending`]. See [`Bus`] for the guarantees.
    pub fn listen_local<P: Point>(
        &self,
        id: impl Into<String>,
        opts: ListenOpts,
        run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + 'static,
    ) -> Result<(), Refused> {
        self.listen_local_any(PointKey::of::<P>(), id.into(), opts, erase_local::<P>(run))
    }

    /// Adds a waker called, with the thread's id, when an emit queues
    /// local listeners for that thread. A waker that panics is ignored.
    pub fn on_pending(&self, wake: impl Fn(std::thread::ThreadId) + Send + Sync + 'static) {
        self.add_pending_waker(Arc::new(wake));
    }

    /// Passes `value` through `P`'s listeners in order: each edits the
    /// value the previous ones left. A listener that fails leaves it as
    /// it found it.
    pub fn alter<P: Point>(&self, input: P::Input, value: P::Value) -> Altered<P::Value>
    where
        P::Value: Clone,
    {
        let out = self.alter_any(
            PointKey::of::<P>(),
            Arc::new(input),
            Box::new(value),
            clone_value::<P::Value>,
        );
        Altered {
            value: typed::<P>(out.value),
            failures: out.failures,
            deferred: out.deferred,
            refused: out.refused,
        }
    }

    /// Gives each of `P`'s listeners, in order, a fresh default value to
    /// fill, and gathers the values of those that succeed.
    pub fn collect<P: Point>(&self, input: P::Input) -> Collected<P::Value>
    where
        P::Value: Default,
    {
        let out = self.collect_any(
            PointKey::of::<P>(),
            Arc::new(input),
            fresh_value::<P::Value>,
        );
        Collected {
            parts: out
                .parts
                .into_iter()
                .map(|(id, v)| (id, typed::<P>(v)))
                .collect(),
            failures: out.failures,
            deferred: out.deferred,
            refused: out.refused,
        }
    }

    /// Adds a sink called with each failure that dropped a contribution
    /// ([`Failure::dropped`]), as it happens: where the host publishes
    /// its [`FAILED_FACT`] fact or logs. A sink that panics is ignored.
    pub fn on_failure(&self, sink: impl Fn(&Failure) + Send + Sync + 'static) {
        self.add_failure_sink(Arc::new(sink));
    }
}

/// Erases a typed listener of `P`.
pub fn erase<P: Point>(
    run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + Send + Sync + 'static,
) -> AnyListener {
    Arc::new(move |input, value| {
        let Some(input) = input.downcast_ref::<P::Input>() else {
            return Err(HookError::Failed(format!(
                "`{}`: the input is not a `{}`",
                P::ID,
                type_name::<P::Input>()
            )));
        };
        let Some(value) = value.downcast_mut::<P::Value>() else {
            return Err(HookError::Failed(format!(
                "`{}`: the value is not a `{}`",
                P::ID,
                type_name::<P::Value>()
            )));
        };
        run(input, value)
    })
}

/// Erases a typed local listener of `P`.
pub fn erase_local<P: Point>(
    run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + 'static,
) -> AnyLocalListener {
    Rc::new(move |input, value| {
        let Some(input) = input.downcast_ref::<P::Input>() else {
            return Err(HookError::Failed(format!(
                "`{}`: the input is not a `{}`",
                P::ID,
                type_name::<P::Input>()
            )));
        };
        let Some(value) = value.downcast_mut::<P::Value>() else {
            return Err(HookError::Failed(format!(
                "`{}`: the value is not a `{}`",
                P::ID,
                type_name::<P::Value>()
            )));
        };
        run(input, value)
    })
}

/// One line of a library's contract table: a point it declares, built
/// from the point's type in a `const` (`PointDecl::of::<DocClose>(…)`),
/// so the application can read what a library will host before building
/// anything. [`declare_all`] declares a table on a bus.
///
/// What a point needs from a capability contract is data of that
/// contract, made by its crate in a `const`: a [`Contract`] in
/// [`PointDecl::needs`], a [`Facet`] in [`PointDecl::facets`]:
///
/// ```ignore
/// const CODEC: Codec = Codec::of::<DocChanged>();
/// const TABLE: &[PointDecl] = &[
///     PointDecl::of::<DocAsk>("asked after the frame").needs(&[&bus_contract_defer::CONTRACT]),
///     PointDecl::of::<DocChanged>("a document changed")
///         .facets(&[bus_contract_journal::JOURNALED, bus_contract_crossing::relayable(&CODEC)]),
/// ];
/// ```
#[derive(Clone, Copy, Debug)]
pub struct PointDecl {
    /// The point's id.
    pub id: PointId,
    /// What it is for.
    pub kind: PointKind,
    /// What it does, for people and agents reading introspection.
    pub description: &'static str,
    /// The deadline of its listeners that set none; `None` takes the
    /// bus's.
    pub deadline: Option<Duration>,
    /// Whether a listener failure refuses the request
    /// ([`PointSpec::fail_closed`]).
    pub fail_closed: bool,
    /// The contracts the point needs from the bus, besides those of its
    /// facets: [`declare_all`] refuses it on a bus without them.
    pub needs: &'static [&'static Contract],
    /// What its declaration says for capability contracts
    /// ([`PointSpec::facets`]); each needs its contract.
    pub facets: &'static [Facet],
    /// The time one pass of its listeners should take
    /// ([`PointSpec::budget`]).
    pub budget: Option<Duration>,
    /// Its version, from 1 ([`PointSpec::version`]).
    pub version: u32,
    key: fn() -> PointKey,
}

impl PointDecl {
    /// The declaration of the point `P`, described by `description`.
    pub const fn of<P: Point>(description: &'static str) -> PointDecl {
        PointDecl {
            id: P::ID,
            kind: P::KIND,
            description,
            deadline: None,
            fail_closed: false,
            needs: &[],
            facets: &[],
            budget: None,
            version: 1,
            key: PointKey::of::<P>,
        }
    }

    /// The deadline of its listeners that set none.
    pub const fn deadline(mut self, deadline: Duration) -> PointDecl {
        self.deadline = Some(deadline);
        self
    }

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

    /// The contracts the point needs from the bus
    /// (`.needs(&[&bus_contract_defer::CONTRACT])`).
    pub const fn needs(mut self, needs: &'static [&'static Contract]) -> PointDecl {
        self.needs = needs;
        self
    }

    /// What its declaration says for capability contracts
    /// (`.facets(&[bus_contract_journal::JOURNALED])`); each facet's
    /// contract is needed.
    pub const fn facets(mut self, facets: &'static [Facet]) -> PointDecl {
        self.facets = facets;
        self
    }

    /// The time one pass of its listeners should take
    /// ([`PointSpec::budget`]); reported when over, never failed. It
    /// needs no capability: on a bus without the timings contract it is
    /// only shown.
    pub const fn budget(mut self, budget: Duration) -> PointDecl {
        self.budget = Some(budget);
        self
    }

    /// Its version, from 1 ([`PointSpec::version`]): raise it when the
    /// payload changes in a way an older reader cannot use. Two
    /// processes cross the point only at the same version.
    pub const fn version(mut self, version: u32) -> PointDecl {
        self.version = version;
        self
    }

    /// The contracts the point needs: those it names
    /// ([`PointDecl::needs`]), then those of its facets, each once.
    pub fn required(&self) -> Vec<&'static Contract> {
        let mut all: Vec<&'static Contract> = Vec::new();
        for c in self
            .needs
            .iter()
            .copied()
            .chain(self.facets.iter().map(|f| f.contract))
        {
            if !all.contains(&c) {
                all.push(c);
            }
        }
        all
    }

    /// The point's key.
    pub fn key(&self) -> PointKey {
        (self.key)()
    }

    /// The point's spec, as [`Bus::declare_point`] takes it.
    pub fn spec(&self) -> PointSpec {
        let mut spec = PointSpec::new(self.description);
        spec.deadline = self.deadline;
        spec.fail_closed = self.fail_closed;
        spec.budget = self.budget;
        spec.facets = self.facets.to_vec();
        spec.version = self.version;
        spec
    }
}