diff --git a/src/rate_limit.rs b/src/rate_limit.rs index 5476234..484d30d 100644 --- a/src/rate_limit.rs +++ b/src/rate_limit.rs @@ -404,6 +404,28 @@ where /// limiter rather than keeping a dropped one alive (test suites build /// dozens). pub fn share(&self, tier: &'static str, db: Database, db_up: DbHealth) { + self.share_windowed(tier, db, db_up, None); + } + + /// [`RateLimiter::share`] with the wall window pinned, for tests only. + /// + /// A round reads the real clock, so any assertion about *the* shared row + /// is otherwise a bet that the run does not cross a minute mid-round — + /// two limiters of one tier would then report into two rows and neither + /// would see the other's spend. An accidental relationship to the wall + /// clock is precisely what kept the epoch-roll double-charge out of + /// `tests/rate_limit.rs`, so the sharing tests choose their window instead. + pub fn share_pinned(&self, tier: &'static str, db: Database, db_up: DbHealth, epoch: i64) { + self.share_windowed(tier, db, db_up, Some(epoch)); + } + + fn share_windowed( + &self, + tier: &'static str, + db: Database, + db_up: DbHealth, + pinned: Option, + ) { if self.max == 0 { // The tier is off: `check` records nothing, so there is nothing to // share and no reason to hold a task or a table row. @@ -424,7 +446,7 @@ where if !db_up.is_up() { continue; } - let epoch = current_epoch(window); + let epoch = pinned.unwrap_or_else(|| current_epoch(window)); sync_once(tier, &buckets, window, epoch, &db).await; // Piggybacked cleanup, once per window: rows for a window that // has passed can never be read again. diff --git a/tests/rate_limit.rs b/tests/rate_limit.rs index 69471be..b9fcbdf 100644 --- a/tests/rate_limit.rs +++ b/tests/rate_limit.rs @@ -422,15 +422,24 @@ async fn sync_round() { tokio::time::pause(); } -/// Two limiters of one tier, sharing `db`. +/// One fixed wall window for every round below. The sync task reads the real +/// clock, so without this the tests here assert about "the" shared row while a +/// minute boundary landing between two limiters' rounds would give them a row +/// each — a run that passes because of when it ran, which is the same +/// accidental clock dependency that hid the epoch-roll double-charge from this +/// suite. Rolling *between* windows is covered by the unit tests, which drive +/// `sync_once`'s epoch directly. +const PINNED_WINDOW: i64 = 60_000; + +/// Two limiters of one tier, sharing `db` and one wall window. fn two_replicas(max: u32, db: &Database) -> (UserRateLimiter, UserRateLimiter, DbHealth) { let health = DbHealth::default(); let (a, b) = ( UserRateLimiter::per_user_minute(max), UserRateLimiter::per_user_minute(max), ); - a.share("test", db.clone(), health.clone()); - b.share("test", db.clone(), health.clone()); + a.share_pinned("test", db.clone(), health.clone(), PINNED_WINDOW); + b.share_pinned("test", db.clone(), health.clone(), PINNED_WINDOW); (a, b, health) }