feat: add rate limiting configurations

This commit is contained in:
xfy 2026-06-08 16:57:48 +08:00
parent 771b155a88
commit 76f1b8dd53
2 changed files with 56 additions and 2 deletions

View File

@ -28,6 +28,7 @@ syntect = { version = "5", default-features = false, features = ["default-syntax
image = { version = "0.25", optional = true }
moka = { version = "0.12", features = ["future"], optional = true }
tower_governor = { version = "0.7", optional = true }
governor = { version = "0.8", optional = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
web-sys = { version = "0.3", features = ["Document", "Window", "HtmlDocument", "Storage", "Element", "DomTokenList", "MediaQueryList", "HtmlScriptElement", "HtmlImageElement", "MouseEvent", "KeyboardEvent", "Node", "HtmlButtonElement", "EventTarget", "HtmlElement"] }
@ -61,4 +62,5 @@ server = [
"dep:image",
"dep:moka",
"dep:tower_governor",
"dep:governor",
]

View File

@ -1,2 +1,54 @@
// Placeholder for rate_limit module (Task 7)
// This module will be implemented in a future task.
#![allow(clippy::unused_unit)]
#[cfg(feature = "server")]
use std::sync::Arc;
#[cfg(feature = "server")]
use tower_governor::governor::GovernorConfigBuilder;
#[cfg(feature = "server")]
use tower_governor::GovernorLayer;
#[cfg(feature = "server")]
use tower_governor::key_extractor::SmartIpKeyExtractor;
#[cfg(feature = "server")]
use governor::middleware::NoOpMiddleware;
/// 通用限流配置:每分钟 60 请求
#[cfg(feature = "server")]
pub fn general_limit() -> GovernorLayer<SmartIpKeyExtractor, NoOpMiddleware> {
let config = GovernorConfigBuilder::default()
.per_second(1)
.burst_size(30)
.key_extractor(SmartIpKeyExtractor)
.finish()
.unwrap();
GovernorLayer {
config: Arc::new(config),
}
}
/// 严格限流配置:每分钟 10 请求(用于登录、注册等敏感操作)
#[cfg(feature = "server")]
pub fn strict_limit() -> GovernorLayer<SmartIpKeyExtractor, NoOpMiddleware> {
let config = GovernorConfigBuilder::default()
.per_second(1)
.burst_size(5)
.key_extractor(SmartIpKeyExtractor)
.finish()
.unwrap();
GovernorLayer {
config: Arc::new(config),
}
}
/// 上传限流配置:每分钟 20 请求
#[cfg(feature = "server")]
pub fn upload_limit() -> GovernorLayer<SmartIpKeyExtractor, NoOpMiddleware> {
let config = GovernorConfigBuilder::default()
.per_second(1)
.burst_size(10)
.key_extractor(SmartIpKeyExtractor)
.finish()
.unwrap();
GovernorLayer {
config: Arc::new(config),
}
}