ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Protocols

Integrations

RecipesServe static filesCompress responsesSecurity headers and CSRFSessions with tower-sessionsCookies with tower-cookiesRequest IDsAccess logError reporting with SentryLocalised responses with FluentA client as a providerA MongoDB ODM over the injected clientExplicit transactions with SQLxA mailer over lettreObject storage over the AWS SDKA CLI command with clapMocks with mockallFeature flags with OpenFeatureAuthorization with CedarMoving from axum or actix-web

Operating

Reference

Recipes

Request IDs

Give every request an x-request-id and echo it on the response with the tower-http SetRequestIdLayer and PropagateRequestIdLayer.

Each request carries an x-request-id: the caller's when it sent one, a new UUID otherwise. The handler reads it from the request headers and the response returns it, including the answers the framework writes for paths no route matches.

The recipe builds on examples/17-http-pre-dispatch. It compiled and ran on port 0 against tower-http 0.7.1 (feature request-id, which brings uuid with it).

tower-http = { version = "0.7", features = ["request-id"] }

The code

use tower_http::request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer};
use ulo::{App, AppBuilder, Module, ModuleDef, ModuleIdentity, controller, handlers, module};
use ulo_http::{HeaderMap, PreDispatch};

pub struct RequestIdModule;

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

    fn register(&self, m: &mut ModuleDef<'_>) {
        m.meta::<PreDispatch>()
            .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid))
            .layer(PropagateRequestIdLayer::x_request_id());
    }
}

#[controller]
pub struct EchoController;

#[handlers]
impl EchoController {
    #[ulo_http::get("/whoami")]
    fn whoami(&self, headers: HeaderMap) -> String {
        let id = headers.get("x-request-id").and_then(|value| value.to_str().ok()).unwrap_or("none");
        format!("handler saw {id}")
    }
}

#[module(imports = [RequestIdModule], controllers = [EchoController])]
pub struct AppModule;

pub fn builder() -> AppBuilder {
    App::builder(AppModule)
}

What each seam does

SetRequestIdLayer::x_request_id(MakeRequestUuid) sets x-request-id on the request when it has none and leaves a caller's value. PropagateRequestIdLayer::x_request_id() copies the request's x-request-id onto the response.

Declaration order is nesting order: the first layer declared is outermost. Set is declared first so it runs before Propagate reads the request header.

Observed with curl:

RequestAnswer
GET /whoamix-request-id: c3d6050d-0976-45b5-ba8e-0720def201cd, body handler saw c3d6050d-0976-45b5-ba8e-0720def201cd
GET /whoami, x-request-id: abc-123x-request-id: abc-123, body handler saw abc-123
GET /nowhere404 with a generated x-request-id

Failure modes

Declared in the other order, the generated id never reaches the response. With PropagateRequestIdLayer declared first, GET /whoami answered with the handler seeing a generated id and no x-request-id header on the response. A caller-supplied id still came back, because the header was already on the request.

The id is not on the span. The call span has no request-id field, so the access log lines do not print it. Log it from the handler (tracing::info!(request_id = ..)) or an interceptor.

A caller's id is trusted as sent. The layer keeps whatever x-request-id arrives. Do not use it as a key for anything that must be unique or unforgeable.

Outgoing calls do not carry it. The framework has no HTTP client, so forwarding the id downstream is the caller's code. For service-to-service correlation, trace context travels on every transport.

Reference

  • Middleware: layer and the order entries run in.
  • Logging and tracing: trace context across transports.

Cookies with tower-cookies

Read, set and sign cookies from a handler with the tower-cookies layer and a Host<Cookies> extractor.

Access log

One log line per request, with status and duration, from tracing-subscriber span-close events on the call span.

On this page

The codeWhat each seam doesFailure modesReference