Files
mtusi2026lab7/app/db/login_limit.py
T

37 lines
1.0 KiB
Python

"""One atomic login budget across API replicas."""
import hashlib
from redis.asyncio import Redis
from redis.exceptions import RedisError
from ..domain.errors import Unavailable
_RESERVE = """
local used = redis.call('GET', KEYS[1])
if not used then
redis.call('SET', KEYS[1], '1', 'EX', ARGV[2])
return 0
end
if tonumber(used) >= tonumber(ARGV[1]) then
return math.max(redis.call('TTL', KEYS[1]), 1)
end
redis.call('INCR', KEYS[1])
return 0
"""
class LoginLimiter:
def __init__(self, redis: Redis, limit: int, window_seconds: int) -> None:
self.redis = redis
self.limit = limit
self.window_seconds = window_seconds
async def reserve(self, client_ip: str) -> int:
key = 'login:' + hashlib.sha256(client_ip.encode('utf-8')).hexdigest()
try:
return int(await self.redis.eval(_RESERVE, 1, key, self.limit, self.window_seconds))
except RedisError:
raise Unavailable('ограничитель входа недоступен') from None