ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Request LifecycleMiddlewareGuardsInterceptorsError Handling

Protocols

Integrations

Operating

Reference

Request Lifecycle

Middleware

The pre-dispatch stage on HTTP, where CORS, tower layers and path-scoped middleware run before a guard does.

Middleware is the one role that runs before the handler is chosen. It takes the whole HTTP request and either passes it on or answers it. Anything that needs a route, a context or a typed error belongs in a guard or an interceptor instead.

Middleware is HTTP-specific, and gRPC has a stage of the same shape (PreDispatch<Grpc>). The example for this page is examples/17-http-pre-dispatch.

Writing a middleware

A middleware implements Middleware, takes the request and a Next, and answers a Result<Response, BoxError>. It is an ordinary container binding, so it takes dependencies with Dep<T>. Hits below is the example's own request counter.

use std::sync::atomic::Ordering;

use ulo::{BoxError, Dep, injectable};
use ulo_http::middleware::Next;
use ulo_http::{CallError, Middleware, Request, Response};

#[injectable]
pub struct ApiKey {
    hits: Dep<Hits>,
}

impl Middleware for ApiKey {
    async fn handle(&self, req: Request, next: Next<'_>) -> Result<Response, BoxError> {
        self.hits.count.fetch_add(1, Ordering::SeqCst);
        if req.headers().get("x-api-key").is_none_or(|key| key != "sesame") {
            return Err(CallError::unauthorized("ApiKey").into());
        }
        next.run(req).await
    }
}

A middleware does not render its own failures. It returns Err, and the application's error handlers shape the answer. Unclaimed, CallError::unauthorized("ApiKey") becomes a 401 with WWW-Authenticate: ApiKey. A panic in a middleware is caught at the entry's boundary and arrives as PanicRecovered.

next.run(req) answers Ok with the response of everything inside, including the response an inner failure was already rendered into. An outer middleware therefore decorates the 401 an inner one produced: a CORS entry adds its headers to it, which a browser needs to read the status.

Declaring the stage

The stage is module metadata, m.meta::<PreDispatch>(). The #[module] macro has no slot for it, so a module that declares one implements Module by hand.

use ulo::{Module, ModuleDef, ModuleIdentity};
use ulo_http::{Cors, Method, PreDispatch};

impl Module for EdgeModule {
    fn identity(&self) -> ModuleIdentity {
        ModuleIdentity::of_type::<Self>()
    }

    fn register(&self, m: &mut ModuleDef<'_>) {
        m.provide::<Hits>();
        m.provide::<ApiKey>();
        m.export::<Hits>();
        m.meta::<PreDispatch>()
            .layer(served_by())
            .apply_value(TagTenant)
            .apply_value(Cors::new().allow_origin("https://app.example").allow_methods([Method::GET]))
            .apply_for::<ApiKey>(["/admin/*"])
            .exclude(["/admin/health"]);
    }
}
MethodEffect
apply::<M>()the middleware M, resolved through the container, for every request
apply_value(m)a middleware value built at the declaration site
apply_for::<M>(patterns)M for requests whose path matches one of the patterns
layer(l)a tower::Layer for every request
layer_for(patterns, l)a tower layer scoped by pattern
exclude(patterns)removes paths from the entry written just before it
adopt::<T>()copies a T the request carries in its http::Extensions into the execution
supplies::<T>()declares that the entry before it inserts a T; read only by an embedding

Several modules may declare entries. The stage runs them in the order written, with modules in collection order.

Scopes

A scope is a route pattern whose last segment may be * or {*name}, matching one or more segments. /admin/* matches /admin/users and /admin/7/notes, not /admin. The scope is matched against the request path whether or not a route matches it, so an anonymous /admin/x answers 401 from ApiKey. The status does not tell a caller which admin routes exist.

The server refuses to start when a scope shares no path with any route: ["/admin/*", "/typo"] fails for /typo. An empty pattern list is refused too.

In the example, /admin/panel runs the entry and /admin/health skips it. tests/pre_dispatch.rs asserts that neither the excluded route nor a route outside /admin/* increments the counter.

Two sub-steps

The stage runs in two sub-steps because a path rewrite has to happen before routing, while a scoped entry's failure goes to the matched handler's error tiers.

  1. Unscoped entries run first. They can rewrite the path with req.set_path(..), they see misses, and they can answer without calling next, which is how a CORS preflight is answered.
  2. The route is matched. Entries whose scope matches the path run next, and a request no route matches runs them too, before its 404 or 405.

An unscoped entry's failure reaches only the global error handlers. A scoped entry's failure reaches the matched handler's tiers first.

Tower layers

.layer(l) takes any tower::Layer over ulo_http::Service, and .layer_for(patterns, l) scopes one by pattern. Layers are composed once at startup. An unscoped layer wraps the whole stage, so it sees misses and preflights.

pub fn served_by() -> tower::util::MapResponseLayer<fn(Response) -> Response> {
    tower::util::MapResponseLayer::new(|mut reply: Response| {
        reply.headers_mut().insert("x-served-by", HeaderValue::from_static("ulo"));
        reply
    })
}

In the example this layer stamps every answer, a 401 refusal, a 404 and a CORS preflight included.

Two limits come with tower:

  • A layer's Err and panic reach the error handlers. A response a layer builds itself, such as tower-http's auth layer answering 401, stays a response, and the handlers do not see it.
  • The chain behind a layer is one-shot. A layer that calls its inner service twice for one request, a retry layer for example, or that builds a new request without the original's extensions, gets a bare 500 and an error log line. Retries belong in a client.

Handing a value to a handler

A middleware that authenticates a request often has a value to pass on. It inserts the value into the request's http::Extensions, and a handler takes it as Host<T>.

#[derive(Clone)]
pub struct Tenant(pub String);

impl Middleware for TagTenant {
    async fn handle(&self, mut req: Request, next: Next<'_>) -> Result<Response, BoxError> {
        if let Some(tenant) = req.headers().get("x-tenant").and_then(|value| value.to_str().ok()).map(str::to_owned) {
            req.head.extensions.insert(Tenant(tenant));
        }
        next.run(req).await
    }
}
#[ulo_http::get("/tenant")]
fn tenant(&self, Host(tenant): Host<Tenant>) -> String {
    tenant.0
}

#[ulo_http::get("/tenant-or-none")]
fn tenant_or_none(&self, tenant: Option<Host<Tenant>>) -> String {
    tenant.map_or_else(|| "none".to_owned(), |Host(tenant)| tenant.0)
}

A request without the header is a 500 for Host<Tenant>, because the missing value is a deployment fault and the type stays server-side. Option<Host<Tenant>> reads None instead.

.adopt::<T>() copies a value from the request's extensions into the execution at its place in the declaration order, so downstream code reads it as Ext<T>. It adds an entry and does not insert anything itself.

CORS

Cors is a middleware that ships with ulo-http. CORS covers its options.

What is not here

There is no per-module middleware. Auth for a group of routes is a pattern-scoped entry, which runs before guards and can hand a value to the handler. Logging, metrics or transforming responses is an interceptor, and rejecting a call by a rule is a guard.

Request Lifecycle

The one pipeline every transport runs a call through, in the order it runs.

Guards

Admit or refuse a call before the interceptors and the handler are built.

On this page

Writing a middlewareDeclaring the stageScopesTwo sub-stepsTower layersHanding a value to a handlerCORSWhat is not here