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