:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(capture): redis-backed dynamic custom rate-limit thresholds (#71408)
Eli Reisman987ed12fd965
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 5f7bd9dc6c2c..f270dedef2c6 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -1785,6 +1785,7 @@ name = "capture"version = "0.1.0"dependencies = ["anyhow",+ "arc-swap","assert-json-diff","async-compression","async-trait",@@ -6157,6 +6158,7 @@ name = "limiters"version = "0.1.0"dependencies = ["anyhow",+ "arc-swap","async-trait","chrono","common-redis",@@ -6168,6 +6170,7 @@ dependencies = ["metrics-util","moka","rand 0.8.5",+ "serde_json","strum 0.26.3","tokio","tracing",diff --git a/rust/capture/Cargo.toml b/rust/capture/Cargo.tomlindex c52f5a12f291..a2073e435546 100644--- a/rust/capture/Cargo.toml+++ b/rust/capture/Cargo.toml@@ -12,6 +12,7 @@ workspace = true[dependencies]anyhow = { workspace = true }+arc-swap = { workspace = true }async-compression = { workspace = true }async-trait = { workspace = true }axum = { workspace = true }diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rsindex a69b76274759..3611812ab598 100644--- a/rust/capture/src/config.rs+++ b/rust/capture/src/config.rs@@ -191,6 +191,18 @@ pub struct Config {/// Defaults to redis_connection_timeout_ms if unset.pub global_rate_limit_redis_connection_timeout_ms: Option<u64>,+ /// Redis key holding the dynamic custom per-key rate-limit thresholds+ /// (JSON object of `{key: threshold}`), written by Django. When set, the+ /// per-(token, distinct_id) limiter refreshes its custom thresholds from+ /// this key on a timer, overriding the static CSV overrides. Sourced from+ /// the same Redis as event restrictions (`event_restrictions_redis_url`).+ /// When unset, the limiter uses only the static CSV overrides.+ pub global_rate_limit_custom_threshold_key: Option<String>,++ /// How often to refresh the dynamic custom thresholds from Redis (seconds).+ #[envconfig(default = "60")]+ pub global_rate_limit_custom_threshold_refresh_secs: u64,+// Event restrictions configuration (reads from Redis, synced by Django)#[envconfig(default = "false")]pub event_restrictions_enabled: bool,diff --git a/rust/capture/src/global_rate_limiter.rs b/rust/capture/src/global_rate_limiter.rsindex fdb93f6561f3..6676d0582c4b 100644--- a/rust/capture/src/global_rate_limiter.rs+++ b/rust/capture/src/global_rate_limiter.rs@@ -4,11 +4,14 @@ use std::sync::Arc;use std::time::Duration;use crate::config::Config;+use arc_swap::ArcSwap;use chrono::Utc;use common_redis::Client;+use limiters::custom_key_source::{CustomKeyThresholdSource, RedisCustomKeyThresholdSource};use limiters::global_rate_limiter::{- EvalResult, GlobalRateLimitResponse, GlobalRateLimiter as CommonGlobalRateLimiter,- GlobalRateLimiterConfig, GlobalRateLimiterImpl as CommonGlobalRateLimiterImpl,+ CustomKeyResolver, EvalResult, GlobalRateLimitResponse,+ GlobalRateLimiter as CommonGlobalRateLimiter, GlobalRateLimiterConfig,+ GlobalRateLimiterImpl as CommonGlobalRateLimiterImpl,};use metrics::counter;use tracing::{error, info, warn};@@ -81,6 +84,7 @@ impl GlobalRateLimiter {config.global_rate_limit_token_distinctid_local_cache_max_entries,&prefix,&metrics_scope,+ config.global_rate_limit_custom_threshold_key.is_some(),)}@@ -100,9 +104,32 @@ impl GlobalRateLimiter {config.global_rate_limit_token_local_cache_max_entries,&prefix,&metrics_scope,+ // The token-only limiter is not wired to the dynamic refresh source.+ // (The hierarchical resolver is still set but is a no-op for bare+ // token keys, which have no `:distinct_id` suffix.)+ false,)}+ /// Hierarchical custom-key resolver. Always applied to capture limiters,+ /// whether thresholds come from the static CSV seed or the dynamic source.+ ///+ /// A lookup key is either `token` or `token:distinct_id` (the limiter's cache+ /// key). Resolution tries the exact key first, then falls back to the token+ /// prefix (everything before the first `:`) so a token-level override applies+ /// to all of that token's `token:distinct_id` keys. Keeps capture's key+ /// structure out of the common crate.+ fn hierarchical_resolver() -> CustomKeyResolver {+ Arc::new(|key: &str, map: &HashMap<String, u64>| {+ if let Some(v) = map.get(key) {+ return Some(*v);+ }+ key.split_once(':')+ .and_then(|(token, _)| map.get(token).copied())+ })+ }++ #[allow(clippy::too_many_arguments)]fn build(config: &Config,redis_instances: Vec<Arc<dyn Client + Send + Sync>>,@@ -111,14 +138,63 @@ impl GlobalRateLimiter {local_cache_max_entries: u64,redis_key_prefix: &str,metrics_scope: &str,+ enable_dynamic_source: bool,) -> anyhow::Result<Self> {+ // Seed the (swappable) custom-key map from the static CSV overrides. When a+ // dynamic source is enabled, the common refresh loop replaces this map only+ // from an explicit Redis blob; an absent key or an unreachable Redis is+ // fail-static, so the CSV seed keeps applying until a blob is written.+ let seed = Self::format_custom_keys(custom_keys_csv);++ // Build the dynamic source when enabled and its Redis key + URL are set.+ // The source reads the JSON blob from the event-restrictions Redis (a+ // separate store from the traffic-count Redis in `redis_instances`) and+ // owns its own connection/reconnect; the common limiter runs the loop.+ let custom_key_source: Option<Arc<dyn CustomKeyThresholdSource>> = if enable_dynamic_source+ {+ match (+ config.global_rate_limit_custom_threshold_key.as_ref(),+ config.event_restrictions_redis_url.as_ref(),+ ) {+ (Some(key), Some(redis_url)) => {+ let response_timeout = (config.redis_response_timeout_ms != 0)+ .then(|| Duration::from_millis(config.redis_response_timeout_ms));+ let connection_timeout = (config.redis_connection_timeout_ms != 0)+ .then(|| Duration::from_millis(config.redis_connection_timeout_ms));+ Some(Arc::new(RedisCustomKeyThresholdSource::new(+ redis_url.clone(),+ key.clone(),+ response_timeout,+ connection_timeout,+ )))+ }+ _ => {+ warn!(+ "Dynamic custom thresholds requested but threshold key or Redis URL is unset; using static CSV seed"+ );+ None+ }+ }+ } else {+ None+ };+let grl_config = GlobalRateLimiterConfig {global_threshold: threshold,window_interval: Duration::from_secs(config.global_rate_limit_window_interval_secs),sync_interval: Duration::from_secs(config.global_rate_limit_sync_interval_secs),tick_interval: Duration::from_millis(config.global_rate_limit_tick_interval_ms),redis_key_prefix: redis_key_prefix.to_string(),- custom_keys: Self::format_custom_keys(custom_keys_csv),+ custom_keys: Arc::new(ArcSwap::from_pointee(seed)),+ // Capture keys are always `token` or `token:distinct_id`, so the+ // hierarchical resolver is always the correct policy — a token-level+ // override applies to all of that token's `token:distinct_id` keys,+ // for both the CSV seed and the dynamic map.+ custom_key_resolver: Some(Self::hierarchical_resolver()),+ custom_key_source,+ custom_key_refresh_interval: Duration::from_secs(+ config.global_rate_limit_custom_threshold_refresh_secs,+ ),local_cache_max_entries,metrics_scope: metrics_scope.to_string(),..Default::default()@@ -144,18 +220,31 @@ impl GlobalRateLimiter {})}- /// Check if a key is rate limited. Routes to custom or global check based on- /// whether the key is registered in the custom_keys map. Exactly one check- /// fires per call — no double-enqueue to the Redis batch channel.+ /// Check if a key is rate limited. The key is resolved against the custom-key+ /// map exactly once: `check_custom_limit` returns `NotApplicable` for keys+ /// without a custom override, and only then do we fall back to the global+ /// threshold check. Routing and threshold therefore come from a single map+ /// snapshot, so a concurrent custom-map swap can't misroute a request (a+ /// prior `is_custom_key` probe + separate check made two independent loads+ /// that could straddle a swap). Exactly one enforcing check fires — the+ /// `NotApplicable` probe returns before touching the cache or Redis batch+ /// channel, so there's no double-enqueue.////// In dry-run mode the underlying limiter is still evaluated (counts are/// tracked, Redis is synced) but the result is suppressed: metrics and a/// warn log are emitted, then `None` is returned so callers never enforce.pub async fn is_limited(&self, key: &str, count: u64) -> Option<GlobalRateLimitResponse> {- let result = if self.limiter.is_custom_key(key) {- self.is_custom_key_limited(key, count).await- } else {- self.is_global_key_limited(key, count).await+ let result = match self+ .limiter+ .check_custom_limit(key, count, Some(Utc::now()))+ .await+ {+ // No custom override for this key: enforce the global threshold.+ EvalResult::NotApplicable => self.is_global_key_limited(key, count).await,+ EvalResult::Limited(response) => Some(response),+ // Allowed / FailOpen on a key that HAS a custom override: not limited,+ // and we must not re-check it against the global threshold.+ _ => None,};match (result, self.dry_run) {@@ -190,26 +279,18 @@ impl GlobalRateLimiter {}}- async fn is_custom_key_limited(- &self,- key: &str,- count: u64,- ) -> Option<GlobalRateLimitResponse> {- match self- .limiter- .check_custom_limit(key, count, Some(Utc::now()))- .await- {- EvalResult::Limited(response) => Some(response),- _ => None,- }- }-- // trigger shutdown and stop pushing updates to global cache+ // trigger shutdown and stop pushing updates to global cache. Also stops the+ // common custom-key refresh loop, if one was spawned.pub fn shutdown(&mut self) {self.limiter.shutdown();}+ /// Returns true if the key resolves to a custom threshold (exact match, or+ /// token-prefix fallback via the hierarchical resolver).+ pub fn is_custom_key(&self, key: &str) -> bool {+ self.limiter.is_custom_key(key)+ }+pub async fn build_redis_client(config: &Config,shared_redis: Arc<dyn Client + Send + Sync>,@@ -268,6 +349,33 @@ impl GlobalRateLimiter {}}+ /// Test helper: build a real limiter with the hierarchical resolver and its+ /// custom-key map seeded from `csv` (no dynamic source), backed by a mock+ /// Redis client. Exercises the static-CSV path with hierarchical resolution.+ #[cfg(test)]+ pub(crate) fn for_test_hierarchical_seeded(csv: Option<&str>) -> Self {+ let csv_owned = csv.map(|s| s.to_string());+ let grl_config = GlobalRateLimiterConfig {+ global_threshold: 300_000,+ redis_key_prefix: "test:grl".to_string(),+ custom_keys: Arc::new(ArcSwap::from_pointee(Self::format_custom_keys(+ csv_owned.as_ref(),+ ))),+ custom_key_resolver: Some(Self::hierarchical_resolver()),+ metrics_scope: "test".to_string(),+ ..Default::default()+ };+ let limiter = CommonGlobalRateLimiterImpl::new(+ grl_config,+ vec![Arc::new(common_redis::MockRedisClient::new())],+ )+ .expect("failed to build test limiter");+ Self {+ limiter: Box::new(limiter),+ dry_run: false,+ }+ }+#[cfg(test)]pub(crate) fn new_with_dry_run(limiter: impl CommonGlobalRateLimiter + 'static) -> Self {Self {@@ -373,6 +481,7 @@ impl GlobalRateLimiter {mod tests {use super::*;use async_trait::async_trait;+ use rstest::rstest;use std::collections::HashSet;use std::sync::Mutex;use std::time::Duration;@@ -457,7 +566,11 @@ mod tests {assert!(result.is_some());assert!(!result.unwrap().is_custom_limited);- assert_eq!(*calls.lock().unwrap(), vec!["is_custom_key", "check_limit"]);+ assert_eq!(+ *calls.lock().unwrap(),+ vec!["check_custom_limit", "check_limit"],+ "no custom override (NotApplicable) must fall back to the global check"+ );}#[tokio::test]@@ -475,7 +588,8 @@ mod tests {assert!(result.unwrap().is_custom_limited);assert_eq!(*calls.lock().unwrap(),- vec!["is_custom_key", "check_custom_limit"]+ vec!["check_custom_limit"],+ "a custom Limited result must not trigger a second global check");}@@ -493,8 +607,8 @@ mod tests {assert!(result.is_none());assert_eq!(*calls.lock().unwrap(),- vec!["is_custom_key", "check_custom_limit"],- "must NOT call check_limit when key is registered as custom"+ vec!["check_custom_limit"],+ "an Allowed custom key must NOT fall through to the global check");}@@ -619,7 +733,7 @@ mod tests {);assert_eq!(*calls.lock().unwrap(),- vec!["is_custom_key", "check_limit"],+ vec!["check_custom_limit", "check_limit"],"underlying limiter must still be called in dry-run mode");}@@ -641,7 +755,7 @@ mod tests {);assert_eq!(*calls.lock().unwrap(),- vec!["is_custom_key", "check_custom_limit"],+ vec!["check_custom_limit"],"underlying limiter must still be called in dry-run mode");}@@ -679,4 +793,67 @@ mod tests {"non-dry-run should return Some(response) when limited");}++ // --- Hierarchical custom-key resolver ---+ //+ // The resolver is capture's key-resolution policy, injected into the common+ // limiter. A lookup key is `token` or `token:distinct_id`. Resolution: exact+ // match first, then the token prefix (everything before the first `:`). It is+ // colon-delimited, NOT a string prefix match.++ fn resolver_map(pairs: &[(&str, u64)]) -> HashMap<String, u64> {+ pairs.iter().map(|(k, v)| (k.to_string(), *v)).collect()+ }++ #[rstest]+ // Token-scope override: applies to the token and ALL of its token:distinct_id keys.+ #[case::token_scope_exact(&[("phc_tok", 10)], "phc_tok", Some(10))]+ #[case::token_scope_matches_any_distinct_id(&[("phc_tok", 10)], "phc_tok:alice", Some(10))]+ #[case::token_scope_matches_other_distinct_id(&[("phc_tok", 10)], "phc_tok:bob", Some(10))]+ #[case::token_scope_other_token_unmatched(&[("phc_tok", 10)], "other:alice", None)]+ #[case::token_scope_other_bare_token_unmatched(&[("phc_tok", 10)], "other", None)]+ // token:distinct_id-scope override: applies to that exact pair only.+ #[case::distinct_scope_exact(&[("phc_tok:alice", 5)], "phc_tok:alice", Some(5))]+ #[case::distinct_scope_other_distinct_unmatched(&[("phc_tok:alice", 5)], "phc_tok:bob", None)]+ #[case::distinct_scope_bare_token_unmatched(&[("phc_tok:alice", 5)], "phc_tok", None)]+ // Exact match wins over the token-prefix fallback.+ #[case::exact_wins_over_fallback(&[("phc_tok", 10), ("phc_tok:vip", 100)], "phc_tok:vip", Some(100))]+ #[case::fallback_when_no_exact(&[("phc_tok", 10), ("phc_tok:vip", 100)], "phc_tok:other", Some(10))]+ #[case::bare_token_with_both(&[("phc_tok", 10), ("phc_tok:vip", 100)], "phc_tok", Some(10))]+ // Safety: fallback is colon-delimited, never a raw string prefix.+ #[case::not_string_prefix_bare(&[("phc_tok", 10)], "phc_tokEXTRA", None)]+ #[case::not_string_prefix_with_distinct(&[("phc_tok", 10)], "phc_tokEXTRA:alice", None)]+ // Corner cases: empty distinct_id, extra colons, empty token, utf8.+ #[case::empty_distinct_id_falls_back(&[("phc_tok", 10)], "phc_tok:", Some(10))]+ #[case::only_first_colon_splits(&[("phc_tok", 10)], "phc_tok:a:b", Some(10))]+ #[case::empty_token_key(&[("", 3)], ":alice", Some(3))]+ #[case::utf8_distinct_id_falls_back(&[("phc_tok", 10)], "phc_tok:ünïcödé", Some(10))]+ #[case::empty_map_no_match(&[], "phc_tok:alice", None)]+ fn test_hierarchical_resolver(+ #[case] pairs: &[(&str, u64)],+ #[case] key: &str,+ #[case] expected: Option<u64>,+ ) {+ let resolver = GlobalRateLimiter::hierarchical_resolver();+ let map = resolver_map(pairs);+ assert_eq!(resolver(key, &map), expected, "key={key}");+ }++ #[tokio::test]+ async fn test_static_csv_seed_resolves_hierarchically() {+ // Gap fix vs master: a static-CSV token-level override (dynamic source+ // OFF) now applies to that token's token:distinct_id keys too, because+ // the hierarchical resolver is always set — not just on the dynamic path.+ let limiter = GlobalRateLimiter::for_test_hierarchical_seeded(Some("phc_seed=7"));++ assert!(limiter.is_custom_key("phc_seed"), "exact token override");+ assert!(+ limiter.is_custom_key("phc_seed:any_user"),+ "token override must apply to token:distinct_id (master only did exact match)"+ );+ assert!(+ !limiter.is_custom_key("other_tok:any_user"),+ "unrelated token must not match"+ );+ }}diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex 14370be54ff5..c56e83a2a894 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -178,6 +178,9 @@ pub async fn build_components(.expect("failed to create redis client"),);+ // The dynamic custom-threshold refresh loop is owned by the common limiter:+ // when GLOBAL_RATE_LIMIT_CUSTOM_THRESHOLD_KEY is set, `build()` wires a Redis+ // source into the limiter, which spawns and manages the refresh task itself.let global_rate_limiter_token_distinctid = if config.global_rate_limit_enabled {let limiter = GlobalRateLimiter::try_from_config(&config, redis_client.clone()).awaitdiff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rsindex 21a11feb969c..1ec79b7eda75 100644--- a/rust/capture/src/v1/quota_limiter_shim.rs+++ b/rust/capture/src/v1/quota_limiter_shim.rs@@ -138,6 +138,8 @@ mod tests {global_rate_limit_redis_reader_url: None,global_rate_limit_redis_response_timeout_ms: None,global_rate_limit_redis_connection_timeout_ms: None,+ global_rate_limit_custom_threshold_key: None,+ global_rate_limit_custom_threshold_refresh_secs: 60,event_restrictions_enabled: false,event_restrictions_redis_url: None,event_restrictions_refresh_interval_secs: 30,diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rsindex 1affadc7e618..7f68cf0d2322 100644--- a/rust/capture/tests/common/utils.rs+++ b/rust/capture/tests/common/utils.rs@@ -54,6 +54,8 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {global_rate_limit_redis_reader_url: None,global_rate_limit_redis_response_timeout_ms: None,global_rate_limit_redis_connection_timeout_ms: None,+ global_rate_limit_custom_threshold_key: None,+ global_rate_limit_custom_threshold_refresh_secs: 60,event_restrictions_enabled: false,event_restrictions_redis_url: None,event_restrictions_refresh_interval_secs: 30,diff --git a/rust/common/limiters/Cargo.toml b/rust/common/limiters/Cargo.tomlindex f6cc4de5ea54..e7b5b010fcb0 100644--- a/rust/common/limiters/Cargo.toml+++ b/rust/common/limiters/Cargo.toml@@ -4,6 +4,7 @@ version = "0.1.0"edition = "2021"[dependencies]+arc-swap = { workspace = true }async-trait = { workspace = true }anyhow = { workspace = true }common-redis = { path = "../redis" }@@ -13,6 +14,7 @@ governor = { workspace = true }metrics = { workspace = true }moka = { workspace = true, features = ["sync"] }rand = { workspace = true }+serde_json = { workspace = true }strum = { version = "0.26", features = ["derive"] }tokio = { workspace = true }tracing = { workspace = true }@@ -21,7 +23,7 @@ chrono = { workspace = true }[dev-dependencies]criterion = { version = "0.5", features = ["async_tokio"] }metrics-util = { workspace = true }-tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }+tokio = { workspace = true, features = ["rt-multi-thread", "macros", "test-util"] }[[bench]]name = "global_rate_limiter"diff --git a/rust/common/limiters/benches/global_rate_limiter.rs b/rust/common/limiters/benches/global_rate_limiter.rsindex cf2a602fcabb..d32834345758 100644--- a/rust/common/limiters/benches/global_rate_limiter.rs+++ b/rust/common/limiters/benches/global_rate_limiter.rs@@ -80,7 +80,10 @@ fn bench_config() -> GlobalRateLimiterConfig {local_cache_idle_timeout: Duration::from_secs(600),local_cache_max_entries: 100_000,channel_capacity: 100_000,- custom_keys: HashMap::new(),+ custom_keys: std::sync::Arc::new(arc_swap::ArcSwap::from_pointee(HashMap::new())),+ custom_key_resolver: None,+ custom_key_source: None,+ custom_key_refresh_interval: Duration::from_secs(60),global_read_timeout: Duration::from_millis(50),global_write_timeout: Duration::from_millis(50),metrics_scope: "bench".to_string(),@@ -374,11 +377,13 @@ fn bench_custom_key_evaluation(c: &mut Criterion) {};// Config with some registered custom keys- let mut config = bench_config();- for i in 0..100 {- config- .custom_keys- .insert(format!("registered_key_{i}"), 50_000);+ let config = bench_config();+ {+ let mut map = HashMap::new();+ for i in 0..100 {+ map.insert(format!("registered_key_{i}"), 50_000);+ }+ config.custom_keys.store(std::sync::Arc::new(map));}// Pre-prime Redis epoch keys for registered keysdiff --git a/rust/common/limiters/src/custom_key_source.rs b/rust/common/limiters/src/custom_key_source.rsnew file mode 100644index 000000000000..b25ce9bd29f5--- /dev/null+++ b/rust/common/limiters/src/custom_key_source.rs@@ -0,0 +1,315 @@+use std::collections::HashMap;+use std::sync::Arc;+use std::time::Duration;++use async_trait::async_trait;+use common_redis::{Client, CompressionConfig, CustomRedisError, RedisClient, RedisValueFormat};+use futures::future::BoxFuture;+use tokio::sync::Mutex;+use tracing::warn;++/// Metric emitted per fetch attempt, tagged with the outcome. Unscoped: a source+/// is not tied to a particular limiter instance (the scoped `..._loaded` /+/// `..._last_refresh` gauges live on the refresh loop instead).+const FETCH_COUNTER: &str = "global_rate_limiter_custom_thresholds_fetch_total";++/// A pluggable source of custom-key thresholds for the global rate limiter.+///+/// The refresh loop calls `fetch` on a timer and atomically swaps the returned+/// map into the limiter. `Ok(Some(map))` replaces the current thresholds,+/// `Ok(None)` means "no thresholds configured" (clears them), and `Err` leaves+/// the current map untouched (fail-static). Implementations own their own+/// connection lifecycle, including reconnecting after a transient failure.+#[async_trait]+pub trait CustomKeyThresholdSource: Send + Sync {+ async fn fetch(&self) -> Result<Option<HashMap<String, u64>>, CustomRedisError>;+}++/// Parse the dynamic-threshold JSON blob.+///+/// The blob is a flat JSON object mapping a fully-resolved key to its threshold,+/// e.g. `{"phc_abc": 1000, "phc_abc:noisy_user": 50}`. The key structure is+/// opaque to this crate; callers give meaning to keys via a `CustomKeyResolver`.+pub fn parse_thresholds(json_str: &str) -> Result<HashMap<String, u64>, CustomRedisError> {+ serde_json::from_str(json_str)+ .map_err(|e| CustomRedisError::ParseError(format!("Failed to parse thresholds JSON: {e}")))+}++/// Builds a fresh client on demand. Returns a boxed future so the concrete+/// connection type (real Redis in production, a mock in tests) is hidden behind+/// one code path through `client()`/`reset_client()`.+type ClientBuilder = Arc<+ dyn Fn() -> BoxFuture<'static, Result<Arc<dyn Client + Send + Sync>, CustomRedisError>>+ + Send+ + Sync,+>;++/// Redis-backed source. Reads a single key holding the plain JSON blob (UTF-8, no+/// compression), mirroring the event-restrictions repository format.+///+/// `MultiplexedConnection` does not self-heal (only `ConnectionManager` does), so+/// this source owns reconnect itself: it builds its client lazily and drops it on+/// a connection failure, rebuilding on the next `fetch`. A Redis outage at+/// startup or mid-run therefore leaves the limiter on its current thresholds and+/// recovers automatically once Redis is reachable again.+pub struct RedisCustomKeyThresholdSource {+ key: String,+ /// Constructs a new client; invoked on first use and again after a reset.+ build_client: ClientBuilder,+ /// Lazily built; reset to `None` on connection failure so the next `fetch`+ /// rebuilds. The `Mutex` is only contended at the refresh cadence (seconds).+ client: Mutex<Option<Arc<dyn Client + Send + Sync>>>,+}++impl RedisCustomKeyThresholdSource {+ pub fn new(+ redis_url: String,+ key: String,+ response_timeout: Option<Duration>,+ connection_timeout: Option<Duration>,+ ) -> Self {+ // The client is UTF-8 / uncompressed to match the JSON blob Django writes.+ let build_client: ClientBuilder = Arc::new(+ move || -> BoxFuture<'static, Result<Arc<dyn Client + Send + Sync>, CustomRedisError>> {+ let redis_url = redis_url.clone();+ Box::pin(async move {+ let client: Arc<dyn Client + Send + Sync> = Arc::new(+ RedisClient::with_config(+ redis_url,+ CompressionConfig::disabled(),+ RedisValueFormat::Utf8,+ response_timeout,+ connection_timeout,+ )+ .await?,+ );+ Ok(client)+ })+ },+ );+ Self {+ key,+ build_client,+ client: Mutex::new(None),+ }+ }++ /// Test seam: build a source from a custom client factory so the+ /// lazy-connect + reconnect path can be exercised without a real Redis.+ #[cfg(test)]+ fn with_client_builder(key: String, build_client: ClientBuilder) -> Self {+ Self {+ key,+ build_client,+ client: Mutex::new(None),+ }+ }++ /// Return the current client, building one if needed.+ async fn client(&self) -> Result<Arc<dyn Client + Send + Sync>, CustomRedisError> {+ let mut guard = self.client.lock().await;+ if let Some(client) = guard.as_ref() {+ return Ok(Arc::clone(client));+ }+ let client = (self.build_client)().await?;+ *guard = Some(Arc::clone(&client));+ Ok(client)+ }++ /// Drop the current client so the next `fetch` rebuilds it.+ async fn reset_client(&self) {+ *self.client.lock().await = None;+ }+}++#[async_trait]+impl CustomKeyThresholdSource for RedisCustomKeyThresholdSource {+ async fn fetch(&self) -> Result<Option<HashMap<String, u64>>, CustomRedisError> {+ let client = match self.client().await {+ Ok(client) => client,+ Err(e) => {+ metrics::counter!(FETCH_COUNTER, "result" => "connection_error").increment(1);+ warn!(key = %self.key, error = %e, "Failed to connect to custom-threshold Redis");+ return Err(e);+ }+ };++ let json_str = match client.get(self.key.clone()).await {+ Ok(s) => s,+ Err(CustomRedisError::NotFound) => {+ metrics::counter!(FETCH_COUNTER, "result" => "not_found").increment(1);+ return Ok(None);+ }+ Err(e) => {+ metrics::counter!(FETCH_COUNTER, "result" => "connection_error").increment(1);+ warn!(key = %self.key, error = %e, "Failed to fetch custom rate-limit thresholds from Redis");+ // Drop the (likely dead) connection so the next fetch reconnects.+ self.reset_client().await;+ return Err(e);+ }+ };++ match parse_thresholds(&json_str) {+ Ok(map) => {+ metrics::counter!(FETCH_COUNTER, "result" => "success").increment(1);+ Ok(Some(map))+ }+ Err(e) => {+ // Parse failures are a data problem, not a connection problem:+ // keep the connection and let ops fix the blob.+ metrics::counter!(FETCH_COUNTER, "result" => "parse_error").increment(1);+ warn!(key = %self.key, error = %e, "Failed to parse custom rate-limit thresholds from Redis");+ Err(e)+ }+ }+ }+}++#[cfg(test)]+pub mod testing {+ use super::*;++ /// Mock source for unit-testing the refresh path. Returns a fixed, cloneable+ /// result each `fetch`.+ pub struct MockCustomKeyThresholdSource {+ result: Mutex<Result<Option<HashMap<String, u64>>, CustomRedisError>>,+ }++ impl MockCustomKeyThresholdSource {+ pub fn with_thresholds(map: Option<HashMap<String, u64>>) -> Self {+ Self {+ result: Mutex::new(Ok(map)),+ }+ }++ pub fn with_error(error: CustomRedisError) -> Self {+ Self {+ result: Mutex::new(Err(error)),+ }+ }++ /// Change what the next `fetch` returns (simulates a Redis-side update).+ pub async fn set_thresholds(&self, map: Option<HashMap<String, u64>>) {+ *self.result.lock().await = Ok(map);+ }+ }++ #[async_trait]+ impl CustomKeyThresholdSource for MockCustomKeyThresholdSource {+ async fn fetch(&self) -> Result<Option<HashMap<String, u64>>, CustomRedisError> {+ self.result.lock().await.clone()+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_parse_thresholds_flat_object() {+ let json = r#"{"phc_abc": 1000, "phc_abc:noisy": 50}"#;+ let map = parse_thresholds(json).unwrap();+ assert_eq!(map.get("phc_abc"), Some(&1000));+ assert_eq!(map.get("phc_abc:noisy"), Some(&50));+ assert_eq!(map.len(), 2);+ }++ #[test]+ fn test_parse_thresholds_empty_object() {+ assert!(parse_thresholds("{}").unwrap().is_empty());+ }++ #[test]+ fn test_parse_thresholds_rejects_malformed() {+ assert!(parse_thresholds("not json").is_err());+ // Non-numeric threshold values are rejected.+ assert!(parse_thresholds(r#"{"k": "abc"}"#).is_err());+ }++ // --- RedisCustomKeyThresholdSource fetch/reconnect (via injected client) ---++ use common_redis::MockRedisClient;+ use std::sync::atomic::{AtomicUsize, Ordering};++ /// Build a source whose client factory is driven by `make`, counting how many+ /// times a client is (re)built so tests can assert rebuild-vs-reuse.+ fn source_with<F>(key: &str, make: F) -> (RedisCustomKeyThresholdSource, Arc<AtomicUsize>)+ where+ F: Fn(usize) -> MockRedisClient + Send + Sync + 'static,+ {+ let builds = Arc::new(AtomicUsize::new(0));+ let builds_c = builds.clone();+ let make = Arc::new(make);+ let build: ClientBuilder = Arc::new(+ move || -> BoxFuture<'static, Result<Arc<dyn Client + Send + Sync>, CustomRedisError>> {+ let n = builds_c.fetch_add(1, Ordering::SeqCst);+ let make = make.clone();+ Box::pin(async move {+ let client: Arc<dyn Client + Send + Sync> = Arc::new(make(n));+ Ok(client)+ })+ },+ );+ (+ RedisCustomKeyThresholdSource::with_client_builder(key.to_string(), build),+ builds,+ )+ }++ #[tokio::test]+ async fn test_fetch_success_parses_and_reuses_client() {+ let (source, builds) = source_with("thresholds", |_| {+ MockRedisClient::new().get_ret("thresholds", Ok(r#"{"phc_abc": 1000}"#.to_string()))+ });++ let map = source.fetch().await.unwrap().unwrap();+ assert_eq!(map.get("phc_abc"), Some(&1000));++ // A healthy connection is cached: the second fetch does not rebuild.+ source.fetch().await.unwrap();+ assert_eq!(builds.load(Ordering::SeqCst), 1);+ }++ #[tokio::test]+ async fn test_fetch_not_found_returns_none_and_keeps_client() {+ let (source, builds) = source_with("k", |_| {+ MockRedisClient::new().get_ret("k", Err(CustomRedisError::NotFound))+ });++ assert!(source.fetch().await.unwrap().is_none());+ // NotFound is a normal "no config" answer, not a connection failure.+ assert!(source.fetch().await.unwrap().is_none());+ assert_eq!(builds.load(Ordering::SeqCst), 1);+ }++ #[tokio::test]+ async fn test_fetch_connection_error_resets_and_rebuilds() {+ // First build errors on GET (connection dead); second build succeeds.+ let (source, builds) = source_with("k", |n| {+ if n == 0 {+ MockRedisClient::new().get_ret("k", Err(CustomRedisError::Timeout))+ } else {+ MockRedisClient::new().get_ret("k", Ok(r#"{"phc": 5}"#.to_string()))+ }+ });++ assert!(source.fetch().await.is_err());+ let map = source.fetch().await.unwrap().unwrap();+ assert_eq!(map.get("phc"), Some(&5));+ // The dead connection was dropped and rebuilt on the retry.+ assert_eq!(builds.load(Ordering::SeqCst), 2);+ }++ #[tokio::test]+ async fn test_fetch_parse_error_keeps_client() {+ let (source, builds) = source_with("k", |_| {+ MockRedisClient::new().get_ret("k", Ok("not json".to_string()))+ });++ assert!(source.fetch().await.is_err());+ // A bad blob is a data problem, not a connection problem: no rebuild.+ assert!(source.fetch().await.is_err());+ assert_eq!(builds.load(Ordering::SeqCst), 1);+ }+}diff --git a/rust/common/limiters/src/global_rate_limiter.rs b/rust/common/limiters/src/global_rate_limiter.rsindex f13487bdf65b..625f93d866e2 100644--- a/rust/common/limiters/src/global_rate_limiter.rs+++ b/rust/common/limiters/src/global_rate_limiter.rs@@ -4,6 +4,7 @@ use std::hash::{Hash, Hasher};use std::sync::Arc;use std::time::{Duration, Instant};+use arc_swap::ArcSwap;use dashmap::DashSet;use async_trait::async_trait;@@ -11,7 +12,20 @@ use chrono::{DateTime, Utc};use common_redis::Client;use moka::sync::Cache;use tokio::sync::mpsc;-use tracing::{error, warn};+use tracing::{error, info, warn};++use crate::custom_key_source::CustomKeyThresholdSource;++/// Resolver for custom-key thresholds. Given a lookup key and a snapshot of the+/// current custom-key map, returns the threshold to apply (or `None` if the key+/// is not subject to a custom limit).+///+/// The default resolver (when `custom_key_resolver` is `None`) is an exact map+/// lookup. Callers can inject a closure to implement richer policies (e.g. a+/// hierarchical `token:distinct_id` -> `token` fallback) without leaking their+/// key structure into this crate. The closure receives the authoritative map by+/// reference so it always resolves against the latest swapped-in thresholds.+pub type CustomKeyResolver = Arc<dyn Fn(&str, &HashMap<String, u64>) -> Option<u64> + Send + Sync>;const GLOBAL_RATE_LIMITER_EVAL_COUNTER: &str = "global_rate_limiter_eval_counts_total";const GLOBAL_RATE_LIMITER_CACHE_COUNTER: &str = "global_rate_limiter_cache_counts_total";@@ -28,6 +42,11 @@ const GLOBAL_RATE_LIMITER_ESTIMATE_DRIFT_HISTOGRAM: &str = "global_rate_limiter_const GLOBAL_RATE_LIMITER_SYNC_STALENESS_HISTOGRAM: &str = "global_rate_limiter_sync_staleness_ms";const GLOBAL_RATE_LIMITER_CACHE_SIZE_GAUGE: &str = "global_rate_limiter_cache_size";const GLOBAL_RATE_LIMITER_EVICTION_COUNTER: &str = "global_rate_limiter_eviction_total";+/// Number of custom-key thresholds applied at the last successful refresh.+const CUSTOM_THRESHOLDS_LOADED_GAUGE: &str = "global_rate_limiter_custom_thresholds_loaded";+/// Unix timestamp of the last successful custom-key threshold refresh.+const CUSTOM_THRESHOLDS_LAST_REFRESH_GAUGE: &str =+ "global_rate_limiter_custom_thresholds_last_refresh_timestamp";/// Full-cache scan cadence (ticks) for the per-tier distribution gauges. The/// distribution moves slowly and prod metrics dedup to 60s, so a periodic scan@@ -163,7 +182,26 @@ pub struct GlobalRateLimiterConfig {/// Capacity of the mpsc channel for async global cache updatespub channel_capacity: usize,/// Per-key custom limits. Overrides the default limit for specific *more granular* keys.- pub custom_keys: HashMap<String, u64>,+ ///+ /// Wrapped in `Arc<ArcSwap<_>>` so the map can be atomically replaced at+ /// runtime (by the refresh task via `custom_keys.store(...)`) without locking+ /// hot-path readers. Every clone of the config shares the same underlying+ /// `ArcSwap`, so a swap through any clone (e.g. the copy held by the+ /// background task) is visible everywhere.+ pub custom_keys: Arc<ArcSwap<HashMap<String, u64>>>,+ /// Optional policy for resolving a lookup key to a custom threshold. When+ /// `None`, resolution is an exact lookup in `custom_keys`. When set, the+ /// closure is consulted with the key and a snapshot of the current map.+ pub custom_key_resolver: Option<CustomKeyResolver>,+ /// Optional source of dynamically-refreshed custom-key thresholds. When set,+ /// `GlobalRateLimiterImpl::new` spawns a background task that fetches the map+ /// every `custom_key_refresh_interval` and atomically swaps it into+ /// `custom_keys`. When `None`, `custom_keys` is static (e.g. seeded once from+ /// config) and no refresh task runs.+ pub custom_key_source: Option<Arc<dyn CustomKeyThresholdSource>>,+ /// Cadence for the custom-key refresh task. Ignored when `custom_key_source`+ /// is `None`.+ pub custom_key_refresh_interval: Duration,/// Tag value applied to all metrics emitted by this limiter instance./// Allows distinguishing multiple limiter instances in the same process.pub metrics_scope: String,@@ -179,6 +217,20 @@ impl GlobalRateLimiterConfig {pub fn leak_rate_for(&self, threshold: u64) -> f64 {threshold as f64 / self.window_interval.as_secs_f64()}++ /// Resolve a lookup key to its custom threshold, if any.+ ///+ /// Snapshots the current custom-key map once (lock-free) and applies the+ /// configured resolver, falling back to an exact lookup when no resolver is+ /// injected. Returns `None` when the key is not subject to a custom limit.+ pub fn resolve_custom(&self, key: &str) -> Option<u64> {+ let guard = self.custom_keys.load();+ let map: &HashMap<String, u64> = &guard;+ match &self.custom_key_resolver {+ Some(resolver) => resolver(key, map),+ None => map.get(key).copied(),+ }+ }}impl Default for GlobalRateLimiterConfig {@@ -197,7 +249,10 @@ impl Default for GlobalRateLimiterConfig {global_write_timeout: Duration::from_millis(100),local_cache_max_entries: 300_000,channel_capacity: 1_000_000,- custom_keys: HashMap::new(),+ custom_keys: Arc::new(ArcSwap::from_pointee(HashMap::new())),+ custom_key_resolver: None,+ custom_key_source: None,+ custom_key_refresh_interval: Duration::from_secs(60),metrics_scope: "default".to_string(),}}@@ -350,6 +405,9 @@ pub struct GlobalRateLimiterImpl {update_tx: Option<mpsc::Sender<UpdateRequest>>,pending_sync: Arc<DashSet<String>>,scope: &'static str,+ /// Drop-to-stop signal for the custom-key refresh task (mirrors `update_tx`).+ /// `None` when no `custom_key_source` was configured.+ custom_key_refresh_stop: Option<mpsc::Sender<()>>,}#[async_trait]@@ -375,11 +433,13 @@ impl GlobalRateLimiter for GlobalRateLimiterImpl {}fn is_custom_key(&self, key: &str) -> bool {- self.config.custom_keys.contains_key(key)+ self.config.resolve_custom(key).is_some()}fn shutdown(&mut self) {let _ = self.update_tx.take();+ // Dropping the sender closes the refresh task's stop channel.+ let _ = self.custom_key_refresh_stop.take();}}@@ -421,12 +481,28 @@ impl GlobalRateLimiterImpl {let (update_tx, update_rx) = mpsc::channel(config.channel_capacity);let pending_sync = Arc::new(DashSet::new());+ // Spawn the custom-key refresh task when a source is configured. The+ // source owns its own reconnect; we only hold a drop-to-stop signal,+ // mirroring how `update_tx` closes the tick loop on shutdown.+ let custom_key_refresh_stop = config.custom_key_source.clone().map(|source| {+ let (stop_tx, stop_rx) = mpsc::channel::<()>(1);+ Self::spawn_custom_key_refresh_task(+ config.clone(),+ source,+ config.custom_key_refresh_interval,+ stop_rx,+ scope,+ );+ stop_tx+ });+let limiter = Self {config: config.clone(),cache: cache.clone(),update_tx: Some(update_tx),pending_sync: pending_sync.clone(),scope,+ custom_key_refresh_stop,};Self::spawn_background_task(@@ -453,8 +529,8 @@ impl GlobalRateLimiterImpl {timestamp: Option<DateTime<Utc>>,) -> EvalResult {let threshold = match mode {- CheckMode::Custom => match self.config.custom_keys.get(key) {- Some(&custom_limit) => custom_limit,+ CheckMode::Custom => match self.config.resolve_custom(key) {+ Some(custom_limit) => custom_limit,None => return EvalResult::NotApplicable,},CheckMode::Global => self.config.global_threshold,@@ -571,6 +647,83 @@ impl GlobalRateLimiterImpl {}}+ /// Spawn the background task that periodically refreshes custom-key thresholds.+ ///+ /// `tokio::time::interval` fires immediately, so the first fetch happens+ /// without delay. The task exits when `stop_rx` closes (all senders dropped+ /// via `shutdown`, or when the limiter is dropped).+ fn spawn_custom_key_refresh_task(+ config: GlobalRateLimiterConfig,+ source: Arc<dyn CustomKeyThresholdSource>,+ refresh_interval: Duration,+ mut stop_rx: mpsc::Receiver<()>,+ scope: &'static str,+ ) {+ tokio::spawn(async move {+ // `tokio::time::interval` panics on a zero period. A misconfigured+ // interval must not kill this (detached) task and silently freeze+ // dynamic refreshes, so clamp to a 1s floor and warn instead.+ let period = refresh_interval.max(Duration::from_secs(1));+ if period != refresh_interval {+ warn!(+ scope,+ ?refresh_interval,+ "Custom-key refresh interval below 1s floor; clamping to 1s"+ );+ }+ let mut tick = tokio::time::interval(period);+ loop {+ tokio::select! {+ _ = stop_rx.recv() => {+ info!(scope, "Custom-key threshold refresh task shutting down");+ break;+ }+ _ = tick.tick() => {+ Self::refresh_custom_keys_once(&config, source.as_ref(), scope).await;+ }+ }+ }+ });+ }++ /// Fetch custom-key thresholds once and atomically swap them into the config.+ ///+ /// Only an explicit Redis blob is authoritative: `Ok(Some)` replaces the map+ /// (an empty blob — `{}` — is the deliberate clear signal). An absent key+ /// (`Ok(None)`) is ambiguous — fresh rollout before the writer runs, an+ /// eviction, or an accidental delete — so it is treated as fail-static, the+ /// same as `Err`: the current map is kept rather than silently wiping the+ /// (fail-open) hot overrides. The source handles its own reconnect, so the+ /// next tick retries.+ async fn refresh_custom_keys_once(+ config: &GlobalRateLimiterConfig,+ source: &dyn CustomKeyThresholdSource,+ scope: &'static str,+ ) {+ match source.fetch().await {+ Ok(Some(map)) => {+ let count = map.len();+ config.custom_keys.store(Arc::new(map));+ metrics::gauge!(CUSTOM_THRESHOLDS_LOADED_GAUGE, "scope" => scope).set(count as f64);+ metrics::gauge!(CUSTOM_THRESHOLDS_LAST_REFRESH_GAUGE, "scope" => scope)+ .set(Utc::now().timestamp() as f64);+ }+ Ok(None) => {+ // Absent key: keep the current map (fail-static). A deliberate+ // clear arrives as an explicit empty blob via the `Ok(Some)` arm;+ // the `not_found` counter is already emitted by the source's+ // fetch(), so we neither touch the map nor stomp the gauges here.+ }+ Err(e) => {+ error!(+ scope,+ error = %e,+ "Failed to refresh custom-key thresholds, keeping current values"+ );+ }+ }+ }+/// Spawn the unified background tick loop that handles both reads and writes.////// Every tick_interval:@@ -906,9 +1059,7 @@ impl GlobalRateLimiterImpl {let estimated = weighted_count(prev_count, current_count, now, config.window_interval);let threshold = config- .custom_keys- .get(key)- .copied()+ .resolve_custom(key).unwrap_or(config.global_threshold);let pressure = estimated / threshold as f64;@@ -1004,6 +1155,7 @@ fn parse_redis_count(value: &Option<Vec<u8>>) -> u64 {#[cfg(test)]mod tests {use super::*;+ use crate::custom_key_source::testing::MockCustomKeyThresholdSource;use common_redis::MockRedisClient;fn test_config() -> GlobalRateLimiterConfig {@@ -1018,13 +1170,23 @@ mod tests {local_cache_idle_timeout: Duration::from_millis(500),local_cache_max_entries: 100,channel_capacity: 100,- custom_keys: HashMap::new(),+ custom_keys: Arc::new(ArcSwap::from_pointee(HashMap::new())),+ custom_key_resolver: None,+ custom_key_source: None,+ custom_key_refresh_interval: Duration::from_secs(60),global_read_timeout: Duration::from_millis(5),global_write_timeout: Duration::from_millis(10),metrics_scope: "test".to_string(),}}+ /// Seed a config's custom-key map (whole-map swap), mirroring how the+ /// dynamic refresh path replaces thresholds at runtime.+ fn set_custom_keys(config: &GlobalRateLimiterConfig, pairs: &[(&str, u64)]) {+ let map: HashMap<String, u64> = pairs.iter().map(|(k, v)| (k.to_string(), *v)).collect();+ config.custom_keys.store(Arc::new(map));+ }+// --- Epoch calculation tests (parameterized) ---#[test]@@ -1187,7 +1349,8 @@ mod tests {assert_eq!(config.global_write_timeout, Duration::from_millis(100));assert_eq!(config.local_cache_max_entries, 300_000);assert_eq!(config.channel_capacity, 1_000_000);- assert!(config.custom_keys.is_empty());+ assert!(config.custom_keys.load().is_empty());+ assert!(config.custom_key_resolver.is_none());assert_eq!(config.metrics_scope, "default");}@@ -1394,8 +1557,8 @@ mod tests {#[tokio::test]async fn test_custom_mode_unknown_key_returns_not_applicable() {let client = Arc::new(MockRedisClient::new());- let mut config = test_config();- config.custom_keys.insert("known_key".to_string(), 5);+ let config = test_config();+ set_custom_keys(&config, &[("known_key", 5)]);let limiter = GlobalRateLimiterImpl::new(config, vec![client]).unwrap();let result = limiter.check_custom_limit("unknown_key", 100, None).await;@@ -1408,8 +1571,8 @@ mod tests {#[tokio::test]async fn test_custom_mode_uses_custom_limit() {let client = Arc::new(MockRedisClient::new());- let mut config = test_config();- config.custom_keys.insert("custom_key".to_string(), 5);+ let config = test_config();+ set_custom_keys(&config, &[("custom_key", 5)]);let limiter = GlobalRateLimiterImpl::new(config, vec![client]).unwrap();limiter.cache.insert(@@ -1433,8 +1596,8 @@ mod tests {#[tokio::test]async fn test_custom_mode_under_custom_limit() {let client = Arc::new(MockRedisClient::new());- let mut config = test_config();- config.custom_keys.insert("custom_key".to_string(), 10);+ let config = test_config();+ set_custom_keys(&config, &[("custom_key", 10)]);let limiter = GlobalRateLimiterImpl::new(config, vec![client]).unwrap();limiter.cache.insert(@@ -1457,8 +1620,8 @@ mod tests {#[tokio::test]async fn test_is_custom_key() {let client = Arc::new(MockRedisClient::new()) as Arc<dyn Client + Send + Sync>;- let mut config = test_config();- config.custom_keys.insert("registered".to_string(), 42);+ let config = test_config();+ set_custom_keys(&config, &[("registered", 42)]);let limiter = GlobalRateLimiterImpl::new(config, vec![client]).unwrap();assert!(limiter.is_custom_key("registered"));@@ -1478,9 +1641,8 @@ mod tests {#[tokio::test]async fn test_custom_key_behavior() {let client = Arc::new(MockRedisClient::new());- let mut config = test_config();- config.custom_keys.insert("custom_a".to_string(), 5);- config.custom_keys.insert("custom_b".to_string(), 10);+ let config = test_config();+ set_custom_keys(&config, &[("custom_a", 5), ("custom_b", 10)]);let limiter = GlobalRateLimiterImpl::new(config, vec![client]).unwrap();limiter.cache.insert(@@ -1705,8 +1867,8 @@ mod tests {#[test]fn test_process_read_results_custom_key_pressure() {- let mut config = test_config();- config.custom_keys.insert("custom_entity".to_string(), 100);+ let config = test_config();+ set_custom_keys(&config, &[("custom_entity", 100)]);let cache = Cache::builder().max_capacity(100).time_to_live(Duration::from_secs(60))@@ -1846,4 +2008,250 @@ mod tests {assert_eq!(parse_redis_count(&Some(b"not_a_number".to_vec())), 0);assert_eq!(parse_redis_count(&Some(vec![])), 0);}++ // --- Dynamic custom-key map tests (ArcSwap + resolver) ---++ #[test]+ fn test_resolve_custom_default_exact_match() {+ let config = test_config();+ set_custom_keys(&config, &[("tok:did", 5), ("tok2", 9)]);++ assert_eq!(config.resolve_custom("tok:did"), Some(5));+ assert_eq!(config.resolve_custom("tok2"), Some(9));+ assert_eq!(config.resolve_custom("missing"), None);+ // Default resolver is exact: a token prefix must not match a token:did entry.+ assert_eq!(config.resolve_custom("tok"), None);+ }++ #[test]+ fn test_resolve_custom_injected_resolver_hierarchical() {+ let mut config = test_config();+ // Hierarchical policy: exact key first, then the token prefix before ':'.+ config.custom_key_resolver = Some(Arc::new(|key: &str, map: &HashMap<String, u64>| {+ if let Some(v) = map.get(key) {+ return Some(*v);+ }+ key.split_once(':')+ .and_then(|(tok, _)| map.get(tok).copied())+ }));+ set_custom_keys(&config, &[("tok", 7), ("tok:vip", 100)]);++ assert_eq!(config.resolve_custom("tok:vip"), Some(100)); // exact wins+ assert_eq!(config.resolve_custom("tok:other"), Some(7)); // falls back to token+ assert_eq!(config.resolve_custom("tok"), Some(7)); // token itself+ assert_eq!(config.resolve_custom("nope:x"), None); // no match at any level+ }++ #[tokio::test]+ async fn test_custom_keys_swap_visible_to_running_limiter() {+ let client = Arc::new(MockRedisClient::new());+ let config = test_config();+ // The refresh task swaps through a clone of the config; hold one here to+ // drive the same shared ArcSwap the running limiter reads.+ let cfg_handle = config.clone();+ let limiter = GlobalRateLimiterImpl::new(config, vec![client]).unwrap();++ assert!(!limiter.is_custom_key("dyn_key"));+ let result = limiter.check_custom_limit("dyn_key", 1, None).await;+ assert!(matches!(result, EvalResult::NotApplicable));++ cfg_handle+ .custom_keys+ .store(Arc::new(HashMap::from([("dyn_key".to_string(), 42u64)])));++ assert!(limiter.is_custom_key("dyn_key"));+ // Now subject to a custom limit: a fresh key is Allowed (cache miss), not NotApplicable.+ let result = limiter.check_custom_limit("dyn_key", 1, None).await;+ assert!(+ matches!(result, EvalResult::Allowed),+ "swapped-in custom key should be evaluated, got {result:?}"+ );+ }++ #[test]+ fn test_custom_keys_swap_shared_across_config_clones() {+ // The background task holds a *clone* of the config; a swap through the+ // clone must be visible to the original (shared ArcSwap).+ let config = test_config();+ let bg_clone = config.clone();++ assert_eq!(config.resolve_custom("k"), None);+ bg_clone+ .custom_keys+ .store(Arc::new(HashMap::from([("k".to_string(), 3u64)])));+ assert_eq!(config.resolve_custom("k"), Some(3));+ }++ #[test]+ fn test_custom_keys_concurrent_read_is_consistent() {+ // Readers never observe a torn map: each load sees either the fully-old+ // or fully-new map, never a missing/partial value.+ use std::sync::atomic::{AtomicBool, Ordering};++ let config = Arc::new(test_config());+ set_custom_keys(&config, &[("k", 1)]);++ let stop = Arc::new(AtomicBool::new(false));+ let reader = {+ let config = config.clone();+ let stop = stop.clone();+ std::thread::spawn(move || {+ while !stop.load(Ordering::Relaxed) {+ let v = config.resolve_custom("k");+ assert!(matches!(v, Some(1) | Some(100)), "torn read: {v:?}");+ }+ })+ };++ for i in 0..10_000 {+ let v = if i % 2 == 0 { 1u64 } else { 100u64 };+ config+ .custom_keys+ .store(Arc::new(HashMap::from([("k".to_string(), v)])));+ }+ stop.store(true, Ordering::Relaxed);+ reader.join().unwrap();+ }++ // --- Refresh path tests (refresh_custom_keys_once via a mock source) ---++ #[tokio::test]+ async fn test_refresh_once_applies_thresholds() {+ let config = test_config();+ set_custom_keys(&config, &[("seed", 1)]);++ let source = MockCustomKeyThresholdSource::with_thresholds(Some(HashMap::from([(+ "dyn".to_string(),+ 99u64,+ )])));+ GlobalRateLimiterImpl::refresh_custom_keys_once(&config, &source, "test").await;++ // Fetched map replaces the seed wholesale (Redis is authoritative).+ assert_eq!(config.resolve_custom("dyn"), Some(99));+ assert_eq!(config.resolve_custom("seed"), None);+ }++ #[tokio::test]+ async fn test_refresh_once_absent_key_is_fail_static() {+ let config = test_config();+ set_custom_keys(&config, &[("seed", 1)]);++ let source = MockCustomKeyThresholdSource::with_thresholds(None);+ GlobalRateLimiterImpl::refresh_custom_keys_once(&config, &source, "test").await;++ // Absent key is ambiguous (fresh rollout / eviction / accidental delete),+ // not an authoritative clear: the current thresholds must survive.+ assert_eq!(config.resolve_custom("seed"), Some(1));+ }++ #[tokio::test]+ async fn test_refresh_once_empty_blob_clears_thresholds() {+ let config = test_config();+ set_custom_keys(&config, &[("seed", 1)]);++ // An explicit empty blob (`{}` in Redis) is the deliberate clear signal,+ // distinct from an absent key: it replaces the map with an empty one.+ let source = MockCustomKeyThresholdSource::with_thresholds(Some(HashMap::new()));+ GlobalRateLimiterImpl::refresh_custom_keys_once(&config, &source, "test").await;++ assert_eq!(config.resolve_custom("seed"), None);+ }++ #[tokio::test]+ async fn test_refresh_once_error_is_fail_static() {+ let config = test_config();+ set_custom_keys(&config, &[("keep", 7)]);++ let source =+ MockCustomKeyThresholdSource::with_error(common_redis::CustomRedisError::Timeout);+ GlobalRateLimiterImpl::refresh_custom_keys_once(&config, &source, "test").await;++ // A failed fetch must not disturb the current thresholds.+ assert_eq!(config.resolve_custom("keep"), Some(7));+ }++ // --- Refresh task lifecycle (spawn on new(), stop on shutdown()) ---++ /// Poll `cond`, driving the paused clock forward so the interval-based refresh+ /// task gets a chance to tick, up to a bounded number of iterations.+ async fn wait_until<F: Fn() -> bool>(cond: F) -> bool {+ for _ in 0..50 {+ if cond() {+ return true;+ }+ tokio::time::advance(Duration::from_secs(60)).await;+ tokio::task::yield_now().await;+ }+ cond()+ }++ #[tokio::test(start_paused = true)]+ async fn test_refresh_task_spawns_ticks_and_stops_on_shutdown() {+ let mock = Arc::new(MockCustomKeyThresholdSource::with_thresholds(Some(+ HashMap::from([("first".to_string(), 11u64)]),+ )));+ let mut config = test_config();+ // Hold the shared ArcSwap so we can observe swaps the spawned task makes.+ let observed = config.custom_keys.clone();+ config.custom_key_source = Some(mock.clone() as Arc<dyn CustomKeyThresholdSource>);+ config.custom_key_refresh_interval = Duration::from_secs(60);++ let client = Arc::new(MockRedisClient::new());+ let mut limiter = GlobalRateLimiterImpl::new(config, vec![client]).unwrap();++ // The task ticks immediately on spawn and applies the initial map.+ assert!(+ wait_until(|| observed.load().get("first") == Some(&11)).await,+ "refresh task should apply the initial map after spawn"+ );++ // A subsequent Redis-side change is picked up on the next tick.+ mock.set_thresholds(Some(HashMap::from([("second".to_string(), 22u64)])))+ .await;+ assert!(+ wait_until(|| observed.load().get("second") == Some(&22)).await,+ "refresh task should apply an updated map on a later tick"+ );++ // After shutdown the task must exit: let it observe the closed stop channel.+ limiter.shutdown();+ for _ in 0..20 {+ tokio::task::yield_now().await;+ }++ // A change made after shutdown must never be applied.+ mock.set_thresholds(Some(HashMap::from([("third".to_string(), 33u64)])))+ .await;+ for _ in 0..10 {+ tokio::time::advance(Duration::from_secs(120)).await;+ tokio::task::yield_now().await;+ }+ assert!(+ observed.load().get("third").is_none(),+ "refresh task must not apply changes after shutdown"+ );+ // The last pre-shutdown value is still in place.+ assert_eq!(observed.load().get("second"), Some(&22));+ }++ #[tokio::test(start_paused = true)]+ async fn test_zero_refresh_interval_is_clamped_not_panicking() {+ // A zero interval would panic `tokio::time::interval` and kill the+ // detached refresh task; the clamp must keep it running and ticking.+ let mock = Arc::new(MockCustomKeyThresholdSource::with_thresholds(Some(+ HashMap::from([("only".to_string(), 9u64)]),+ )));+ let mut config = test_config();+ let observed = config.custom_keys.clone();+ config.custom_key_source = Some(mock.clone() as Arc<dyn CustomKeyThresholdSource>);+ config.custom_key_refresh_interval = Duration::ZERO;++ let client = Arc::new(MockRedisClient::new());+ let _limiter = GlobalRateLimiterImpl::new(config, vec![client]).unwrap();++ assert!(+ wait_until(|| observed.load().get("only") == Some(&9)).await,+ "clamped refresh task should still apply the initial map"+ );+ }}diff --git a/rust/common/limiters/src/lib.rs b/rust/common/limiters/src/lib.rsindex 15dc14cfeccb..8353efc3c28a 100644--- a/rust/common/limiters/src/lib.rs+++ b/rust/common/limiters/src/lib.rs@@ -1,8 +1,12 @@+pub mod custom_key_source;pub mod global_rate_limiter;pub mod overflow;pub mod redis;pub mod token_dropper;+pub use custom_key_source::{+ parse_thresholds, CustomKeyThresholdSource, RedisCustomKeyThresholdSource,+};pub use global_rate_limiter::{EvalResult, FailOpenReason, GlobalRateLimitResponse, GlobalRateLimiter,GlobalRateLimiterConfig, GlobalRateLimiterImpl,diff --git a/rust/common/limiters/tests/global_rate_limiter_integration_tests.rs b/rust/common/limiters/tests/global_rate_limiter_integration_tests.rsindex b1cdc6024766..7149812a5069 100644--- a/rust/common/limiters/tests/global_rate_limiter_integration_tests.rs+++ b/rust/common/limiters/tests/global_rate_limiter_integration_tests.rs@@ -48,7 +48,10 @@ fn test_config(test_name: &str) -> GlobalRateLimiterConfig {local_cache_idle_timeout: Duration::from_secs(30),local_cache_max_entries: 1000,channel_capacity: 10_000,- custom_keys: HashMap::new(),+ custom_keys: std::sync::Arc::new(arc_swap::ArcSwap::from_pointee(HashMap::new())),+ custom_key_resolver: None,+ custom_key_source: None,+ custom_key_refresh_interval: Duration::from_secs(60),global_read_timeout: Duration::from_millis(500),global_write_timeout: Duration::from_millis(500),metrics_scope: "integration_test".to_string(),@@ -363,7 +366,9 @@ async fn test_custom_key_high_threshold_sync_and_limit() {let key = format!("high_limit_{}", Utc::now().timestamp());let mut config = test_config("custom_high");config.global_threshold = 1000;- config.custom_keys.insert(key.clone(), 100_000);+ config+ .custom_keys+ .store(std::sync::Arc::new(HashMap::from([(key.clone(), 100_000)])));let now = Utc::now();let epoch = epoch_from_timestamp(now, config.window_interval);