mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +00:00
fix(pubsub): round the rate-limit retry hint up from PTTL (#9552)
## Summary The Redis rate limiter built its `retry in Ns` hint from `TTL`, which truncates to whole seconds. With 400 ms left in the window, a denied request was told `retry in 0s`, and a client that sleeps for exactly the hint retried straight into another refusal. This reads `PTTL` and rounds the milliseconds up to whole seconds, so the hint is never 0 while the window is still open. The no-expiry repair path is unchanged. ## Testing - New `rate_limiter::tests::retry_hint_rounds_a_partial_second_up` (`#[ignore = "requires Redis"]`, like the other Redis tests in this crate) seeds an exhausted window with 400 ms left and asserts the denial reports 1 second. Against the old `TTL` code it fails with `left: 0, right: 1`; with this change it passes. - `cargo nextest run -p buzz-pubsub --lib`: 38 passed. Ignored Redis `rate_limiter` and `nip98_replay` tests: 5 passed against a local Redis. - `cargo nextest run -p buzz-relay --lib` with local Postgres and Redis: 1762 passed. The relay `rejection::`/`admission::` lane with `--run-ignored all`: 16 passed. - Pre-push hooks (including rust-tests) passed. CI note: the Redis-backed pubsub tests only run in CI when they are named in `.github/workflows/_ci-relay.yml`, so the new test isn't selected there yet. Adding `or test(/^rate_limiter::tests::/)` to the "Pubsub subscriber reconciliation regression" filter would cover it. I left that out here because this branch can't push workflow file changes. --------- Signed-off-by: Wes <wesb@block.xyz> Co-authored-by: Groot <f4c08302591916fb4b80926bf7e18d22eef8aa0c877e4e841acc46405a45700b@buzz.block.builderlab.xyz> Co-authored-by: Star Lord <b89298dbe87c6b3fd8a425b535d9d161f23c88d555a47925ae0b04dfe02b201e@buzz.block.builderlab.xyz>
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user