Skip to main content

Crate bus_contract

Crate bus_contract 

Source
Expand description

§bus-contract

github Latest version Documentation Build Status MSRV 1.95 no unsafe no dependencies MIT Apache

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.

CrateWhat forTrait, getterDetails
bus-contractThe core: points, order, alter and collect, requests, local listeners, introspection, the capability lookupBusthis page
bus-contract-deferCode that cannot be re-entered (an interface drawing): requests asked now, run at the next drainDefer, BusDefer → bus.defer()defer
bus-contract-timingsFinding slow listeners: times per point and per listener, budgets reportedTimings, BusTimings → bus.timings()timings
bus-contract-journalPublishers that must not wait: numbered events, read again, delivered off the publisher (facet JOURNALED)Journal, BusJournal → bus.journal()journal
bus-contract-crossingOne 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 bad PointId in a const is a compile error.
  • Local listeners: listen_local::<P> for state that is not Send, bound to its thread, ordered with the others; an emit from another thread queues it for that thread’s run_pending().
  • Refusals: a listener of a request returns HookError::refuse(reason) and the request stops there; a point declared fail_closed turns a listener failure into a refusal.
  • Capabilities: needing one (needs, facets: if you mark a point JOURNALED, the bus must provide Journal, or declare_all refuses 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 Bus stay.
  • Implementations of Bus: a method added to Bus in 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 as IdError) may gain variants in a minor release.
  • Text meant for people may change in any release: Display and Debug output, error messages, the format of order_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 alter emit.
Collected
The result of a collect emit.
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 as CONTRACT (bus_contract_journal::CONTRACT); a point names those it needs in its table (PointDecl::needs) and declare_all refuses 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 by PointDecl::facets and PointSpec::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).
ListenOpts
How a listener is placed and limited.
ListenerId
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.
ListenerInfo
A listener as introspection shows it.
PendingRun
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).
PointDecl
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_all declares a table on a bus.
PointId
A point’s id (Point::ID), checked when made against the naming rule (check_id): <crate>.<subject>.<moment>.
PointInfo
A point as introspection shows it.
PointKey
A point as the erased methods of Bus name it: its id, its kind and its type, so an implementation refuses one id registered with two types.
PointSpec
A point’s declaration: its description and limits, for introspection.
Provided
A capability found on a bus (Bus::capability): the bus as Any and the cast from it to the capability’s trait. capability turns 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§

FailureKind
What went wrong with one listener during an emit.
HookError
What a listener returns instead of Ok(()): it failed, or it refuses the request.
IdError
Why an id was refused (check_id).
PointKind
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 Failure its sinks receive (Bus::add_failure_sink).
LAST
The after target that places a listener after every other listener of its point (ListenOpts::last): one per point, a second is refused as a Refused::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::deadline or PointSpec::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’s Kernel) 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 C of bus, a trait object type such as dyn Journal: what Bus::capability answers for TypeId::of::<C>(), cast to C. None when the bus does not offer it through the lookup.
check_id
Checks id against 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: the CloneFn of a point whose value is V. 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: the FreshFn of a point whose value is V.
missing_targets
The ordering constraints of points that name a listener not there: point: listener -> target. A test ends with none.
offers
Whether bus offers contract: it answers the lookup for the contract’s type (Bus::capability), and offers every contract it requires.
order_dump
The order the listeners of points run 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.
AnyLocalListener
A local listener, its types erased: like AnyListener, but neither Send nor Sync. 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 as Any to C. A plain function, usually a static, 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).
FailureSink
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).
PendingWaker
Called when local work is queued for a thread (Bus::add_pending_waker), with that thread’s id, on the emitting thread.