diff --git a/crates/buzz-pubsub/src/rate_limiter.rs b/crates/buzz-pubsub/src/rate_limiter.rs index 095e6591e1..570e2d8330 100644 --- a/crates/buzz-pubsub/src/rate_limiter.rs +++ b/crates/buzz-pubsub/src/rate_limiter.rs @@ -17,7 +17,9 @@ use buzz_core::TenantContext; use nostr::PublicKey; use redis::Script; -/// Atomically INCR the key, set EXPIRE on first call, and return (count, ttl). +/// Atomically INCR the key, set EXPIRE on first call, and return +/// (count, ttl_ms). The TTL is in milliseconds because `TTL` truncates to +/// whole seconds and would report 0 while part of a second remains. /// /// Using a Lua script ensures INCR and EXPIRE are executed atomically — /// a crash between them can no longer leave a key without a TTL. @@ -26,7 +28,7 @@ local count = redis.call('INCR', KEYS[1]) if count == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end -local ttl = redis.call('TTL', KEYS[1]) +local ttl = redis.call('PTTL', KEYS[1]) return {count, ttl} "#; @@ -45,7 +47,7 @@ async fn run_rate_limit( let mut conn = pool.clone(); let script = Script::new(RATE_LIMIT_SCRIPT); - let (count, ttl): (u64, i64) = script + let (count, ttl_ms): (u64, i64) = script .key(key) .arg(window_secs as i64) .invoke_async(&mut conn) @@ -54,7 +56,7 @@ async fn run_rate_limit( // ttl == -1 means the key exists but has no expiry — broken state from a // prior crash between INCR and EXPIRE. Repair it now. - let reset_in_secs = if ttl < 0 { + let reset_in_secs = if ttl_ms < 0 { tracing::warn!(key = %key, "rate limit key has no TTL — repairing"); let _: () = redis::cmd("EXPIRE") .arg(key) @@ -65,7 +67,8 @@ async fn run_rate_limit( // After repair, the window resets to the full duration. window_secs } else { - ttl.max(0) as u64 + // Round up so the retry hint is never 0 while the window is open. + (ttl_ms as u64).div_ceil(1000) }; if count <= limit { @@ -116,3 +119,35 @@ impl RateLimiter for RedisRateLimiter { run_rate_limit(&self.pool, &key, window_secs, limit).await } } + +#[cfg(test)] +mod tests { + use super::*; + + fn redis_pool() -> crate::RedisConnection { + let url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".into()); + crate::redis_connection(&url).expect("redis connection") + } + + #[tokio::test] + #[ignore = "requires Redis"] + async fn retry_hint_rounds_a_partial_second_up() { + let pool = redis_pool(); + let key = format!("buzz:test:ratelimit:{}", uuid::Uuid::new_v4()); + let _: () = redis::cmd("SET") + .arg(&key) + .arg(1) + .arg("PX") + .arg(1400) + .query_async(&mut pool.clone()) + .await + .expect("seed exhausted window"); + + let result = run_rate_limit(&pool, &key, 60, 1) + .await + .expect("rate limit"); + + assert!(!result.allowed); + assert_eq!(result.reset_in_secs, 2); + } +}