import hashlib from app import config, rediscli from app.errors import AppError def _slot(prefix: str, value: str) -> str: digest = hashlib.sha256(value.encode("utf-8")).hexdigest() return prefix + digest async def reserve_login(username: str, ip: str) -> int | None: """Count a login attempt on the shared Redis. Returns Retry-After seconds when limited. Both replicas use the same keys, so the limit is not per process. The attempt is counted before Argon2 so a flood cannot spend the memory budget. """ user_key = _slot("login:u:", username[:128]) ip_key = _slot("login:ip:", ip[:64]) window = config.LOGIN_RATE_WINDOW_SECONDS try: redis = rediscli.require() async with redis.pipeline(transaction=True) as pipe: pipe.incr(user_key) pipe.expire(user_key, window, nx=True) pipe.incr(ip_key) pipe.expire(ip_key, window, nx=True) user_count, _, ip_count, _ = await pipe.execute() if user_count > config.LOGIN_RATE_LIMIT or ip_count > config.LOGIN_IP_RATE_LIMIT: ttl = int(await redis.ttl(user_key)) return max(ttl, 1) except AppError: raise except Exception: raise AppError(503, "service unavailable") from None return None