refactor: add UserRateLimitEntry constructor and settings_changed method

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
master
oabrivard 3 months ago
parent c1f2f1456f
commit b961f82f01

@ -37,6 +37,25 @@ pub struct UserRateLimitEntry {
pub limiter: RateLimiter, pub limiter: RateLimiter,
} }
impl UserRateLimitEntry {
/// Create a new entry, building the underlying rate limiter from the given settings.
pub fn new(max_requests: i32, window_seconds: i32) -> Self {
Self {
max_requests,
window_seconds,
limiter: RateLimiter::new(
max_requests as usize,
std::time::Duration::from_secs(window_seconds as u64),
),
}
}
/// Returns `true` if the cached settings differ from the given values.
pub fn settings_changed(&self, max_requests: i32, window_seconds: i32) -> bool {
self.max_requests != max_requests || self.window_seconds != window_seconds
}
}
impl AppState { impl AppState {
/// Create a new `AppState` instance. /// Create a new `AppState` instance.
pub fn new(config: AppConfig, pool: PgPool, http_client: reqwest::Client) -> Self { pub fn new(config: AppConfig, pool: PgPool, http_client: reqwest::Client) -> Self {

@ -397,26 +397,13 @@ fn get_user_rate_limiter(
settings.rate_limit_time_window_seconds, settings.rate_limit_time_window_seconds,
) { ) {
(Some(max_req), Some(window_sec)) => { (Some(max_req), Some(window_sec)) => {
let mut entry = state.user_rate_limiters.entry(user_id).or_insert_with(|| { let mut entry = state
UserRateLimitEntry { .user_rate_limiters
max_requests: max_req, .entry(user_id)
window_seconds: window_sec, .or_insert_with(|| UserRateLimitEntry::new(max_req, window_sec));
limiter: crate::services::rate_limiter::RateLimiter::new(
max_req as usize,
Duration::from_secs(window_sec as u64),
),
}
});
// Replace if user's settings changed since the limiter was created // Replace if user's settings changed since the limiter was created
if entry.max_requests != max_req || entry.window_seconds != window_sec { if entry.settings_changed(max_req, window_sec) {
*entry = UserRateLimitEntry { *entry = UserRateLimitEntry::new(max_req, window_sec);
max_requests: max_req,
window_seconds: window_sec,
limiter: crate::services::rate_limiter::RateLimiter::new(
max_req as usize,
Duration::from_secs(window_sec as u64),
),
};
} }
Some(entry.limiter.clone()) Some(entry.limiter.clone())
} }

Loading…
Cancel
Save