wordval-web 1.0.13

Wordval web layer: router, middleware, extractors, responses, session-based authentication
Documentation
//! IP 限流中间件(固定窗口,单实例本地限流)
//!
//! 使用 DashMap 实现无锁分片并发访问,后台定期清理过期 IP 条目,
//! 避免长时间运行后内存无限增长。
//!
//! 客户端 IP 由 [`super::client_identity::ClientIdentityLayer`] 统一解析后
//! 从 request extensions 读取,本层不再自行解析代理头,保证与访问日志
//! 使用同一可信代理策略。
//!
//! 注意:本实现为**单实例本地限流**——多实例部署时每个进程独立计数,
//! 真实总额度会随副本数增长;固定窗口边界允许短时间双倍突发。
//! 需要集中式限流时可将 `RateLimitLayer::store` 替换为 Redis 等共享计数存储。
//!
//! # 配置
//!
//! 在 `config.toml` 的 `[middleware.rate_limit]` 中设置:
//!
//! ```toml
//! [middleware.rate_limit]
//! enabled = true
//! requests_per_window = 100
//! window_secs = 60
//! # 可选:前置可信反代时开启
//! trust_xff = true
//! trusted_proxies = ["10.0.0.0/8", "192.168.1.10"]
//! ```
//!
//! 超限返回 429 Too Many Requests。

use axum::{body::Body, extract::Request, response::Response};
use dashmap::DashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use tower::{Layer, Service};
use wordval_core::api::ApiError;
use wordval_utils::web::TrustedProxies;

#[derive(Clone)]
pub struct RateLimitLayer {
    /// 时间窗口内允许的最大请求数
    pub requests_per_window: u64,
    /// 时间窗口宽度(秒)
    pub window_secs: u64,
    /// IP → 计数器映射(共享状态)
    pub store: Arc<DashMap<String, IpWindow>>,
    /// 可信代理网段(供 ClientIdentityLayer 解析客户端 IP 使用)
    pub trusted: Arc<TrustedProxies>,
}

/// IP 固定窗口计数器——记录时间窗口内的请求次数
pub struct IpWindow {
    /// 当前窗口内的请求计数
    pub count: u64,
    /// 窗口起始时刻
    pub window_start: Instant,
}

impl RateLimitLayer {
    /// 启动后台清理任务,定期移除过期的 IP 条目。
    ///
    /// 清理间隔为 `window_secs` 的 2 倍,确保已过期的窗口被回收。
    /// 应在 `App::start()` 中调用一次。
    pub fn start_cleanup_task(&self) {
        let store = self.store.clone();
        let window_dur = Duration::from_secs(self.window_secs);
        // 清理间隔下限 1s:防御 window_secs=0 时退化为忙循环
        let cleanup_interval = (window_dur * 2).max(Duration::from_secs(1));

        tokio::spawn(async move {
            loop {
                tokio::time::sleep(cleanup_interval).await;
                let now = Instant::now();
                let before = store.len();
                store.retain(|_, w| now.duration_since(w.window_start) <= window_dur);
                let removed = before - store.len();
                if removed > 0 {
                    tracing::debug!("限流器清理过期 IP 条目: {} 个", removed);
                }
            }
        });
    }
}

impl<S> Layer<S> for RateLimitLayer {
    type Service = RateLimitService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        RateLimitService {
            inner,
            requests_per_window: self.requests_per_window,
            window_secs: self.window_secs,
            store: self.store.clone(),
        }
    }
}

#[derive(Clone)]
/// 限流服务——固定窗口算法实现 IP 级别请求限流
pub struct RateLimitService<S> {
    /// 下游服务
    inner: S,
    /// 时间窗口内允许的最大请求数
    requests_per_window: u64,
    /// 时间窗口宽度(秒)
    window_secs: u64,
    /// IP → 窗口计数器映射
    store: Arc<DashMap<String, IpWindow>>,
}

impl<S> Service<Request<Body>> for RateLimitService<S>
where
    S: Service<Request<Body>, Response = Response> + Clone + Send + 'static,
    S::Future: Send + 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: Request<Body>) -> Self::Future {
        // 统一从 ClientIdentity 层解析的扩展读取客户端 IP(与访问日志同一结论)
        let ip = req
            .extensions()
            .get::<super::client_identity::ClientIp>()
            .map(|c| c.0.clone())
            .unwrap_or_else(|| "0.0.0.0".to_string());

        let max_req = self.requests_per_window;
        let win_secs = self.window_secs;
        let store = self.store.clone();
        let window_dur = Duration::from_secs(win_secs);

        // DashMap 分片锁:每个 IP 只锁自己的分片,不同 IP 完全并行
        let allowed = {
            let now = Instant::now();
            // 使用 entry API 原子地获取或创建窗口
            let mut entry = store.entry(ip).or_insert(IpWindow {
                count: 0,
                window_start: now,
            });

            if now.duration_since(entry.window_start) > window_dur {
                entry.count = 0;
                entry.window_start = now;
            }

            if entry.count < max_req {
                entry.count += 1;
                true
            } else {
                false
            }
            // entry 的写锁在此自动释放
        };

        if allowed {
            let replacement = self.inner.clone();
            let mut inner = std::mem::replace(&mut self.inner, replacement);
            Box::pin(async move { inner.call(req).await })
        } else {
            let resp =
                super::error_response(ApiError::too_many_requests("请求过于频繁,请稍后再试"));
            Box::pin(async move { Ok(resp) })
        }
    }
}