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