Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to bind a variable to a request in tower-http / hyper / axum?

I'm trying to add a request id to each tracing event. I can do it with tower_http::trace like this:

#[derive(Clone)]
pub struct RequestSpan;

impl<B> tower_http::trace::MakeSpan<B> for RequestSpan {
    fn make_span(&mut self, request: &http::Request<B>) -> tracing::Span {
        tracing::error_span!(
            "rq",
            id = %ulid::Ulid::new().to_string(),
            method = %request.method(),
            uri = %request.uri(),
            version = ?request.version(),
        )
    }
}

...

let middleware_stack = tower::ServiceBuilder::new()
    .layer(TraceLayer::new_for_http().make_span_with(RequestSpan))

It works in the scope of the server, but I also need to pass the request id into an external task queue. Any suggestions?

like image 538
imbolc Avatar asked Oct 22 '25 16:10

imbolc


1 Answers

Custom data can be stored on requests via Extensions. They are accessible via .extensions() and .extensions_mut() on a http::request::Request (which works for hyper and tower-http) or via the same methods on axum::response::RequestParts (which works for axum).

Extensions are primarily used to move data between services/middleware to the route handler and vice-versa. The collection acts like a map with values keyed-off of their type, so if you want to store a Ulid you probably want to wrap it in some more descriptive type like RequestId(Ulid) just to ensure it doesn't conflict with other uses.

See also:

  • What is the role of a "Extension" in actix-web?
  • What are Rust's HTTP extensions? (blog)
like image 102
kmdreko Avatar answered Oct 24 '25 13:10

kmdreko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!