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 factoryLINE 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>, notalloc::sync::Arc<my_app::db::PgPool>. - Where one report would print two different types alike,
a::Configandb::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, orPgPool @ 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.
| Pass | Checks | Variants |
|---|---|---|
| 1. Module graph | Identities deduplicated; settings compared across imports; a module importing itself; re-exports visible; exports bound; keyed modules | ImportCycle, DifferingSettings, DuplicateSetting, ExportNotBound, ReexportNotVisible, ReexportAmbiguous, NestedKeyed, KeyedInput |
| 2. Bindings | Duplicate 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 replacements | DuplicateBinding, KindMix, DanglingAlias, ValueFailed, QualifiedRoleContribution, SingleRoleBinding, DuplicateReadiness, UnreadPrefix, ControllerProvided, InputConflict, Override*, Replacement*, DuplicateReplacement, TimerOverride, RuntimeOverride |
| 3. Visibility | Every injection point against its module's table; controller keys read by non-controllers | Missing, Ambiguous, ControllerRead |
| 4. Cycles | A depth-first search over the resolved edges, one report per strongly connected component | Cycle |
| 5. Scopes | Needs-execution inference; hooks on per-execution types; closures that read execution data; inputs a transport does not seed | ScopeViolation, HooksOnPerExecution, ClosureNeedsExecution, ClosureScopeViolation, InputNotSeeded |
| 6. Environment | Every wait has a Timer; no zero bound | BoundWithoutTimer, 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
Missingwhose key matches a bound key up to a trailing+ Send + SyncsaysPersistenceModule exportsdyn Repo + Send + Sync; the injection point readsdyn Repo``. The two are different keys. - A
Missingfordyn Timerordyn Runtimesays to set one on the app with.timer(..)or.runtime(..). - A
Missingwhose key is the same type from two versions of its crate sayscargo tree -dlists them. - A
ValueFailedis anexpr?in aproviderslist that returnedErr. The text is redacted. - A
ControllerReadnames the controller, the reader and both modules. Move the shared logic into a provider both can read. - A
ControllerProvidednames 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
ImportCycleis 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 aCycle. - A
DuplicateSettingis a setting name written twice in one module'ssettings, 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 transportsThe 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:
| Error | From | Meaning |
|---|---|---|
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. |
LookupError | get, ModuleRef::get, exec.get | NotFound, NotReady, WrongType, WrongKind, ExecutionRequired, ExecutionEnded, Ambiguous, AmbiguousModule, Construct, Closed. |
LoadError | AppHandle::load | Wiring, Connect, Refused(LoadRefusal) or Closed. |
ShutdownError | serve, close | Hook, 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