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

Providers

Declaring a provider, injecting it with Dep, and what happens when its constructor fails.

A provider is a type the container builds once and hands to everything that asks for it. You ask by writing Dep<T> as a field or a parameter. The container reads the type, finds the binding, and fills it in.

This page follows examples/02-providers.

Two ways to declare one

Put #[injectable] on a struct and every field is injected. A field marked #[injectable(default)] is the type's own state and is set from Default.

Put #[injectable] on an impl block and the constructor is the function named new, or the one marked #[construct]. Its parameters are injected. It may be async and it may return Self or Result<Self, E>.

use ulo::{App, AppBuilder, Dep, controller, handlers, injectable, module};

/// A value the module binds; `Greeter::new` reads it like any provider.
pub struct Settings {
    pub salutation: &'static str,
}

/// Struct style: every field is injected unless marked `default`, which owns its state.
#[injectable]
pub struct Counter {
    #[injectable(default)]
    hits: AtomicU64,
}

pub struct Greeter {
    counter: Dep<Counter>,
    salutation: &'static str,
}

/// Constructor style: the parameters are injected, and the body may await and fail.
#[injectable]
impl Greeter {
    pub async fn new(counter: Dep<Counter>, settings: Dep<Settings>) -> Result<Self, EmptySalutation> {
        if settings.salutation.is_empty() {
            return Err(EmptySalutation);
        }
        Ok(Greeter { counter, salutation: settings.salutation })
    }
}

A controller is declared with #[controller], which takes the same field rules with a defaulted field marked #[controller(default)]. Its handlers go in a #[handlers] impl. It is listed under controllers, and providers go under providers:

#[controller]
pub struct HelloController {
    greeter: Dep<Greeter>,
}

#[handlers]
impl HelloController {
    #[ulo_http::get("/")]
    fn hello(&self) -> String {
        self.greeter.greet()
    }
}
#[module(
    providers = [Counter, Greeter, Settings { salutation: "Hello" }],
    controllers = [HelloController],
)]
pub struct AppModule;

Settings { salutation: "Hello" } is a value. An expression in a providers list binds the value it evaluates to, under its own type. A bare path reads as a type, so a constant is written with a block, { LIMITS }. An expression followed by ? binds the Ok value, and an Err is reported by wire() with the other wiring errors.

What Dep<T> is

Dep<T> holds an Arc<T>. Every holder of a binding holds the same Arc, whether the binding was aliased, exported or re-exported. A service is never cloned; Dep clones the pointer. Mutation goes through interior mutability, which is why Counter holds an AtomicU64.

The example's test reads the counter from outside the application and checks that it is the instance the requests used:

let counter: Dep<Counter> = server.handle.get().await.unwrap();
assert_eq!(counter.next(), 3);
let again: Dep<Counter> = server.handle.get().await.unwrap();
assert!(Arc::ptr_eq(counter.arc(), again.arc()));

T must be Send + Sync. For a trait, make both supertraits of the trait (trait UserRepo: Send + Sync), as Traits and qualifiers shows.

A provider that reads another type

Every injection point is its type. A field of a type the container cannot provide, such as a bare u32, is a compile error that tells you to write Dep<T> or to mark the field #[injectable(default)]. A missing or ambiguous binding is not a compile error, because the compiler sees one type at a time. The container finds those when the application starts, in wire(), and reports them all together. See The wiring report.

When a constructor fails

Singletons are built during connect(), after wire() has checked the graph. A constructor that returns Err, panics or exceeds its time limit fails connect() with StartupError::Connect(ConnectError::Construct { key, module, reason }).

#[module(
    providers = [Counter, Greeter, Settings { salutation: "" }],
    controllers = [HelloController],
)]
struct EmptySalutationModule;

let Err(error) = ulo::App::builder(EmptySalutationModule)
    .runtime(Tokio::current())
    .wire()
    .unwrap()
    .connect()
    .await
else {
    panic!("connect should fail");
};
let StartupError::Connect(ConnectError::Construct { key, module, reason }) = &error else {
    panic!("expected a construct failure, got {error}");
};
assert_eq!(key.to_string(), "Greeter");
assert_eq!(module.to_string(), "EmptySalutationModule");
assert_eq!(reason.to_string(), "the salutation is empty");

StartupError and ConnectError are exported from ulo. error.to_string() reads failed to construct `Greeter` in EmptySalutationModule: the salutation is empty. The error that comes from your constructor passes through the container's redaction first: a registered ulo::Secret<_> (a wrapper for a credential; see Secrets) in its text is replaced, and so is the userinfo of anything shaped like a URL.

A constructor's wait is bounded. The default is construct_timeout, 30 seconds, set on the builder with App::builder(..).construct_timeout(..), and #[injectable(timeout = Duration::from_secs(5))] sets one for a type. Bounds need a clock. See Application phases.

Running the example

cargo run -p ex-02-providers
curl http://127.0.0.1:3000/    # Hello #1, then Hello #2

The server listens on PORT, default 3000.

Core Concepts

Providers, modules, scopes, lifecycle and the container that wires them.

Traits and qualifiers

Binding a provider under a trait, and telling two instances of one type apart with a qualifier.

On this page

Two ways to declare oneWhat Dep<T> isA provider that reads another typeWhen a constructor failsRunning the example