ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Protocols

Integrations

Operating

Reference

API ReferenceCrate mapMacrosHandler attributesCore typesErrors and diagnosticsFeatures and environment
API Reference

Core types

The types of the ulo crate an application names, with their signatures and when to use each.

Signatures are copied from crates/ulo/src. Each type is re-exported at the crate root, so use ulo::{App, Dep, Many} is the import. Nothing here needs a runtime crate: the core uses std::future, a BoxFuture alias and the pluggable Timer, Spawn and Runtime traits.

The application

An application moves through typestates. Each step consumes the previous value and returns the next, so calling serve on an app that was never bound does not compile.

App::builder(root) -> AppBuilder
  .wire()    -> App<Wired>      graph built and validated; no instances, no I/O
  .connect() -> App<Connected>  singletons built, readiness checks passed, init and bootstrap hooks run
  .bind(s)   -> App<Connected>  a transport queued
  .listen()  -> App<Bound>      every queued transport prepared and bound
  .serve(signal) -> Shutdown    until the signal, a close, or a transport ending

The sequence as main writes it, from examples/01-hello:

let app = ex_01_hello::builder()
    .runtime(Tokio::current())
    .wire()?
    .connect()
    .await?
    .bind(Server::new(format!("127.0.0.1:{port}")))
    .listen()
    .await?;
for bound in app.addresses() {
    println!("listening on http://{}", bound.addr);
}
app.serve(shutdown_signal()).await?;

A job, a CLI command or a test stops after connect(), reads with get or execute, and ends with close.

App

pub struct App<S = Wired> { /* .. */ }

pub enum Wired {}
pub enum Connected {}
pub enum Bound {}

impl App {
    pub fn builder(root: impl Module) -> AppBuilder;
}

App<S> holds the validated graph and the singleton store. Keep the App value, or the future serving it, alive for as long as the app serves. An AppHandle is a view without ownership, and dropping the App ends the app. Dropping an app that was bound but never served releases its servers without running their close.

Methods by state:

StateMethods
App<Wired>connect
App<Connected>bind, listen, handle, get, module, module_keyed, module_of, execute, close
App<Bound>handle, addresses, serve
impl App<Wired> {
    pub async fn connect(self) -> Result<App<Connected>, StartupError>;
}

impl App<Connected> {
    pub fn bind(mut self, server: impl Server) -> App<Connected>;
    pub async fn listen(mut self) -> Result<App<Bound>, StartupError>;
    pub fn handle(&self) -> AppHandle;
    pub async fn get<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Dep<T>, LookupError>;
    pub fn module<M: 'static>(&self) -> Result<ModuleRef, LookupError>;
    pub fn module_keyed<M: 'static, Q: 'static>(&self) -> Result<ModuleRef, LookupError>;
    pub fn module_of<M: Module>(&self, config: &M) -> Result<ModuleRef, LookupError>;
    pub async fn execute<F, R>(&self, opts: ExecOptions, f: F) -> Result<R, Closed>
    where
        F: AsyncFnOnce(&Execution) -> R;
    pub async fn close(self, signal: Signal) -> Result<Shutdown, ShutdownError>;
}

impl App<Bound> {
    pub fn handle(&self) -> AppHandle;
    pub fn addresses(&self) -> Vec<BoundAddr>;
    pub async fn serve(self, signal: impl Future<Output = Signal> + Send) -> Result<Shutdown, ShutdownError>;
}

listen prepares every queued server first, so a configuration error is always reported before a port conflict. An app that binds a transport with no Runtime is refused before either step (StartupError::Bind carrying RuntimeMissing). serve returns when the signal resolves, when close is called on any handle, or when a transport's serve ends. The first to arrive starts the shutdown, and its Signal is the one the shutdown hooks receive. addresses reports the port the OS chose for port 0.

get and execute resolve with the root module's visibility. A binding exported only inside a subtree is reached through module::<M>().

AppBuilder

impl AppBuilder {
    pub fn timer(mut self, timer: impl Timer) -> Self;
    pub fn runtime(mut self, runtime: impl Runtime) -> Self;
    pub fn drain_timeout(mut self, d: Duration) -> Self;
    pub fn shutdown_timeout(mut self, d: Duration) -> Self;
    pub fn hook_timeout(mut self, d: Duration) -> Self;
    pub fn construct_timeout(mut self, d: Duration) -> Self;
    pub fn trace(mut self, mode: TraceMode) -> Self;
    pub fn wire(self) -> Result<App<Wired>, StartupError>;
}
MethodMeaningUnset
runtime(r)The clock and the executor. Every transport spawns its connections and calls through it. Bound for services as Dep<dyn Runtime> and Dep<dyn Timer>.none; listen() refuses an app that binds a transport
timer(t)The clock alone, enough for an app that binds no transport. After runtime(r) it replaces only the clock.none
drain_timeout(d)How long in-flight executions get to end at shutdown.10 s with a Timer; zero without
shutdown_timeout(d)A cap on the whole close sequence, from the trigger. Set it a few seconds under the orchestrator's grace period.no cap
hook_timeout(d)The Default bound of every hook.10 s
construct_timeout(d)The Default bound of every construction and of one attempt of a readiness check.30 s
trace(mode)Whether the app reads and writes W3C trace headers. TraceMode::On or TraceMode::Off.On

runtime and timer compose in call order: .timer(t).runtime(r) spawns and times on r, and .runtime(r).timer(t) spawns on r and times with t. The four timing knobs are timed by the Timer and are a wiring error on an app with none. construct_timeout and hook_timeout are refused at zero; drain_timeout and shutdown_timeout accept it.

AppHandle

A Clone + Send + Sync view of the shared state, available from Connected on. Take it before serve, which consumes the app.

impl AppHandle {
    pub async fn get<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Dep<T>, LookupError>;
    pub fn module<M: 'static>(&self) -> Result<ModuleRef, LookupError>;
    pub fn module_keyed<M: 'static, Q: 'static>(&self) -> Result<ModuleRef, LookupError>;
    pub fn module_of<M: Module>(&self, config: &M) -> Result<ModuleRef, LookupError>;
    pub async fn execute<F, R>(&self, opts: ExecOptions, f: F) -> Result<R, Closed>;
    pub fn load(&self, module: impl Module) -> impl Future<Output = Result<ModuleRef, LoadError>>;
    pub fn close(&self, signal: Signal) -> impl Future<Output = Result<Shutdown, ShutdownError>> + Send + use<>;
    pub fn draining(&self) -> Draining<'_>;
    pub fn is_draining(&self) -> bool;
    pub fn drain_timeout(&self) -> Duration;
    pub fn timer(&self) -> Option<&Arc<dyn Timer>>;
    pub fn runtime(&self) -> Option<&Arc<dyn Runtime>>;
    pub fn phase(&self) -> Phase;
}

Use it for anything that needs the app while it serves: a background loop, a request handler that loads a lazy module, a task that closes the app. A loop reads draining() to stop pulling work when the transports stop accepting, and runs each unit of work through execute so the drain waits for it. load wires a module against the frozen graph and connects it. Loading is refused with LoadError::Closed from the Stopping phase on. A module with controllers, middleware, global exports, execution inputs or contributions to a collection it does not introduce is refused with LoadError::Refused. AppHandle also carries the transport-facing methods handlers, mounted, root, redact, trace_source, trace_mode and catch_panic.

pub enum Phase {
    Running,
    Stopping,
    Draining,
    Destroying,
    Closed,
}

Phase is #[non_exhaustive] and ordered. Running is serving, or connected and not yet serving. Stopping is the before-shutdown stage, where traffic is normal and is_draining() is false. Draining runs from stop-accepting to the drain's end, and new executions are refused with Closed. Destroying runs from the first destroy hook, and singleton lookups answer LookupError::Closed. The shutdown order is: before-shutdown hooks, stop accepting, drain, destroy hooks, sockets closed, shutdown hooks.

Signal

pub struct Signal { /* .. */ }

impl Signal {
    pub fn new(name: impl Into<Cow<'static, str>>) -> Self;
    pub fn name(&self) -> &str;
}

The reason a shutdown started. ulo_runtime_tokio::shutdown_signal() resolves to one on SIGTERM or Ctrl-C. A job passes Signal::new("done") to close. Shutdown hooks receive it as &Signal.

Injection points

An injection point is its type. A field, a constructor parameter, a factory parameter, an enhancer closure parameter and a hook closure parameter all accept any type that implements FromContainer.

pub trait FromContainer: Sized + Send + 'static {
    fn describe(req: &mut Requirement);
    fn from_container(r: &Resolver<'_>) -> impl Future<Output = Result<Self, LookupError>> + Send;
}

Implement it for a type that reads the container in a way the core's types do not; ulo_ws::Session<T> is one. A type that is not FromContainer fails with `String` cannot be obtained from the container and a note to write Dep<String>.

Dep

pub struct Dep<T: ?Sized, Q = ()> { /* .. */ }

impl<T: ?Sized, Q> Dep<T, Q> {
    pub fn from_arc(inner: Arc<T>) -> Self;
    pub fn into_arc(self) -> Arc<T>;
    pub fn arc(&self) -> &Arc<T>;
}

The shared instance of the single binding T @ Q. Dep<T> derefs to T and clones the pointer. Every holder of a binding holds the same Arc, so mutation goes through interior mutability. T must be Send + Sync, and a trait read as Dep<dyn Repo> needs Send + Sync as supertraits of Repo. Use it for every ordinary dependency.

Many

pub struct Many<T: ?Sized, Q = ()> { /* .. */ }

impl<T: ?Sized, Q> Many<T, Q> {
    pub fn iter(&self) -> std::slice::Iter<'_, Arc<T>>;
}

Every contribution to the collection T @ Q, gathered from every module in the application, in collection order. Collection order is depth-first post-order over imports from the root, imports in the order written, then declaration order inside a module. Many<T> is eager: reading it constructs every contribution. A transport reads a role collection lazily through Resolver::entries. Use it for plugins, health indicators and global enhancers.

Ext

pub struct Ext<T>(Arc<T>);

A typed view of per-execution data: the extension of type T that a guard or other code wrote with exec.extensions().insert(..). It needs an execution, so a type declared singleton cannot hold one. Wrap it in Option where the extension may not have been written.

Option

Option<S> is None exactly when S would fail with LookupError::NotFound: a key no module binds, an extension no guard wrote, an input this execution was not seeded with. Every other error propagates: a construction failure, ExecutionRequired, an ambiguous key. From examples/04-collections-and-optional:

#[injectable]
pub struct Host {
    pub plugins: Many<dyn Plugin>,
    pub audit: Option<Dep<AuditLog>>,
    pub mailer: Option<Dep<dyn Mailer>>,
}

ModuleRef and ExecutionRef

ModuleRef is a handle to a module; as an injection point it is the enclosing module. ExecutionRef is a cheap-clone handle to the current execution and needs one. Both are described under Modules and Executions below.

Requirement and Dependencies

impl Requirement {
    pub fn dep(&mut self, key: Key);
    pub fn many(&mut self, key: Key);
    pub fn ext<T: 'static>(&mut self);
    pub fn execution(&mut self);
    pub fn module(&mut self);
    pub fn optional<S: FromContainer>(&mut self);
}

impl Dependencies {
    pub fn field<S: FromContainer>(&mut self, name: &'static str) -> &mut Self;
    pub fn param<S: FromContainer>(&mut self, name: &'static str) -> &mut Self;
    pub fn add<S: FromContainer>(&mut self) -> &mut Self;
    pub fn mark<C: Controller>(&mut self) -> &mut Self;
}

What the wiring pass reads. Requirement is filled by FromContainer::describe. Dependencies is the declared injection points of a binding or a closure. field and param carry a name for diagnostics. A hand-written Construct states its reads here and again in construct, and the first construction refuses a read the declaration omits. mark::<Self>() records that the type is a controller, so wire() refuses it as a provider even where the graph never registers it as a controller (WiringError::ControllerProvided). The method is bounded on Controller, so it does not compile on a type that is not one.

Resolver

impl Resolver<'_> {
    pub async fn dep<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Dep<T>, LookupError>;
    pub async fn dep_qualified<T: ?Sized + Send + Sync + 'static, Q: 'static>(&self) -> Result<Dep<T, Q>, LookupError>;
    pub async fn many<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Many<T>, LookupError>;
    pub async fn many_qualified<T: ?Sized + Send + Sync + 'static, Q: 'static>(&self) -> Result<Many<T, Q>, LookupError>;
    pub fn entries<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Entries<'_, T>, LookupError>;
    pub fn ext<T: Send + Sync + 'static>(&self) -> Result<Ext<T>, LookupError>;
    pub fn input<T: Send + Sync + 'static>(&self) -> Result<Dep<T>, LookupError>;
    pub fn module(&self) -> ModuleRef;
    pub fn execution(&self) -> Result<ExecutionRef, LookupError>;
    pub async fn by_key<T: ?Sized + Send + Sync + 'static>(&self, key: Key) -> Result<Arc<T>, LookupError>;
}

The hand-written way to read the container, handed to Construct::construct and FromContainer::from_container. The qualified form is a second method because a function's type parameters take no defaults.

Keys and qualifiers

pub struct Key { /* .. */ }

impl Key {
    pub fn of<T: ?Sized + 'static, Q: 'static>() -> Key;
    pub fn type_name(&self) -> TypeName;
}

impl TypeName {
    pub fn of<T: ?Sized + 'static>() -> TypeName;
}

A key is the pair of a type and a qualifier, Key::of::<PgPool, Replica>(). The qualifier defaults to (). Identity is by TypeId, so a type alias or a renamed import names the same binding. Reports print PgPool and PgPool @ Replica, with full paths where two different types would print alike.

A qualifier is any 'static type, usually a unit struct: pub struct Replica;. There are no strings to misspell. Bind under one with Type @ Q in #[module] or .qualified::<Q>() on a binding handle; read it with Dep<T, Q> or Many<T, Q>; export it with exports = [Db @ Primary]. A bare exports = [Db] names Db @ () and is ExportNotBound beside a binding that is only Db @ Primary. A trait object's Send + Sync marker is part of the type: dyn Repo and dyn Repo + Send + Sync are different keys, and the missing-dependency report names both spellings.

Scopes

pub mod scope {
    pub struct Singleton;
    pub struct PerExecution;
    pub struct Transient;
    pub struct Auto;
}

pub trait Scope: sealed::Sealed + 'static {
    const KIND: ScopeKind;
}

pub trait HookCapable: Scope {}
pub trait AllowedIn<S: Scope> {}
ScopeLifetime
SingletonBuilt once during connect, in dependency order.
PerExecutionBuilt once per execution and shared inside it.
TransientBuilt fresh at every injection point.
AutoWhat #[injectable] and #[controller] mean with no scope written. A provider is a singleton. A controller or enhancer is a singleton unless something below it needs an execution, then per execution.

HookCapable is implemented for Singleton and Auto, so a hook on an explicit execution-scoped or transient type is a compile error. AllowedIn<S> is what refuses Ext and ExecutionRef in an explicit singleton. An explicit singleton that needs an execution, and an Auto provider that does, are refused at wire(). Inference reads only what a closure takes. A closure that creates per-call state but reads nothing is written with(execution). See Scopes.

Construct and lifecycle hooks

pub trait Construct: Sized + Send + Sync + 'static {
    type Scope: Scope;
    const CONSTRUCT_TIMEOUT: Bound = Bound::Default;
    fn dependencies(d: &mut Dependencies);
    fn construct(r: &Resolver<'_>) -> impl Future<Output = Result<Self, ConstructError>> + Send;
    fn hooks(_h: &mut Hooks<Self>) {}
}

How the container builds a type. #[injectable] and #[controller] write it. Implement it by hand for a type the macro cannot express. A hand-written construct returns ConstructError::from(lookup_error) through ? on a dependency read, and .map_err(ConstructError::failed)? for its own errors.

pub trait OnModuleInit: Construct<Scope: HookCapable> {
    const TIMEOUT: Bound = Bound::Default;
    fn on_module_init(&self) -> impl Future<Output = Result<(), BoxError>> + Send;
}
pub trait OnApplicationBootstrap: Construct<Scope: HookCapable> {
    const TIMEOUT: Bound = Bound::Default;
    fn on_application_bootstrap(&self) -> impl Future<Output = Result<(), BoxError>> + Send;
}
pub trait OnModuleDestroy: Construct<Scope: HookCapable> {
    const TIMEOUT: Bound = Bound::Default;
    fn on_module_destroy(&self) -> impl Future<Output = ()> + Send;
}
pub trait BeforeApplicationShutdown: Construct<Scope: HookCapable> {
    const TIMEOUT: Bound = Bound::Default;
    fn before_application_shutdown(&self, signal: &Signal) -> impl Future<Output = ()> + Send;
}
pub trait OnApplicationShutdown: Construct<Scope: HookCapable> {
    const TIMEOUT: Bound = Bound::Default;
    fn on_application_shutdown(&self, signal: &Signal) -> impl Future<Output = ()> + Send;
}

The five hooks, in the order they run. connect builds the singletons in dependency order, running each binding's readiness check right after it, then every OnModuleInit hook, then every OnApplicationBootstrap hook. Shutdown runs BeforeApplicationShutdown while the app still serves, then stops accepting and drains, then OnModuleDestroy, then closes the sockets, then OnApplicationShutdown, all in reverse connect order. TIMEOUT is per trait, so a type implementing two hooks bounds each separately. Default is the app's hook_timeout. A hook that returns Err during connect fails the start as StartupError::Connect. A failing shutdown step is recorded and never stops the sequence.

From examples/09-lifecycle:

impl OnModuleInit for Cache {
    async fn on_module_init(&self) -> Result<(), BoxError> {
        self.journal.push("Cache init");
        Ok(())
    }
}

impl OnApplicationShutdown for Cache {
    async fn on_application_shutdown(&self, signal: &Signal) {
        self.journal.push(format!("Cache shutdown ({signal})"));
    }
}

#[injectable] and #[controller] register whichever hook traits a type implements. A hand-written Construct::hooks calls h.on_module_init() and kin on Hooks<T>, each of which compiles only where T implements the trait, or ulo::hooks!(h) to probe all five. Hooks run on types the container constructs. A factory's output is a plain value, so its hooks are closures on the binding handle (below).

pub enum HookKind {
    OnModuleInit,
    OnApplicationBootstrap,
    OnModuleDestroy,
    BeforeApplicationShutdown,
    OnApplicationShutdown,
}

Bound

pub enum Bound {
    Default,
    After(Duration),
    Unbounded,
}

How long a hook, a construction or a readiness check may take. Default takes the app's default for that kind of item, and only when a Timer is configured. After(d) is explicit and needs a Timer. Unbounded needs none. The outer shutdown_timeout still contains it. After(Duration::ZERO) is refused as ZeroBound.

Modules

pub trait Module: Send + Sync + 'static {
    fn identity(&self) -> ModuleIdentity;
    fn register(&self, m: &mut ModuleDef<'_>);
    fn settings(&self) -> ModuleSettings { ModuleSettings::new() }
    fn keyed<Q: 'static>(self) -> Keyed<Q, Self> where Self: Sized;
}

identity is the module's TypeId, plus its configuration value if it has one, plus a qualifier if it is keyed. Two configurations of one type are two modules; the same configuration imported twice is one. register is synchronous, free of I/O and never returns early. A value that may fail goes through m.try_value(result), which wire() reports beside every other error. settings names what the module is configured with outside its identity, such as a connect bound, so that a second import of an equal identity with other settings is refused as DifferingSettings.

impl ModuleIdentity {
    pub fn of_type<M: 'static>() -> Self;
    pub fn of_value<M: Eq + Hash + Clone + Send + Sync + 'static>(m: &M) -> Self;
    pub fn of_owner<O: 'static, C: Eq + Hash + Clone + Send + Sync + 'static>(config: &C) -> Self;
    pub fn label(self, name: &'static str) -> Self;
}

impl ModuleSettings {
    pub fn new() -> Self;
    pub fn with(mut self, name: &'static str, value: impl fmt::Debug) -> Self;
}

#[module] writes Module for a struct. Implement it by hand for a readiness check, a closure hook, a qualified closure binding, the enhancer mark or module metadata, which #[module] has no spelling for. The configuration's Debug output is never printed because it may hold credentials. A setting name written twice in one module's settings is refused as DuplicateSetting.

ModuleDef

The registration API register receives and the macros lower to.

impl ModuleDef<'_> {
    pub fn import<M: Module>(&mut self, module: M);
    pub fn global(&mut self);
    pub fn export<T: ?Sized + 'static>(&mut self);
    pub fn export_qualified<T: ?Sized + 'static, Q: 'static>(&mut self);
    pub fn reexport<T: ?Sized + 'static>(&mut self);
    pub fn reexport_qualified<T: ?Sized + 'static, Q: 'static>(&mut self);
    pub fn secret<T: fmt::Display>(&mut self, secret: &Secret<T>);
    pub fn meta<T: Meta>(&mut self) -> &mut T;
    pub fn provide<T: Construct>(&mut self) -> Handle<'_, T, Binding<T::Scope, Set>>;
    pub fn value<T: Send + Sync + 'static>(&mut self, value: T) -> Handle<'_, T, Binding<Singleton, Set>>;
    pub fn try_value<T, E>(&mut self, value: Result<T, E>) -> Handle<'_, T, Binding<Singleton, Set>>;
    pub fn with<Args, F>(&mut self, factory: F) -> Handle<'_, F::Output, Binding<Auto, Open>>;
    pub fn singleton<Args, F>(&mut self, factory: F) -> Handle<'_, F::Output, Binding<Singleton, Open>>;
    pub fn execution<Args, F>(&mut self, factory: F) -> Handle<'_, F::Output, Binding<PerExecution, Open>>;
    pub fn transient<Args, F>(&mut self, factory: F) -> Handle<'_, F::Output, Binding<Transient, Open>>;
    pub fn contribute<U: ?Sized + Send + Sync + 'static>(&mut self) -> Contribute<'_, U>;
    pub fn enhancer<R: Role + ?Sized>(&mut self) -> Contribute<'_, R, (), Enhancer>;
    pub fn alias<T: ?Sized + Send + Sync + 'static, Q: 'static>(&mut self) -> Alias<'_, T, Q>;
    pub fn input<T: Send + Sync + 'static>(&mut self) -> Input<'_, T>;
    pub fn controller<C: Handlers>(&mut self) -> ControllerHandle<'_>;
    pub fn on_init<Args, F, E>(&mut self, hook: F) -> ModuleHook<'_>;
    pub fn on_destroy<Args, F>(&mut self, hook: F) -> ModuleHook<'_>;
    pub fn before_shutdown<Args, F>(&mut self, hook: F) -> ModuleHook<'_>;
    pub fn on_shutdown<Args, F>(&mut self, hook: F) -> ModuleHook<'_>;
}

Bounds on F elided. try_ forms exist for with, singleton, execution, transient and provide_with. Each scope has a plain and a fallible method because one method cannot serve both outputs. A factory's parameters are injection points and its output type is the key. A Construct type that needs a custom build goes through provide_with::<T>(factory), which runs T::hooks.

Controller and Handlers

pub trait Controller: Construct {}

pub trait Handlers: Controller {
    fn mount(m: &mut Mount<'_>);
}

Controller is the mark of a dispatch target: a Construct type a transport reaches through handlers. It has no methods. #[controller] writes the impl, bounded on Self: Handlers, so a #[controller] type with no handler impl fails to compile.

Handlers carries what a controller mounts. #[handlers] writes mount, which declares each handler of the impl block through Mount::handler. ModuleDef::controller::<C>() and #[module]'s controllers accept a type that implements Handlers, and through it Controller. A type that is only a Controller mounts nothing and is refused there.

A controller written by hand implements Construct, Controller and Handlers, and calls d.mark::<Self>() in its dependencies. A WebSocket gateway implementing Gateway by hand implements Handlers with <Self as Gateway>::mount(m). See Without macros.

With Auto scope a controller is a singleton if nothing below it needs an execution, and is built per call otherwise. wire() refuses a read of a controller by any binding that is not a controller (ControllerRead) and a controller registered as a provider (ControllerProvided).

Binding handles

provide, value and the factory methods return a Handle, whose typestate decides which methods exist.

impl Handle<'_, T, ..> {
    pub fn also_as<U: ?Sized + Send + Sync + 'static>(self, ..) -> ..;
    pub fn qualified<Q: 'static>(self) -> ..;
    pub fn ready<Args, F, E>(self, check: F) -> ..;
    pub fn on_init<Args, F, E>(self, hook: F) -> ..;
    pub fn on_destroy<Args, F>(self, hook: F) -> ..;
    pub fn before_shutdown<Args, F>(self, hook: F) -> ..;
    pub fn on_shutdown<Args, F>(self, hook: F) -> ..;
    pub fn timeout(self, d: Duration) -> ..;
    pub fn unbounded(self) -> ..;
    pub fn attempt_timeout(self, d: Duration) -> ..;
    pub fn retries(self, n: u32) -> Self;
    pub fn backoff(self, d: Duration) -> Self;
}

The signatures are abbreviated. The generic parameters carry the typestate. ready, on_init and the other hooks exist on singleton and Auto handles only, not on execution-scoped or transient ones. timeout and unbounded bound whatever item was written last, the construction right after the factory, the check after ready, the hook after on_destroy. A bound is written once per item: a second timeout, or unbounded beside a bound, is E0599 at the second call. retries, backoff and attempt_timeout exist on a readiness item. A check that writes no bound takes construct_timeout for each attempt when a Timer exists. also_as binds a second key under another type, as in m.provide::<RedisCache>().also_as::<dyn Cache>(|a| a).

From examples/09-lifecycle:

m.singleton(move || async move { Link { fail_first, attempts: AtomicU32::new(0) } })
    .ready(|link: Dep<Link>, journal: Dep<Journal>| async move { link.ping(&journal) })
    .retries(3)
    .backoff(BACKOFF)
    .on_destroy(|journal: Dep<Journal>| async move { journal.push("Link destroy") });
m.on_init(|journal: Dep<Journal>| async move {
    journal.push("LinkModule init");
    Ok::<(), BoxError>(())
});

Keyed, DynamicModule and ModuleRef

Keyed<Q, M> is itself a module. Inside M, injection points stay unqualified; at the export boundary every unqualified export, re-exports included, is requalified as T @ Q. Its identity includes Q, so DbModule::for_root(url).keyed::<Primary>() and .keyed::<Replica>() are two modules. Keying a module twice is refused as NestedKeyed. Contributions are not exports and keep their key.

impl DynamicModule {
    pub fn new<O: 'static, C: Eq + Hash + Clone + Send + Sync + 'static>(
        config: C,
        register: impl FnOnce(&mut ModuleDef<'_>) + Send + 'static,
    ) -> Self;
    pub fn label(self, name: &'static str) -> Self;
    pub fn with_settings(self, settings: ModuleSettings) -> Self;
}

A module built at runtime from a value with no struct of its own. Its identity is the owner type O plus the configuration C. What the closure captures beside the configuration is opaque to the graph. with_settings names it. From examples/08-dynamic-and-lazy:

pub fn feature_module(name: String) -> DynamicModule {
    DynamicModule::new::<FeatureOwner, _>(name.clone(), move |m| {
        m.value(Feature(name));
        m.export::<Feature>();
    })
    .label("FeatureModule")
}
impl ModuleRef {
    pub async fn get<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Dep<T>, LookupError>;
    pub async fn execute<F, R>(&self, opts: ExecOptions, f: F) -> Result<R, Closed>;
    pub fn name(&self) -> ModuleName;
}

A handle limited to what one module sees. Use app.module::<M>() to reach a service exported only inside a subtree, and inject ModuleRef to read from the enclosing module. During connect, get for a singleton not yet built answers LookupError::NotReady.

Meta

pub trait Meta: Default + Send + Sync + 'static {
    fn dependencies(&self, _d: &mut Dependencies) {}
}

Typed module metadata written through m.meta::<T>(), such as ulo_http::PreDispatch and ulo_http::Upgrades. A transport reads it when it binds, so a lazily loaded module that writes any is refused with LoadRefusal::Middleware. It is not a contribution key, so into PreDispatch: [..] does not compile.

Executions

One execution is one HTTP request, WebSocket message, RPC call or gRPC call, or one execute closure. A WebSocket connection is not an execution. Per-connection state is held in ulo_ws::Session<T>.

impl Execution {
    pub fn open(module: &ModuleRef, opts: ExecOptions) -> Result<Execution, Closed>;
    pub fn open_terminal(token: &DrainToken, module: &ModuleRef, opts: ExecOptions) -> Result<Execution, Closed>;
    pub fn seed<T: Send + Sync + 'static>(&self, input: T);
    pub fn handle(&self) -> ExecutionRef;
    pub fn extensions(&self) -> &Extensions;
    pub fn cancelled(&self) -> Cancelled<'_>;
    pub fn is_cancelled(&self) -> bool;
    pub fn draining(&self) -> Draining<'_>;
    pub fn is_draining(&self) -> bool;
    pub fn deadline(&self) -> Option<Instant>;
    pub fn cancel(&self);
    pub fn cancel_with(&self, reason: CancelReason);
    pub fn cancel_reason(&self) -> Option<CancelReason>;
    pub fn on_stream_end(&self, f: impl FnOnce(StreamOutcome) + Send + 'static);
    pub fn handler(&self) -> Option<&HandlerInfo>;
    pub async fn get<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Dep<T>, LookupError>;
}

Execution is not Clone: the holder, a transport or execute, owns it. The execution ends when the holder drops it, and that drops the execution-scoped instances. Everyone else holds an ExecutionRef, which has the same methods except seed, with owned cancelled() and draining() futures. Three events are distinct. Draining is the notice that shutdown has begun; a streaming reply finishes what it has and ends. Cancellation fires while clones are alive: a disconnect, a passed deadline, the drain's end, or cancel(). It is not fired by execute completing. End of execution is the holder's drop; a clone kept past it still answers what the execution recorded, and its get answers LookupError::ExecutionEnded.

seed is on Execution alone. A transport seeds the inputs it declares. A standalone execution that does not seed an input an injection point reads gets LookupError::NotFound at runtime.

pub struct ExecOptions { /* .. */ }

impl ExecOptions {
    pub fn new() -> Self;
    pub fn deadline(self, at: Instant) -> Self;
    pub fn trace(self, ctx: TraceContext) -> Self;
    pub fn span(self, span: tracing::Span) -> Self;
}
impl Extensions {
    pub fn insert<T: Send + Sync + 'static>(&self, value: T);
    pub fn get<T: Send + Sync + 'static>(&self) -> Option<Arc<T>>;
    pub fn contains<T: Send + Sync + 'static>(&self) -> bool;
    pub fn remove<T: Send + Sync + 'static>(&self) -> Option<Arc<T>>;
}

The typed bag an execution carries. A guard writes an extension with cx.extensions().insert(CurrentUser(user)) and a later injection point reads it as Ext<CurrentUser>. Every method takes &self. The bag is an Arc<Mutex<..>> handle.

execute opens a standalone execution, from examples/12-standalone:

app.execute(ExecOptions::new(), async |exec| {
    exec.extensions().insert(Tenant(tenant));
    Ok(exec.get::<ReportJob>().await?.run())
})
.await

The closure is async |exec|, an AsyncFnOnce, so the future can borrow the execution. execute answers Closed from the Draining phase on. A deadline is enforced on the app's Timer. On an app with none it is stored, reported by deadline(), and never fires.

pub enum CancelReason {
    Disconnected,
    ClientCancelled,
    Deadline,
    Drain,
    Explicit,
}

pub enum StreamOutcome {
    Completed,
    CutOff(Option<CancelReason>),
}

The first reason written to an execution stays, and a cancelled execution always has one.

CancelReasonWritten when
DisconnectedThe backend observes the peer close the connection or reset the stream: a dropped response body, a closed connection, an HTTP/2 RST_STREAM. The call's future dropped before its response head is produced, because the peer closed an HTTP/1.1 connection or reset an HTTP/2 stream, writes it before the handler's future drops. A host that keeps the call running declares so with without_pending_close and without_pending_reset in its EmbedLimits. The server dropping an unread request body is not a disconnect.
ClientCancelledA WebSocket or RPC cancel frame, or a gRPC RST_STREAM(CANCEL).
DeadlineA passed grpc-timeout, RPC deadline-ms header, configured route timeout or standalone execution deadline. A transport renders Timeout for it.
DrainThe end of the drain.
Explicitcancel() by whoever holds the execution.

StreamOutcome::Completed is a reply stream that returned None and was written out. CutOff is a stream dropped before that, holding the execution's reason when it was cancelled and None when the stream was cut off without a cancellation: ended on an error item, or dropped by a transport that recorded no reason. on_stream_end callbacks receive it.

Time and runtime

pub trait Timer: Send + Sync + 'static {
    fn sleep(&self, d: Duration) -> BoxFuture<'static, ()>;
    fn now(&self) -> Instant;
    fn try_sleep(&self, d: Duration) -> BoxFuture<'static, Result<(), Refused>>;
}

pub trait Spawn: Send + Sync + 'static {
    fn spawn(&self, fut: BoxFuture<'static, ()>) -> TaskHandle;
    fn try_spawn(&self, fut: BoxFuture<'static, ()>) -> Result<TaskHandle, Refused>;
}

pub trait Runtime: Timer + Spawn {}

The core has no clock or executor of its own. A Runtime is a Timer with an executor and is implemented for every Timer + Spawn. ulo-runtime-tokio and ulo-runtime-smol provide one each. A runtime written outside the repository runs the published ulo-runtime-conformance suite, stamped with runtime_suite! from its tests/conformance.rs, to check it keeps the same promises. A runtime that has shut down refuses as a value and never panics: try_sleep and try_spawn answer Err(Refused). The core binds the configured timer for services as Dep<dyn Timer> and the runtime as Dep<dyn Runtime>. These are the app's wrapper around the runtime given, which carries the graph's secret redaction for a spawned task's panic. The free functions timeout(timer, d, fut) and timeout_at(timer, until, fut) race a future against a bound and answer Result<F::Output, Cut>.

Secrets and redaction

pub struct Secret<T> { /* .. */ }

impl<T> Secret<T> {
    pub fn new(value: T) -> Self;
    pub fn expose(&self) -> &T;
    pub fn into_inner(self) -> T;
}

pub struct Redacted { /* .. */ }

impl Redacted {
    pub fn downcast_ref<E: Error + 'static>(&self) -> Option<&E>;
    pub fn into_inner(self) -> BoxError;
}

Secret<T> prints as redacted text under Display and Debug. A secret registered with the graph (by m.secret(&s), by #[module] for every Secret field of a configured module, or by m.value(..) for Secret<String> and Secret<&'static str>) is replaced in every error the graph reports. An error from outside the core passes through the redaction function before it is stored in a core error type, and is stored as a Redacted: Display and Debug write the redacted text, source() is None, and the original is reached through downcast_ref and into_inner alone. A secret shorter than four characters stays registered and is matched against no message. Secret<T>: Deserialize behind the serde feature.

Enhancers and transports

pub trait Transport: 'static {
    const KEY: &'static str;
    const READS_PREFIX: bool = false;
    const BUILDS_CONTROLLER: bool = true;
    type Cx: Clone + Send + Sync;
    type Reply: Send;
}

pub trait Guard<T: Transport>: Send + Sync + 'static {
    fn can_activate(&self, cx: &T::Cx) -> impl Future<Output = Result<bool, BoxError>> + Send;
}

pub trait Interceptor<T: Transport>: Send + Sync + 'static {
    fn intercept(&self, cx: &T::Cx, next: Next<'_, T>) -> impl Future<Output = Result<T::Reply, BoxError>> + Send;
}

pub trait ErrorHandler<T: Transport>: Send + Sync + 'static {
    fn handle(&self, err: BoxError, cx: &T::Cx) -> impl Future<Output = Result<T::Reply, BoxError>> + Send;
}

A Transport is a marker type from a transport crate (ulo_http::Http, ulo_rpc::Rpc, ulo_ws::Ws and ulo_ws::WsConnect, ulo_grpc::Grpc). Cx is the per-call context, a cheap-clone handle to the execution plus the call's wire data. Guard<Http> and Guard<Rpc> are different traits, so an HTTP guard and an RPC guard are different roles, and a type that implements both is a guard for both. A guard returns Ok(false) to refuse with GuardRejected (HTTP 403, gRPC PermissionDenied); it returns Err to refuse with its own error. An interceptor calls next.run() to continue and may reshape the result. An error handler returns Ok(reply) to claim the failure and Err to pass it on.

A role comes only from a trait implementation, and which contributions are enhancers is decided by TypeId at freeze. The role keys are AnyGuard<T>, AnyInterceptor<T> and AnyErrorHandler<T>, the sealed Role trait's implementors. A global enhancer is a contribution under one:

From examples/16-http-enhancers:

into AnyErrorHandler<Http>: [order::Shape],
into AnyGuard<Http>: [with = |trace: Dep<Trace>| Stamp::new("global", trace)],
into AnyInterceptor<Http>: [with = |trace: Dep<Trace>| Stamp::new("global", trace)],

EnhancerSpec is what a transport's attribute fills for one handler: guard_with(f), interceptor_with(f), error_handler_with(f) and the _in::<S> forms that take a scope, plus the _arc forms for impl-level shared values.

pub trait Server: Send + Sync + 'static {
    fn prepare(&mut self, mounted: Mounted<'_, Self::Transport>) -> impl Future<Output = Result<(), BoxError>> + Send;
    fn bind(&mut self, mounted: Mounted<'_, Self::Transport>) -> impl Future<Output = Result<(), BoxError>> + Send;
    fn serve(&self) -> impl Future<Output = Result<(), BoxError>> + Send;
    fn drain(&self, token: DrainToken) -> impl Future<Output = ()> + Send;
    fn close(&self) -> impl Future<Output = Result<(), BoxError>> + Send;
    fn bound(&self) -> Vec<BoundAddr>;
}

What a transport's server implements, and what App::bind accepts. Signatures abbreviated: prepare has a default body and bound a default of the empty list. prepare runs for every server before any binds. drain receives the DrainToken that lets the server open terminal executions during the drain. close is guaranteed to run once on every shutdown path that reaches the close step.

Testing

impl TestApp {
    pub fn of(root: impl Module) -> TestApp<Settled>;
    pub fn override_value<T: ?Sized + Send + Sync + 'static>(self, value: Arc<T>) -> TestApp<Pending>;
    pub fn override_factory<Args, F>(self, factory: F) -> TestApp<Pending>;
    pub fn override_try_factory<Args, F, T, E>(self, factory: F) -> TestApp<Pending>;
    pub fn override_many<T: ?Sized + Send + Sync + 'static>(self, items: impl IntoIterator<Item = Arc<T>>) -> TestApp<PendingMany>;
    pub fn replace_module(self, original: impl Module, replacement: impl Module) -> TestApp<Settled>;
    pub fn timer(self, timer: impl Timer) -> TestApp<Settled>;
    pub fn runtime(self, runtime: impl Runtime) -> TestApp<Settled>;
    pub fn drain_timeout(self, d: Duration) -> TestApp<Settled>;
    pub fn shutdown_timeout(self, d: Duration) -> TestApp<Settled>;
    pub fn hook_timeout(self, d: Duration) -> TestApp<Settled>;
    pub fn construct_timeout(self, d: Duration) -> TestApp<Settled>;
    pub fn trace(self, mode: TraceMode) -> TestApp<Settled>;
    pub fn wire(self) -> Result<App<Wired>, StartupError>;
    pub async fn connect(self) -> Result<App<Connected>, StartupError>;
}

impl TestApp<Pending> {
    pub fn qualified<Q: 'static>(self) -> TestApp<Pending>;
    pub fn in_module<M: 'static>(self) -> TestApp<Settled>;
    pub fn in_module_keyed<M: 'static, Q: 'static>(self) -> TestApp<Settled>;
    pub fn in_module_of<M: Module>(self, config: &M) -> TestApp<Settled>;
    pub fn everywhere(self) -> TestApp<Settled>;
}

impl TestApp<PendingMany> {
    pub fn qualified<Q: 'static>(self) -> TestApp<Settled>;
}

The production module, with replacements. Use it in a test in place of App::builder: it wires the same graph and applies overrides before wire(). In the Pending state after an override, .qualified, .in_module* and .everywhere() describe the override.

Override rules:

  • An override replaces the recipe of an existing key and keeps its origin module, visibility and exports.
  • It must match exactly one binding. One that matches none is OverrideUnmatched, which catches stale mocks after a refactor. One that matches several, two modules each binding the key privately, is OverrideAmbiguous listing every match. .everywhere() replaces all, and .in_module::<M>() scopes it to one.
  • It targets T @ (); .qualified::<Q>() reaches a qualified binding.
  • It cannot change a key's kind. override_many replaces a whole collection.
  • replace_module swaps by identity. The replacement must export a superset of the original's keys, or wiring reports ReplacementMissingExports.
  • The Timer and the Runtime are configuration, not bindings: override_value::<dyn Timer> is TimerOverride and override_value::<dyn Runtime> is RuntimeOverride. Set them with TestApp::timer(..) and TestApp::runtime(..).

From examples/13-testing:

let app = test_app()
    .override_value::<dyn Mailer>(Arc::new(FakeMailer))
    .override_factory(|| async { Stamp("2026-01-01".to_owned()) })
    .override_value::<Ledger>(Arc::new(Ledger("test")))
    .in_module::<BillingModule>()
    .connect()
    .await
    .unwrap();

where test_app() is TestApp::of(AppModule).runtime(Tokio::current()).

impl ScriptedTimer {
    pub fn new() -> ScriptedTimer;
    pub fn advance(&self, by: Duration);
    pub fn live(&self, length: Duration) -> usize;
    pub fn pending_at(&self, length: Duration) -> Option<Duration>;
    pub fn refuse(&self, length: Duration);
    pub fn refused(&self, length: Duration) -> usize;
    pub fn elapsed(&self) -> Duration;
}

ulo::testing::ScriptedTimer is a Timer whose sleeps end only when the test calls advance. It counts the live sleeps by length, records the clock time at which a sleep last answered Pending, and answers a named length as a runtime that has shut down does. It needs no runtime and no cargo feature. A paused tokio clock is the wrong tool for an app with servers: it advances on its own whenever the runtime has nothing else to run. See Testing.

Handler attributes

The attributes each transport crate adds for its handlers, the arguments they take and what each refuses at compile time.

Errors and diagnostics

Every error type the core returns, the wiring failures with their report text, and the compile-time diagnostics, by the phase that raises them.

On this page

The applicationAppAppBuilderAppHandleSignalInjection pointsDepManyExtOptionModuleRef and ExecutionRefRequirement and DependenciesResolverKeys and qualifiersScopesConstruct and lifecycle hooksBoundModulesModuleDefController and HandlersBinding handlesKeyed, DynamicModule and ModuleRefMetaExecutionsTime and runtimeSecrets and redactionEnhancers and transportsTesting