api: add ingress request throttling

This commit is contained in:
a.tolmachev
2026-05-01 17:03:53 +00:00
parent 411d662676
commit 5f68fcbd04
7 changed files with 241 additions and 3 deletions
+17 -1
View File
@@ -41,6 +41,11 @@ pub enum ApiError {
context: Option<Value>,
},
#[error("{message}")]
RateLimited {
message: String,
context: Option<Value>,
},
#[error("{message}")]
Internal {
message: String,
context: Option<Value>,
@@ -76,6 +81,13 @@ impl ApiError {
}
}
pub(crate) fn rate_limited_with_context(message: impl Into<String>, context: Value) -> Self {
Self::RateLimited {
message: message.into(),
context: Some(context),
}
}
pub(crate) fn validation_with_context(message: impl Into<String>, context: Value) -> Self {
Self::Validation {
message: message.into(),
@@ -104,6 +116,7 @@ impl ApiError {
Self::Validation { .. } => StatusCode::BAD_REQUEST,
Self::NotFound { .. } => StatusCode::NOT_FOUND,
Self::Conflict { .. } => StatusCode::CONFLICT,
Self::RateLimited { .. } => StatusCode::TOO_MANY_REQUESTS,
Self::Internal { .. } => StatusCode::INTERNAL_SERVER_ERROR,
}
}
@@ -115,6 +128,7 @@ impl ApiError {
Self::Validation { .. } => "validation_error",
Self::NotFound { .. } => "not_found",
Self::Conflict { .. } => "conflict",
Self::RateLimited { .. } => "rate_limited",
Self::Internal { .. } => "internal_error",
}
}
@@ -130,7 +144,8 @@ impl IntoResponse for ApiError {
| Self::Forbidden { message, .. }
| Self::Validation { message, .. }
| Self::NotFound { message, .. }
| Self::Conflict { message, .. } => {
| Self::Conflict { message, .. }
| Self::RateLimited { message, .. } => {
warn!(error_code = self.code(), error_message = %message)
}
}
@@ -159,6 +174,7 @@ impl ApiError {
| Self::Validation { context, .. }
| Self::NotFound { context, .. }
| Self::Conflict { context, .. }
| Self::RateLimited { context, .. }
| Self::Internal { context, .. } => context.clone(),
}
}