use std::sync::Arc;
use axum::Router;
use axum::http::HeaderValue;
use tower_governor::{GovernorLayer, governor::GovernorConfigBuilder};
use tower_http::cors::{AllowOrigin, CorsLayer};
pub fn apply_rate_limit(app: Router, rate_limit: u32) -> Router {
if rate_limit == 0 {
return app;
}
let governor_conf = match GovernorConfigBuilder::default()
.per_second(rate_limit as u64)
.burst_size(rate_limit)
.finish()
{
Some(c) => c,
None => {
tracing::error!("invalid governor rate-limit configuration");
std::process::exit(1);
}
};
app.layer(GovernorLayer::new(Arc::new(governor_conf)))
}
pub fn build_cors_layer(cors_origins: &str) -> CorsLayer {
if cors_origins == "*" {
tracing::warn!(
"CORS is permissive (*). Set PG_RIPPLE_HTTP_CORS_ORIGINS to a comma-separated list \
of allowed origins for production use."
);
CorsLayer::permissive()
} else if cors_origins.is_empty() {
CorsLayer::new()
} else {
let origins: Vec<HeaderValue> = cors_origins
.split(',')
.filter_map(|o| o.trim().parse().ok())
.collect();
CorsLayer::new().allow_origin(AllowOrigin::list(origins))
}
}