Skip to main content

bus_contract/
lib.rs

1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3#![warn(missing_docs)]
4
5mod tools;
6mod types;
7
8use std::any::{Any, TypeId, type_name};
9use std::rc::Rc;
10use std::sync::Arc;
11use std::time::Duration;
12
13pub use tools::{declare_all, missing_targets, order_dump};
14pub use types::*;
15
16/// A point as the erased methods of [`Bus`] name it: its id, its kind and
17/// its type, so an implementation refuses one id registered with two
18/// types.
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
20pub struct PointKey {
21    /// The point's id ([`Point::ID`]).
22    pub id: &'static str,
23    /// What it is for ([`Point::KIND`]).
24    pub kind: PointKind,
25    /// The point type's id.
26    pub type_id: TypeId,
27    /// The point type's name, for messages.
28    pub type_name: &'static str,
29}
30
31impl PointKey {
32    /// The key of the point `P`.
33    pub fn of<P: Point>() -> PointKey {
34        PointKey {
35            id: P::ID,
36            kind: P::KIND,
37            type_id: TypeId::of::<P>(),
38            type_name: type_name::<P>(),
39        }
40    }
41}
42
43/// An emit's input, its type erased: a point's [`Point::Input`].
44pub type AnyInput = Arc<dyn Any + Send + Sync>;
45
46/// A value going through an emit, its type erased: a point's
47/// [`Point::Value`].
48pub type AnyValue = Box<dyn Any + Send>;
49
50/// A listener, its types erased: it reads the input and edits the value
51/// in place.
52pub type AnyListener = Arc<
53    dyn Fn(&(dyn Any + Send + Sync), &mut (dyn Any + Send)) -> Result<(), HookError> + Send + Sync,
54>;
55
56/// A local listener, its types erased: like [`AnyListener`], but neither
57/// `Send` nor `Sync`. It is bound to the thread that registered it
58/// ([`Bus::listen_local_any`]).
59pub type AnyLocalListener =
60    Rc<dyn Fn(&(dyn Any + Send + Sync), &mut (dyn Any + Send)) -> Result<(), HookError>>;
61
62/// Called when local work is queued for a thread
63/// ([`Bus::add_pending_waker`]), with that thread's id, on the emitting
64/// thread.
65pub type PendingWaker = Arc<dyn Fn(std::thread::ThreadId) + Send + Sync>;
66
67/// Copies an erased value of a point's type (an alter keeps the value as
68/// it was when a listener fails).
69pub type CloneFn = fn(&(dyn Any + Send)) -> AnyValue;
70
71/// Makes a fresh erased value of a point's type (each listener's part in
72/// a collect).
73pub type FreshFn = fn() -> AnyValue;
74
75/// Receives each failure that dropped a contribution
76/// ([`Failure::dropped`]).
77pub type FailureSink = Arc<dyn Fn(&Failure) + Send + Sync>;
78
79/// The bus contract: hook points, their listeners in a declared order,
80/// emits and introspection. An application supplies one implementation
81/// (its own, or one written for it, such as `egui-pop-hooks`'s `Kernel`)
82/// and hands it to each
83/// library at construction; a library never constructs the bus it
84/// publishes on.
85///
86/// The methods are object safe and their values erased, so a library
87/// holds an `Arc<dyn Bus>`; the typed calls (`declare::<P>`,
88/// `listen::<P>`, `alter::<P>`, `collect::<P>`, `on_failure`) are methods
89/// of `dyn Bus`, written once here over these.
90///
91/// What an implementation promises:
92///
93/// - Listeners run ordered by `after` / `before` first (the target
94///   [`LAST`] places one after every other of its point, one per point),
95///   then by priority (higher first), then by registration. A cycle is
96///   refused at registration ([`Refused::Cycle`]); a target not there is
97///   reported ([`FailureKind::MissingTarget`]) and ignored.
98/// - A listener's edit counts only when it returns `Ok` within its
99///   deadline without panicking; otherwise it is dropped, the others
100///   still run, and the failure is returned and sent to the sinks.
101/// - The value an emit returns is of the point's type: the typed calls
102///   panic otherwise, as a defect of the implementation.
103/// - Listeners run with no lock held, so a listener may emit or listen.
104///
105/// Refusals, on a point declared [`PointKind::Request`]:
106///
107/// - A listener that returns [`HookError::Refuse`] stops the request: its
108///   own edit is dropped, no later listener runs (on this thread or
109///   another: nothing is queued), and the result names the refusal
110///   ([`Altered::refused`], [`Collected::refused`]). It is not a failure
111///   and does not reach the failure sinks.
112/// - On a point declared fail-closed ([`PointSpec::fail_closed`]), a
113///   listener that fails (error, panic, missed deadline) stops the
114///   request the same way: the failure is reported as usual and the
115///   result names a refusal with [`Refusal::failed`] set. A threaded
116///   listener that misses its deadline stops it at once.
117/// - On the other kinds, [`HookError::Refuse`] counts as a failure
118///   ([`FailureKind::Error`] with the reason) and `fail_closed` is
119///   ignored.
120///
121/// Capabilities: an implementation may offer more than this core, each
122/// as a trait of its own found at run time through a provided method
123/// that returns `None` by default ([`Bus::defer`]). A library that needs
124/// one names it in its contract table ([`PointDecl::needs`]);
125/// [`declare_all`] then refuses the point on a bus without it
126/// ([`Refused::Unsupported`]). A library that can do without checks the
127/// method and falls back.
128///
129/// Local listeners ([`Bus::listen_local_any`]) are for state that is not
130/// `Send` (`Rc`, `RefCell`), such as an interface's. Each is bound to the
131/// thread that registered it:
132///
133/// - It takes its place in the same order as the other listeners of its
134///   point (`after` / `before` / [`LAST`], priority, registration), keeps
135///   its owner and deadline, and shows in introspection
136///   ([`ListenerInfo::local`]).
137/// - An emit on its thread runs it in that order, inline, with the
138///   others.
139/// - An emit on another thread runs every other listener in order and
140///   queues the local ones for their thread; the result names them
141///   ([`Altered::deferred`], [`Collected::deferred`]) and the wakers
142///   ([`Bus::add_pending_waker`]) are called. The thread runs them when
143///   it calls [`Bus::run_pending`], in their order, emits in the order
144///   they were queued. A deferred alter's listeners edit a copy of the
145///   value the emit returned; a deferred collect's listeners each fill a
146///   fresh value. What they do is reported by [`Bus::run_pending`], not
147///   to the emitter.
148/// - A listener removed ([`Bus::unlisten`], [`Bus::forget`]), from any
149///   thread, does not run again, queued or not.
150pub trait Bus: Send + Sync {
151    /// Declares a point: its description and deadline. Listeners may
152    /// register before or after; declaring twice is refused.
153    fn declare_point(&self, point: PointKey, spec: PointSpec) -> Result<(), Refused>;
154
155    /// Registers a listener on a point under `id`. Refused, with nothing
156    /// changed, when the id is taken on the point, when its constraints
157    /// close a cycle, or when the point is registered with another type.
158    fn listen_any(
159        &self,
160        point: PointKey,
161        id: String,
162        opts: ListenOpts,
163        run: AnyListener,
164    ) -> Result<(), Refused>;
165
166    /// Registers a local listener on a point under `id`, bound to the
167    /// calling thread: it runs only on that thread. Refused as
168    /// [`Bus::listen_any`] is, and when `opts` asks for a thread of its
169    /// own ([`Refused::Threaded`]).
170    fn listen_local_any(
171        &self,
172        point: PointKey,
173        id: String,
174        opts: ListenOpts,
175        run: AnyLocalListener,
176    ) -> Result<(), Refused>;
177
178    /// Runs the local listeners queued for the calling thread by emits
179    /// on other threads, emit by emit in the order they were queued;
180    /// what each emit's deferred part did. Empty when nothing waits.
181    fn run_pending(&self) -> Vec<PendingRun>;
182
183    /// Adds a waker called when an emit queues local listeners for a
184    /// thread, with that thread's id: where the host asks that thread to
185    /// call [`Bus::run_pending`] (a repaint request, a message to its
186    /// loop). A waker that panics is ignored.
187    fn add_pending_waker(&self, wake: PendingWaker);
188
189    /// Removes the listener `id` of the point `point`; whether it was
190    /// there.
191    fn unlisten(&self, point: &str, id: &str) -> bool;
192
193    /// Removes every listener of `owner`, on every point; how many.
194    fn forget(&self, owner: &str) -> usize;
195
196    /// Passes `value` through the point's listeners in order, each
197    /// editing what the previous ones left; `clone` copies it so a
198    /// failing listener leaves it as it found it.
199    fn alter_any(
200        &self,
201        point: PointKey,
202        input: AnyInput,
203        value: AnyValue,
204        clone: CloneFn,
205    ) -> Altered<AnyValue>;
206
207    /// Gives each of the point's listeners, in order, a value from
208    /// `fresh` to fill, and gathers those that succeed.
209    fn collect_any(&self, point: PointKey, input: AnyInput, fresh: FreshFn) -> Collected<AnyValue>;
210
211    /// Adds a sink called with each failure that dropped a contribution,
212    /// as it happens.
213    fn add_failure_sink(&self, sink: FailureSink);
214
215    /// Every point, in id order, with its listeners in the order they
216    /// run.
217    fn points(&self) -> Vec<PointInfo>;
218
219    /// The listeners of the point `point`, in the order they run; `None`
220    /// for a point nobody declared or listened to.
221    fn listeners(&self, point: &str) -> Option<Vec<ListenerInfo>>;
222
223    /// The [`Defer`] capability: requests asked now, heard at the next
224    /// drain on the same thread. `None` (the default) when the
225    /// implementation does not offer it.
226    fn defer(&self) -> Option<&dyn Defer> {
227        None
228    }
229}
230
231/// Whether `bus` offers `capability`.
232pub fn offers(bus: &dyn Bus, capability: Capability) -> bool {
233    match capability {
234        Capability::Defer => bus.defer().is_some(),
235    }
236}
237
238/// A capability of a bus ([`Bus::defer`]): a request asked now, whose
239/// listeners run at the bus's next drain on the same thread.
240///
241/// It is for code that cannot be re-entered while it runs, such as an
242/// interface drawing a panel with its state borrowed: the panel asks,
243/// and the listeners run after the drawing, when the host calls
244/// [`Defer::drain`].
245///
246/// What an implementation promises:
247///
248/// - An ask is queued for the calling thread and returns at once with
249///   its number, increasing in ask order across the bus. The wakers
250///   ([`Bus::add_pending_waker`]) are called with the thread's id.
251/// - [`Defer::drain`] runs the asks queued for the calling thread, in
252///   ask order, each as an alter emit of its point with the listeners
253///   registered when it runs (one removed since the ask does not run;
254///   one added since does). Every rule of [`Bus`] holds, refusals and
255///   fail-closed points included; a local listener of another thread is
256///   queued for that thread's [`Bus::run_pending`] as usual.
257/// - Each ask's outcome is reported by the drain ([`PendingRun`], with
258///   [`PendingRun::ask`] set): the listeners that ran, their failures,
259///   a refusal. The asker gets nothing back; a listener placed last
260///   ([`ListenOpts::last`]) reads the final value.
261/// - An ask made during a drain (by a listener) waits for the next one.
262/// - An immediate emit made after an ask, before the drain, runs before
263///   it.
264pub trait Defer: Send + Sync {
265    /// Queues an alter emit of `point` with `input` and `value` for the
266    /// calling thread's next [`Defer::drain`]; the ask's number.
267    fn ask_any(&self, point: PointKey, input: AnyInput, value: AnyValue, clone: CloneFn) -> u64;
268
269    /// Runs the asks queued for the calling thread, in ask order; what
270    /// each did. Empty when nothing waits.
271    fn drain(&self) -> Vec<PendingRun>;
272
273    /// How many asks wait for the calling thread's drain (zero before a
274    /// clean exit).
275    fn waiting(&self) -> usize;
276}
277
278impl<'a> dyn Defer + 'a {
279    /// Asks the request `P` now: its listeners run at the calling
280    /// thread's next [`Defer::drain`]. The ask's number.
281    pub fn ask<P: Point>(&self, input: P::Input, value: P::Value) -> u64
282    where
283        P::Value: Clone,
284    {
285        self.ask_any(
286            PointKey::of::<P>(),
287            Arc::new(input),
288            Box::new(value),
289            clone_value::<P::Value>,
290        )
291    }
292}
293
294/// A shared bus is a bus: `&Arc<dyn Bus>` goes where `&dyn Bus` is
295/// asked, and an application may hand out `Arc<MyBus>` as it is.
296impl<B: Bus + ?Sized> Bus for Arc<B> {
297    fn declare_point(&self, point: PointKey, spec: PointSpec) -> Result<(), Refused> {
298        (**self).declare_point(point, spec)
299    }
300
301    fn listen_any(
302        &self,
303        point: PointKey,
304        id: String,
305        opts: ListenOpts,
306        run: AnyListener,
307    ) -> Result<(), Refused> {
308        (**self).listen_any(point, id, opts, run)
309    }
310
311    fn listen_local_any(
312        &self,
313        point: PointKey,
314        id: String,
315        opts: ListenOpts,
316        run: AnyLocalListener,
317    ) -> Result<(), Refused> {
318        (**self).listen_local_any(point, id, opts, run)
319    }
320
321    fn run_pending(&self) -> Vec<PendingRun> {
322        (**self).run_pending()
323    }
324
325    fn add_pending_waker(&self, wake: PendingWaker) {
326        (**self).add_pending_waker(wake);
327    }
328
329    fn unlisten(&self, point: &str, id: &str) -> bool {
330        (**self).unlisten(point, id)
331    }
332
333    fn forget(&self, owner: &str) -> usize {
334        (**self).forget(owner)
335    }
336
337    fn alter_any(
338        &self,
339        point: PointKey,
340        input: AnyInput,
341        value: AnyValue,
342        clone: CloneFn,
343    ) -> Altered<AnyValue> {
344        (**self).alter_any(point, input, value, clone)
345    }
346
347    fn collect_any(&self, point: PointKey, input: AnyInput, fresh: FreshFn) -> Collected<AnyValue> {
348        (**self).collect_any(point, input, fresh)
349    }
350
351    fn add_failure_sink(&self, sink: FailureSink) {
352        (**self).add_failure_sink(sink);
353    }
354
355    fn points(&self) -> Vec<PointInfo> {
356        (**self).points()
357    }
358
359    fn listeners(&self, point: &str) -> Option<Vec<ListenerInfo>> {
360        (**self).listeners(point)
361    }
362
363    fn defer(&self) -> Option<&dyn Defer> {
364        (**self).defer()
365    }
366}
367
368/// Copies an erased value of type `V`.
369fn clone_value<V: Clone + Send + 'static>(value: &(dyn Any + Send)) -> AnyValue {
370    match value.downcast_ref::<V>() {
371        Some(v) => Box::new(v.clone()),
372        None => panic!(
373            "a bus implementation passed a value that is not a `{}`",
374            type_name::<V>()
375        ),
376    }
377}
378
379/// A fresh erased value of type `V`.
380fn fresh_value<V: Default + Send + 'static>() -> AnyValue {
381    Box::new(V::default())
382}
383
384/// Takes the typed value back from what an implementation returned.
385fn typed<P: Point>(value: AnyValue) -> P::Value {
386    match value.downcast::<P::Value>() {
387        Ok(v) => *v,
388        Err(_) => panic!(
389            "the bus returned a value of another type than `{}`'s ({})",
390            P::ID,
391            type_name::<P::Value>()
392        ),
393    }
394}
395
396impl<'a> dyn Bus + 'a {
397    /// Declares the point `P`: its description and deadline. Listeners
398    /// may register before or after; declaring twice is refused.
399    pub fn declare<P: Point>(&self, spec: PointSpec) -> Result<(), Refused> {
400        self.declare_point(PointKey::of::<P>(), spec)
401    }
402
403    /// Registers a listener on `P` under `id`. It reads the emit's input
404    /// and edits the value; its edit counts only when it returns `Ok`
405    /// within its deadline without panicking.
406    ///
407    /// Refused, with nothing changed, when the id is taken on the point
408    /// or when its `after`/`before` close a cycle. A constraint naming a
409    /// listener not (yet) registered is accepted, reported by each emit
410    /// and by introspection, and ignored.
411    pub fn listen<P: Point>(
412        &self,
413        id: impl Into<String>,
414        opts: ListenOpts,
415        run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + Send + Sync + 'static,
416    ) -> Result<(), Refused> {
417        self.listen_any(PointKey::of::<P>(), id.into(), opts, erase::<P>(run))
418    }
419
420    /// Registers a local listener on `P` under `id`, bound to the calling
421    /// thread: it may hold state that is not `Send` (`Rc<RefCell<…>>`).
422    /// It takes its place in the point's order with the other listeners;
423    /// an emit from another thread queues it for this thread's next
424    /// [`Bus::run_pending`]. See [`Bus`] for the guarantees.
425    pub fn listen_local<P: Point>(
426        &self,
427        id: impl Into<String>,
428        opts: ListenOpts,
429        run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + 'static,
430    ) -> Result<(), Refused> {
431        self.listen_local_any(PointKey::of::<P>(), id.into(), opts, erase_local::<P>(run))
432    }
433
434    /// Adds a waker called, with the thread's id, when an emit queues
435    /// local listeners for that thread. A waker that panics is ignored.
436    pub fn on_pending(&self, wake: impl Fn(std::thread::ThreadId) + Send + Sync + 'static) {
437        self.add_pending_waker(Arc::new(wake));
438    }
439
440    /// Passes `value` through `P`'s listeners in order: each edits the
441    /// value the previous ones left. A listener that fails leaves it as
442    /// it found it.
443    pub fn alter<P: Point>(&self, input: P::Input, value: P::Value) -> Altered<P::Value>
444    where
445        P::Value: Clone,
446    {
447        let out = self.alter_any(
448            PointKey::of::<P>(),
449            Arc::new(input),
450            Box::new(value),
451            clone_value::<P::Value>,
452        );
453        Altered {
454            value: typed::<P>(out.value),
455            failures: out.failures,
456            deferred: out.deferred,
457            refused: out.refused,
458        }
459    }
460
461    /// Gives each of `P`'s listeners, in order, a fresh default value to
462    /// fill, and gathers the values of those that succeed.
463    pub fn collect<P: Point>(&self, input: P::Input) -> Collected<P::Value>
464    where
465        P::Value: Default,
466    {
467        let out = self.collect_any(
468            PointKey::of::<P>(),
469            Arc::new(input),
470            fresh_value::<P::Value>,
471        );
472        Collected {
473            parts: out
474                .parts
475                .into_iter()
476                .map(|(id, v)| (id, typed::<P>(v)))
477                .collect(),
478            failures: out.failures,
479            deferred: out.deferred,
480            refused: out.refused,
481        }
482    }
483
484    /// Adds a sink called with each failure that dropped a contribution
485    /// ([`Failure::dropped`]), as it happens: where the host publishes
486    /// its [`FAILED_FACT`] fact or logs. A sink that panics is ignored.
487    pub fn on_failure(&self, sink: impl Fn(&Failure) + Send + Sync + 'static) {
488        self.add_failure_sink(Arc::new(sink));
489    }
490}
491
492/// Erases a typed listener of `P`.
493pub fn erase<P: Point>(
494    run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + Send + Sync + 'static,
495) -> AnyListener {
496    Arc::new(move |input, value| {
497        let Some(input) = input.downcast_ref::<P::Input>() else {
498            return Err(HookError::Failed(format!(
499                "`{}`: the input is not a `{}`",
500                P::ID,
501                type_name::<P::Input>()
502            )));
503        };
504        let Some(value) = value.downcast_mut::<P::Value>() else {
505            return Err(HookError::Failed(format!(
506                "`{}`: the value is not a `{}`",
507                P::ID,
508                type_name::<P::Value>()
509            )));
510        };
511        run(input, value)
512    })
513}
514
515/// Erases a typed local listener of `P`.
516pub fn erase_local<P: Point>(
517    run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + 'static,
518) -> AnyLocalListener {
519    Rc::new(move |input, value| {
520        let Some(input) = input.downcast_ref::<P::Input>() else {
521            return Err(HookError::Failed(format!(
522                "`{}`: the input is not a `{}`",
523                P::ID,
524                type_name::<P::Input>()
525            )));
526        };
527        let Some(value) = value.downcast_mut::<P::Value>() else {
528            return Err(HookError::Failed(format!(
529                "`{}`: the value is not a `{}`",
530                P::ID,
531                type_name::<P::Value>()
532            )));
533        };
534        run(input, value)
535    })
536}
537
538/// One line of a library's contract table: a point it declares, built
539/// from the point's type in a `const` (`PointDecl::of::<DocClose>(…)`),
540/// so the application can read what a library will host before building
541/// anything. [`declare_all`] declares a table on a bus.
542#[derive(Clone, Copy, Debug)]
543pub struct PointDecl {
544    /// The point's id.
545    pub id: &'static str,
546    /// What it is for.
547    pub kind: PointKind,
548    /// What it does, for people and agents reading introspection.
549    pub description: &'static str,
550    /// The deadline of its listeners that set none; `None` takes the
551    /// bus's.
552    pub deadline: Option<Duration>,
553    /// Whether a listener failure refuses the request
554    /// ([`PointSpec::fail_closed`]).
555    pub fail_closed: bool,
556    /// The capabilities the point needs from the bus: [`declare_all`]
557    /// refuses it on a bus without them.
558    pub needs: &'static [Capability],
559    key: fn() -> PointKey,
560}
561
562impl PointDecl {
563    /// The declaration of the point `P`, described by `description`.
564    pub const fn of<P: Point>(description: &'static str) -> PointDecl {
565        PointDecl {
566            id: P::ID,
567            kind: P::KIND,
568            description,
569            deadline: None,
570            fail_closed: false,
571            needs: &[],
572            key: PointKey::of::<P>,
573        }
574    }
575
576    /// The deadline of its listeners that set none.
577    pub const fn deadline(mut self, deadline: Duration) -> PointDecl {
578        self.deadline = Some(deadline);
579        self
580    }
581
582    /// A listener failure refuses the request
583    /// ([`PointSpec::fail_closed`]).
584    pub const fn fail_closed(mut self) -> PointDecl {
585        self.fail_closed = true;
586        self
587    }
588
589    /// The capabilities the point needs from the bus
590    /// (`.needs(&[Capability::Defer])`).
591    pub const fn needs(mut self, needs: &'static [Capability]) -> PointDecl {
592        self.needs = needs;
593        self
594    }
595
596    /// The point's key.
597    pub fn key(&self) -> PointKey {
598        (self.key)()
599    }
600
601    /// The point's spec, as [`Bus::declare_point`] takes it.
602    pub fn spec(&self) -> PointSpec {
603        let mut spec = PointSpec::new(self.description);
604        spec.deadline = self.deadline;
605        spec.fail_closed = self.fail_closed;
606        spec
607    }
608}