CMDCGateway.RateLimiter (cmdc_gateway v0.4.2)

Copy Markdown View Source

API Key 级别令牌桶限流。

基于 ETS 的滑动窗口计数器,在 Plug 管道中拦截超限请求。 超限时返回 HTTP 429 + Retry-After 头。

配置

通过 Application env 配置(config :cmdc_gateway, CMDCGateway.RateLimiter):

  • :rpm — 每分钟最大请求数,默认 60
  • :enabled — 是否启用限流,默认 true
  • :cleanup_interval_ms — 过期条目清理间隔,默认 60_000

热更新

CMDCGateway.RateLimiter.update_config(rpm: 120)

Summary

Functions

检查给定 api_key 是否允许请求。

Returns a specification to start this module under a supervisor.

获取某个 api_key 当前窗口内的请求计数。

重置某个 api_key 的请求计数。

热更新限流配置(:rpm:enabled)。

Functions

check(api_key)

@spec check(String.t()) :: :ok | {:error, :rate_limited, non_neg_integer()}

检查给定 api_key 是否允许请求。

返回 :ok{:error, :rate_limited, retry_after_seconds}

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

current_count(api_key)

@spec current_count(String.t()) :: non_neg_integer()

获取某个 api_key 当前窗口内的请求计数。

reset(api_key)

@spec reset(String.t()) :: :ok

重置某个 api_key 的请求计数。

start_link(opts \\ [])

@spec start_link(keyword()) :: GenServer.on_start()

update_config(new_opts)

@spec update_config(keyword()) :: :ok

热更新限流配置(:rpm:enabled)。