Skip to content

Commit

Permalink
feature: adding timeout http layer + db connection timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
kaplanelad committed Dec 3, 2023
1 parent d7d3a6d commit bca0bfa
Show file tree
Hide file tree
Showing 12 changed files with 73 additions and 3 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,11 @@ tracing-subscriber = { version = "0.3.16", features = ["env-filter"] }
duct = "0.13.6"

config = "0.13.3"
tower-http = { version = "0.5.0", features = ["trace", "catch-panic"] }
tower-http = { version = "0.5.0", features = [
"trace",
"catch-panic",
"timeout",
] }
byte-unit = "4.0.19"

jsonwebtoken = { version = "9.1.0", optional = true }
Expand Down
1 change: 1 addition & 0 deletions examples/demo/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions examples/demo/config/development.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ server:
enable: true
catch_panic:
enable: true
catch_panic:
enable: true
timeout_request:
enable: true
timeout: 5000
workers:
mode: BackgroundQueue
mailer:
Expand All @@ -29,6 +34,8 @@ database:
uri: postgres://loco:loco@localhost:5432/loco_app
# uri: sqlite://db.sqlite?mode=rwc
enable_logging: false
connect_timeout: 500
idle_timeout: 500
min_connections: 1
max_connections: 1
auto_migrate: true
Expand Down
7 changes: 6 additions & 1 deletion examples/demo/config/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@ server:
enable: true
catch_panic:
enable: true
timeout_request:
enable: true
timeout: 5000
workers:
mode: ForegroundBlocking
mode: ForegroundBlockingc
mailer:
smtp:
enable: true
Expand All @@ -27,6 +30,8 @@ mailer:
database:
uri: postgres://loco:loco@localhost:5432/loco_app
enable_logging: false
connect_timeout: 500
idle_timeout: 1000
min_connections: 1
max_connections: 1
auto_migrate: true
Expand Down
13 changes: 13 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ pub struct Database {
pub min_connections: u32,
/// Maximum number of connections for a pool
pub max_connections: u32,
/// Set the timeout duration when acquiring a connection
pub connect_timeout: u64,
/// Set the idle duration before closing a connection
pub idle_timeout: u64,
#[serde(default)]
/// Run migration up when application loaded
pub auto_migrate: bool,
Expand Down Expand Up @@ -129,6 +133,15 @@ pub struct Middlewares {
pub logger: Option<EnableMiddleware>,
/// catch any code panic and log the error.
pub catch_panic: Option<EnableMiddleware>,
/// Setting a global timeout for the requests
pub timeout_request: Option<TimeoutRequestMiddleware>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TimeoutRequestMiddleware {
pub enable: bool,
// Timeout request in milliseconds
pub timeout: u64,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
Expand Down
22 changes: 21 additions & 1 deletion src/controller/app_routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
use axum::{http::Request, Router as AXRouter};
use lazy_static::lazy_static;
use regex::Regex;
use tower_http::{catch_panic::CatchPanicLayer, trace::TraceLayer};
use std::time::Duration;
use tower_http::{catch_panic::CatchPanicLayer, timeout::TimeoutLayer, trace::TraceLayer};

use super::routes::Routes;
use crate::{app::AppContext, config, Result};
Expand Down Expand Up @@ -173,6 +174,16 @@ impl AppRoutes {
app = Self::add_logger_middleware(app);
}
}
if let Some(logger) = &ctx.config.server.middlewares.logger {
if logger.enable {
app = Self::add_logger_middleware(app);
}
}
if let Some(timeout_request) = &ctx.config.server.middlewares.timeout_request {
if timeout_request.enable {
app = Self::add_timeout_middleware(app, timeout_request);
}
}
Ok(app.with_state(ctx))
}

Expand Down Expand Up @@ -212,4 +223,13 @@ impl AppRoutes {
tracing::info!("[Middleware] Adding log trace id",);
app
}
fn add_timeout_middleware(
app: AXRouter<AppContext>,
config: &config::TimeoutRequestMiddleware,
) -> AXRouter<AppContext> {
let app = app.layer(TimeoutLayer::new(Duration::from_millis(config.timeout)));

tracing::info!("[Middleware] Adding timeout layer");
app
}
}
3 changes: 3 additions & 0 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use crate::{
app::{AppContext, Hooks},
config,
};
use std::time::Duration;

/// converge database logic
///
Expand Down Expand Up @@ -60,6 +61,8 @@ pub async fn connect(config: &config::Database) -> Result<DbConn, sea_orm::DbErr
let mut opt = ConnectOptions::new(&config.uri);
opt.max_connections(config.max_connections)
.min_connections(config.min_connections)
.connect_timeout(Duration::from_millis(config.connect_timeout))
.idle_timeout(Duration::from_millis(config.idle_timeout))
.sqlx_logging(config.enable_logging);

Database::connect(opt).await
Expand Down
5 changes: 5 additions & 0 deletions starters/saas/config/development.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ server:
enable: true
catch_panic:
enable: true
timeout_request:
enable: false
timeout: 5000
workers:
mode: BackgroundQueue
mailer:
Expand All @@ -29,6 +32,8 @@ database:
uri: postgres://loco:loco@localhost:5432/loco_app
# uri: sqlite://db.sqlite?mode=rwc
enable_logging: false
connect_timeout: 500
idle_timeout: 1000
min_connections: 1
max_connections: 1
auto_migrate: true
Expand Down
5 changes: 5 additions & 0 deletions starters/saas/config/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ server:
enable: true
catch_panic:
enable: true
timeout_request:
enable: true
timeout: 5000
workers:
mode: ForegroundBlocking
mailer:
Expand All @@ -28,6 +31,8 @@ mailer:
database:
uri: postgres://loco:loco@localhost:5432/loco_app
enable_logging: false
connect_timeout: 500
idle_timeout: 1000
min_connections: 1
max_connections: 1
auto_migrate: true
Expand Down
3 changes: 3 additions & 0 deletions starters/stateless/config/development.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ server:
enable: true
catch_panic:
enable: true
timeout_request:
enable: false
timeout: 5000
workers:
mode: BackgroundQueue
mailer:
Expand Down
3 changes: 3 additions & 0 deletions starters/stateless/config/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ server:
enable: true
catch_panic:
enable: true
timeout_request:
enable: true
timeout: 5000
workers:
mode: ForegroundBlocking
mailer:
Expand Down

0 comments on commit bca0bfa

Please sign in to comment.