-- IP速率限制统一配置模块 -- 从公共配置加载,提供便捷的访问接口 local _M = {} local common_config = require "config.common_config" -- 处置策略枚举 _M.ACTION_ALLOW = "allow" -- 放行 _M.ACTION_RATE_LIMIT = "rate_limit" -- 限制速率(返回429) _M.ACTION_BLOCK = "block" -- 封禁(返回403) -- ============================================ -- 预设配置模板(可选使用) -- ============================================ _M.presets = { -- 宽松模式:放行 allow_all = { time_window = 60, max_requests = 10000, action = _M.ACTION_ALLOW }, -- 标准模式:限制速率 standard = { time_window = 60, max_requests = 100, action = _M.ACTION_RATE_LIMIT }, -- 严格模式:封禁 strict = { time_window = 60, max_requests = 50, action = _M.ACTION_BLOCK }, -- API接口保护 api_protection = { time_window = 60, max_requests = 30, action = _M.ACTION_RATE_LIMIT, status_code = 429, message = "API rate limit exceeded" }, -- 登录防暴力破解 login_protection = { time_window = 300, max_requests = 10, action = _M.ACTION_BLOCK, message = "Too many login attempts" } } -- ============================================ -- 配置管理函数 -- ============================================ -- 获取配置(从公共配置读取) function _M.get_config() return common_config.rate_limit end -- 更新配置 function _M.update_config(new_config) local cfg = common_config.rate_limit for k, v in pairs(new_config) do cfg[k] = v end -- 如果没有手动指定状态码,根据action自动设置 if not new_config.status_code then if cfg.action == _M.ACTION_RATE_LIMIT then cfg.status_code = 429 elseif cfg.action == _M.ACTION_BLOCK then cfg.status_code = 403 else cfg.status_code = 200 end end -- 如果没有手动指定消息,根据action自动设置 if not new_config.message then if cfg.action == _M.ACTION_RATE_LIMIT then cfg.message = "Rate limit exceeded. Please try again later." elseif cfg.action == _M.ACTION_BLOCK then cfg.message = "Access denied." else cfg.message = "" end end end -- 应用预设配置 function _M.apply_preset(preset_name) local preset = _M.presets[preset_name] if preset then _M.update_config(preset) return true end return false end -- 快速配置函数 -- @param time_window: 时间窗口(秒) -- @param max_requests: 最大请求次数 -- @param action: 处置策略(allow/rate_limit/block) function _M.configure(time_window, max_requests, action) _M.update_config({ time_window = time_window, max_requests = max_requests, action = action }) end return _M