наблюдаемость: завершить базовый контур Community
Добавить структурированные журналы, метрики, трассировку и безопасный канал критических ошибок. Усилить границы рантайма, тесты, проверку зависимостей и сценарии развёртывания.
This commit is contained in:
1 parent
99bd05c145
commit
0e8f1ca03a
160 files changed
+13506
-1499
No files matched your search
@@ -4,8 +4,9 @@ use std::{
|
||||
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
use crank_core::{RateLimitBucketState, RateLimitStateStore};
|
||||
use crank_core::{RateLimitDecision, RateLimitStateStore};
|
||||
use thiserror::Error;
|
||||
use tracing::warn;
|
||||
|
||||
const STALE_KEY_TTL: Duration = Duration::from_secs(300);
|
||||
const TOKEN_SCALE: u64 = 1_000_000;
|
||||
@@ -47,6 +48,12 @@ pub struct RateLimitRejection {
|
||||
pub retry_after_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RateLimitCheckError {
|
||||
Rejected(RateLimitRejection),
|
||||
StoreUnavailable,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RequestRateLimiter {
|
||||
config: RequestRateLimitConfig,
|
||||
@@ -87,14 +94,24 @@ impl RequestRateLimiter {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn check(&self, key: &str) -> Result<(), RateLimitRejection> {
|
||||
match &self.backend {
|
||||
RequestRateLimiterBackend::Local { .. } => self.check_local_at(key, Instant::now()),
|
||||
pub async fn check(&self, key: &str) -> Result<(), RateLimitCheckError> {
|
||||
let result = match &self.backend {
|
||||
RequestRateLimiterBackend::Local { .. } => self
|
||||
.check_local_at(key, Instant::now())
|
||||
.map_err(RateLimitCheckError::Rejected),
|
||||
RequestRateLimiterBackend::Shared { store } => {
|
||||
self.check_shared_at(store.as_ref(), key, now_unix_ms())
|
||||
.await
|
||||
}
|
||||
};
|
||||
if matches!(result, Err(RateLimitCheckError::Rejected(_))) {
|
||||
metrics::counter!(
|
||||
"crank_runtime_limit_rejections_total",
|
||||
"stage" => "rate_limit"
|
||||
)
|
||||
.increment(1);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn check_local_at(&self, key: &str, now: Instant) -> Result<(), RateLimitRejection> {
|
||||
@@ -137,35 +154,35 @@ impl RequestRateLimiter {
|
||||
store: &dyn RateLimitStateStore,
|
||||
key: &str,
|
||||
now_unix_ms: i64,
|
||||
) -> Result<(), RateLimitRejection> {
|
||||
let burst_tokens = u64::from(self.config.burst) * TOKEN_SCALE;
|
||||
let refill_per_second = u64::from(self.config.requests_per_second) * TOKEN_SCALE;
|
||||
let mut state =
|
||||
store
|
||||
.get_bucket(key)
|
||||
.await
|
||||
.unwrap_or(None)
|
||||
.unwrap_or(RateLimitBucketState {
|
||||
tokens_micros: burst_tokens,
|
||||
last_refill_unix_ms: now_unix_ms,
|
||||
});
|
||||
|
||||
let elapsed_ms = (now_unix_ms - state.last_refill_unix_ms).max(0) as u64;
|
||||
let replenished =
|
||||
state.tokens_micros + (elapsed_ms.saturating_mul(refill_per_second) / 1000);
|
||||
state.tokens_micros = replenished.min(burst_tokens);
|
||||
state.last_refill_unix_ms = now_unix_ms;
|
||||
|
||||
if state.tokens_micros >= TOKEN_SCALE {
|
||||
state.tokens_micros -= TOKEN_SCALE;
|
||||
let _ = store.put_bucket(key, state, STALE_KEY_TTL).await;
|
||||
return Ok(());
|
||||
) -> Result<(), RateLimitCheckError> {
|
||||
let decision = match store
|
||||
.consume_token(
|
||||
key,
|
||||
u64::from(self.config.burst) * TOKEN_SCALE,
|
||||
u64::from(self.config.requests_per_second) * TOKEN_SCALE,
|
||||
now_unix_ms,
|
||||
STALE_KEY_TTL,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(decision) => decision,
|
||||
Err(_) => {
|
||||
warn!(
|
||||
name: "runtime.rate_limit.failed_closed",
|
||||
error_category = "coordination_store",
|
||||
"shared rate limiter failed closed"
|
||||
);
|
||||
return Err(RateLimitCheckError::StoreUnavailable);
|
||||
}
|
||||
};
|
||||
match decision {
|
||||
RateLimitDecision::Allowed => Ok(()),
|
||||
RateLimitDecision::Rejected { retry_after_ms } => {
|
||||
Err(RateLimitCheckError::Rejected(RateLimitRejection {
|
||||
retry_after_ms,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
let missing_tokens = TOKEN_SCALE.saturating_sub(state.tokens_micros);
|
||||
let retry_after_ms = missing_tokens.div_ceil(refill_per_second).max(1);
|
||||
let _ = store.put_bucket(key, state, STALE_KEY_TTL).await;
|
||||
Err(RateLimitRejection { retry_after_ms })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,6 +202,11 @@ mod tests {
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use crank_core::{
|
||||
CacheStoreError, RateLimitBucketState, RateLimitDecision, RateLimitStateStore,
|
||||
};
|
||||
|
||||
use crate::InMemoryRateLimitStateStore;
|
||||
|
||||
use super::{RequestRateLimitConfig, RequestRateLimitConfigError, RequestRateLimiter};
|
||||
@@ -234,7 +256,12 @@ mod tests {
|
||||
assert!(limiter.check_shared_at_store("key", 0).await.is_ok());
|
||||
|
||||
let rejection = limiter.check_shared_at_store("key", 0).await.unwrap_err();
|
||||
assert_eq!(rejection.retry_after_ms, 1);
|
||||
assert_eq!(
|
||||
rejection,
|
||||
super::RateLimitCheckError::Rejected(super::RateLimitRejection {
|
||||
retry_after_ms: 500,
|
||||
})
|
||||
);
|
||||
|
||||
assert!(limiter.check_shared_at_store("key", 500).await.is_ok());
|
||||
}
|
||||
@@ -254,12 +281,120 @@ mod tests {
|
||||
assert!(second.check_shared_at_store("shared", 1000).await.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shared_limiter_does_not_refill_when_clock_moves_backwards() {
|
||||
let limiter = RequestRateLimiter::new_shared(
|
||||
RequestRateLimitConfig::new(1, 1).unwrap(),
|
||||
Arc::new(InMemoryRateLimitStateStore::default()),
|
||||
);
|
||||
|
||||
assert!(limiter.check_shared_at_store("clock", 1_000).await.is_ok());
|
||||
assert_eq!(
|
||||
limiter
|
||||
.check_shared_at_store("clock", 500)
|
||||
.await
|
||||
.unwrap_err(),
|
||||
super::RateLimitCheckError::Rejected(super::RateLimitRejection {
|
||||
retry_after_ms: 1_000,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
limiter
|
||||
.check_shared_at_store("clock", 1_500)
|
||||
.await
|
||||
.unwrap_err(),
|
||||
super::RateLimitCheckError::Rejected(super::RateLimitRejection {
|
||||
retry_after_ms: 500,
|
||||
})
|
||||
);
|
||||
assert!(limiter.check_shared_at_store("clock", 2_000).await.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shared_limiter_consumes_burst_atomically_under_concurrency() {
|
||||
let limiter = RequestRateLimiter::new_shared(
|
||||
RequestRateLimitConfig::new(1, 8).unwrap(),
|
||||
Arc::new(InMemoryRateLimitStateStore::default()),
|
||||
);
|
||||
let attempts = (0..64).map(|_| limiter.check_shared_at_store("concurrent", 0));
|
||||
let results = futures_util::future::join_all(attempts).await;
|
||||
|
||||
assert_eq!(results.iter().filter(|result| result.is_ok()).count(), 8);
|
||||
assert!(
|
||||
results
|
||||
.iter()
|
||||
.filter_map(|result| result.as_ref().err())
|
||||
.all(|rejection| {
|
||||
*rejection
|
||||
== super::RateLimitCheckError::Rejected(super::RateLimitRejection {
|
||||
retry_after_ms: 1_000,
|
||||
})
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shared_limiter_fails_closed_when_store_is_unavailable() {
|
||||
let limiter = RequestRateLimiter::new_shared(
|
||||
RequestRateLimitConfig::new(10, 10).unwrap(),
|
||||
Arc::new(UnavailableRateLimitStore),
|
||||
);
|
||||
|
||||
let error = limiter
|
||||
.check_shared_at_store("unavailable", 0)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error, super::RateLimitCheckError::StoreUnavailable);
|
||||
}
|
||||
|
||||
struct UnavailableRateLimitStore;
|
||||
|
||||
#[async_trait]
|
||||
impl RateLimitStateStore for UnavailableRateLimitStore {
|
||||
async fn get_bucket(
|
||||
&self,
|
||||
_key: &str,
|
||||
) -> Result<Option<RateLimitBucketState>, CacheStoreError> {
|
||||
Err(unavailable())
|
||||
}
|
||||
|
||||
async fn put_bucket(
|
||||
&self,
|
||||
_key: &str,
|
||||
_value: RateLimitBucketState,
|
||||
_ttl: Duration,
|
||||
) -> Result<(), CacheStoreError> {
|
||||
Err(unavailable())
|
||||
}
|
||||
|
||||
async fn delete_bucket(&self, _key: &str) -> Result<(), CacheStoreError> {
|
||||
Err(unavailable())
|
||||
}
|
||||
|
||||
async fn consume_token(
|
||||
&self,
|
||||
_key: &str,
|
||||
_burst_tokens_micros: u64,
|
||||
_refill_per_second_micros: u64,
|
||||
_now_unix_ms: i64,
|
||||
_ttl: Duration,
|
||||
) -> Result<RateLimitDecision, CacheStoreError> {
|
||||
Err(unavailable())
|
||||
}
|
||||
}
|
||||
|
||||
fn unavailable() -> CacheStoreError {
|
||||
CacheStoreError::Unavailable {
|
||||
message: "test store is unavailable".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
impl RequestRateLimiter {
|
||||
async fn check_shared_at_store(
|
||||
&self,
|
||||
key: &str,
|
||||
now_unix_ms: i64,
|
||||
) -> Result<(), super::RateLimitRejection> {
|
||||
) -> Result<(), super::RateLimitCheckError> {
|
||||
let super::RequestRateLimiterBackend::Shared { store } = &self.backend else {
|
||||
panic!("check_shared_at_store called for non-shared limiter");
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user