add code for level 4
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
import json
|
||||
from uuid import UUID
|
||||
|
||||
from redis.asyncio import Redis
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
|
||||
class HistoryCache:
|
||||
"""Кэш только первой страницы истории; PostgreSQL остаётся источником истины."""
|
||||
|
||||
def __init__(self, url: str | None, ttl_seconds: int) -> None:
|
||||
self._url = url
|
||||
self._ttl_seconds = ttl_seconds
|
||||
self._client: Redis | None = None
|
||||
self._disabled = not bool(url)
|
||||
|
||||
async def connect(self) -> None:
|
||||
if self._disabled:
|
||||
return
|
||||
try:
|
||||
client = Redis.from_url(
|
||||
self._url,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=1,
|
||||
socket_timeout=1,
|
||||
max_connections=10,
|
||||
)
|
||||
await client.ping()
|
||||
self._client = client
|
||||
except RedisError:
|
||||
self._disabled = True
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._client is not None:
|
||||
await self._client.aclose()
|
||||
|
||||
@staticmethod
|
||||
def _key(chat_id: UUID, version: int, limit: int) -> str:
|
||||
return f"history:first:{chat_id}:v{version}:l{limit}"
|
||||
|
||||
async def get(self, chat_id: UUID, version: int, limit: int) -> list[dict] | None:
|
||||
if self._disabled or self._client is None:
|
||||
return None
|
||||
try:
|
||||
value = await self._client.get(self._key(chat_id, version, limit))
|
||||
return json.loads(value) if value else None
|
||||
except (RedisError, ValueError, TypeError):
|
||||
self._disabled = True
|
||||
return None
|
||||
|
||||
async def set(self, chat_id: UUID, version: int, limit: int, items: list[dict]) -> None:
|
||||
if self._disabled or self._client is None:
|
||||
return
|
||||
try:
|
||||
encoded = json.dumps(items, default=str, separators=(",", ":"))
|
||||
await self._client.set(
|
||||
self._key(chat_id, version, limit), encoded, ex=self._ttl_seconds
|
||||
)
|
||||
except RedisError:
|
||||
self._disabled = True
|
||||
+46
-22
@@ -26,7 +26,7 @@ class PostgresStore:
|
||||
self._pool = await asyncpg.create_pool(
|
||||
self._database_url, min_size=1, max_size=10, command_timeout=5
|
||||
)
|
||||
except asyncpg.PostgresError as error:
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
async def close(self) -> None:
|
||||
@@ -87,7 +87,7 @@ class PostgresStore:
|
||||
async def ready(self) -> None:
|
||||
try:
|
||||
await self.pool.fetchval("SELECT 1")
|
||||
except asyncpg.PostgresError as error:
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
|
||||
async def create_user(self, username: str, display_name: str, password: str) -> dict:
|
||||
@@ -101,7 +101,7 @@ class PostgresStore:
|
||||
)
|
||||
except asyncpg.UniqueViolationError as error:
|
||||
raise ApiError(409, "conflict", "Username уже занят") from error
|
||||
except asyncpg.PostgresError as error:
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return self._user(row)
|
||||
|
||||
@@ -110,7 +110,7 @@ class PostgresStore:
|
||||
row = await self.pool.fetchrow(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id = $1", user_id
|
||||
)
|
||||
except asyncpg.PostgresError as error:
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return self._user(row) if row else None
|
||||
|
||||
@@ -120,7 +120,7 @@ class PostgresStore:
|
||||
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1",
|
||||
username,
|
||||
)
|
||||
except asyncpg.PostgresError as error:
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
if row is None:
|
||||
return None
|
||||
@@ -140,7 +140,7 @@ class PostgresStore:
|
||||
user["id"],
|
||||
ttl_seconds,
|
||||
)
|
||||
except asyncpg.PostgresError as error:
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return {"token": token, "token_type": "Bearer", "expires_at": row["expires_at"], "user": user}
|
||||
|
||||
@@ -151,7 +151,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 as error:
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return self._user(row) if row else None
|
||||
|
||||
@@ -160,7 +160,7 @@ class PostgresStore:
|
||||
await self.pool.execute(
|
||||
"DELETE FROM sessions WHERE token_hash = $1", sha256(token.encode("ascii")).hexdigest()
|
||||
)
|
||||
except asyncpg.PostgresError as error:
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) 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 +182,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 as error:
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return {
|
||||
"id": row["id"],
|
||||
@@ -198,7 +198,7 @@ class PostgresStore:
|
||||
chat_id,
|
||||
user_id,
|
||||
)
|
||||
except asyncpg.PostgresError as error:
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
if row is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
@@ -216,23 +216,47 @@ class PostgresStore:
|
||||
args.append(limit + 1)
|
||||
try:
|
||||
rows = await self.pool.fetch(query, *args)
|
||||
except asyncpg.PostgresError as error:
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return [self._chat(row) for row in rows]
|
||||
|
||||
async def create_message(self, chat_id: UUID, sender_id: UUID, text: str) -> dict:
|
||||
await self.get_chat_for_member(chat_id, sender_id)
|
||||
try:
|
||||
row = await self.pool.fetchrow(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, $4) RETURNING id, chat_id, sender_id, text, created_at",
|
||||
uuid4(),
|
||||
chat_id,
|
||||
sender_id,
|
||||
text,
|
||||
)
|
||||
except asyncpg.PostgresError as error:
|
||||
async with self.pool.acquire() as connection, connection.transaction():
|
||||
member = await connection.fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
|
||||
chat_id,
|
||||
sender_id,
|
||||
)
|
||||
if member is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
row = await connection.fetchrow(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, $4) RETURNING id, chat_id, sender_id, text, created_at",
|
||||
uuid4(),
|
||||
chat_id,
|
||||
sender_id,
|
||||
text,
|
||||
)
|
||||
version = await connection.fetchval(
|
||||
"UPDATE chats SET history_version = history_version + 1 WHERE id = $1 RETURNING history_version",
|
||||
chat_id,
|
||||
)
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return self._message(row)
|
||||
return self._message(row), version
|
||||
|
||||
async def history_version_for_member(self, chat_id: UUID, user_id: UUID) -> int:
|
||||
try:
|
||||
version = await self.pool.fetchval(
|
||||
"SELECT c.history_version FROM chats c JOIN chat_members cm ON cm.chat_id = c.id WHERE c.id = $1 AND cm.user_id = $2",
|
||||
chat_id,
|
||||
user_id,
|
||||
)
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
if version is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
return version
|
||||
|
||||
async def list_messages_for_member(
|
||||
self, chat_id: UUID, user_id: UUID, after: tuple[datetime, UUID] | None, limit: int
|
||||
@@ -247,6 +271,6 @@ class PostgresStore:
|
||||
args.append(limit + 1)
|
||||
try:
|
||||
rows = await self.pool.fetch(query, *args)
|
||||
except asyncpg.PostgresError as error:
|
||||
except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return [self._message(row) for row in rows]
|
||||
|
||||
Reference in New Issue
Block a user