Skip to content

Commit db6a62f

Browse files
committed
chore: [#468] set and propagate request ID
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.
1 parent 3ec28ba commit db6a62f

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

src/web/api/server/v1/routes.rs

+17
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,19 @@ use std::env;
33
use std::sync::Arc;
44

55
use axum::extract::DefaultBodyLimit;
6+
use axum::http::{HeaderName, HeaderValue};
67
use axum::response::Redirect;
78
use axum::routing::get;
89
use axum::{Json, Router};
10+
use hyper::Request;
911
use serde_json::{json, Value};
1012
use tower_http::compression::CompressionLayer;
1113
use tower_http::cors::CorsLayer;
14+
use tower_http::propagate_header::PropagateHeaderLayer;
15+
use tower_http::request_id::{MakeRequestId, RequestId, SetRequestIdLayer};
1216
use tower_http::trace::{DefaultMakeSpan, DefaultOnRequest, DefaultOnResponse, TraceLayer};
1317
use tracing::Level;
18+
use uuid::Uuid;
1419

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

6269
/// Endpoint for container health check.
@@ -67,3 +74,13 @@ async fn health_check_handler() -> Json<Value> {
6774
async fn redirect_to_about() -> Redirect {
6875
Redirect::permanent(&format!("/{API_VERSION_URL_PREFIX}/about"))
6976
}
77+
78+
#[derive(Clone, Default)]
79+
struct RequestIdGenerator;
80+
81+
impl MakeRequestId for RequestIdGenerator {
82+
fn make_request_id<B>(&mut self, _request: &Request<B>) -> Option<RequestId> {
83+
let id = HeaderValue::from_str(&Uuid::new_v4().to_string()).expect("UUID is a valid HTTP header value");
84+
Some(RequestId::new(id))
85+
}
86+
}

0 commit comments

Comments
 (0)