Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SetRequestId and PropagateRequestId middleware #150

Merged
merged 13 commits into from
Nov 22, 2021
Merged

Conversation

davidpdrsn
Copy link
Member

@davidpdrsn davidpdrsn commented Oct 6, 2021

Fixes #135

Example usage:

use http::{Request, Response, header::HeaderName};
use tower::{Service, ServiceExt, ServiceBuilder};
use tower_http::request_id::{
    SetRequestIdLayer, PropagateRequestIdLayer, MakeRequestId, RequestId,
};
use hyper::Body;
use std::sync::{Arc, atomic::{AtomicU64, Ordering}};

// A `MakeRequestId` that increments an atomic counter
#[derive(Clone, Default)]
struct MyMakeRequestId {
    counter: Arc<AtomicU64>,
}

impl MakeRequestId for MyMakeRequestId {
    fn make_request_id<B>(&mut self, request: &Request<B>) -> Option<RequestId> {
        let request_id = self.counter
            .fetch_add(1, Ordering::SeqCst)
            .to_string()
            .parse()
            .unwrap();

        Some(RequestId::new(request_id))
    }
}

let x_request_id = HeaderName::from_static("x-request-id");

ServiceBuilder::new()
    // set `x-request-id` header on all requests
    .layer(SetRequestIdLayer::new(
        x_request_id.clone(),
        MyMakeRequestId::default(),
    ))
    // propagate `x-request-id` headers from request to response
    .layer(PropagateRequestIdLayer::new(x_request_id))
    .service(handler);

Or slightly shorter using ServiceBuilderExt:

use tower_http::ServiceBuilderExt;

ServiceBuilder::new()
    .set_x_request_id(MyMakeRequestId::default())
    .propagate_x_request_id()
    .service(handler);

These are two different middleware since they need to be applied around any logging you might have. The docs have an example.

@davidpdrsn davidpdrsn added the A-new-middleware Area: new middleware proposals label Oct 6, 2021
@davidpdrsn davidpdrsn added this to the 0.2.0 milestone Nov 8, 2021
@davidpdrsn davidpdrsn changed the title Add SetRequestId middleware Add SetRequestId and PropagateRequestId middleware Nov 19, 2021
@davidpdrsn davidpdrsn marked this pull request as ready for review November 19, 2021 14:45
@davidpdrsn
Copy link
Member Author

@DoumanAsh what do you think about this?

Copy link

@DoumanAsh DoumanAsh left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That looks pretty good and generic too for most use cases
I left some comments based on my own middleware

tower-http/src/request_id.rs Outdated Show resolved Hide resolved
tower-http/src/request_id.rs Outdated Show resolved Hide resolved
tower-http/src/request_id.rs Show resolved Hide resolved
tower-http/src/request_id.rs Outdated Show resolved Hide resolved
tower-http/src/request_id.rs Show resolved Hide resolved
davidpdrsn added a commit that referenced this pull request Nov 20, 2021
OpenTelemetry defines a bunch of [conventions for HTTP
spans][conventions]. This makes adopting those conventions easy when
using `Trace`:

```rust
.layer(TraceLayer::new_for_http().opentelemetry_server())
```

This changes the span for the request to:

- Name: HTTP request
- Fields:
  - `http.flavor`: "1.1"
  - `http.host`: "localhost:3000"
  - `http.method`: "GET"
  - `http.route`: "/users/123". Can be configured by user to instead be
  the path pattern for the route, ie `/users/:id`
  - `http.scheme`: "http". Must be set by user as middleware don't know
  this
  - `http.target`: "/users/123"
  - `http.user_agent`: "curl/7.64.1"
  - `http.client_ip`: Must be extracted by user in a "make service"
  - `http.status_code`: 200
  - `request_id`: Requires #150.
  - `otel.kind`: "server"
  - `otel.status_code`: Unset or "ERROR"
  - `exception.message`: Set by user based on response classification.
  - `exception.details`: Set by user based on response classification.

The fields are a bit different for HTTP clients hence the name
`opentelemetry_server`. I don't think supporting clients initially is
required. We can always add it later.

TODO

- [ ] Add `Trace::opentelemetry_server` method. Currently it only exists
  on the layer
- [ ] Docs
- [ ] Example using axum and `opentelemetry_jaeger`
- [ ] Changelog

[conventions]: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md
Copy link
Collaborator

@Nehliin Nehliin left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Really like this feature! Will be super nice when its merged, I only had a couple of small comments

tower-http/src/builder.rs Outdated Show resolved Hide resolved
tower-http/src/builder.rs Outdated Show resolved Hide resolved
tower-http/src/request_id.rs Show resolved Hide resolved
tower-http/src/request_id.rs Show resolved Hide resolved
tower-http/src/request_id.rs Outdated Show resolved Hide resolved
tower-http/src/request_id.rs Outdated Show resolved Hide resolved
Copy link
Collaborator

@Nehliin Nehliin left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎉

Copy link
Collaborator

@MarcusGrass MarcusGrass left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, convenient implementation

@davidpdrsn davidpdrsn enabled auto-merge (squash) November 22, 2021 11:51
@davidpdrsn davidpdrsn merged commit 37fce42 into master Nov 22, 2021
@davidpdrsn davidpdrsn deleted the request-id branch November 22, 2021 12:01
@davidpdrsn davidpdrsn mentioned this pull request Dec 1, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-new-middleware Area: new middleware proposals
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Proposal for X-Request-Id
4 participants