ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Core Concepts

Providers and injection

ProvidersTraits and qualifiersCollections and optional dependenciesScopes

Modules

ModulesConfigured modulesDynamic and lazy modules

Running the application

Application phasesLifecycle hooksShutdownStandalone executions

Diagnostics and the value API

The wiring reportWithout macros

Protocols

Integrations

Operating

Reference

Core Concepts

Without macros

The value API the macros expand to: Construct, Module and ModuleDef, written by hand.

Every macro in ulo expands to calls on a public value API. An integration crate calls that API directly to register its bindings.

This page follows examples/14-without-macros, which writes example 06's providers, controller and modules by hand.

A provider by hand

#[injectable] writes an impl Construct, and #[controller] writes one for a controller. A Construct type declares its scope, the injection points it reads, and how to build itself.

pub struct UserService {
    hasher: Dep<PasswordHasher>,
}

impl Construct for UserService {
    type Scope = Auto;

    fn dependencies(d: &mut Dependencies) {
        d.field::<Dep<PasswordHasher>>("hasher");
    }

    async fn construct(r: &Resolver<'_>) -> Result<Self, ConstructError> {
        Ok(UserService { hasher: r.dep::<PasswordHasher>().await? })
    }
}
  • Scope is a marker from ulo::scope: Singleton, PerExecution, Transient or Auto.
  • dependencies declares every read. wire() uses it to check the graph before anything is built. field and param carry a name that diagnostics print, as in Snooper (field `_hasher`).
  • construct builds the instance. r.dep::<T>() reads T @ (), and r.dep_qualified::<T, Q>() reads a qualified key. many, many_qualified, ext, entries, module and execution are the other reads. ? passes a LookupError through as ConstructError::Dependency. ConstructError::failed(e) wraps your own error.
  • fn hooks(h: &mut Hooks<Self>) registers the lifecycle traits the type implements. The default registers none.

The two lists must agree. A read in construct that dependencies did not declare is refused at the type's first construction, in every build, with ConstructError holding an UndeclaredRead that names the key and the reading type. A hand-written type is therefore subject to the checks wire() ran.

A module by hand

#[module] writes an impl Module. identity names the module for deduplication and reports. register declares everything and is synchronous and free of I/O.

pub struct UsersModule;

impl Module for UsersModule {
    fn identity(&self) -> ModuleIdentity {
        ModuleIdentity::of_type::<Self>()
    }

    fn register(&self, m: &mut ModuleDef<'_>) {
        m.provide::<PasswordHasher>();
        m.provide::<UserService>();
        m.export::<UserService>();
    }
}

pub struct BillingModule;

impl Module for BillingModule {
    fn identity(&self) -> ModuleIdentity {
        ModuleIdentity::of_type::<Self>()
    }

    fn register(&self, m: &mut ModuleDef<'_>) {
        m.import(UsersModule);
        m.provide::<InvoiceService>();
        m.controller::<InvoiceController>();
    }
}

Identity comes from ModuleIdentity::of_type::<Self>() for a unit module, ModuleIdentity::of_value(self) for a configured one that is Eq + Hash + Clone, and ModuleIdentity::of_owner::<O, C>(&config) for an owner type with a configuration. .label("name") overrides what reports print. A hand-written module and a macro-written one are the same kind of module: imports = [HandWritten] works, and so does m.import(Attributed) inside register.

register returns () and never returns early. A value that may fail to build goes through m.try_value(result), which records an Err for wire() to report beside the other problems. Stopping at the first failure would hide the rest.

A controller by hand

The imports for these listings are at the top of examples/14-without-macros/src/lib.rs: the core types come from ulo, ulo::scope::Auto is the scope marker, and Http, HttpCx, HttpHandler, Method and Response come from ulo_http.

A controller is three impls. Construct builds it, and its dependencies calls d.mark::<Self>() so that wire() knows the type is a controller. impl Controller for X {} is the mark and writes nothing else. impl Handlers for X declares the handlers in mount, which is where #[handlers] writes each handler. The transport's own crate provides the handler value:

impl Construct for InvoiceController {
    type Scope = Auto;

    fn dependencies(d: &mut Dependencies) {
        d.mark::<Self>();
        d.field::<Dep<InvoiceService>>("invoices");
    }

    async fn construct(r: &Resolver<'_>) -> Result<Self, ConstructError> {
        Ok(InvoiceController { invoices: r.dep::<InvoiceService>().await? })
    }
}

/// What `#[controller]` writes beside the `Construct` impl: the mark of a controller.
impl Controller for InvoiceController {}

/// What `#[ulo_http::get("/")]` on `open` writes: one GET handler at `/`, named after the method.
impl Handlers for InvoiceController {
    fn mount(m: &mut Mount<'_>) {
        m.handler(HandlerSpec::<Http, _>::new("open", HttpHandler::new(Method::GET, open)).route("/"));
    }
}

async fn open(cx: HttpCx) -> Result<Response, BoxError> {
    let controller = cx.exec().get::<InvoiceController>().await?;
    Ok(controller.open().into_reply(&cx)?)
}

A controller registered with m.provide::<X>() instead of m.controller::<X>() is a ControllerProvided wiring error, since its handlers would never mount. d.mark::<Self>() is what lets wire() see that.

What the macros lower to

In #[module]Value API
imports = [M]m.import(M)
UserServicem.provide::<UserService>()
PgUserRepo as dyn UserRepom.provide::<PgUserRepo>().also_as::<dyn UserRepo>(|a| a)
expr / expr?m.value(expr) / m.try_value(expr)
with = |..| ..m.with(..), or m.try_with(..) for a closure answering a Result
with(singleton | execution | transient) = ..m.singleton(..), m.execution(..), m.transient(..), each with a try_ form
Type @ Q, expr @ Qthe same call followed by .qualified::<Q>()
into dyn Plugin: [A, B]m.contribute::<dyn Plugin>().provide::<A>(|a| a) for each item
controllers = [C]m.controller::<C>()
exports = [T], [reexport T]m.export::<T>(), m.reexport::<T>()
exports = [T @ Q]m.export_qualified::<T, Q>(), m.reexport_qualified::<T, Q>()
globalm.global()

The \|a\| a is a coercion. Stable Rust cannot unsize generically, but a closure whose expected type is fn(Arc<RedisCache>) -> Arc<dyn Cache> coerces at its return, and that is what as dyn T writes.

Each scope has a plain and a fallible method: singleton/try_singleton, execution/try_execution, transient/try_transient. The first binds the future's output. The try_ form binds its Ok type and reports an Err as the construction's failure.

What only the value API has

#[module] has no spelling for these, so a module that needs one implements Module:

  • A readiness check, .ready(..) with .retries(..), .backoff(..), .attempt_timeout(..).
  • A closure hook, .on_init(..), .on_destroy(..), .before_shutdown(..), .on_shutdown(..), on a binding or on the module.
  • A qualified closure binding, m.singleton(..).qualified::<Q>(), and a qualified collection, m.contribute::<K>().qualified::<Q>().
  • m.alias::<T, Q>().of::<Existing>().
  • m.provide_with(..), for a Construct type that needs a custom build and keeps its hooks.
  • Module metadata, m.meta::<T>(), such as an HTTP pre-dispatch stage.
  • m.secret(&s), registering a secret for redaction.
  • Module settings, compared across imports.

Lifecycle hooks shows a module using the first two.

The two spellings answer alike

The example's test runs one assertion body against example 06 and this example. They give the same answer through a ModuleRef, the same reply to GET / with the same handler reported for it, and the same refusal when a module reads the unexported binding:

fn refusal(builder: AppBuilder, key: &str, consumer: &str, module: &str) {
    let Err(StartupError::Wiring(errors)) = builder.wire() else { panic!("wiring should fail") };
    let [WiringError::Missing { key: missing, consumer: reader, module: reading, .. }] = errors.iter().collect::<Vec<_>>()[..] else {
        panic!("expected one missing dependency, got {errors}");
    };
    assert_eq!(missing.to_string(), key);
    assert_eq!(reader, consumer);
    assert_eq!(reading.to_string(), module);
}

Running the example

cargo run -p ex-14-without-macros

It prints invoice for ada registered with hashed:secret.

The wiring report

Every startup refusal in one pass: what wire() checks, how the report reads, and how to read it as data.

Request Lifecycle

The one pipeline every transport runs a call through, in the order it runs.

On this page

A provider by handA module by handA controller by handWhat the macros lower toWhat only the value API hasThe two spellings answer alikeRunning the example