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