Реализовать ЛР 7 на оценку 3

This commit is contained in:
2026-12-04 14:27:18 +03:00
parent 31d441184b
commit 7996ebbb48
59 changed files with 2236 additions and 498 deletions
+36
View File
@@ -0,0 +1,36 @@
"""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
+1
View File
@@ -18,6 +18,7 @@ def create_engine(url: str) -> AsyncEngine:
max_overflow=5,
pool_timeout=5,
pool_pre_ping=True,
hide_parameters=True,
connect_args={'server_settings': {'statement_timeout': '5000'}},
)
instruments = get_metrics()
+7 -1
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import os
from datetime import datetime, timedelta, timezone
from uuid import UUID
@@ -11,7 +12,12 @@ from ..domain.errors import Unavailable
def create_redis(url: str) -> Redis:
return Redis.from_url(url, decode_responses=True, socket_connect_timeout=3, socket_timeout=3)
tls_options = {}
if url.startswith('rediss://'):
tls_options = {'ssl_ca_certs': os.getenv('TLS_CA_FILE'), 'ssl_check_hostname': True}
return Redis.from_url(
url, decode_responses=True, socket_connect_timeout=3, socket_timeout=3, **tls_options
)
class RedisSessionStore: