The hook kernel
The contract of the family “Hook kernel”
(ADR 0027): egui-pop-hooks, a small
crate without egui that re-exports bus-kernel,
an implementation of the bus contract
(bus-contract, no
dependencies of its own), for named points where
several parts of a program contribute to one result, in an order they
declare, and where one failing contribution never breaks the others.
Its README has the full examples; this page is its contract.
It is not the application API’s alter hooks and steps
(egui_pop_api::hooks, egui_pop_api::steps, ADR 0011), which are
tied to App: the kernel works in any Rust program, the interface
thread or not. Applications use it for their own extension points.
ADR 0029 makes it part of egui-pop’s own
central bus: the steps (requests), the journal (events) and this kernel
for the listeners of each, named and run in the order they declare, the
window lifecycle first. egui-pop-api depends on it: each application
holds a kernel (AppHandle::bus) where the window points
(egui_pop_api::bus) and their listeners live. The kernel itself stays
no bus: it carries nothing and keeps no record. That ADR added one
constraint to it, “last” (an invariants listener after every other of
its point).
ADR 0030 makes the bus a contract
the application supplies: the traits and types live in the external
bus-contract crate (re-exported here), and Kernel is its default
implementation, the one egui-pop-api builds when the application gives
it no bus (AppBuilder::bus). A library never constructs a kernel
(cargo xtask bus --check); an application may, or write its own
implementation of bus_contract::Bus.
Owns: typed hook points, listeners with ids ordered by
after/before and priority, alter and collect emits, a
per-listener error boundary (errors, caught panics, deadlines), failure
sinks, introspection.
Refuses: UI of any kind; event buses, and anything across processes (a listener answering from another process is the caller’s transport, given a longer deadline).
The API
use egui_pop_hooks::{Kernel, ListenOpts, Point, PointId, PointSpec};
/// The findings of a health report: each check adds its own.
struct HealthReport;
impl Point for HealthReport {
const ID: PointId = PointId::new("health.report");
type Input = ();
type Value = Vec<String>;
}
let kernel = Kernel::new();
kernel.declare::<HealthReport>(PointSpec::new("The findings of the health report")).unwrap();
kernel
.listen::<HealthReport>("storage.free-space", ListenOpts::new().owner("storage"), |_, out| {
out.push("disk 91% full".into());
Ok(())
})
.unwrap();
let report = kernel.collect::<HealthReport>(());
assert!(report.failures.is_empty());
- A point is a type (
bus_kernel::Point): its id, theInputevery listener reads, theValuea listener edits. Declaring it (Kernel::declare, with aPointSpec) is optional and adds a description and a deadline for introspection. - Ids are checked (bus-contract 0.5 and later): a point id is a
PointId, checked when made, so a bad one in aconstdoes not compile; a listener id breaking the same rule (<prefix>.<segment>…, the first segment[a-z][a-z0-9_-]*) is refused withRefused::BadIdand nothing is registered. - Listeners (
Kernel::listen) have ids, unique per point. They run ordered byafter/before, then by priority (higher first), then by registration order: the same listeners always run in the same order.ListenOpts::lastruns one after every other listener of its point (itsafterholdsbus_kernel::LAST); a second one on a point closes a cycle and is refused.Kernel::unlistenremoves one,Kernel::forgetevery listener of an owner. alterpasses one value through the listeners in order (Altered: the value and the failures);collectgives each listener a fresh value and gathers each successful part with its listener’s id (Collected).- Introspection:
Kernel::pointsandKernel::listenerslist the points, their listeners in run order, owners, constraints, deadlines, missing targets and counters (runs, failures, the last failure).
Failure behaviour
-
Registration refusals (
Refused) change nothing: a duplicate id, an ordering cycle (named with the listeners in it), a point id registered with another type, a point declared twice. -
Per listener: an edit counts only when the listener returns
Ok, without panicking (panics are caught), within its deadline. Otherwise the edit is dropped, the other listeners still run, and the emit returns aFailure(FailureKind::Error,Panic,Late). -
Deadlines: one second by default (
bus_kernel::DEFAULT_DEADLINE), set per point and per listener (PLUGIN_DEADLINE, five seconds, for listeners answering from another process); a listener’s own deadline wins over its point’s, which wins over the kernel’s. An inline listener runs on the emitting thread and counts as late once it returns; athreadedone runs on a thread of its own and the emit stops waiting at the deadline. -
A missing
after/beforetarget is reported (FailureKind::MissingTarget) and ignored; the listener’s part still counts. It is not sent to the sinks. -
An emit on a point registered with another type runs no listener and reports
FailureKind::TypeMismatch. -
Sinks (
Kernel::on_failure) receive each dropped contribution as it happens; a host publishes them as ahook.failedfact (bus_kernel::FAILED_FACT) or logs them. -
Listeners may call the kernel again (re-entry), and emits may come from several threads: the kernel is
Send + Sync. -
Local listeners (
listen_local::<P>) hold state that is notSend(an interface’sRc<RefCell<…>>). Each is bound to the thread that registered it and takes its place in the same order as the others. An emit on that thread runs it inline; an emit from another thread runs the others, queues it (Altered::deferred,Collected::deferred) and calls theon_pendingwakers; the thread runs the queue in order withrun_pending(). egui-pop’s application callsAppHandle::run_pendingonce per pass, before theOn::Passhandlers, and asks for a pass when work is queued. -
Listeners for a window (
AppHandle::listen_local_in::<P>(window, …)): a local listener registered for an application window wakes that window each time it runs, inline or from the queue, so what it changed is drawn there within one frame without a hand-writtenrequest_repaint_of. The main window is still woken to run the queue and the asks; the window’s wake comes in addition. A window drawn in the main one (the main window, a detached panel’s, every window where they are embedded: the web, kittest) or no longer open wakes the main window.AppHandle::wake_windowasks a window’s pass the same way. -
Requests heard after the drawing (the contract’s
Defercapability, which the kernel offers): code that cannot be re-entered while it draws (a panel with its state borrowed) asks a request withAppHandle::ask::<P>(orbus.defer()?.ask::<P>); it returns at once and the listeners run at the thread’s next drain. egui-pop’s application drains (AppHandle::drain_asks) once per pass, after the main window’s panels, its detached panels’ windows and its zones are drawn, so an ask made while drawing is heard in the same pass; and before it quits (App::exit: before theon_exitfunctions, and after them for what they asked), so no ask is lost. An ask made by a listener during a drain waits for the next one. A drain that ran something asks for a pass. An application window (a deferred viewport) is drawn on the same thread after the main window: its asks wait in the same queue, and the main window’s next pass is asked for.AppHandle::asks_waitingcounts what waits; on a bus withoutDefer,askanswersNoneand the caller asks at once or keeps its own queue. -
Listener times and budgets (the contract’s
Timingscapability, which the kernel offers): every listener run is timed (the two clock reads the deadlines already make, then a few relaxed atomic adds into a log histogram of √2 steps), per listener and per pass. A pass is what one emit’s listeners ran on one thread (an inline emit, a queued run, a drained ask).bus.timings()?.points()gives count, total, max, p50 and p95 (within a bucket) andPointTimings::slowest;reset()starts a new window;Kernel::set_timing(false)stops counting. A point may declare a budget for a pass (PointDecl::budget); a pass over it goes to theon_over_budgetsinks and its results are kept: a budget is not a deadline. egui-pop’s application says it as thebus.overBudgetfact (point,took_us,budget_us, each listener’s time,slowest, andunsaid: the passes over budget not said since) and one warning in the log, at most once a minute per point. The debug collectorbusshows each point’s budget and passes, each listener’s runs, andslowestacross points. -
A journal and a relay from the host (the contract’s
JournalandRelaycapabilities, which the kernel delegates): a host that runs a fact bus (entries numbered, read again from a number, relayed between processes) hands it to the kernel withKernel::with_journalandKernel::with_relay;bus.journal()andbus.relay()(theBusJournalandBusCrossingextension traits ofbus-contract-journalandbus-contract-crossing) then answer, and points may be declared journaled (.facets(&[JOURNALED])) or relayable (.facets(&[relayable_event::<P>()])). Without them such points are refused (Refused::Unsupported), bydeclare_alland byKernel::declare_pointalike, and a relay with no journal is not offered. The kernel checks each publish itself: a point it does not hold declared journaled, or under another type, is refused (the journal contract’sRefused::Contract,Refused::TypeMismatch) before the host sees it. The host keeps the entries and runs the pump: each entry of a journaled point is delivered by a collect emit on the kernel (Bus::collect_any) from the pump’s thread, never the publisher’s, in number order; every rule of an emit holds (order, deadlines, failures, local listeners queued for their thread’srun_pending). The host reads a point’s declaration (its journaled flag, its codec) withKernel::declaration. A host journal that needs the kernel to deliver is built withArc::new_cyclic, holding aWeakof the kernel:let kernel = Arc::new_cyclic(|me: &Weak<Kernel>| { let host = Arc::new(MyJournal::new(me.clone())); Kernel::new().with_journal(host.clone()).with_relay(host) });Given to the application (
AppBuilder::bus), it is the busAppHandle::busreturns. The debug collectorbusshows each point’sjournaledandrelayable, the bus’scapabilitiesand itsjournal_seq. -
One journal per process (ADR 0030, slice 3): when the application’s bus offers the
Journalcapability, egui-pop’s own journal (AppHandle::publish,AppHandle::events_since,AppHandle::last_event, so the agents’wait, the debug bridge’sjournalreads, the jobs’job.*events, the links’link.*and the agent sessions’agent.*) is that journal, unless the host keeps a journal of its own (Host::last_seqanswers): the default host then keeps none. egui-pop declares one journaled point for it,pop.journal(bus::HOST_JOURNAL, kept out ofCONTRACTsince a bus without a journal refuses it); each event it publishes is an entry of that point, its input abus::HostEvent(source, name, data), its number and cause the entry’s. Read back throughAppHandle::events_since, an egui-pop entry keeps its name (command.done); any other entry, a fact of the application’s, is an event named by its point (library.imported), its source the process it was relayed from orbus, its data its text read as JSON (null when the entry holds its input only typed). What changes for awaiton such a bus:- numbers are the process journal’s: egui-pop’s events and the
application’s facts share them, so two egui-pop events in a row may
be numbers apart, and
last(the nextsince) counts the facts too; { "event": <name> }matches an application fact by its point’s id as well as egui-pop’s events by name;- the window is the bus journal’s (an application’s, sized for its facts too), not egui-pop’s 1024 events: an agent that falls behind it misses entries as before, sooner when facts are many.
Without a journal on the bus, or with a host keeping its own, nothing changes: egui-pop’s in-memory journal, or the host’s.
- numbers are the process journal’s: egui-pop’s events and the
application’s facts share them, so two egui-pop events in a row may
be numbers apart, and
-
Names: several libraries share one bus, so a point’s id starts with the prefix of the crate declaring it (bus-contract’s “Naming points”:
<crate>.<subject>.<moment>). egui-pop’s prefix ispop.: every point it declares (pop.window.close,pop.command.run,pop.layout.changed…) and every listener it registers (pop.window.registry,pop.jobs.model…) carries it; egui_stack’s arestack.*. A test fails on an egui-pop point or listener without it. An application names its own points and listeners under its own prefix, neverpop.. -
Refusals and fail-closed points: a listener on a request returns
HookError::refuse(reason)and the request stops there; on a point declaredfail_closed, a listener’s error, panic or missed deadline refuses it too. egui-pop’spop.command.run(bus::CommandRun) is such a point: every command run (a key, the palette, a menu, a toolbar, an agent) is asked on it before its handler; a refusal stops the run, which never reaches the host, and is journaled ascommand.refusedwithby(the listener),reasonandfailed. With nobody listening, commands run as before. A run whose arguments do not match its command’s JSON Schema is refused before the point is asked (by: "pop.command.args",bus::ARGS_VALIDATOR). -
A command’s live text:
pop.command.label(bus::CommandLabel, an alter point egui-pop does not answer itself) asks the application for a command’s title and tooltip (bus::CommandText) each time a menu item, a toolbar button, the menu bar’s end or a layout control naming it is drawn: “Zen: Compare” for the panel zen would show.AppHandle::command_titleandAppHandle::command_tooltipread it; with nobody answering, the declared title and description are shown.
Accessibility
None: the kernel has no UI. What a host builds from its results (a health report, a menu) follows the rules of the family that draws it.
Tier
From API stability: Experimental (“The hook kernel
(egui-pop-hooks): new; its API may move while the first applications
move their extension points onto it”). The kernel itself is the
bus-kernel crate, which
egui-pop-hooks re-exports.
Tests
The kernel’s own tests live in bus-kernel (its tests/kernel.rs,
tests/journal.rs, tests/timings.rs, and its conformance suite run on
itself). tests/kernel.rs there: ordering by constraints,
priority and registration; cycles refused; missing targets; duplicate
ids and mismatched types; alter keeping only successful edits;
collect in order; inline and threaded deadlines and their resolution;
sinks; introspection; forget and unlisten; re-entry and emits across
threads; local listeners in order, deferred from another thread, removed
from any thread. tests/journal.rs there: journaled
and relayable points refused without a host journal or relay, shown by
introspection; with an in-memory host journal, entries delivered once
in order off the publisher’s thread, local listeners at their thread’s
run_pending, a slow listener not holding the publisher, publishes on
other points refused by the kernel, and a relay’s resume and ingest
between two kernels (a restart and refusals included).
crates/egui-pop-api/tests/it/host_journal.rs: egui-pop’s journal on a
bus offering one, its events and the application’s facts in one
sequence with no hole, a wait (in-process and through the bridge)
returning the command.done entry among facts, a host keeping its own
journal and a bus without one unchanged; and bus-kernel’s conformance
suite on egui-pop’s application bus, bare and with a journal and relay.
crates/egui-pop-api/tests/it/bus_defer.rs: an ask made in a panel heard after
it in the same pass, asks made before and during exit heard, a palette
command refused by a pop.command.run listener, a failing listener refusing
on the fail-closed point. crates/egui-pop-api/tests/it/app_bus.rs: a local listener
on pop.window.close in its place, and run at the next pass when the
request comes from a worker, and a host’s journal reachable from
AppHandle::bus and shown by the bus collector. The README’s examples run as doc tests.