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    /// Looks a capability up by the `TypeId` of its trait object type
243    /// (`TypeId::of::<dyn Journal>()`): the bus as [`Any`] and the cast
244    /// to that trait ([`Provided`]), or `None` (the default) when the
245    /// implementation does not offer it. The typed call is
246    /// [`capability`] (`capability::<dyn Journal, _>(bus)`, or
247    /// `bus.get::<dyn Journal>()` on a `dyn Bus`).
248    ///
249    /// This is how a bus offers a capability whose trait the core does
250    /// not name: an extension contract defines its trait, a bus answers
251    /// for its `TypeId`, and a library reaches it through [`capability`].
252    /// The four getters below ([`Bus::defer`], [`Bus::timings`],
253    /// [`Bus::journal`], [`Bus::relay`]) default to this lookup, so a
254    /// new implementation writes `capability` only.
255    ///
256    /// An implementation that overrides the getters and not this method
257    /// keeps working through the getters, [`offers`] and [`declare_all`],
258    /// but the lookup does not see those capabilities. One that writes
259    /// both answers the same through each: a getter and the lookup give
260    /// `Some` together, and the same object.
261    ///
262    /// ```
263    /// use std::any::{Any, TypeId};
264    /// use bus_contract::{Cast, Provided};
265    /// # trait Journal {}
266    /// # struct MyBus;
267    /// # impl Journal for MyBus {}
268    /// fn as_journal(bus: &dyn Any) -> Option<&(dyn Journal + 'static)> {
269    ///     bus.downcast_ref::<MyBus>().map(|b| b as _)
270    /// }
271    /// static AS_JOURNAL: Cast<dyn Journal> = as_journal;
272    ///
273    /// // in `impl Bus for MyBus`:
274    /// fn capability(bus: &MyBus, contract: TypeId) -> Option<Provided<'_>> {
275    ///     (contract == TypeId::of::<dyn Journal>())
276    ///         .then(|| Provided::new::<dyn Journal>(bus, &AS_JOURNAL))
277    /// }
278    /// # assert!(capability(&MyBus, TypeId::of::<dyn Journal>()).is_some());
279    /// ```
280    fn capability(&self, contract: TypeId) -> Option<Provided<'_>> {
281        let _ = contract;
282        None
283    }
284
285    /// The [`Defer`] capability: requests asked now, heard at the next
286    /// drain on the same thread. `None` when the implementation does not
287    /// offer it. By default, what [`Bus::capability`] answers for
288    /// `dyn Defer`.
289    fn defer(&self) -> Option<&dyn Defer> {
290        capability::<dyn Defer, Self>(self)
291    }
292
293    /// The [`Timings`] capability: how long listeners take, per point and
294    /// listener, and passes over a point's budget reported. `None` when
295    /// the implementation does not offer it. By default, what
296    /// [`Bus::capability`] answers for `dyn Timings`.
297    fn timings(&self) -> Option<&dyn Timings> {
298        capability::<dyn Timings, Self>(self)
299    }
300
301    /// The [`Journal`] capability: events of journaled points kept with a
302    /// number, read again from one, delivered after the publisher has
303    /// moved on. `None` when the implementation does not offer it. By
304    /// default, what [`Bus::capability`] answers for `dyn Journal`.
305    fn journal(&self) -> Option<&dyn Journal> {
306        capability::<dyn Journal, Self>(self)
307    }
308
309    /// The [`Relay`] capability: events of relayable points served to
310    /// another process from a cursor and taken in from one, asks of
311    /// relayable requests answered for one. `None` when the
312    /// implementation does not offer it; a bus that offers it offers
313    /// [`Bus::journal`]. By default, what [`Bus::capability`] answers for
314    /// `dyn Relay`.
315    fn relay(&self) -> Option<&dyn Relay> {
316        capability::<dyn Relay, Self>(self)
317    }
318}
319
320/// The cast a bus gives for the capability `C` ([`Provided::new`]): from
321/// the bus as [`Any`] to `C`. A plain function, usually a `static`, that
322/// downcasts to the implementation's type and coerces.
323pub type Cast<C> = for<'x> fn(&'x dyn Any) -> Option<&'x C>;
324
325/// A capability found on a bus ([`Bus::capability`]): the bus as [`Any`]
326/// and the cast from it to the capability's trait. [`capability`] turns
327/// it into `&C`.
328///
329/// The cast travels as `Any` because `C` is unsized (`dyn Journal`),
330/// which `downcast_ref` cannot target, while a function pointer is
331/// sized: the lookup checks the cast is a [`Cast<C>`] for the `C` asked,
332/// so a bus that answers one `TypeId` with another capability's cast
333/// gives `None`, never a wrong type.
334#[derive(Clone, Copy)]
335pub struct Provided<'a> {
336    this: &'a dyn Any,
337    cast: &'static (dyn Any + Send + Sync),
338}
339
340impl<'a> Provided<'a> {
341    /// The capability `C` of the bus `this`, reached through `cast`.
342    pub fn new<C: ?Sized + 'static>(this: &'a dyn Any, cast: &'static Cast<C>) -> Provided<'a> {
343        Provided { this, cast }
344    }
345}
346
347impl std::fmt::Debug for Provided<'_> {
348    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
349        f.debug_struct("Provided").finish_non_exhaustive()
350    }
351}
352
353/// The capability `C` of `bus`, a trait object type such as
354/// `dyn Journal`: what [`Bus::capability`] answers for
355/// `TypeId::of::<C>()`, cast to `C`. `None` when the bus does not offer
356/// it through the lookup.
357///
358/// ```ignore
359/// let journal = bus_contract::capability::<dyn Journal, _>(&bus);
360/// ```
361pub fn capability<C: ?Sized + 'static, B: Bus + ?Sized>(bus: &B) -> Option<&C> {
362    let provided = bus.capability(TypeId::of::<C>())?;
363    let cast = provided.cast.downcast_ref::<Cast<C>>()?;
364    cast(provided.this)
365}
366
367impl<'a> dyn Bus + 'a {
368    /// The capability `C` of this bus, a trait object type such as
369    /// `dyn Journal` ([`capability`]).
370    pub fn get<C: ?Sized + 'static>(&self) -> Option<&C> {
371        capability::<C, Self>(self)
372    }
373}
374
375/// Whether `bus` offers `capability`.
376pub fn offers(bus: &dyn Bus, capability: Capability) -> bool {
377    match capability {
378        Capability::Defer => bus.defer().is_some(),
379        Capability::Timings => bus.timings().is_some(),
380        Capability::Journal => bus.journal().is_some(),
381        Capability::Relay => bus.relay().is_some() && bus.journal().is_some(),
382    }
383}
384
385/// A capability of a bus ([`Bus::timings`]): how long listeners take,
386/// per point and per listener, and the passes over a point's budget
387/// ([`PointSpec::budget`]) reported as they happen.
388///
389/// A pass is what the listeners of one emit ran on one thread: the
390/// inline part of an alter or collect emit, one emit's local listeners
391/// run by [`Bus::run_pending`], or one ask run by [`Defer::drain`]. Its
392/// time is its listeners' times added up.
393///
394/// What an implementation promises:
395///
396/// - Every listener run it makes is timed, whatever its outcome (a
397///   threaded listener that misses its deadline counts the time the
398///   emit waited), and counted in the listener's and the pass's
399///   [`TimingStats`] until [`Timings::reset`].
400/// - A pass of a point with a budget that takes longer is reported to
401///   the budget sinks, on the thread that ran it, after the pass, with
402///   each listener's time ([`OverBudget`]). The pass's results are kept:
403///   a budget is not a deadline, and a pass over it is not a failure.
404/// - Quantiles may be approximate; counts, totals and maxima are exact.
405/// - Timing costs little next to a listener: clock reads and counters,
406///   no allocation per run.
407pub trait Timings: Send + Sync {
408    /// Every point that ran a pass since the last reset, in id order.
409    fn points(&self) -> Vec<PointTimings>;
410
411    /// The timings of the point `point`; `None` when it ran no pass
412    /// since the last reset.
413    fn point(&self, point: &str) -> Option<PointTimings>;
414
415    /// Starts a new window: every count back to zero (after a start-up
416    /// phase, before a measured run).
417    fn reset(&self);
418
419    /// Adds a sink called with each pass over its point's budget, on the
420    /// thread that ran it: where the host publishes its
421    /// [`OVER_BUDGET_FACT`] fact or logs. A sink that panics is ignored.
422    fn add_budget_sink(&self, sink: BudgetSink);
423}
424
425impl<'a> dyn Timings + 'a {
426    /// Adds a sink called with each pass over its point's budget
427    /// ([`Timings::add_budget_sink`]).
428    pub fn on_over_budget(&self, sink: impl Fn(&OverBudget) + Send + Sync + 'static) {
429        self.add_budget_sink(Arc::new(sink));
430    }
431}
432
433/// A capability of a bus ([`Bus::defer`]): a request asked now, whose
434/// listeners run at the bus's next drain on the same thread.
435///
436/// It is for code that cannot be re-entered while it runs, such as an
437/// interface drawing a panel with its state borrowed: the panel asks,
438/// and the listeners run after the drawing, when the host calls
439/// [`Defer::drain`].
440///
441/// What an implementation promises:
442///
443/// - An ask is queued for the calling thread and returns at once with
444///   its number, increasing in ask order across the bus. The wakers
445///   ([`Bus::add_pending_waker`]) are called with the thread's id.
446/// - [`Defer::drain`] runs the asks queued for the calling thread, in
447///   ask order, each as an alter emit of its point with the listeners
448///   registered when it runs (one removed since the ask does not run;
449///   one added since does). Every rule of [`Bus`] holds, refusals and
450///   fail-closed points included; a local listener of another thread is
451///   queued for that thread's [`Bus::run_pending`] as usual.
452/// - Each ask's outcome is reported by the drain ([`PendingRun`], with
453///   [`PendingRun::ask`] set): the listeners that ran, their failures,
454///   a refusal. The asker gets nothing back; a listener placed last
455///   ([`ListenOpts::last`]) reads the final value.
456/// - An ask made during a drain (by a listener) waits for the next one.
457/// - An immediate emit made after an ask, before the drain, runs before
458///   it.
459pub trait Defer: Send + Sync {
460    /// Queues an alter emit of `point` with `input` and `value` for the
461    /// calling thread's next [`Defer::drain`]; the ask's number.
462    fn ask_any(&self, point: PointKey, input: AnyInput, value: AnyValue, clone: CloneFn) -> u64;
463
464    /// Runs the asks queued for the calling thread, in ask order; what
465    /// each did. Empty when nothing waits.
466    fn drain(&self) -> Vec<PendingRun>;
467
468    /// How many asks wait for the calling thread's drain (zero before a
469    /// clean exit).
470    fn waiting(&self) -> usize;
471}
472
473impl<'a> dyn Defer + 'a {
474    /// Asks the request `P` now: its listeners run at the calling
475    /// thread's next [`Defer::drain`]. The ask's number.
476    pub fn ask<P: Point>(&self, input: P::Input, value: P::Value) -> u64
477    where
478        P::Value: Clone,
479    {
480        self.ask_any(
481            PointKey::of::<P>(),
482            Arc::new(input),
483            Box::new(value),
484            clone_value::<P::Value>,
485        )
486    }
487}
488
489/// A shared bus is a bus: `&Arc<dyn Bus>` goes where `&dyn Bus` is
490/// asked, and an application may hand out `Arc<MyBus>` as it is.
491impl<B: Bus + ?Sized> Bus for Arc<B> {
492    fn declare_point(&self, point: PointKey, spec: PointSpec) -> Result<(), Refused> {
493        (**self).declare_point(point, spec)
494    }
495
496    fn listen_any(
497        &self,
498        point: PointKey,
499        id: String,
500        opts: ListenOpts,
501        run: AnyListener,
502    ) -> Result<(), Refused> {
503        (**self).listen_any(point, id, opts, run)
504    }
505
506    fn listen_local_any(
507        &self,
508        point: PointKey,
509        id: String,
510        opts: ListenOpts,
511        run: AnyLocalListener,
512    ) -> Result<(), Refused> {
513        (**self).listen_local_any(point, id, opts, run)
514    }
515
516    fn run_pending(&self) -> Vec<PendingRun> {
517        (**self).run_pending()
518    }
519
520    fn add_pending_waker(&self, wake: PendingWaker) {
521        (**self).add_pending_waker(wake);
522    }
523
524    fn unlisten(&self, point: &str, id: &str) -> bool {
525        (**self).unlisten(point, id)
526    }
527
528    fn forget(&self, owner: &str) -> usize {
529        (**self).forget(owner)
530    }
531
532    fn alter_any(
533        &self,
534        point: PointKey,
535        input: AnyInput,
536        value: AnyValue,
537        clone: CloneFn,
538    ) -> Altered<AnyValue> {
539        (**self).alter_any(point, input, value, clone)
540    }
541
542    fn collect_any(&self, point: PointKey, input: AnyInput, fresh: FreshFn) -> Collected<AnyValue> {
543        (**self).collect_any(point, input, fresh)
544    }
545
546    fn add_failure_sink(&self, sink: FailureSink) {
547        (**self).add_failure_sink(sink);
548    }
549
550    fn points(&self) -> Vec<PointInfo> {
551        (**self).points()
552    }
553
554    fn listeners(&self, point: &str) -> Option<Vec<ListenerInfo>> {
555        (**self).listeners(point)
556    }
557
558    fn capability(&self, contract: TypeId) -> Option<Provided<'_>> {
559        (**self).capability(contract)
560    }
561
562    fn defer(&self) -> Option<&dyn Defer> {
563        (**self).defer()
564    }
565
566    fn timings(&self) -> Option<&dyn Timings> {
567        (**self).timings()
568    }
569
570    fn journal(&self) -> Option<&dyn Journal> {
571        (**self).journal()
572    }
573
574    fn relay(&self) -> Option<&dyn Relay> {
575        (**self).relay()
576    }
577}
578
579/// Copies an erased value of type `V`.
580fn clone_value<V: Clone + Send + 'static>(value: &(dyn Any + Send)) -> AnyValue {
581    match value.downcast_ref::<V>() {
582        Some(v) => Box::new(v.clone()),
583        None => panic!(
584            "a bus implementation passed a value that is not a `{}`",
585            type_name::<V>()
586        ),
587    }
588}
589
590/// A fresh erased value of type `V`.
591fn fresh_value<V: Default + Send + 'static>() -> AnyValue {
592    Box::new(V::default())
593}
594
595/// Takes the typed value back from what an implementation returned.
596fn typed<P: Point>(value: AnyValue) -> P::Value {
597    match value.downcast::<P::Value>() {
598        Ok(v) => *v,
599        Err(_) => panic!(
600            "the bus returned a value of another type than `{}`'s ({})",
601            P::ID,
602            type_name::<P::Value>()
603        ),
604    }
605}
606
607impl<'a> dyn Bus + 'a {
608    /// Declares the point `P`: its description and deadline. Listeners
609    /// may register before or after; declaring twice is refused.
610    pub fn declare<P: Point>(&self, spec: PointSpec) -> Result<(), Refused> {
611        self.declare_point(PointKey::of::<P>(), spec)
612    }
613
614    /// Registers a listener on `P` under `id`. It reads the emit's input
615    /// and edits the value; its edit counts only when it returns `Ok`
616    /// within its deadline without panicking.
617    ///
618    /// Refused, with nothing changed, when the id is taken on the point
619    /// or when its `after`/`before` close a cycle. A constraint naming a
620    /// listener not (yet) registered is accepted, reported by each emit
621    /// and by introspection, and ignored.
622    pub fn listen<P: Point>(
623        &self,
624        id: impl Into<String>,
625        opts: ListenOpts,
626        run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + Send + Sync + 'static,
627    ) -> Result<(), Refused> {
628        self.listen_any(PointKey::of::<P>(), id.into(), opts, erase::<P>(run))
629    }
630
631    /// Registers a local listener on `P` under `id`, bound to the calling
632    /// thread: it may hold state that is not `Send` (`Rc<RefCell<…>>`).
633    /// It takes its place in the point's order with the other listeners;
634    /// an emit from another thread queues it for this thread's next
635    /// [`Bus::run_pending`]. See [`Bus`] for the guarantees.
636    pub fn listen_local<P: Point>(
637        &self,
638        id: impl Into<String>,
639        opts: ListenOpts,
640        run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + 'static,
641    ) -> Result<(), Refused> {
642        self.listen_local_any(PointKey::of::<P>(), id.into(), opts, erase_local::<P>(run))
643    }
644
645    /// Adds a waker called, with the thread's id, when an emit queues
646    /// local listeners for that thread. A waker that panics is ignored.
647    pub fn on_pending(&self, wake: impl Fn(std::thread::ThreadId) + Send + Sync + 'static) {
648        self.add_pending_waker(Arc::new(wake));
649    }
650
651    /// Passes `value` through `P`'s listeners in order: each edits the
652    /// value the previous ones left. A listener that fails leaves it as
653    /// it found it.
654    pub fn alter<P: Point>(&self, input: P::Input, value: P::Value) -> Altered<P::Value>
655    where
656        P::Value: Clone,
657    {
658        let out = self.alter_any(
659            PointKey::of::<P>(),
660            Arc::new(input),
661            Box::new(value),
662            clone_value::<P::Value>,
663        );
664        Altered {
665            value: typed::<P>(out.value),
666            failures: out.failures,
667            deferred: out.deferred,
668            refused: out.refused,
669        }
670    }
671
672    /// Gives each of `P`'s listeners, in order, a fresh default value to
673    /// fill, and gathers the values of those that succeed.
674    pub fn collect<P: Point>(&self, input: P::Input) -> Collected<P::Value>
675    where
676        P::Value: Default,
677    {
678        let out = self.collect_any(
679            PointKey::of::<P>(),
680            Arc::new(input),
681            fresh_value::<P::Value>,
682        );
683        Collected {
684            parts: out
685                .parts
686                .into_iter()
687                .map(|(id, v)| (id, typed::<P>(v)))
688                .collect(),
689            failures: out.failures,
690            deferred: out.deferred,
691            refused: out.refused,
692        }
693    }
694
695    /// Adds a sink called with each failure that dropped a contribution
696    /// ([`Failure::dropped`]), as it happens: where the host publishes
697    /// its [`FAILED_FACT`] fact or logs. A sink that panics is ignored.
698    pub fn on_failure(&self, sink: impl Fn(&Failure) + Send + Sync + 'static) {
699        self.add_failure_sink(Arc::new(sink));
700    }
701}
702
703/// Erases a typed listener of `P`.
704pub fn erase<P: Point>(
705    run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + Send + Sync + 'static,
706) -> AnyListener {
707    Arc::new(move |input, value| {
708        let Some(input) = input.downcast_ref::<P::Input>() else {
709            return Err(HookError::Failed(format!(
710                "`{}`: the input is not a `{}`",
711                P::ID,
712                type_name::<P::Input>()
713            )));
714        };
715        let Some(value) = value.downcast_mut::<P::Value>() else {
716            return Err(HookError::Failed(format!(
717                "`{}`: the value is not a `{}`",
718                P::ID,
719                type_name::<P::Value>()
720            )));
721        };
722        run(input, value)
723    })
724}
725
726/// Erases a typed local listener of `P`.
727pub fn erase_local<P: Point>(
728    run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + 'static,
729) -> AnyLocalListener {
730    Rc::new(move |input, value| {
731        let Some(input) = input.downcast_ref::<P::Input>() else {
732            return Err(HookError::Failed(format!(
733                "`{}`: the input is not a `{}`",
734                P::ID,
735                type_name::<P::Input>()
736            )));
737        };
738        let Some(value) = value.downcast_mut::<P::Value>() else {
739            return Err(HookError::Failed(format!(
740                "`{}`: the value is not a `{}`",
741                P::ID,
742                type_name::<P::Value>()
743            )));
744        };
745        run(input, value)
746    })
747}
748
749/// One line of a library's contract table: a point it declares, built
750/// from the point's type in a `const` (`PointDecl::of::<DocClose>(…)`),
751/// so the application can read what a library will host before building
752/// anything. [`declare_all`] declares a table on a bus.
753#[derive(Clone, Copy, Debug)]
754pub struct PointDecl {
755    /// The point's id.
756    pub id: &'static str,
757    /// What it is for.
758    pub kind: PointKind,
759    /// What it does, for people and agents reading introspection.
760    pub description: &'static str,
761    /// The deadline of its listeners that set none; `None` takes the
762    /// bus's.
763    pub deadline: Option<Duration>,
764    /// Whether a listener failure refuses the request
765    /// ([`PointSpec::fail_closed`]).
766    pub fail_closed: bool,
767    /// The capabilities the point needs from the bus: [`declare_all`]
768    /// refuses it on a bus without them.
769    pub needs: &'static [Capability],
770    /// The time one pass of its listeners should take
771    /// ([`PointSpec::budget`]).
772    pub budget: Option<Duration>,
773    /// Its events go through the bus's journal ([`PointSpec::journaled`]).
774    pub journaled: bool,
775    /// How it crosses a process, when it is relayable
776    /// ([`PointSpec::relay`]).
777    pub relay: Option<Codec>,
778    /// Its version, from 1 ([`PointSpec::version`]).
779    pub version: u32,
780    key: fn() -> PointKey,
781}
782
783impl PointDecl {
784    /// The declaration of the point `P`, described by `description`.
785    pub const fn of<P: Point>(description: &'static str) -> PointDecl {
786        PointDecl {
787            id: P::ID,
788            kind: P::KIND,
789            description,
790            deadline: None,
791            fail_closed: false,
792            needs: &[],
793            budget: None,
794            journaled: false,
795            relay: None,
796            version: 1,
797            key: PointKey::of::<P>,
798        }
799    }
800
801    /// The deadline of its listeners that set none.
802    pub const fn deadline(mut self, deadline: Duration) -> PointDecl {
803        self.deadline = Some(deadline);
804        self
805    }
806
807    /// A listener failure refuses the request
808    /// ([`PointSpec::fail_closed`]).
809    pub const fn fail_closed(mut self) -> PointDecl {
810        self.fail_closed = true;
811        self
812    }
813
814    /// The capabilities the point needs from the bus
815    /// (`.needs(&[Capability::Defer])`).
816    pub const fn needs(mut self, needs: &'static [Capability]) -> PointDecl {
817        self.needs = needs;
818        self
819    }
820
821    /// The time one pass of its listeners should take
822    /// ([`PointSpec::budget`]); reported when over, never failed. It
823    /// needs no capability: on a bus without [`Timings`] it is only
824    /// shown.
825    pub const fn budget(mut self, budget: Duration) -> PointDecl {
826        self.budget = Some(budget);
827        self
828    }
829
830    /// Its events go through the bus's journal: published with a number,
831    /// delivered after the publisher has moved on ([`Journal`]). For an
832    /// event point; [`declare_all`] refuses it on a bus without the
833    /// journal ([`Refused::Unsupported`]) and on another kind
834    /// ([`Refused::NotEvent`]).
835    pub const fn journaled(mut self) -> PointDecl {
836        self.journaled = true;
837        self
838    }
839
840    /// The point crosses processes ([`Relay`]):
841    ///
842    /// - an event point's events, their input written and read by
843    ///   `codec` ([`Codec::of::<P>()`](Codec::of)); journaled too;
844    /// - a request point's asks, from another process, their input and
845    ///   value written and read by `codec`
846    ///   ([`Codec::request::<P>()`](Codec::request)); fail-closed too, so
847    ///   no answer in time is a refusal.
848    ///
849    /// [`declare_all`] refuses it on a bus without the relay
850    /// ([`Refused::Unsupported`]), on an alter or collect point and on a
851    /// request whose codec has no value ([`Refused::NotCrossable`]), and
852    /// with a codec of another point ([`Refused::TypeMismatch`]).
853    pub const fn relayable(mut self, codec: Codec) -> PointDecl {
854        match self.kind {
855            PointKind::Event => self.journaled = true,
856            PointKind::Request => self.fail_closed = true,
857            _ => {}
858        }
859        self.relay = Some(codec);
860        self
861    }
862
863    /// Its version, from 1 ([`PointSpec::version`]): raise it when the
864    /// payload changes in a way an older reader cannot use. Two
865    /// processes cross the point only at the same version.
866    pub const fn version(mut self, version: u32) -> PointDecl {
867        self.version = version;
868        self
869    }
870
871    /// The capabilities the point needs: those it names
872    /// ([`PointDecl::needs`]), then [`Capability::Journal`] when it is
873    /// journaled and [`Capability::Relay`] when it is relayable.
874    pub fn required(&self) -> Vec<Capability> {
875        let mut all = self.needs.to_vec();
876        if self.journaled && !all.contains(&Capability::Journal) {
877            all.push(Capability::Journal);
878        }
879        if self.relay.is_some() && !all.contains(&Capability::Relay) {
880            all.push(Capability::Relay);
881        }
882        all
883    }
884
885    /// The point's key.
886    pub fn key(&self) -> PointKey {
887        (self.key)()
888    }
889
890    /// The point's spec, as [`Bus::declare_point`] takes it.
891    pub fn spec(&self) -> PointSpec {
892        let mut spec = PointSpec::new(self.description);
893        spec.deadline = self.deadline;
894        spec.fail_closed = self.fail_closed;
895        spec.budget = self.budget;
896        spec.journaled = self.journaled;
897        spec.relay = self.relay;
898        spec.version = self.version;
899        spec
900    }
901}