Skip to main content

bus_contract/
lib.rs

1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3#![warn(missing_docs)]
4
5mod journal;
6mod tools;
7mod types;
8
9/// What an implementation guarantees and what it does not, contract by
10/// contract, each property with a stable id and the conformance check
11/// that proves it. Documentation only: this module has no items.
12#[doc = include_str!("../GUARANTEES.md")]
13pub mod guarantees {}
14
15use std::any::{Any, TypeId, type_name};
16use std::rc::Rc;
17use std::sync::Arc;
18use std::time::Duration;
19
20pub use journal::{
21    Answer, Authority, Codec, Crossing, Cursor, DecodeFn, DecodeValueFn, EncodeFn, EncodeValueFn,
22    IngestError, Journal, JournalEntry, Lost, Origin, Relay, Relayed, RelayedAnswer, RelayedAsk,
23    RelayedEntry, RelayedRequest, Resumed, Since, ask_run, far_listener, kind_matches,
24};
25pub use tools::{declare_all, missing_targets, order_dump};
26pub use types::*;
27
28/// A point as the erased methods of [`Bus`] name it: its id, its kind and
29/// its type, so an implementation refuses one id registered with two
30/// types.
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32pub struct PointKey {
33    /// The point's id ([`Point::ID`]).
34    pub id: &'static str,
35    /// What it is for ([`Point::KIND`]).
36    pub kind: PointKind,
37    /// The point type's id.
38    pub type_id: TypeId,
39    /// The point type's name, for messages.
40    pub type_name: &'static str,
41}
42
43impl PointKey {
44    /// The key of the point `P`.
45    pub fn of<P: Point>() -> PointKey {
46        PointKey {
47            id: P::ID,
48            kind: P::KIND,
49            type_id: TypeId::of::<P>(),
50            type_name: type_name::<P>(),
51        }
52    }
53}
54
55/// An emit's input, its type erased: a point's [`Point::Input`].
56pub type AnyInput = Arc<dyn Any + Send + Sync>;
57
58/// A value going through an emit, its type erased: a point's
59/// [`Point::Value`].
60pub type AnyValue = Box<dyn Any + Send>;
61
62/// A listener, its types erased: it reads the input and edits the value
63/// in place.
64pub type AnyListener = Arc<
65    dyn Fn(&(dyn Any + Send + Sync), &mut (dyn Any + Send)) -> Result<(), HookError> + Send + Sync,
66>;
67
68/// A local listener, its types erased: like [`AnyListener`], but neither
69/// `Send` nor `Sync`. It is bound to the thread that registered it
70/// ([`Bus::listen_local_any`]).
71pub type AnyLocalListener =
72    Rc<dyn Fn(&(dyn Any + Send + Sync), &mut (dyn Any + Send)) -> Result<(), HookError>>;
73
74/// Called when local work is queued for a thread
75/// ([`Bus::add_pending_waker`]), with that thread's id, on the emitting
76/// thread.
77pub type PendingWaker = Arc<dyn Fn(std::thread::ThreadId) + Send + Sync>;
78
79/// Copies an erased value of a point's type (an alter keeps the value as
80/// it was when a listener fails).
81pub type CloneFn = fn(&(dyn Any + Send)) -> AnyValue;
82
83/// Makes a fresh erased value of a point's type (each listener's part in
84/// a collect).
85pub type FreshFn = fn() -> AnyValue;
86
87/// Receives each failure that dropped a contribution
88/// ([`Failure::dropped`]).
89pub type FailureSink = Arc<dyn Fn(&Failure) + Send + Sync>;
90
91/// Receives each pass over a point's budget ([`OverBudget`]).
92pub type BudgetSink = Arc<dyn Fn(&OverBudget) + Send + Sync>;
93
94/// The bus contract: hook points, their listeners in a declared order,
95/// emits and introspection. An application supplies one implementation
96/// (its own, or one written for it, such as `bus-kernel`'s `Kernel`)
97/// and hands it to each
98/// library at construction; a library never constructs the bus it
99/// publishes on.
100///
101/// The methods are object safe and their values erased, so a library
102/// holds an `Arc<dyn Bus>`; the typed calls (`declare::<P>`,
103/// `listen::<P>`, `alter::<P>`, `collect::<P>`, `on_failure`) are methods
104/// of `dyn Bus`, written once here over these.
105///
106/// What an implementation promises:
107///
108/// - Listeners run ordered by `after` / `before` first (the target
109///   [`LAST`] places one after every other of its point, one per point),
110///   then by priority (higher first), then by registration. A cycle is
111///   refused at registration ([`Refused::Cycle`]); a target not there is
112///   reported ([`FailureKind::MissingTarget`]) and ignored.
113/// - A listener's edit counts only when it returns `Ok` within its
114///   deadline without panicking; otherwise it is dropped, the others
115///   still run, and the failure is returned and sent to the sinks.
116/// - The value an emit returns is of the point's type: the typed calls
117///   panic otherwise, as a defect of the implementation.
118/// - Listeners run with no lock held, so a listener may emit or listen.
119///
120/// Every property, with its stable id, what it does not guarantee and
121/// the check that proves it: [`guarantees`].
122///
123/// Refusals, on a point declared [`PointKind::Request`]:
124///
125/// - A listener that returns [`HookError::Refuse`] stops the request: its
126///   own edit is dropped, no later listener runs (on this thread or
127///   another: nothing is queued), and the result names the refusal
128///   ([`Altered::refused`], [`Collected::refused`]). It is not a failure
129///   and does not reach the failure sinks.
130/// - On a point declared fail-closed ([`PointSpec::fail_closed`]), a
131///   listener that fails (error, panic, missed deadline) stops the
132///   request the same way: the failure is reported as usual and the
133///   result names a refusal with [`Refusal::failed`] set. A threaded
134///   listener that misses its deadline stops it at once.
135/// - On the other kinds, [`HookError::Refuse`] counts as a failure
136///   ([`FailureKind::Error`] with the reason) and `fail_closed` is
137///   ignored.
138///
139/// Capabilities: an implementation may offer more than this core, each
140/// as a trait of its own found at run time through a provided method
141/// that returns `None` by default ([`Bus::defer`], [`Bus::timings`],
142/// [`Bus::journal`], [`Bus::relay`]). A library that needs
143/// one names it in its contract table ([`PointDecl::needs`]);
144/// [`declare_all`] then refuses the point on a bus without it
145/// ([`Refused::Unsupported`]). A library that can do without checks the
146/// method and falls back.
147///
148/// Local listeners ([`Bus::listen_local_any`]) are for state that is not
149/// `Send` (`Rc`, `RefCell`), such as an interface's. Each is bound to the
150/// thread that registered it:
151///
152/// - It takes its place in the same order as the other listeners of its
153///   point (`after` / `before` / [`LAST`], priority, registration), keeps
154///   its owner and deadline, and shows in introspection
155///   ([`ListenerInfo::local`]).
156/// - An emit on its thread runs it in that order, inline, with the
157///   others.
158/// - An emit on another thread runs every other listener in order and
159///   queues the local ones for their thread; the result names them
160///   ([`Altered::deferred`], [`Collected::deferred`]) and the wakers
161///   ([`Bus::add_pending_waker`]) are called. The thread runs them when
162///   it calls [`Bus::run_pending`], in their order, emits in the order
163///   they were queued. A deferred alter's listeners edit a copy of the
164///   value the emit returned; a deferred collect's listeners each fill a
165///   fresh value. What they do is reported by [`Bus::run_pending`], not
166///   to the emitter.
167/// - A listener removed ([`Bus::unlisten`], [`Bus::forget`]), from any
168///   thread, does not run again, queued or not.
169pub trait Bus: Send + Sync {
170    /// Declares a point: its description and deadline. Listeners may
171    /// register before or after; declaring twice is refused.
172    fn declare_point(&self, point: PointKey, spec: PointSpec) -> Result<(), Refused>;
173
174    /// Registers a listener on a point under `id`. Refused, with nothing
175    /// changed, when the id is taken on the point, when its constraints
176    /// close a cycle, or when the point is registered with another type.
177    fn listen_any(
178        &self,
179        point: PointKey,
180        id: String,
181        opts: ListenOpts,
182        run: AnyListener,
183    ) -> Result<(), Refused>;
184
185    /// Registers a local listener on a point under `id`, bound to the
186    /// calling thread: it runs only on that thread. Refused as
187    /// [`Bus::listen_any`] is, and when `opts` asks for a thread of its
188    /// own ([`Refused::Threaded`]).
189    fn listen_local_any(
190        &self,
191        point: PointKey,
192        id: String,
193        opts: ListenOpts,
194        run: AnyLocalListener,
195    ) -> Result<(), Refused>;
196
197    /// Runs the local listeners queued for the calling thread by emits
198    /// on other threads, emit by emit in the order they were queued;
199    /// what each emit's deferred part did. Empty when nothing waits.
200    fn run_pending(&self) -> Vec<PendingRun>;
201
202    /// Adds a waker called when an emit queues local listeners for a
203    /// thread, with that thread's id: where the host asks that thread to
204    /// call [`Bus::run_pending`] (a repaint request, a message to its
205    /// loop). A waker that panics is ignored.
206    fn add_pending_waker(&self, wake: PendingWaker);
207
208    /// Removes the listener `id` of the point `point`; whether it was
209    /// there.
210    fn unlisten(&self, point: &str, id: &str) -> bool;
211
212    /// Removes every listener of `owner`, on every point; how many.
213    fn forget(&self, owner: &str) -> usize;
214
215    /// Passes `value` through the point's listeners in order, each
216    /// editing what the previous ones left; `clone` copies it so a
217    /// failing listener leaves it as it found it.
218    fn alter_any(
219        &self,
220        point: PointKey,
221        input: AnyInput,
222        value: AnyValue,
223        clone: CloneFn,
224    ) -> Altered<AnyValue>;
225
226    /// Gives each of the point's listeners, in order, a value from
227    /// `fresh` to fill, and gathers those that succeed.
228    fn collect_any(&self, point: PointKey, input: AnyInput, fresh: FreshFn) -> Collected<AnyValue>;
229
230    /// Adds a sink called with each failure that dropped a contribution,
231    /// as it happens.
232    fn add_failure_sink(&self, sink: FailureSink);
233
234    /// Every point, in id order, with its listeners in the order they
235    /// run.
236    fn points(&self) -> Vec<PointInfo>;
237
238    /// The listeners of the point `point`, in the order they run; `None`
239    /// for a point nobody declared or listened to.
240    fn listeners(&self, point: &str) -> Option<Vec<ListenerInfo>>;
241
242    /// The [`Defer`] capability: requests asked now, heard at the next
243    /// drain on the same thread. `None` (the default) when the
244    /// implementation does not offer it.
245    fn defer(&self) -> Option<&dyn Defer> {
246        None
247    }
248
249    /// The [`Timings`] capability: how long listeners take, per point and
250    /// listener, and passes over a point's budget reported. `None` (the
251    /// default) when the implementation does not offer it.
252    fn timings(&self) -> Option<&dyn Timings> {
253        None
254    }
255
256    /// The [`Journal`] capability: events of journaled points kept with a
257    /// number, read again from one, delivered after the publisher has
258    /// moved on. `None` (the default) when the implementation does not
259    /// offer it.
260    fn journal(&self) -> Option<&dyn Journal> {
261        None
262    }
263
264    /// The [`Relay`] capability: events of relayable points served to
265    /// another process from a cursor and taken in from one, asks of
266    /// relayable requests answered for one. `None` (the default) when
267    /// the implementation does not offer it; a bus that offers it offers
268    /// [`Bus::journal`].
269    fn relay(&self) -> Option<&dyn Relay> {
270        None
271    }
272}
273
274/// Whether `bus` offers `capability`.
275pub fn offers(bus: &dyn Bus, capability: Capability) -> bool {
276    match capability {
277        Capability::Defer => bus.defer().is_some(),
278        Capability::Timings => bus.timings().is_some(),
279        Capability::Journal => bus.journal().is_some(),
280        Capability::Relay => bus.relay().is_some() && bus.journal().is_some(),
281    }
282}
283
284/// A capability of a bus ([`Bus::timings`]): how long listeners take,
285/// per point and per listener, and the passes over a point's budget
286/// ([`PointSpec::budget`]) reported as they happen.
287///
288/// A pass is what the listeners of one emit ran on one thread: the
289/// inline part of an alter or collect emit, one emit's local listeners
290/// run by [`Bus::run_pending`], or one ask run by [`Defer::drain`]. Its
291/// time is its listeners' times added up.
292///
293/// What an implementation promises:
294///
295/// - Every listener run it makes is timed, whatever its outcome (a
296///   threaded listener that misses its deadline counts the time the
297///   emit waited), and counted in the listener's and the pass's
298///   [`TimingStats`] until [`Timings::reset`].
299/// - A pass of a point with a budget that takes longer is reported to
300///   the budget sinks, on the thread that ran it, after the pass, with
301///   each listener's time ([`OverBudget`]). The pass's results are kept:
302///   a budget is not a deadline, and a pass over it is not a failure.
303/// - Quantiles may be approximate; counts, totals and maxima are exact.
304/// - Timing costs little next to a listener: clock reads and counters,
305///   no allocation per run.
306pub trait Timings: Send + Sync {
307    /// Every point that ran a pass since the last reset, in id order.
308    fn points(&self) -> Vec<PointTimings>;
309
310    /// The timings of the point `point`; `None` when it ran no pass
311    /// since the last reset.
312    fn point(&self, point: &str) -> Option<PointTimings>;
313
314    /// Starts a new window: every count back to zero (after a start-up
315    /// phase, before a measured run).
316    fn reset(&self);
317
318    /// Adds a sink called with each pass over its point's budget, on the
319    /// thread that ran it: where the host publishes its
320    /// [`OVER_BUDGET_FACT`] fact or logs. A sink that panics is ignored.
321    fn add_budget_sink(&self, sink: BudgetSink);
322}
323
324impl<'a> dyn Timings + 'a {
325    /// Adds a sink called with each pass over its point's budget
326    /// ([`Timings::add_budget_sink`]).
327    pub fn on_over_budget(&self, sink: impl Fn(&OverBudget) + Send + Sync + 'static) {
328        self.add_budget_sink(Arc::new(sink));
329    }
330}
331
332/// A capability of a bus ([`Bus::defer`]): a request asked now, whose
333/// listeners run at the bus's next drain on the same thread.
334///
335/// It is for code that cannot be re-entered while it runs, such as an
336/// interface drawing a panel with its state borrowed: the panel asks,
337/// and the listeners run after the drawing, when the host calls
338/// [`Defer::drain`].
339///
340/// What an implementation promises:
341///
342/// - An ask is queued for the calling thread and returns at once with
343///   its number, increasing in ask order across the bus. The wakers
344///   ([`Bus::add_pending_waker`]) are called with the thread's id.
345/// - [`Defer::drain`] runs the asks queued for the calling thread, in
346///   ask order, each as an alter emit of its point with the listeners
347///   registered when it runs (one removed since the ask does not run;
348///   one added since does). Every rule of [`Bus`] holds, refusals and
349///   fail-closed points included; a local listener of another thread is
350///   queued for that thread's [`Bus::run_pending`] as usual.
351/// - Each ask's outcome is reported by the drain ([`PendingRun`], with
352///   [`PendingRun::ask`] set): the listeners that ran, their failures,
353///   a refusal. The asker gets nothing back; a listener placed last
354///   ([`ListenOpts::last`]) reads the final value.
355/// - An ask made during a drain (by a listener) waits for the next one.
356/// - An immediate emit made after an ask, before the drain, runs before
357///   it.
358pub trait Defer: Send + Sync {
359    /// Queues an alter emit of `point` with `input` and `value` for the
360    /// calling thread's next [`Defer::drain`]; the ask's number.
361    fn ask_any(&self, point: PointKey, input: AnyInput, value: AnyValue, clone: CloneFn) -> u64;
362
363    /// Runs the asks queued for the calling thread, in ask order; what
364    /// each did. Empty when nothing waits.
365    fn drain(&self) -> Vec<PendingRun>;
366
367    /// How many asks wait for the calling thread's drain (zero before a
368    /// clean exit).
369    fn waiting(&self) -> usize;
370}
371
372impl<'a> dyn Defer + 'a {
373    /// Asks the request `P` now: its listeners run at the calling
374    /// thread's next [`Defer::drain`]. The ask's number.
375    pub fn ask<P: Point>(&self, input: P::Input, value: P::Value) -> u64
376    where
377        P::Value: Clone,
378    {
379        self.ask_any(
380            PointKey::of::<P>(),
381            Arc::new(input),
382            Box::new(value),
383            clone_value::<P::Value>,
384        )
385    }
386}
387
388/// A shared bus is a bus: `&Arc<dyn Bus>` goes where `&dyn Bus` is
389/// asked, and an application may hand out `Arc<MyBus>` as it is.
390impl<B: Bus + ?Sized> Bus for Arc<B> {
391    fn declare_point(&self, point: PointKey, spec: PointSpec) -> Result<(), Refused> {
392        (**self).declare_point(point, spec)
393    }
394
395    fn listen_any(
396        &self,
397        point: PointKey,
398        id: String,
399        opts: ListenOpts,
400        run: AnyListener,
401    ) -> Result<(), Refused> {
402        (**self).listen_any(point, id, opts, run)
403    }
404
405    fn listen_local_any(
406        &self,
407        point: PointKey,
408        id: String,
409        opts: ListenOpts,
410        run: AnyLocalListener,
411    ) -> Result<(), Refused> {
412        (**self).listen_local_any(point, id, opts, run)
413    }
414
415    fn run_pending(&self) -> Vec<PendingRun> {
416        (**self).run_pending()
417    }
418
419    fn add_pending_waker(&self, wake: PendingWaker) {
420        (**self).add_pending_waker(wake);
421    }
422
423    fn unlisten(&self, point: &str, id: &str) -> bool {
424        (**self).unlisten(point, id)
425    }
426
427    fn forget(&self, owner: &str) -> usize {
428        (**self).forget(owner)
429    }
430
431    fn alter_any(
432        &self,
433        point: PointKey,
434        input: AnyInput,
435        value: AnyValue,
436        clone: CloneFn,
437    ) -> Altered<AnyValue> {
438        (**self).alter_any(point, input, value, clone)
439    }
440
441    fn collect_any(&self, point: PointKey, input: AnyInput, fresh: FreshFn) -> Collected<AnyValue> {
442        (**self).collect_any(point, input, fresh)
443    }
444
445    fn add_failure_sink(&self, sink: FailureSink) {
446        (**self).add_failure_sink(sink);
447    }
448
449    fn points(&self) -> Vec<PointInfo> {
450        (**self).points()
451    }
452
453    fn listeners(&self, point: &str) -> Option<Vec<ListenerInfo>> {
454        (**self).listeners(point)
455    }
456
457    fn defer(&self) -> Option<&dyn Defer> {
458        (**self).defer()
459    }
460
461    fn timings(&self) -> Option<&dyn Timings> {
462        (**self).timings()
463    }
464
465    fn journal(&self) -> Option<&dyn Journal> {
466        (**self).journal()
467    }
468
469    fn relay(&self) -> Option<&dyn Relay> {
470        (**self).relay()
471    }
472}
473
474/// Copies an erased value of type `V`.
475fn clone_value<V: Clone + Send + 'static>(value: &(dyn Any + Send)) -> AnyValue {
476    match value.downcast_ref::<V>() {
477        Some(v) => Box::new(v.clone()),
478        None => panic!(
479            "a bus implementation passed a value that is not a `{}`",
480            type_name::<V>()
481        ),
482    }
483}
484
485/// A fresh erased value of type `V`.
486fn fresh_value<V: Default + Send + 'static>() -> AnyValue {
487    Box::new(V::default())
488}
489
490/// Takes the typed value back from what an implementation returned.
491fn typed<P: Point>(value: AnyValue) -> P::Value {
492    match value.downcast::<P::Value>() {
493        Ok(v) => *v,
494        Err(_) => panic!(
495            "the bus returned a value of another type than `{}`'s ({})",
496            P::ID,
497            type_name::<P::Value>()
498        ),
499    }
500}
501
502impl<'a> dyn Bus + 'a {
503    /// Declares the point `P`: its description and deadline. Listeners
504    /// may register before or after; declaring twice is refused.
505    pub fn declare<P: Point>(&self, spec: PointSpec) -> Result<(), Refused> {
506        self.declare_point(PointKey::of::<P>(), spec)
507    }
508
509    /// Registers a listener on `P` under `id`. It reads the emit's input
510    /// and edits the value; its edit counts only when it returns `Ok`
511    /// within its deadline without panicking.
512    ///
513    /// Refused, with nothing changed, when the id is taken on the point
514    /// or when its `after`/`before` close a cycle. A constraint naming a
515    /// listener not (yet) registered is accepted, reported by each emit
516    /// and by introspection, and ignored.
517    pub fn listen<P: Point>(
518        &self,
519        id: impl Into<String>,
520        opts: ListenOpts,
521        run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + Send + Sync + 'static,
522    ) -> Result<(), Refused> {
523        self.listen_any(PointKey::of::<P>(), id.into(), opts, erase::<P>(run))
524    }
525
526    /// Registers a local listener on `P` under `id`, bound to the calling
527    /// thread: it may hold state that is not `Send` (`Rc<RefCell<…>>`).
528    /// It takes its place in the point's order with the other listeners;
529    /// an emit from another thread queues it for this thread's next
530    /// [`Bus::run_pending`]. See [`Bus`] for the guarantees.
531    pub fn listen_local<P: Point>(
532        &self,
533        id: impl Into<String>,
534        opts: ListenOpts,
535        run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + 'static,
536    ) -> Result<(), Refused> {
537        self.listen_local_any(PointKey::of::<P>(), id.into(), opts, erase_local::<P>(run))
538    }
539
540    /// Adds a waker called, with the thread's id, when an emit queues
541    /// local listeners for that thread. A waker that panics is ignored.
542    pub fn on_pending(&self, wake: impl Fn(std::thread::ThreadId) + Send + Sync + 'static) {
543        self.add_pending_waker(Arc::new(wake));
544    }
545
546    /// Passes `value` through `P`'s listeners in order: each edits the
547    /// value the previous ones left. A listener that fails leaves it as
548    /// it found it.
549    pub fn alter<P: Point>(&self, input: P::Input, value: P::Value) -> Altered<P::Value>
550    where
551        P::Value: Clone,
552    {
553        let out = self.alter_any(
554            PointKey::of::<P>(),
555            Arc::new(input),
556            Box::new(value),
557            clone_value::<P::Value>,
558        );
559        Altered {
560            value: typed::<P>(out.value),
561            failures: out.failures,
562            deferred: out.deferred,
563            refused: out.refused,
564        }
565    }
566
567    /// Gives each of `P`'s listeners, in order, a fresh default value to
568    /// fill, and gathers the values of those that succeed.
569    pub fn collect<P: Point>(&self, input: P::Input) -> Collected<P::Value>
570    where
571        P::Value: Default,
572    {
573        let out = self.collect_any(
574            PointKey::of::<P>(),
575            Arc::new(input),
576            fresh_value::<P::Value>,
577        );
578        Collected {
579            parts: out
580                .parts
581                .into_iter()
582                .map(|(id, v)| (id, typed::<P>(v)))
583                .collect(),
584            failures: out.failures,
585            deferred: out.deferred,
586            refused: out.refused,
587        }
588    }
589
590    /// Adds a sink called with each failure that dropped a contribution
591    /// ([`Failure::dropped`]), as it happens: where the host publishes
592    /// its [`FAILED_FACT`] fact or logs. A sink that panics is ignored.
593    pub fn on_failure(&self, sink: impl Fn(&Failure) + Send + Sync + 'static) {
594        self.add_failure_sink(Arc::new(sink));
595    }
596}
597
598/// Erases a typed listener of `P`.
599pub fn erase<P: Point>(
600    run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + Send + Sync + 'static,
601) -> AnyListener {
602    Arc::new(move |input, value| {
603        let Some(input) = input.downcast_ref::<P::Input>() else {
604            return Err(HookError::Failed(format!(
605                "`{}`: the input is not a `{}`",
606                P::ID,
607                type_name::<P::Input>()
608            )));
609        };
610        let Some(value) = value.downcast_mut::<P::Value>() else {
611            return Err(HookError::Failed(format!(
612                "`{}`: the value is not a `{}`",
613                P::ID,
614                type_name::<P::Value>()
615            )));
616        };
617        run(input, value)
618    })
619}
620
621/// Erases a typed local listener of `P`.
622pub fn erase_local<P: Point>(
623    run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + 'static,
624) -> AnyLocalListener {
625    Rc::new(move |input, value| {
626        let Some(input) = input.downcast_ref::<P::Input>() else {
627            return Err(HookError::Failed(format!(
628                "`{}`: the input is not a `{}`",
629                P::ID,
630                type_name::<P::Input>()
631            )));
632        };
633        let Some(value) = value.downcast_mut::<P::Value>() else {
634            return Err(HookError::Failed(format!(
635                "`{}`: the value is not a `{}`",
636                P::ID,
637                type_name::<P::Value>()
638            )));
639        };
640        run(input, value)
641    })
642}
643
644/// One line of a library's contract table: a point it declares, built
645/// from the point's type in a `const` (`PointDecl::of::<DocClose>(…)`),
646/// so the application can read what a library will host before building
647/// anything. [`declare_all`] declares a table on a bus.
648#[derive(Clone, Copy, Debug)]
649pub struct PointDecl {
650    /// The point's id.
651    pub id: &'static str,
652    /// What it is for.
653    pub kind: PointKind,
654    /// What it does, for people and agents reading introspection.
655    pub description: &'static str,
656    /// The deadline of its listeners that set none; `None` takes the
657    /// bus's.
658    pub deadline: Option<Duration>,
659    /// Whether a listener failure refuses the request
660    /// ([`PointSpec::fail_closed`]).
661    pub fail_closed: bool,
662    /// The capabilities the point needs from the bus: [`declare_all`]
663    /// refuses it on a bus without them.
664    pub needs: &'static [Capability],
665    /// The time one pass of its listeners should take
666    /// ([`PointSpec::budget`]).
667    pub budget: Option<Duration>,
668    /// Its events go through the bus's journal ([`PointSpec::journaled`]).
669    pub journaled: bool,
670    /// How it crosses a process, when it is relayable
671    /// ([`PointSpec::relay`]).
672    pub relay: Option<Codec>,
673    /// Its version, from 1 ([`PointSpec::version`]).
674    pub version: u32,
675    key: fn() -> PointKey,
676}
677
678impl PointDecl {
679    /// The declaration of the point `P`, described by `description`.
680    pub const fn of<P: Point>(description: &'static str) -> PointDecl {
681        PointDecl {
682            id: P::ID,
683            kind: P::KIND,
684            description,
685            deadline: None,
686            fail_closed: false,
687            needs: &[],
688            budget: None,
689            journaled: false,
690            relay: None,
691            version: 1,
692            key: PointKey::of::<P>,
693        }
694    }
695
696    /// The deadline of its listeners that set none.
697    pub const fn deadline(mut self, deadline: Duration) -> PointDecl {
698        self.deadline = Some(deadline);
699        self
700    }
701
702    /// A listener failure refuses the request
703    /// ([`PointSpec::fail_closed`]).
704    pub const fn fail_closed(mut self) -> PointDecl {
705        self.fail_closed = true;
706        self
707    }
708
709    /// The capabilities the point needs from the bus
710    /// (`.needs(&[Capability::Defer])`).
711    pub const fn needs(mut self, needs: &'static [Capability]) -> PointDecl {
712        self.needs = needs;
713        self
714    }
715
716    /// The time one pass of its listeners should take
717    /// ([`PointSpec::budget`]); reported when over, never failed. It
718    /// needs no capability: on a bus without [`Timings`] it is only
719    /// shown.
720    pub const fn budget(mut self, budget: Duration) -> PointDecl {
721        self.budget = Some(budget);
722        self
723    }
724
725    /// Its events go through the bus's journal: published with a number,
726    /// delivered after the publisher has moved on ([`Journal`]). For an
727    /// event point; [`declare_all`] refuses it on a bus without the
728    /// journal ([`Refused::Unsupported`]) and on another kind
729    /// ([`Refused::NotEvent`]).
730    pub const fn journaled(mut self) -> PointDecl {
731        self.journaled = true;
732        self
733    }
734
735    /// The point crosses processes ([`Relay`]):
736    ///
737    /// - an event point's events, their input written and read by
738    ///   `codec` ([`Codec::of::<P>()`](Codec::of)); journaled too;
739    /// - a request point's asks, from another process, their input and
740    ///   value written and read by `codec`
741    ///   ([`Codec::request::<P>()`](Codec::request)); fail-closed too, so
742    ///   no answer in time is a refusal.
743    ///
744    /// [`declare_all`] refuses it on a bus without the relay
745    /// ([`Refused::Unsupported`]), on an alter or collect point and on a
746    /// request whose codec has no value ([`Refused::NotCrossable`]), and
747    /// with a codec of another point ([`Refused::TypeMismatch`]).
748    pub const fn relayable(mut self, codec: Codec) -> PointDecl {
749        match self.kind {
750            PointKind::Event => self.journaled = true,
751            PointKind::Request => self.fail_closed = true,
752            _ => {}
753        }
754        self.relay = Some(codec);
755        self
756    }
757
758    /// Its version, from 1 ([`PointSpec::version`]): raise it when the
759    /// payload changes in a way an older reader cannot use. Two
760    /// processes cross the point only at the same version.
761    pub const fn version(mut self, version: u32) -> PointDecl {
762        self.version = version;
763        self
764    }
765
766    /// The capabilities the point needs: those it names
767    /// ([`PointDecl::needs`]), then [`Capability::Journal`] when it is
768    /// journaled and [`Capability::Relay`] when it is relayable.
769    pub fn required(&self) -> Vec<Capability> {
770        let mut all = self.needs.to_vec();
771        if self.journaled && !all.contains(&Capability::Journal) {
772            all.push(Capability::Journal);
773        }
774        if self.relay.is_some() && !all.contains(&Capability::Relay) {
775            all.push(Capability::Relay);
776        }
777        all
778    }
779
780    /// The point's key.
781    pub fn key(&self) -> PointKey {
782        (self.key)()
783    }
784
785    /// The point's spec, as [`Bus::declare_point`] takes it.
786    pub fn spec(&self) -> PointSpec {
787        let mut spec = PointSpec::new(self.description);
788        spec.deadline = self.deadline;
789        spec.fail_closed = self.fail_closed;
790        spec.budget = self.budget;
791        spec.journaled = self.journaled;
792        spec.relay = self.relay;
793        spec.version = self.version;
794        spec
795    }
796}