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

The wiring report

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

wire() checks the whole application before any instance is built. It collects every problem it finds and returns them in one report, so one run shows the missing dependency, the cycle and the scope mistake.

This page follows examples/11-wiring-report, whose BrokenModule has one mistake of each of five kinds.

The five mistakes

/// Reads a binding nothing provides.
#[injectable]
pub struct Notifier {
    _mailer: Dep<dyn Mailer>,
}

#[module(providers = [SqlRepo as dyn Repo], exports = [dyn Repo])]
pub struct SqlModule;

#[module(providers = [MemoryRepo as dyn Repo], exports = [dyn Repo])]
pub struct MemoryModule;

/// A singleton cannot depend on something built per request.
#[injectable(execution)]
pub struct Session;

#[injectable(singleton)]
pub struct Directory {
    _session: Dep<Session>,
}

/// Two providers that need each other.
#[injectable]
pub struct Chicken {
    _egg: Dep<Egg>,
}

#[injectable]
pub struct Egg {
    _chicken: Dep<Chicken>,
}

#[module(
    imports = [SqlModule, MemoryModule, TwiceModule],
    providers = [Notifier, Reports, Session, Directory, Chicken, Egg],
)]
pub struct BrokenModule;

TwiceModule binds u32 twice with m.value(7_u32); m.value(8_u32);. It is written against the value API (impl Module, see Without macros) so that it can register the same key twice.

main prints the report on standard error and exits with status 1:

match ex_11_wiring_report::builder().wire() {
    Ok(_) => println!("wired"),
    Err(StartupError::Wiring(errors)) => {
        eprintln!("{errors}");
        std::process::exit(1);
    }
    Err(other) => panic!("{other}"),
}

Reading the report

The report opens with a count and then one block per problem. The first line of a block is the problem. The lines under it give its context: who reads the key, where it was declared, and a help: line.

error: wiring failed with 5 errors

  × duplicate binding for `u32` in TwiceModule
    ├─ first bound at src/lib.rs:LINE
    ├─ bound again at src/lib.rs:LINE
    └─ help: remove one, or give one a qualifier with `.qualified::<Q>()`

  × missing dependency `dyn Mailer`
    ├─ needed by Notifier (field `_mailer`) in BrokenModule
    └─ help: import a module that exports `dyn Mailer`, or provide it in BrokenModule

  × ambiguous dependency `dyn Repo` in BrokenModule
    ├─ needed by Reports (field `_repo`)
    ├─ exported by SqlModule      (src/lib.rs:LINE)
    └─ exported by MemoryModule   (src/lib.rs:LINE)

  × dependency cycle: Chicken → Egg → Chicken
    ├─ `Chicken` in BrokenModule
    └─ `Egg` in BrokenModule

  × scope violation: singleton `Directory` in BrokenModule depends on per-execution data
    └─ Directory → Session (execution)
       help: declare Directory #[injectable(execution)], or inject a factory

LINE stands for the line of the registration call. The example's test checks each headline.

  • A type name is cut to its last path segment, inside generic arguments too: Arc<PgPool>, not alloc::sync::Arc<my_app::db::PgPool>.
  • Where one report would print two different types alike, a::Config and b::Config, it prints those two with their full paths and the rest short. The same rule applies to module names.
  • A key prints as PgPool, or PgPool @ Replica. A collection adds (collection).
  • The second and later module of one type and qualifier, in registration order, carries #2, #3.
  • A configuration value is never printed in a module name, because it may hold credentials. A registered Secret<_> is replaced wherever it would appear.

StartupError and WiringErrors implement Debug as the same text as Display, so fn main() -> Result<(), Box<dyn Error>> prints the report when wire()? fails.

As data

A test or a tool reads the same problems as values. StartupError::Wiring(errors) holds WiringErrors, which iterates WiringError variants. The enum is #[non_exhaustive], with one variant per kind of problem.

let Err(StartupError::Wiring(errors)) = builder().wire() else {
    panic!("the broken app should fail wiring");
};
assert_eq!(errors.len(), 5);
let all: Vec<&WiringError> = errors.iter().collect();

let [duplicate, missing, ambiguous, cycle, scope] = all[..] else { unreachable!() };

let WiringError::Missing { key, consumer, module, near } = missing else { panic!("{missing:?}") };
assert_eq!((key.to_string(), consumer.as_str(), module.to_string()), ("dyn Mailer".into(), "Notifier (field `_mailer`)", "BrokenModule".into()));
assert!(near.is_none());

let WiringError::Cycle { path } = cycle else { panic!("{cycle:?}") };

Source locations (first, second, at) are &'static Locations captured by #[track_caller] on the registration call. The report prints them as file:line.

What wire() checks

The passes run in this order, and the errors appear in this order.

PassChecksVariants
1. Module graphIdentities deduplicated; settings compared across imports; a module importing itself; re-exports visible; exports bound; keyed modulesImportCycle, DifferingSettings, DuplicateSetting, ExportNotBound, ReexportNotVisible, ReexportAmbiguous, NestedKeyed, KeyedInput
2. BindingsDuplicate singles, single/collection mixes, dangling aliases, failed ? values, role-key misuse, duplicate readiness checks, unread route prefixes, controllers registered as providers, input conflicts; and in tests, overrides and replacementsDuplicateBinding, KindMix, DanglingAlias, ValueFailed, QualifiedRoleContribution, SingleRoleBinding, DuplicateReadiness, UnreadPrefix, ControllerProvided, InputConflict, Override*, Replacement*, DuplicateReplacement, TimerOverride, RuntimeOverride
3. VisibilityEvery injection point against its module's table; controller keys read by non-controllersMissing, Ambiguous, ControllerRead
4. CyclesA depth-first search over the resolved edges, one report per strongly connected componentCycle
5. ScopesNeeds-execution inference; hooks on per-execution types; closures that read execution data; inputs a transport does not seedScopeViolation, HooksOnPerExecution, ClosureNeedsExecution, ClosureScopeViolation, InputNotSeeded
6. EnvironmentEvery wait has a Timer; no zero boundBoundWithoutTimer, BackoffWithoutTimer, KnobWithoutTimer, ZeroBound, ZeroDefault

A step that depends on a missing piece skips only the affected edges, so one missing binding does not hide unrelated errors.

The same mistake in different places has a different help line. Some of them:

  • A Missing whose key matches a bound key up to a trailing + Send + Sync says PersistenceModule exports dyn Repo + Send + Sync; the injection point reads dyn Repo``. The two are different keys.
  • A Missing for dyn Timer or dyn Runtime says to set one on the app with .timer(..) or .runtime(..).
  • A Missing whose key is the same type from two versions of its crate says cargo tree -d lists them.
  • A ValueFailed is an expr? in a providers list that returned Err. The text is redacted.
  • A ControllerRead names the controller, the reader and both modules. Move the shared logic into a provider both can read.
  • A ControllerProvided names the module and call that registered a controller as a provider, and the module that registers it as a controller when there is one. Register it only as a controller.
  • An ImportCycle is a module that imports itself and prints as "M imports itself". Modules importing each other in a loop wire. An import is a visibility fact, and the instance graph is ordered by dependencies, not by imports. A loop of dependencies is a Cycle.
  • A DuplicateSetting is a setting name written twice in one module's settings, naming both calls.

Input not seeded

A per-execution service that reads a transport's execution input, such as the HTTP request head, fails wiring when it is reachable from a handler on a transport that does not seed that input:

  × input `RequestHead` is seeded by Http, read on a path from the Rpc handler UsersController::get_rpc
    ├─ UsersController::get_rpc (Rpc) → AuditContext (execution) → Dep<RequestHead> (field `head`)
    └─ help: read it as `Option<Dep<RequestHead>>` where the path is shared across transports

The wording is that of InputNotSeeded in crates/ulo/src/error/wiring.rs.

After wire(): runtime errors

Wiring cannot see everything. These arrive later, as values:

ErrorFromMeaning
StartupError::Connect(ConnectError)connect()A construction, readiness check or init hook failed.
StartupError::Configure(ConfigureErrors)listen()One or more servers' prepare failed; collected before anything binds.
StartupError::Bind { transport, source }listen()A socket could not open, or the app has no Runtime.
LookupErrorget, ModuleRef::get, exec.getNotFound, NotReady, WrongType, WrongKind, ExecutionRequired, ExecutionEnded, Ambiguous, AmbiguousModule, Construct, Closed.
LoadErrorAppHandle::loadWiring, Connect, Refused(LoadRefusal) or Closed.
ShutdownErrorserve, closeHook, close or serve failures, and the error carries the report.

Compile-time diagnostics

Whatever is local to one type is checked by the compiler, with messages written as instructions. A field that is not an injection point says to write Dep<T> or mark the field #[injectable(default)]. A provider in a providers list that does not implement Construct points at the entry. A bound on a role says what to implement. Dep<T> with a T that is not Send + Sync gets the auto trait's own error with no hint.

Running the example

cargo run -p ex-11-wiring-report

Standalone executions

Running a job or a command with no server: execute, per-execution data, deadlines and close.

Without macros

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

On this page

The five mistakesReading the reportAs dataWhat wire() checksInput not seededAfter wire(): runtime errorsCompile-time diagnosticsRunning the example