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

Lifecycle hooks

Init, bootstrap, destroy and shutdown hooks, readiness checks with retries, and the order they run in.

A provider often has work to do once it exists: warm a cache, check that a dependency answers, flush a buffer on exit. Hooks run that work at a fixed point in startup or shutdown, in dependency order, with a time limit.

This page follows examples/09-lifecycle. Its main connects, closes and prints a journal with one line per event.

The five hooks

A hook is a trait you implement on an injectable type. #[injectable] registers whichever of the five the type implements. There is no marker attribute.

TraitMethodRuns
OnModuleIniton_module_init(&self) -> Result<(), BoxError>During connect(), after every singleton is built.
OnApplicationBootstrapon_application_bootstrap(&self) -> Result<(), BoxError>During connect(), after every init hook.
BeforeApplicationShutdownbefore_application_shutdown(&self, signal: &Signal)First step of shutdown, while the app still serves.
OnModuleDestroyon_module_destroy(&self)After the drain, before the sockets close.
OnApplicationShutdownon_application_shutdown(&self, signal: &Signal)Last step of shutdown.

The traits, Signal, BoxError and Bound are exported from ulo. All five are async fn. Init and bootstrap return a Result, and an Err fails connect(). The shutdown hooks return nothing, because shutdown cannot be aborted.

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

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

Each trait has an associated const TIMEOUT: Bound. The default is Bound::Default, which means the app's hook_timeout (10 s). Bound::After(Duration) sets a limit for the hook and Bound::Unbounded removes it. A type implementing two hook traits bounds each separately. A bound needs a Timer.

Order

The example's main prints this journal:

Link ready: Err("link refused attempt 1")
Link ready: Err("link refused attempt 2")
Link ready: Ok(3)
Cache built
LinkModule init
Cache init
Cache bootstrap
Cache before shutdown (done)
Cache destroy
Link destroy
Cache shutdown (done)
  • Construction goes in dependency order. Link is built and checked first because Cache::new takes Dep<Link>.
  • All init hooks run after all singletons exist, then all bootstrap hooks.
  • A module's own hook (LinkModule init) runs after the hooks of its providers.
  • Shutdown runs the hooks in the exact reverse of connect order. Link destroy follows Cache destroy because Cache was built later.
  • Init hooks follow dependencies and not the order the providers were written. The example's test registers Report before Store, and Store init still runs first.
  • On one binding, trait hooks run first, then closure hooks in the order written.

The first failure in connect() stops the walk. Nothing built so far gets a destroy or shutdown hook. The instances drop and release their resources.

Hooks are for singletons

Hooks run on singletons only. Execution-scoped and transient instances do not exist at startup or shutdown. A hook trait on a type declared #[injectable(execution)] or #[injectable(transient)] is a compile error, "lifecycle hooks are only allowed on singletons". On an Auto type that inference moved to per-execution, wire() reports HooksOnPerExecution.

A factory's output is a plain value, so trait hooks do not run for it, even when the output type implements one. A Construct type that needs a custom build is bound with m.provide_with(..), which runs its hooks. Any other factory output uses closure hooks.

Closure hooks and readiness checks

#[module] has no spelling for a closure hook or a readiness check. A module that needs one implements Module and calls them on the ModuleDef. It imports and is imported by #[module] modules like any other.

#[derive(Clone, PartialEq, Eq, Hash)]
pub struct LinkModule {
    pub fail_first: u32,
}

impl Module for LinkModule {
    fn identity(&self) -> ModuleIdentity {
        ModuleIdentity::of_value(self)
    }

    fn register(&self, m: &mut ModuleDef<'_>) {
        let fail_first = self.fail_first;
        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>(())
        });
        m.export::<Link>();
    }
}

The closure parameters are injection points, read before the closure runs. If a read fails the hook never runs, and the failure is recorded as FailureReason::Errored holding the LookupError.

Closure hooks are on_init, on_destroy, before_shutdown and on_shutdown, on a binding handle and on the module itself. A shutdown closure takes the Signal as its first parameter. The binding handle is typed: the hook methods and .ready(..) do not exist on execution-scoped or transient handles, so misuse is a compile error.

Readiness checks

.ready(f) runs right after its binding is constructed and before anything that depends on it. It is the place for a ping to a database or a broker, and a reason to construct a client lazily so that construction itself does not need the network.

MethodMeaning
.retries(n)n further attempts after the first. The default is no retries.
.backoff(d)Wait d between attempts. Needs a Timer.
.attempt_timeout(d)Bound one attempt. Catches a single hung ping.
.timeout(d)Bound the whole check, retries and backoff included.
.unbounded()No bound on an attempt or on the whole.

A check that writes neither bound takes construct_timeout as its attempt bound when a Timer exists, because a ping to a host that drops packets never returns, and an unbounded first attempt would never reach its retries. An attempt that times out with retries left is retried like one that returned Err. A second .ready(..) on one binding is a wiring error naming both calls.

The example's check fails twice and then passes, in up to four attempts. A check that never passes fails connect():

let Err(error) = builder(99).runtime(Tokio::current()).wire().unwrap().connect().await else {
    panic!("connect should fail");
};
let StartupError::Connect(ConnectError::Readiness { key, attempts, reason, .. }) = &error else {
    panic!("expected a readiness failure, got {error}");
};
assert_eq!(key.to_string(), "Link");
assert_eq!(*attempts, 4, "the first attempt and three retries");
let FailureReason::Errored(last) = reason else { panic!("expected the last attempt's error, got {reason}") };
assert_eq!(last.to_string(), "link refused attempt 4");

The message reads readiness check of `Link` in LinkModule failed after 4 attempts: link refused attempt 4.

reason says how the check ended:

  • Errored holds the last attempt's error when the retries ran out.
  • TimedOut { limit: Item } means the whole-check bound fired.
  • TimedOut { limit: Attempt } or { limit: Default } means the last attempt hit its own bound with no retries left.
  • Panicked ends the check at once.

The test runs on tokio's paused clock, #[tokio::test(start_paused = true)], so the backoff costs no real time. The two refused attempts waited one backoff each, which the test asserts: started.elapsed() == 2 * BACKOFF. See Clocks in tests.

Secrets in errors

Every error that does not originate in the core passes through one redaction function before it is stored: a hook's error, a constructor's, a panic message. It replaces every registered Secret<_> and strips the userinfo from anything shaped like a URL. #[module] registers every Secret<_> field of a configured module. For a Secret<T> bound with m.value(..) where T is not String or &'static str, write m.secret(&s) beside it.

Running the example

cargo run -p ex-09-lifecycle

Application phases

Builder, wire, connect, bind, listen and serve: what each phase does and what fails in it.

Shutdown

What happens between the signal and the exit: before-shutdown hooks, draining, the timeout cap and the report.

On this page

The five hooksOrderHooks are for singletonsClosure hooks and readiness checksReadiness checksSecrets in errorsRunning the example