This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
import json
|
||||
from asyncio import sleep
|
||||
from secrets import token_urlsafe
|
||||
from uuid import UUID
|
||||
|
||||
from redis.asyncio import Redis
|
||||
@@ -8,11 +10,12 @@ from redis.exceptions import RedisError
|
||||
class HistoryCache:
|
||||
"""Кэш только первой страницы истории; PostgreSQL остаётся источником истины."""
|
||||
|
||||
def __init__(self, url: str | None, ttl_seconds: int) -> None:
|
||||
def __init__(self, url: str | None, ttl_seconds: int, stampede_protection: bool) -> None:
|
||||
self._url = url
|
||||
self._ttl_seconds = ttl_seconds
|
||||
self._client: Redis | None = None
|
||||
self._disabled = not bool(url)
|
||||
self._stampede_protection = stampede_protection
|
||||
|
||||
async def connect(self) -> None:
|
||||
if self._disabled:
|
||||
@@ -23,7 +26,7 @@ class HistoryCache:
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=1,
|
||||
socket_timeout=1,
|
||||
max_connections=10,
|
||||
max_connections=50,
|
||||
)
|
||||
await client.ping()
|
||||
self._client = client
|
||||
@@ -38,6 +41,10 @@ class HistoryCache:
|
||||
def _key(chat_id: UUID, version: int, limit: int) -> str:
|
||||
return f"history:first:{chat_id}:v{version}:l{limit}"
|
||||
|
||||
@classmethod
|
||||
def _lock_key(cls, chat_id: UUID, version: int, limit: int) -> str:
|
||||
return cls._key(chat_id, version, limit) + ":lock"
|
||||
|
||||
async def get(self, chat_id: UUID, version: int, limit: int) -> list[dict] | None:
|
||||
if self._disabled or self._client is None:
|
||||
return None
|
||||
@@ -58,3 +65,43 @@ class HistoryCache:
|
||||
)
|
||||
except RedisError:
|
||||
self._disabled = True
|
||||
|
||||
async def acquire_load_lock(
|
||||
self, chat_id: UUID, version: int, limit: int
|
||||
) -> str | None:
|
||||
if self._disabled or self._client is None or not self._stampede_protection:
|
||||
return None
|
||||
token = token_urlsafe(16)
|
||||
try:
|
||||
locked = await self._client.set(
|
||||
self._lock_key(chat_id, version, limit), token, nx=True, ex=2
|
||||
)
|
||||
return token if locked else ""
|
||||
except RedisError:
|
||||
self._disabled = True
|
||||
return None
|
||||
|
||||
async def wait_for_fill(
|
||||
self, chat_id: UUID, version: int, limit: int
|
||||
) -> list[dict] | None:
|
||||
for _ in range(20):
|
||||
await sleep(0.05)
|
||||
cached = await self.get(chat_id, version, limit)
|
||||
if cached is not None or self._disabled:
|
||||
return cached
|
||||
return None
|
||||
|
||||
async def release_load_lock(
|
||||
self, chat_id: UUID, version: int, limit: int, token: str
|
||||
) -> None:
|
||||
if self._disabled or self._client is None:
|
||||
return
|
||||
try:
|
||||
await self._client.eval(
|
||||
"if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) end return 0",
|
||||
1,
|
||||
self._lock_key(chat_id, version, limit),
|
||||
token,
|
||||
)
|
||||
except RedisError:
|
||||
self._disabled = True
|
||||
|
||||
+17
-25
@@ -14,6 +14,7 @@ from ..errors import ApiError
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
MIGRATIONS = ROOT / "migrations"
|
||||
PASSWORD_HASHER = PasswordHasher()
|
||||
DB_ERRORS = (asyncpg.PostgresError, asyncpg.InterfaceError, OSError)
|
||||
|
||||
|
||||
class PostgresStore:
|
||||
@@ -26,7 +27,7 @@ class PostgresStore:
|
||||
self._pool = await asyncpg.create_pool(
|
||||
self._database_url, min_size=1, max_size=10, command_timeout=5
|
||||
)
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
async def close(self) -> None:
|
||||
@@ -87,7 +88,7 @@ class PostgresStore:
|
||||
async def ready(self) -> None:
|
||||
try:
|
||||
await self.pool.fetchval("SELECT 1")
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
|
||||
async def create_user(self, username: str, display_name: str, password: str) -> dict:
|
||||
@@ -101,26 +102,17 @@ class PostgresStore:
|
||||
)
|
||||
except asyncpg.UniqueViolationError as error:
|
||||
raise ApiError(409, "conflict", "Username уже занят") from error
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return self._user(row)
|
||||
|
||||
async def get_user(self, user_id: UUID) -> dict | None:
|
||||
try:
|
||||
row = await self.pool.fetchrow(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id = $1", user_id
|
||||
)
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return self._user(row) if row else None
|
||||
|
||||
async def authenticate(self, username: str, password: str) -> dict | None:
|
||||
try:
|
||||
row = await self.pool.fetchrow(
|
||||
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1",
|
||||
username,
|
||||
)
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
if row is None:
|
||||
return None
|
||||
@@ -140,7 +132,7 @@ class PostgresStore:
|
||||
user["id"],
|
||||
ttl_seconds,
|
||||
)
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return {"token": token, "token_type": "Bearer", "expires_at": row["expires_at"], "user": user}
|
||||
|
||||
@@ -151,7 +143,7 @@ class PostgresStore:
|
||||
"SELECT u.id, u.username, u.display_name, u.created_at FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = $1 AND s.expires_at > now()",
|
||||
token_hash,
|
||||
)
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return self._user(row) if row else None
|
||||
|
||||
@@ -160,7 +152,7 @@ class PostgresStore:
|
||||
await self.pool.execute(
|
||||
"DELETE FROM sessions WHERE token_hash = $1", sha256(token.encode("ascii")).hexdigest()
|
||||
)
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
|
||||
async def create_chat(self, creator_id: UUID, title: str, member_ids: list[UUID]) -> dict:
|
||||
@@ -182,7 +174,7 @@ class PostgresStore:
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)",
|
||||
[(row["id"], member_id) for member_id in member_ids],
|
||||
)
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return {
|
||||
"id": row["id"],
|
||||
@@ -198,7 +190,7 @@ class PostgresStore:
|
||||
chat_id,
|
||||
user_id,
|
||||
)
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
if row is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
@@ -216,7 +208,7 @@ class PostgresStore:
|
||||
args.append(limit + 1)
|
||||
try:
|
||||
rows = await self.pool.fetch(query, *args)
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return [self._chat(row) for row in rows]
|
||||
|
||||
@@ -237,13 +229,13 @@ class PostgresStore:
|
||||
sender_id,
|
||||
text,
|
||||
)
|
||||
version = await connection.fetchval(
|
||||
"UPDATE chats SET history_version = history_version + 1 WHERE id = $1 RETURNING history_version",
|
||||
await connection.execute(
|
||||
"UPDATE chats SET history_version = history_version + 1 WHERE id = $1",
|
||||
chat_id,
|
||||
)
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return self._message(row), version
|
||||
return self._message(row)
|
||||
|
||||
async def history_version_for_member(self, chat_id: UUID, user_id: UUID) -> int:
|
||||
try:
|
||||
@@ -252,7 +244,7 @@ class PostgresStore:
|
||||
chat_id,
|
||||
user_id,
|
||||
)
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
if version is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
@@ -271,6 +263,6 @@ class PostgresStore:
|
||||
args.append(limit + 1)
|
||||
try:
|
||||
rows = await self.pool.fetch(query, *args)
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return [self._message(row) for row in rows]
|
||||
|
||||
Reference in New Issue
Block a user