Skip to content

Commit

Permalink
feat: [#612] tower middleware to apply timeouts to requests
Browse files Browse the repository at this point in the history
  • Loading branch information
josecelano committed May 15, 2024
1 parent 112b76d commit 9e42a1a
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/servers/apis/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@
use std::sync::Arc;
use std::time::Duration;

use axum::error_handling::HandleErrorLayer;
use axum::http::HeaderName;
use axum::response::Response;
use axum::routing::get;
use axum::{middleware, Router};
use hyper::Request;
use axum::{middleware, BoxError, Router};
use hyper::{Request, StatusCode};
use torrust_tracker_configuration::AccessTokens;
use tower::timeout::TimeoutLayer;
use tower::ServiceBuilder;
use tower_http::compression::CompressionLayer;
use tower_http::propagate_header::PropagateHeaderLayer;
use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer};
Expand All @@ -25,6 +28,8 @@ use super::v1::context::health_check::handlers::health_check_handler;
use super::v1::middlewares::auth::State;
use crate::core::Tracker;

const TIMEOUT: Duration = Duration::from_secs(5);

/// Add all API routes to the router.
#[allow(clippy::needless_pass_by_value)]
pub fn router(tracker: Arc<Tracker>, access_tokens: Arc<AccessTokens>) -> Router {
Expand Down Expand Up @@ -73,4 +78,11 @@ pub fn router(tracker: Arc<Tracker>, access_tokens: Arc<AccessTokens>) -> Router
}),
)
.layer(SetRequestIdLayer::x_request_id(MakeRequestUuid))
.layer(
ServiceBuilder::new()
// this middleware goes above `TimeoutLayer` because it will receive
// errors returned by `TimeoutLayer`
.layer(HandleErrorLayer::new(|_: BoxError| async { StatusCode::REQUEST_TIMEOUT }))
.layer(TimeoutLayer::new(TIMEOUT)),
)
}

0 comments on commit 9e42a1a

Please sign in to comment.