Skip to content

Commit

Permalink
chore: [#468] set and propagate request ID
Browse files Browse the repository at this point in the history
It propagates the request ID to the response.

If the request does not have an ID it sets a newly
generated UUID.

Without providing ID:

```
$ curl -i localhost:3001/v1/about/license
HTTP/1.1 200 OK
content-type: text/html; charset=utf-8
content-length: 1262
x-request-id: cea0efcd-84e0-4f59-96b3-625ca4154396
date: Mon, 12 Feb 2024 16:58:05 GMT
```

Providing ID:

```
$ curl -i -H "x-request-id: a5030c7a-5302-49d4-8e66-f0f0ab0e3ce3" localhost:3001/v1/about/license
HTTP/1.1 200 OK
content-type: text/html; charset=utf-8
content-length: 1262
x-request-id: a5030c7a-5302-49d4-8e66-f0f0ab0e3ce3
date: Mon, 12 Feb 2024 16:59:31 GMT
```

The response contains the provided ID in the request.
  • Loading branch information
josecelano committed Feb 12, 2024
1 parent 3ec28ba commit db6a62f
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/web/api/server/v1/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,19 @@ use std::env;
use std::sync::Arc;

use axum::extract::DefaultBodyLimit;
use axum::http::{HeaderName, HeaderValue};
use axum::response::Redirect;
use axum::routing::get;
use axum::{Json, Router};
use hyper::Request;
use serde_json::{json, Value};
use tower_http::compression::CompressionLayer;
use tower_http::cors::CorsLayer;
use tower_http::propagate_header::PropagateHeaderLayer;
use tower_http::request_id::{MakeRequestId, RequestId, SetRequestIdLayer};
use tower_http::trace::{DefaultMakeSpan, DefaultOnRequest, DefaultOnResponse, TraceLayer};
use tracing::Level;
use uuid::Uuid;

use super::contexts::{about, category, proxy, settings, tag, torrent, user};
use crate::bootstrap::config::ENV_VAR_CORS_PERMISSIVE;
Expand Down Expand Up @@ -57,6 +62,8 @@ pub fn router(app_data: Arc<AppData>) -> Router {
.on_request(DefaultOnRequest::new().level(Level::INFO))
.on_response(DefaultOnResponse::new().level(Level::INFO)),
)
.layer(PropagateHeaderLayer::new(HeaderName::from_static("x-request-id")))
.layer(SetRequestIdLayer::x_request_id(RequestIdGenerator))
}

/// Endpoint for container health check.
Expand All @@ -67,3 +74,13 @@ async fn health_check_handler() -> Json<Value> {
async fn redirect_to_about() -> Redirect {
Redirect::permanent(&format!("/{API_VERSION_URL_PREFIX}/about"))
}

#[derive(Clone, Default)]
struct RequestIdGenerator;

impl MakeRequestId for RequestIdGenerator {
fn make_request_id<B>(&mut self, _request: &Request<B>) -> Option<RequestId> {
let id = HeaderValue::from_str(&Uuid::new_v4().to_string()).expect("UUID is a valid HTTP header value");
Some(RequestId::new(id))
}
}

0 comments on commit db6a62f

Please sign in to comment.