Skip to content

Commit 82c9792

Browse files
committed
feat: [¬12] tower middleware to apply timeouts to requests
1 parent 112b76d commit 82c9792

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

src/servers/apis/routes.rs

+14-2
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,15 @@
88
use std::sync::Arc;
99
use std::time::Duration;
1010

11+
use axum::error_handling::HandleErrorLayer;
1112
use axum::http::HeaderName;
1213
use axum::response::Response;
1314
use axum::routing::get;
14-
use axum::{middleware, Router};
15-
use hyper::Request;
15+
use axum::{middleware, BoxError, Router};
16+
use hyper::{Request, StatusCode};
1617
use torrust_tracker_configuration::AccessTokens;
18+
use tower::timeout::TimeoutLayer;
19+
use tower::ServiceBuilder;
1720
use tower_http::compression::CompressionLayer;
1821
use tower_http::propagate_header::PropagateHeaderLayer;
1922
use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer};
@@ -25,6 +28,8 @@ use super::v1::context::health_check::handlers::health_check_handler;
2528
use super::v1::middlewares::auth::State;
2629
use crate::core::Tracker;
2730

31+
const TIMEOUT: Duration = Duration::from_secs(5);
32+
2833
/// Add all API routes to the router.
2934
#[allow(clippy::needless_pass_by_value)]
3035
pub fn router(tracker: Arc<Tracker>, access_tokens: Arc<AccessTokens>) -> Router {
@@ -73,4 +78,11 @@ pub fn router(tracker: Arc<Tracker>, access_tokens: Arc<AccessTokens>) -> Router
7378
}),
7479
)
7580
.layer(SetRequestIdLayer::x_request_id(MakeRequestUuid))
81+
.layer(
82+
ServiceBuilder::new()
83+
// this middleware goes above `TimeoutLayer` because it will receive
84+
// errors returned by `TimeoutLayer`
85+
.layer(HandleErrorLayer::new(|_: BoxError| async { StatusCode::REQUEST_TIMEOUT }))
86+
.layer(TimeoutLayer::new(TIMEOUT)),
87+
)
7688
}

0 commit comments

Comments
 (0)