Expand description
§bus-contract
Traits and types for an in-process bus of hook points (requests, events, alter, collect) with ordered listeners.
A library declares its points and listeners against the Bus trait.
The application creates the bus and passes it to each library at
construction. There is no global.
§Contents
- Points are types (
Point): an id (doc.close), the input every listener reads, the value a listener edits, and a declared kind (request,event,alter,collect). Bus, an object-safe trait (Arc<dyn Bus>): declare a point; listen under an id and an owner, ordered byafter/before/last, then priority; unlisten; forget an owner;alterandcollectemits that return every listener’s failure (error, panic, missed deadline); failure sinks; introspection.- Local listeners (
listen_local::<P>) for state that is notSend(Rc<RefCell<…>>): bound to the thread that registered them, in the same order as the other listeners. An emit from another thread queues them for their thread’srun_pending(). - Refusals on requests: a listener returns
HookError::refuse(reason)and the request stops there; a point declaredfail_closedturns a listener failure into a refusal. - Optional capabilities, found at run time:
Bus::defer()returns theDefercapability (requests asked now, heard at the next drain on the same thread) orNone. - Typed calls on
dyn Bus(declare::<P>,listen::<P>,listen_local::<P>,alter::<P>,collect::<P>,on_failure,on_pending), written once over the erased methods: an implementation writes only those. - A contract table (
PointDecl): a library’s points as aconst, readable before anything is built, declared withdeclare_all. - Tools on the contract:
order_dump(“who runs when”, for reviewed files and debug views) andmissing_targets(an ordering constraint naming a listener that is not there). - No dependencies, no
unsafe, no async runtime.
This crate has no implementation. One is Kernel in
egui-pop-hooks. The
guarantees an implementation must keep are documented on Bus.
§Example
use std::sync::Arc;
use bus_contract::{Bus, ListenOpts, Point, PointDecl, PointKind, declare_all};
/// The library's request: a document closes.
pub struct DocClose;
impl Point for DocClose {
const ID: &'static str = "doc.close";
const KIND: PointKind = PointKind::Request;
type Input = String;
type Value = Vec<String>;
}
/// The library's points, readable before anything is built.
pub const POINTS: &[PointDecl] = &[PointDecl::of::<DocClose>("A document closes.")];
/// The library takes the bus; it never constructs one.
pub struct Documents(Arc<dyn Bus>);
impl Documents {
pub fn new(bus: Arc<dyn Bus>) -> Documents {
declare_all(&*bus, POINTS);
let opts = ListenOpts::new().owner("docs");
let _ = bus.listen::<DocClose>("docs.autosave", opts, |doc, did| {
did.push(format!("saved {doc}"));
Ok(())
});
Documents(bus)
}
pub fn close(&self, doc: &str) -> Vec<String> {
self.0.alter::<DocClose>(doc.to_owned(), Vec::new()).value
}
}The application creates the bus and passes it to each library:
let bus: Arc<dyn Bus> = Arc::new(egui_pop_hooks::Kernel::new()); // or its own
let docs = Documents::new(bus.clone());
let search = Search::new(bus.clone());
print!("{}", bus_contract::order_dump(&*bus, &["doc.close"]));§Local listeners
A listener registered with listen_local::<P> may hold state that is
not Send, such as an interface’s Rc<RefCell<…>>. It is bound to the
thread that registered it.
- It is ordered with the other listeners of its point (
after,before,last, priority), keeps its owner and deadline, and shows in introspection as local. - An emit on its thread runs it in that order with the others.
- An emit on another thread runs the other listeners, queues the local
ones and names them in the result (
deferred). The wakers added withon_pendingare called with the thread’s id. The thread runs the queued listeners, in order, when it callsrun_pending(), typically once per pass of its loop. unlistenandforgetremove local listeners too, queued runs included.
let panel = Rc::new(RefCell::new(Panel::default()));
let mine = panel.clone();
bus.listen_local::<DocClose>("ui.panel", ListenOpts::new().after("docs.autosave"), move |doc, _| {
mine.borrow_mut().closed(doc);
Ok(())
})?;
bus.on_pending(move |_| ctx.request_repaint());
// each pass of the interface's loop:
bus.run_pending();§Refusals
On a point declared PointKind::Request, a listener may refuse the
request with a reason. The request stops: no later listener runs, the
refusing listener’s edit is dropped, and the result names the refusal
(Altered::refused: point, listener, owner, reason). A refusal is not
a failure and does not reach the failure sinks.
By default a failing listener (error, panic, missed deadline) has its
contribution dropped and the others run. On a point declared
fail_closed, the failure refuses the request instead: the failure is
reported as usual and refused is set with failed: true. A policy
listener placed first on a fail-closed point therefore never lets the
handler run when the policy itself breaks.
pub const POINTS: &[PointDecl] =
&[PointDecl::of::<CommandRun>("A command runs.").fail_closed()];
bus.listen::<CommandRun>("policy", ListenOpts::new().priority(1000), |run, _| {
if run.origin.is_agent() && run.id == "files.delete" {
return Err(HookError::refuse("agents may not delete files"));
}
Ok(())
})?;
let out = bus.alter::<CommandRun>(run, Outcome::default());
if let Some(refusal) = out.refused {
// "hook `command.run`: refused by `policy`: agents may not delete files"
}§Capabilities
The Bus trait is the core every implementation offers. An
implementation may offer more, each part as a trait of its own, found
at run time through a provided method of Bus that returns None by
default. One dyn Bus type works everywhere, whatever the
implementation offers.
- A library that needs a capability names it in its contract table
(
PointDecl::needs).declare_allrefuses such a point on a bus without it (Refused::Unsupported) and leaves it undeclared. - A library that can do without one calls the method and falls back
when it gets
None. offers(bus, Capability::Defer)tells whether a bus has one.
§Defer
Bus::defer() returns Option<&dyn Defer>. A request asked through it
returns at once; its listeners run at the next drain() on the same
thread. It is for code that cannot be re-entered while it runs, such as
an interface drawing a panel with its state borrowed.
- Asks are per thread and run in ask order, each as an alter emit with the listeners registered at the drain. Refusals and fail-closed points apply.
drain()returns what each ask did (PendingRunwithaskset: the listeners that ran, failures, refusal). The asker gets nothing back.- An ask made during a drain waits for the next drain. An immediate emit made after an ask runs before it.
waiting()counts the asks queued for the calling thread, so a host can drain before it exits.
pub const POINTS: &[PointDecl] = &[PointDecl::of::<LibraryWrite>("A library write.")
.needs(&[Capability::Defer])];
// while drawing, with the library borrowed:
bus.defer().expect("declared with needs").ask::<LibraryWrite>(write, Vec::new());
// after drawing, where nothing is borrowed:
for run in bus.defer().map(|d| d.drain()).unwrap_or_default() {
if let Some(refusal) = run.refused { log::warn!("{refusal}"); }
}§Not included
- A journal (events with a revision, catch-up from a revision).
- Transport across processes.
§License
MIT OR Apache-2.0, at your option.
Structs§
- Altered
- The result of an
alteremit. - Collected
- The result of a
collectemit. - Failure
- One listener’s failure: its contribution was dropped (except for a
FailureKind::MissingTarget); the other listeners ran, unless the point is fail-closed (PointSpec::fail_closed). - Listen
Opts - How a listener is placed and limited.
- Listener
Info - A listener as introspection shows it.
- Pending
Run - What listeners run later did: one emit’s local listeners queued for
their thread (
Bus::run_pending), or one deferred request (Defer::drain). - Point
Decl - One line of a library’s contract table: a point it declares, built
from the point’s type in a
const(PointDecl::of::<DocClose>(…)), so the application can read what a library will host before building anything.declare_alldeclares a table on a bus. - Point
Info - A point as introspection shows it.
- Point
Key - A point as the erased methods of
Busname it: its id, its kind and its type, so an implementation refuses one id registered with two types. - Point
Spec - A point’s declaration: its description and limits, for introspection.
- Refusal
- A request stopped by one of its listeners: the listener refused it
(
HookError::Refuse), or failed on a fail-closed point (PointSpec::fail_closed). The listeners after it did not run.
Enums§
- Capability
- A capability a bus may offer beyond the core of
Bus, found at run time (Bus::defer). A library names the ones its points need in its contract table (PointDecl::needs). - Failure
Kind - What went wrong with one listener during an emit.
- Hook
Error - What a listener returns instead of
Ok(()): it failed, or it refuses the request. - Point
Kind - What a point is for, declared for introspection and review. A request
is an alter emit over the request’s input; only a request can be
refused by a listener (
HookError::Refuse) or declared fail-closed (PointSpec::fail_closed). - Refused
- Why a declaration or a listener was refused. Nothing was changed.
Constants§
- DEFAULT_
DEADLINE - The deadline of an in-process listener when neither the listener nor its point sets one.
- FAILED_
FACT - The name a host gives the fact it publishes for each
Failureits sinks receive (Bus::add_failure_sink). - LAST
- The
aftertarget that places a listener after every other listener of its point (ListenOpts::last): one per point, a second is refused as aRefused::Cycle(each would run after the other). - PLUGIN_
DEADLINE - The deadline meant for listeners that answer from another process (a
plugin over RPC): give it with
ListenOpts::deadlineorPointSpec::deadline.
Traits§
- Bus
- The bus contract: hook points, their listeners in a declared order,
emits and introspection. An application supplies one implementation
(its own, or one written for it, such as
egui-pop-hooks’sKernel) and hands it to each library at construction; a library never constructs the bus it publishes on. - Defer
- A capability of a bus (
Bus::defer): a request asked now, whose listeners run at the bus’s next drain on the same thread. - Point
- A hook point: one type per point, so its input and value are checked at compile time. Declared by the crate that owns the result.
Functions§
- declare_
all - Declares every point of a library’s contract table on
bus; the refusals, in table order: a point already declared (another library, or a second application on the same bus), or a point that needs a capability the bus does not offer (Refused::Unsupported, the point left undeclared). - erase
- Erases a typed listener of
P. - erase_
local - Erases a typed local listener of
P. - missing_
targets - The ordering constraints of
pointsthat name a listener not there:point: listener -> target. A test ends with none. - offers
- Whether
busofferscapability. - order_
dump - The order the listeners of
pointsrun in, one point after the other, each listener with its owner and what it declares: “who runs when”, read rather than remembered.
Type Aliases§
- AnyInput
- An emit’s input, its type erased: a point’s
Point::Input. - AnyListener
- A listener, its types erased: it reads the input and edits the value in place.
- AnyLocal
Listener - A local listener, its types erased: like
AnyListener, but neitherSendnorSync. It is bound to the thread that registered it (Bus::listen_local_any). - AnyValue
- A value going through an emit, its type erased: a point’s
Point::Value. - CloneFn
- Copies an erased value of a point’s type (an alter keeps the value as it was when a listener fails).
- Failure
Sink - Receives each failure that dropped a contribution
(
Failure::dropped). - FreshFn
- Makes a fresh erased value of a point’s type (each listener’s part in a collect).
- Pending
Waker - Called when local work is queued for a thread
(
Bus::add_pending_waker), with that thread’s id, on the emitting thread.