refactor(backend): extract governor setup into a function

This commit is contained in:
2026-06-28 17:46:16 +03:00
parent 40d57d7c77
commit 824cd2ad53

View File

@@ -78,31 +78,12 @@ async fn main() -> Result<()> {
.layer(DefaultBodyLimit::max(BODY_LIMIT)); .layer(DefaultBodyLimit::max(BODY_LIMIT));
let user_repository = UserRepository::new(pool); let user_repository = UserRepository::new(pool);
let mut routes_auth = routes_auth(user_repository.clone()); let routes_auth = routes_auth(user_repository.clone());
let routes_auth = if std::env::var("ENVIRONMENT").unwrap_or_default() == "test" {
if std::env::var("ENVIRONMENT").unwrap_or_default() != "test" { routes_auth
let governor_conf_auth = GovernorConfigBuilder::default() } else {
.per_second(4) apply_governor(routes_auth)
.burst_size(2) };
.key_extractor(SmartIpKeyExtractor)
.finish()
.expect("failed to initialize rate limiter configurations");
let governor_auth_limiter = governor_conf_auth.limiter().clone();
let interval = Duration::from_secs(60);
std::thread::spawn(move || {
loop {
std::thread::sleep(interval);
let len = governor_auth_limiter.len();
if len > 0 {
info!("rate limiting auth storage size: {len}");
}
governor_auth_limiter.retain_recent();
}
});
routes_auth = routes_auth.layer(GovernorLayer::new(governor_conf_auth));
}
let mut openapi = AuthApi::openapi(); let mut openapi = AuthApi::openapi();
openapi.merge(FileApi::openapi()); openapi.merge(FileApi::openapi());
@@ -141,3 +122,27 @@ async fn main() -> Result<()> {
Ok(()) Ok(())
} }
fn apply_governor(routes_auth: Router) -> Router {
let governor_conf_auth = GovernorConfigBuilder::default()
.per_second(4)
.burst_size(2)
.key_extractor(SmartIpKeyExtractor)
.finish()
.expect("failed to initialize rate limiter configurations");
let governor_auth_limiter = governor_conf_auth.limiter().clone();
let interval = Duration::from_secs(60);
std::thread::spawn(move || {
loop {
std::thread::sleep(interval);
let len = governor_auth_limiter.len();
if len > 0 {
info!("rate limiting auth storage size: {len}");
}
governor_auth_limiter.retain_recent();
}
});
routes_auth.layer(GovernorLayer::new(governor_conf_auth))
}