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