初版:小白超人(从线上实例导出)
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""进程内限流工具:滑动窗口限速 + 失败锁定。单进程部署下内存实现即可。"""
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
|
||||
_lock = threading.Lock()
|
||||
_windows: dict = {} # key -> deque[timestamps]
|
||||
_failures: dict = {} # key -> [fail_count, first_fail_ts]
|
||||
_MAX_TRACKED = 50000 # 防止 key 无限增长(被伪造 IP 刷爆内存)
|
||||
|
||||
|
||||
def _prune_locked(now: float):
|
||||
"""窗口表过大时清理过期项,避免内存被恶意 IP 撑爆。"""
|
||||
if len(_windows) < _MAX_TRACKED:
|
||||
return
|
||||
for k in [k for k, dq in _windows.items() if not dq or now - dq[-1] > 600]:
|
||||
_windows.pop(k, None)
|
||||
if len(_windows) > _MAX_TRACKED * 2:
|
||||
_windows.clear()
|
||||
|
||||
|
||||
def hit(key, max_requests: int, window_seconds: int):
|
||||
"""滑动窗口限速:窗口内已达上限返回 False(本次不计入),否则记一笔并返回 True。"""
|
||||
now = time.time()
|
||||
with _lock:
|
||||
dq = _windows.setdefault(key, deque())
|
||||
while dq and now - dq[0] > window_seconds:
|
||||
dq.popleft()
|
||||
if len(dq) >= max_requests:
|
||||
_prune_locked(now)
|
||||
return False
|
||||
dq.append(now)
|
||||
_prune_locked(now)
|
||||
return True
|
||||
|
||||
|
||||
def fail_locked(key, max_fails: int, lock_seconds: int):
|
||||
"""该 key 是否已处于锁定状态。返回 (locked, 剩余秒数)。"""
|
||||
now = time.time()
|
||||
with _lock:
|
||||
entry = _failures.get(key)
|
||||
if not entry:
|
||||
return False, 0
|
||||
count, first_ts = entry
|
||||
if now - first_ts > lock_seconds:
|
||||
del _failures[key]
|
||||
return False, 0
|
||||
if count >= max_fails:
|
||||
return True, int(lock_seconds - (now - first_ts))
|
||||
return False, 0
|
||||
|
||||
|
||||
def record_fail(key, max_fails: int, lock_seconds: int):
|
||||
"""记录一次失败;窗口过期则重新计数。返回当前是否触发锁定。"""
|
||||
now = time.time()
|
||||
with _lock:
|
||||
entry = _failures.get(key)
|
||||
if not entry or now - entry[1] > lock_seconds:
|
||||
entry = [1, now]
|
||||
_failures[key] = entry
|
||||
else:
|
||||
entry[0] += 1
|
||||
return entry[0] >= max_fails
|
||||
|
||||
|
||||
def record_success(key):
|
||||
with _lock:
|
||||
_failures.pop(key, None)
|
||||
Reference in New Issue
Block a user