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::sync::Arc;
10use std::time::Duration;
11
12pub use tools::{declare_all, missing_targets, order_dump};
13pub use types::*;
14
15/// A point as the erased methods of [`Bus`] name it: its id, its kind and
16/// its type, so an implementation refuses one id registered with two
17/// types.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
19pub struct PointKey {
20    /// The point's id ([`Point::ID`]).
21    pub id: &'static str,
22    /// What it is for ([`Point::KIND`]).
23    pub kind: PointKind,
24    /// The point type's id.
25    pub type_id: TypeId,
26    /// The point type's name, for messages.
27    pub type_name: &'static str,
28}
29
30impl PointKey {
31    /// The key of the point `P`.
32    pub fn of<P: Point>() -> PointKey {
33        PointKey {
34            id: P::ID,
35            kind: P::KIND,
36            type_id: TypeId::of::<P>(),
37            type_name: type_name::<P>(),
38        }
39    }
40}
41
42/// An emit's input, its type erased: a point's [`Point::Input`].
43pub type AnyInput = Arc<dyn Any + Send + Sync>;
44
45/// A value going through an emit, its type erased: a point's
46/// [`Point::Value`].
47pub type AnyValue = Box<dyn Any + Send>;
48
49/// A listener, its types erased: it reads the input and edits the value
50/// in place.
51pub type AnyListener = Arc<
52    dyn Fn(&(dyn Any + Send + Sync), &mut (dyn Any + Send)) -> Result<(), HookError> + Send + Sync,
53>;
54
55/// Copies an erased value of a point's type (an alter keeps the value as
56/// it was when a listener fails).
57pub type CloneFn = fn(&(dyn Any + Send)) -> AnyValue;
58
59/// Makes a fresh erased value of a point's type (each listener's part in
60/// a collect).
61pub type FreshFn = fn() -> AnyValue;
62
63/// Receives each failure that dropped a contribution
64/// ([`Failure::dropped`]).
65pub type FailureSink = Arc<dyn Fn(&Failure) + Send + Sync>;
66
67/// The bus contract: hook points, their listeners in a declared order,
68/// emits and introspection. An application supplies one implementation
69/// (its own, or one written for it, such as `egui-pop-hooks`'s `Kernel`)
70/// and hands it to each
71/// library at construction; a library never constructs the bus it
72/// publishes on.
73///
74/// The methods are object safe and their values erased, so a library
75/// holds an `Arc<dyn Bus>`; the typed calls (`declare::<P>`,
76/// `listen::<P>`, `alter::<P>`, `collect::<P>`, `on_failure`) are methods
77/// of `dyn Bus`, written once here over these.
78///
79/// What an implementation promises:
80///
81/// - Listeners run ordered by `after` / `before` first (the target
82///   [`LAST`] places one after every other of its point, one per point),
83///   then by priority (higher first), then by registration. A cycle is
84///   refused at registration ([`Refused::Cycle`]); a target not there is
85///   reported ([`FailureKind::MissingTarget`]) and ignored.
86/// - A listener's edit counts only when it returns `Ok` within its
87///   deadline without panicking; otherwise it is dropped, the others
88///   still run, and the failure is returned and sent to the sinks.
89/// - The value an emit returns is of the point's type: the typed calls
90///   panic otherwise, as a defect of the implementation.
91/// - Listeners run with no lock held, so a listener may emit or listen.
92pub trait Bus: Send + Sync {
93    /// Declares a point: its description and deadline. Listeners may
94    /// register before or after; declaring twice is refused.
95    fn declare_point(&self, point: PointKey, spec: PointSpec) -> Result<(), Refused>;
96
97    /// Registers a listener on a point under `id`. Refused, with nothing
98    /// changed, when the id is taken on the point, when its constraints
99    /// close a cycle, or when the point is registered with another type.
100    fn listen_any(
101        &self,
102        point: PointKey,
103        id: String,
104        opts: ListenOpts,
105        run: AnyListener,
106    ) -> Result<(), Refused>;
107
108    /// Removes the listener `id` of the point `point`; whether it was
109    /// there.
110    fn unlisten(&self, point: &str, id: &str) -> bool;
111
112    /// Removes every listener of `owner`, on every point; how many.
113    fn forget(&self, owner: &str) -> usize;
114
115    /// Passes `value` through the point's listeners in order, each
116    /// editing what the previous ones left; `clone` copies it so a
117    /// failing listener leaves it as it found it.
118    fn alter_any(
119        &self,
120        point: PointKey,
121        input: AnyInput,
122        value: AnyValue,
123        clone: CloneFn,
124    ) -> Altered<AnyValue>;
125
126    /// Gives each of the point's listeners, in order, a value from
127    /// `fresh` to fill, and gathers those that succeed.
128    fn collect_any(&self, point: PointKey, input: AnyInput, fresh: FreshFn) -> Collected<AnyValue>;
129
130    /// Adds a sink called with each failure that dropped a contribution,
131    /// as it happens.
132    fn add_failure_sink(&self, sink: FailureSink);
133
134    /// Every point, in id order, with its listeners in the order they
135    /// run.
136    fn points(&self) -> Vec<PointInfo>;
137
138    /// The listeners of the point `point`, in the order they run; `None`
139    /// for a point nobody declared or listened to.
140    fn listeners(&self, point: &str) -> Option<Vec<ListenerInfo>>;
141}
142
143/// A shared bus is a bus: `&Arc<dyn Bus>` goes where `&dyn Bus` is
144/// asked, and an application may hand out `Arc<MyBus>` as it is.
145impl<B: Bus + ?Sized> Bus for Arc<B> {
146    fn declare_point(&self, point: PointKey, spec: PointSpec) -> Result<(), Refused> {
147        (**self).declare_point(point, spec)
148    }
149
150    fn listen_any(
151        &self,
152        point: PointKey,
153        id: String,
154        opts: ListenOpts,
155        run: AnyListener,
156    ) -> Result<(), Refused> {
157        (**self).listen_any(point, id, opts, run)
158    }
159
160    fn unlisten(&self, point: &str, id: &str) -> bool {
161        (**self).unlisten(point, id)
162    }
163
164    fn forget(&self, owner: &str) -> usize {
165        (**self).forget(owner)
166    }
167
168    fn alter_any(
169        &self,
170        point: PointKey,
171        input: AnyInput,
172        value: AnyValue,
173        clone: CloneFn,
174    ) -> Altered<AnyValue> {
175        (**self).alter_any(point, input, value, clone)
176    }
177
178    fn collect_any(&self, point: PointKey, input: AnyInput, fresh: FreshFn) -> Collected<AnyValue> {
179        (**self).collect_any(point, input, fresh)
180    }
181
182    fn add_failure_sink(&self, sink: FailureSink) {
183        (**self).add_failure_sink(sink);
184    }
185
186    fn points(&self) -> Vec<PointInfo> {
187        (**self).points()
188    }
189
190    fn listeners(&self, point: &str) -> Option<Vec<ListenerInfo>> {
191        (**self).listeners(point)
192    }
193}
194
195/// Copies an erased value of type `V`.
196fn clone_value<V: Clone + Send + 'static>(value: &(dyn Any + Send)) -> AnyValue {
197    match value.downcast_ref::<V>() {
198        Some(v) => Box::new(v.clone()),
199        None => panic!(
200            "a bus implementation passed a value that is not a `{}`",
201            type_name::<V>()
202        ),
203    }
204}
205
206/// A fresh erased value of type `V`.
207fn fresh_value<V: Default + Send + 'static>() -> AnyValue {
208    Box::new(V::default())
209}
210
211/// Takes the typed value back from what an implementation returned.
212fn typed<P: Point>(value: AnyValue) -> P::Value {
213    match value.downcast::<P::Value>() {
214        Ok(v) => *v,
215        Err(_) => panic!(
216            "the bus returned a value of another type than `{}`'s ({})",
217            P::ID,
218            type_name::<P::Value>()
219        ),
220    }
221}
222
223impl<'a> dyn Bus + 'a {
224    /// Declares the point `P`: its description and deadline. Listeners
225    /// may register before or after; declaring twice is refused.
226    pub fn declare<P: Point>(&self, spec: PointSpec) -> Result<(), Refused> {
227        self.declare_point(PointKey::of::<P>(), spec)
228    }
229
230    /// Registers a listener on `P` under `id`. It reads the emit's input
231    /// and edits the value; its edit counts only when it returns `Ok`
232    /// within its deadline without panicking.
233    ///
234    /// Refused, with nothing changed, when the id is taken on the point
235    /// or when its `after`/`before` close a cycle. A constraint naming a
236    /// listener not (yet) registered is accepted, reported by each emit
237    /// and by introspection, and ignored.
238    pub fn listen<P: Point>(
239        &self,
240        id: impl Into<String>,
241        opts: ListenOpts,
242        run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + Send + Sync + 'static,
243    ) -> Result<(), Refused> {
244        self.listen_any(PointKey::of::<P>(), id.into(), opts, erase::<P>(run))
245    }
246
247    /// Passes `value` through `P`'s listeners in order: each edits the
248    /// value the previous ones left. A listener that fails leaves it as
249    /// it found it.
250    pub fn alter<P: Point>(&self, input: P::Input, value: P::Value) -> Altered<P::Value>
251    where
252        P::Value: Clone,
253    {
254        let out = self.alter_any(
255            PointKey::of::<P>(),
256            Arc::new(input),
257            Box::new(value),
258            clone_value::<P::Value>,
259        );
260        Altered {
261            value: typed::<P>(out.value),
262            failures: out.failures,
263        }
264    }
265
266    /// Gives each of `P`'s listeners, in order, a fresh default value to
267    /// fill, and gathers the values of those that succeed.
268    pub fn collect<P: Point>(&self, input: P::Input) -> Collected<P::Value>
269    where
270        P::Value: Default,
271    {
272        let out = self.collect_any(
273            PointKey::of::<P>(),
274            Arc::new(input),
275            fresh_value::<P::Value>,
276        );
277        Collected {
278            parts: out
279                .parts
280                .into_iter()
281                .map(|(id, v)| (id, typed::<P>(v)))
282                .collect(),
283            failures: out.failures,
284        }
285    }
286
287    /// Adds a sink called with each failure that dropped a contribution
288    /// ([`Failure::dropped`]), as it happens: where the host publishes
289    /// its [`FAILED_FACT`] fact or logs. A sink that panics is ignored.
290    pub fn on_failure(&self, sink: impl Fn(&Failure) + Send + Sync + 'static) {
291        self.add_failure_sink(Arc::new(sink));
292    }
293}
294
295/// Erases a typed listener of `P`.
296pub fn erase<P: Point>(
297    run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + Send + Sync + 'static,
298) -> AnyListener {
299    Arc::new(move |input, value| {
300        let Some(input) = input.downcast_ref::<P::Input>() else {
301            return Err(HookError(format!(
302                "`{}`: the input is not a `{}`",
303                P::ID,
304                type_name::<P::Input>()
305            )));
306        };
307        let Some(value) = value.downcast_mut::<P::Value>() else {
308            return Err(HookError(format!(
309                "`{}`: the value is not a `{}`",
310                P::ID,
311                type_name::<P::Value>()
312            )));
313        };
314        run(input, value)
315    })
316}
317
318/// One line of a library's contract table: a point it declares, built
319/// from the point's type in a `const` (`PointDecl::of::<DocClose>(…)`),
320/// so the application can read what a library will host before building
321/// anything. [`declare_all`] declares a table on a bus.
322#[derive(Clone, Copy, Debug)]
323pub struct PointDecl {
324    /// The point's id.
325    pub id: &'static str,
326    /// What it is for.
327    pub kind: PointKind,
328    /// What it does, for people and agents reading introspection.
329    pub description: &'static str,
330    /// The deadline of its listeners that set none; `None` takes the
331    /// bus's.
332    pub deadline: Option<Duration>,
333    key: fn() -> PointKey,
334}
335
336impl PointDecl {
337    /// The declaration of the point `P`, described by `description`.
338    pub const fn of<P: Point>(description: &'static str) -> PointDecl {
339        PointDecl {
340            id: P::ID,
341            kind: P::KIND,
342            description,
343            deadline: None,
344            key: PointKey::of::<P>,
345        }
346    }
347
348    /// The deadline of its listeners that set none.
349    pub const fn deadline(mut self, deadline: Duration) -> PointDecl {
350        self.deadline = Some(deadline);
351        self
352    }
353
354    /// The point's key.
355    pub fn key(&self) -> PointKey {
356        (self.key)()
357    }
358
359    /// The point's spec, as [`Bus::declare_point`] takes it.
360    pub fn spec(&self) -> PointSpec {
361        let spec = PointSpec::new(self.description);
362        match self.deadline {
363            Some(d) => spec.deadline(d),
364            None => spec,
365        }
366    }
367}