Application phases
Builder, wire, connect, bind, listen and serve: what each phase does and what fails in it.
An application starts in separate calls, and each call returns a value of a different type. The compiler therefore stops you from serving an application you have not connected. Each phase has one job and its own error.
use ulo_http_hyper::Server;
use ulo_runtime_tokio::{Tokio, shutdown_signal};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let port = std::env::var("PORT").unwrap_or_else(|_| "3000".into());
let app = ex_02_providers::builder()
.runtime(Tokio::current())
.wire()?
.connect()
.await?
.bind(Server::new(format!("127.0.0.1:{port}")))
.listen()
.await?;
for bound in app.addresses() {
println!("listening on http://{}", bound.addr);
}
app.serve(shutdown_signal()).await?;
Ok(())
}This is main in examples/02-providers. Every example that serves HTTP has the same one.
| Call | Type returned | Does | Fails with |
|---|---|---|---|
App::builder(root) | AppBuilder | Names the root module. | |
.runtime(r) / .timer(t) and the timeout knobs | AppBuilder | Sets the clock and executor. | |
.wire() | App<Wired> | Builds the graph and validates all of it. No instances, no I/O. | StartupError::Wiring |
.connect().await | App<Connected> | Builds singletons, runs readiness checks and hooks. | StartupError::Connect |
.bind(server) | App<Connected> | Queues a transport. | |
.listen().await | App<Bound> | Prepares every queued transport, then opens the sockets. | StartupError::Configure, StartupError::Bind |
.serve(signal).await | Result<Shutdown, ShutdownError> | Serves until the signal resolves or something closes the app. | ShutdownError |
Builder: the runtime and the clock
.runtime(Tokio::current()) supplies the executor and the clock. A clock is a Timer. Every wait the core performs is timed by it: construction bounds, hook bounds, readiness backoff, the drain and the shutdown cap. A binding that is read as Dep<dyn Timer> or Dep<dyn Runtime> gets the same objects, so a service that needs the time reads the app's clock and a test can replace it.
.timer(t) sets the clock alone, and is enough for an application that binds no transport. .runtime(r) sets both. Each call overrides only what it sets, in order, so .runtime(r).timer(t) is r's spawning with t's clock.
| Knob | Default | Bounds |
|---|---|---|
construct_timeout | 30 s | One construction. Also the default bound on one attempt of a readiness check. |
hook_timeout | 10 s | One lifecycle hook. |
drain_timeout | 10 s | In-flight executions at shutdown. Zero is accepted. |
shutdown_timeout | unset | The whole close sequence. Zero is accepted. |
All four are timed by the Timer. A knob set on a builder with no timer, or any written wait (.timeout, .attempt_timeout, .backoff, an After(..)), is a wiring error. construct_timeout(ZERO) and hook_timeout(ZERO) are refused too, since every item left at its default would time out before it started. Write .unbounded() on the items instead.
Wire
wire() runs six passes over every module: the module graph, bindings, visibility, dependency cycles, scopes, and the environment (clock and timeouts). It collects errors. It never stops at the first one, and a step that depends on a missing piece skips only the affected edges, so one missing binding does not hide the others.
wire() creates no instance and touches no network, so it is safe in a unit test. See Testing. Its error is the wiring report.
Connect
connect() builds the singleton graph in dependency order. For each binding it constructs the instance and runs that binding's readiness check. It then runs every OnModuleInit hook, then every OnApplicationBootstrap hook.
The order is stable: among bindings whose dependencies are done, the one with the smallest (module position, declaration position) goes next. Two bindings with no edge between them run in the same order every time.
The first failure stops the walk and connect() returns StartupError::Connect(ConnectError). It carries one of:
Construct { key, module, reason }: a constructor or factory returnedErr, panicked or timed out.Readiness { key, module, attempts, reason }: a readiness check never passed.Hook { hook, key, reason }: an init or bootstrap hook failed.
reason is a FailureReason: Errored with your error, Panicked with the message, or TimedOut with the duration and which limit fired. After a failed connect the app is dropped. The singletons built so far run no destroy or shutdown hook, and their resources release as the instances drop.
Bind, listen and serve
bind(server) queues a transport. Pass several: Server for HTTP, and servers from the RPC, WebSocket and gRPC crates. listen() then:
- Refuses an application with no
Runtimebefore anything else, asStartupError::BindwhosesourceisRuntimeMissing { transport }. A runtime is also a timer, so an app given.timer(..)alone is refused. A served app with no clock would run a zero-length drain and cut every in-flight request at shutdown. - Calls
prepareon every server: route tables, duplicate-route checks, TLS loading and similar. Every failure from every server is collected intoStartupError::Configure, so a configuration error is reported before a port conflict. Apreparethat panics is reported as that server's entry. - Opens the sockets, in the order queued. If one fails, those already open are closed before the error returns, as
StartupError::Bind.
app.addresses() lists what each server bound. A server given port 0 reports the port the OS chose. app.handle() returns an AppHandle, a Clone + Send + Sync view that outlives serve.
serve(signal) takes the app by value and runs until the signal future resolves, handle.close(..) is called, or one transport's serve loop ends while the app is running. It returns the Shutdown report.
shutdown_signal() in ulo-runtime-tokio resolves with a Signal named after the signal received: SIGINT or SIGTERM on Unix, and Ctrl-C or Ctrl-Close on Windows ("SIGTERM", "SIGINT", "CTRL_C", "CTRL_CLOSE"). The framework installs no signal handler of its own. Passing this future is how a process wires them.
An application with no server
A job or a command stops after connect(), uses get or execute, and calls close(Signal::new("done")). No transport is bound and listen() is never called. See Standalone executions.
Phases of a running app
handle.phase() reports Phase::Running, Stopping, Draining, Destroying or Closed. The shutdown page lists what each permits.
Where the phases are tested
examples/02-providers/tests/binary.rsruns the compiled binary on a free port and ends it with SIGTERM.crates/ulo/tests/phases.rsandstartup_errors.rscover the typestates and the startup errors.