Crate bus_contract
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.
§Guarantees in five lines
- Ordered listeners: a point’s listeners run in their declared
order (
after,before,last, then priority). - Failure isolation: a failing listener (error, panic, missed deadline) is isolated: its edit is dropped, the others run, and the failure is returned to the caller.
- Veto without rollback: a refusal stops a request, but never rolls back what the listeners before it did.
- Fail-open or fail-closed: a listener failure on a request is
skipped (fail-open), unless the point is declared
fail_closed(relayable requests always are): then it refuses the request. - No global: the application owns the bus and hands it to each library; a library never constructs one.
Each property, with a stable id (core.order.declared,
core.request.veto-stops, …), what is not guaranteed (crossing is
not a distributed transaction, authorities are not a security
boundary, the journal is a window in memory) and the bus-kernel
conformance check that proves it, is in
GUARANTEES.md,
also the guarantees page of the crate docs.
§Getting started
This crate has no implementation: add
bus-kernel (the
reference implementation, Kernel) to get started, or implement Bus
yourself (bus-kernel’s conformance
feature checks any implementation against the guarantees).
A point has one of four kinds. alter transforms a shared value: each
listener edits what the previous ones left, and the caller gets it
back. collect gathers every listener’s answer, each in a fresh value,
and the failures. A request is an alter a listener may refuse; an
event says something happened. PointKind is not only a label:
Request enables refusals, Event gates the journal.
§Example
A library with one request point and one listener, and an application that wires it. The whole block compiles as a doctest of the crate.
use std::sync::Arc;
use bus_contract::{Bus, ListenOpts, Point, PointDecl, PointId, PointKind, declare_all, order_dump};
/// The library's request: a document closes.
pub struct DocClose;
impl Point for DocClose {
// A bad id here is a compile error: see "Naming points".
const ID: PointId = PointId::new("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)
}
/// Asks every listener to close `doc`; returns what each did.
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.
/// `bus` is `Arc::new(bus_kernel::Kernel::new())`, or your own `Bus`.
pub fn app(bus: Arc<dyn Bus>) {
let docs = Documents::new(bus.clone());
assert_eq!(docs.close("notes.txt"), ["saved notes.txt"]);
// "who runs when" on a point, for reviews and debug views:
print!("{}", order_dump(&*bus, &["doc.close"]));
}§What is in the workspace
Each crate is released and versioned on its own
(RELEASING.md).
The core names none of the capabilities: each capability crate owns its
trait, its CONTRACT and its facets, and an extension trait gives its
getter on any bus through the core’s typed lookup Bus::capability,
so a capability contract can change without a core release.
| Crate | What for | Trait, getter | Details |
|---|---|---|---|
bus-contract | The core: points, order, alter and collect, requests, local listeners, introspection, the capability lookup | Bus | this page |
bus-contract-defer | Code that cannot be re-entered (an interface drawing): requests asked now, run at the next drain | Defer, BusDefer → bus.defer() | defer |
bus-contract-timings | Finding slow listeners: times per point and per listener, budgets reported | Timings, BusTimings → bus.timings() | timings |
bus-contract-journal | Publishers that must not wait: numbered events, read again, delivered off the publisher (facet JOURNALED) | Journal, BusJournal → bus.journal() | journal |
bus-contract-crossing | One bus over several processes: what crosses, with origin and authorities (requires the journal; facets relayable_event, relayable_request) | Relay, BusCrossing → bus.relay() | relay, crossing |
Bus is an object-safe trait (Arc<dyn Bus>). The core also gives
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, so an
implementation writes only those; listeners with an owner (forget
removes them all), unlisten, failure sinks and introspection; a
contract table (PointDecl, a const declared with declare_all); and
tools on it: order_dump and missing_targets (an ordering constraint
naming a listener that is not there). No dependencies, no unsafe, no
async runtime.
Upgrading from 0.4: MIGRATION-0.5.md.
§Rules, one page each
- Naming points:
ids are
<crate>.<subject>.<moment>, so libraries sharing a bus cannot collide; a badPointIdin aconstis a compile error. - Local listeners:
listen_local::<P>for state that is notSend, bound to its thread, ordered with the others; an emit from another thread queues it for that thread’srun_pending(). - Refusals:
a listener of a request returns
HookError::refuse(reason)and the request stops there; a point declaredfail_closedturns a listener failure into a refusal. - Capabilities:
needing one (
needs, facets: if you mark a pointJOURNALED, the bus must provideJournal, ordeclare_allrefuses it), doing without one, and offering one from an implementation. - Crossing: what may cross a process boundary and what it means: deadlines that fail closed, vetoes with their reason, asks answered once, origin, authorities.
- Journal and Relay: how to publish, read again and relay events, and why they are shaped this way.
§Stability: 1.x
bus-contract follows Semantic Versioning. From
1.0 on, no 1.x release breaks code that compiled against an earlier
1.x, on either side of the contract:
- Libraries and applications (the callers): every public item
(traits, types, functions, macros, constants) keeps its name, its
path and its signature; the typed calls on
dyn Busstay. - Implementations of
Bus: a method added toBusin 1.x comes with a default body, so an existing implementation keeps compiling; the required methods do not change. - Behaviour: each property of GUARANTEES.md keeps its id and its meaning. A 1.x release may add properties; it never weakens one, and never reuses an id for something else.
- Point and listener ids: an id the 1.0 rules accept stays valid.
- No dependencies, no
unsafe: both stay for all of 1.x.
What 1.x does not promise:
- Raising the MSRV (1.95 today) is a minor release, never a patch.
- Enums marked
#[non_exhaustive](such asIdError) may gain variants in a minor release. - Text meant for people may change in any release:
DisplayandDebugoutput, error messages, the format oforder_dump. - The capability crates (
bus-contract-defer,-timings,-journal,-crossing) are versioned on their own and are not covered by this promise; each says its own status in its README.
A change that would break any of the above waits for 2.0, with a migration guide like MIGRATION-0.5.md.
§Not included
- Transport across processes: a relay reads, takes in and answers; a bridge moves the text (framing, wire format, sockets, reconnection, discovery, back-pressure).
§License
MIT OR Apache-2.0, at your option.
Modules§
- guarantees
- What an implementation guarantees and what it does not, contract by contract, each property with a stable id and the conformance check that proves it. Documentation only: this module has no items.
Structs§
- Altered
- The result of an
alteremit. - Collected
- The result of a
collectemit. - Contract
- A capability contract a bus may offer: its name, its version line and
the trait object type a bus answers for in
Bus::capability. Each contract crate exports one asCONTRACT(bus_contract_journal::CONTRACT); a point names those it needs in its table (PointDecl::needs) anddeclare_allrefuses it on a bus without them. - Facet
- What a point’s declaration says for one capability contract: the
contract, and data only that contract’s crate reads (a journaled
mark, a codec). Made by the contract crate, in a
const(bus_contract_journal::JOURNALED,bus_contract_crossing::relayable(&CODEC)), and carried byPointDecl::facetsandPointSpec::facets. A point with a facet needs its contract. - 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
Id - A listener’s id, checked when made against the naming rule
(
check_id):<crate>.<what>(docs.autosave), so the order dump of a point shows who each listener belongs to. - 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 (the defer contract’s 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. - PointId
- A point’s id (
Point::ID), checked when made against the naming rule (check_id):<crate>.<subject>.<moment>. - 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.
- Provided
- A capability found on a bus (
Bus::capability): the bus asAnyand the cast from it to the capability’s trait.capabilityturns it into&C. - 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§
- 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. - IdError
- Why an id was refused (
check_id). - 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
bus-kernel’sKernel) and hands it to each library at construction; a library never constructs the bus it publishes on. - 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§
- capability
- The capability
Cofbus, a trait object type such asdyn Journal: whatBus::capabilityanswers forTypeId::of::<C>(), cast toC.Nonewhen the bus does not offer it through the lookup. - check_
id - Checks
idagainst the naming rule of point and listener ids,<crate>.<subject>.<moment>(the README’s “Naming points”): - clone_
value - Copies an erased value of type
V: theCloneFnof a point whose value isV. Panics when the value is another type (a defect of the implementation). - declare_
all - Declares every point of a library’s contract table on
bus; the refusals, in table order, each point refused left undeclared: - erase
- Erases a typed listener of
P. - erase_
local - Erases a typed local listener of
P. - fresh_
value - A fresh erased value of type
V: theFreshFnof a point whose value isV. - missing_
targets - The ordering constraints of
pointsthat name a listener not there:point: listener -> target. A test ends with none. - offers
- Whether
busofferscontract: it answers the lookup for the contract’s type (Bus::capability), and offers every contract it requires. - 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. - Cast
- The cast a bus gives for the capability
C(Provided::new): from the bus asAnytoC. A plain function, usually astatic, that downcasts to the implementation’s type and coerces. - 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.