add code for level 4
This commit is contained in:
@@ -10,6 +10,9 @@ _CONFIGURATION_KEYS = {
|
||||
"APP_ENV",
|
||||
"DATABASE_URL",
|
||||
"DATABASE_URL_FILE",
|
||||
"CACHE_URL",
|
||||
"CACHE_URL_FILE",
|
||||
"CACHE_TTL_SECONDS",
|
||||
"SESSION_TTL_SECONDS",
|
||||
}
|
||||
|
||||
@@ -23,6 +26,8 @@ class Settings:
|
||||
environment: str
|
||||
database_url: str
|
||||
session_ttl_seconds: int
|
||||
cache_url: str | None
|
||||
cache_ttl_seconds: int
|
||||
|
||||
|
||||
def load_settings(env_file: Path = ROOT / ".env") -> Settings:
|
||||
@@ -68,10 +73,27 @@ def load_settings(env_file: Path = ROOT / ".env") -> Settings:
|
||||
raise ValueError("SESSION_TTL_SECONDS должен быть целым числом") from error
|
||||
if session_ttl_seconds < 1:
|
||||
raise ValueError("SESSION_TTL_SECONDS должен быть положительным")
|
||||
cache_url_file = os.environ.get("CACHE_URL_FILE", "").strip()
|
||||
cache_url = os.environ.get("CACHE_URL", "").strip()
|
||||
if cache_url_file:
|
||||
try:
|
||||
cache_url = Path(cache_url_file).read_text(encoding="utf-8").strip()
|
||||
except OSError as error:
|
||||
raise ValueError("CACHE_URL_FILE недоступен") from error
|
||||
if cache_url and not cache_url.startswith(("redis://", "rediss://")):
|
||||
raise ValueError("CACHE_URL должен содержать Redis URL")
|
||||
try:
|
||||
cache_ttl_seconds = int(os.environ.get("CACHE_TTL_SECONDS", "60"))
|
||||
except ValueError as error:
|
||||
raise ValueError("CACHE_TTL_SECONDS должен быть целым числом") from error
|
||||
if cache_ttl_seconds < 1:
|
||||
raise ValueError("CACHE_TTL_SECONDS должен быть положительным")
|
||||
return Settings(
|
||||
host=host,
|
||||
port=port,
|
||||
environment=environment,
|
||||
database_url=database_url,
|
||||
session_ttl_seconds=session_ttl_seconds,
|
||||
cache_url=cache_url or None,
|
||||
cache_ttl_seconds=cache_ttl_seconds,
|
||||
)
|
||||
|
||||
@@ -13,6 +13,7 @@ from .errors import ApiError
|
||||
from .models import ErrorDetails, ErrorResponse
|
||||
from .config import load_settings
|
||||
from .routes import router
|
||||
from .storage.history_cache import HistoryCache
|
||||
from .storage.postgres import PostgresStore
|
||||
|
||||
|
||||
@@ -35,9 +36,13 @@ async def lifespan(application: FastAPI):
|
||||
await store.migrate()
|
||||
application.state.store = store
|
||||
application.state.settings = settings
|
||||
cache = HistoryCache(settings.cache_url, settings.cache_ttl_seconds)
|
||||
await cache.connect()
|
||||
application.state.history_cache = cache
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await cache.close()
|
||||
await store.close()
|
||||
|
||||
|
||||
|
||||
+15
-3
@@ -8,6 +8,7 @@ from .cursor import CursorError, decode_cursor, encode_cursor
|
||||
from .errors import ApiError
|
||||
from .models import Chat, ChatPageResponse, CreateChatRequest, CreateMessageRequest, CreateUserRequest, Message, MessagePageResponse, Session, User
|
||||
from .storage.postgres import PostgresStore
|
||||
from .storage.history_cache import HistoryCache
|
||||
|
||||
router = APIRouter()
|
||||
BEARER_CHALLENGE = {'WWW-Authenticate': 'Bearer realm="messenger"'}
|
||||
@@ -16,6 +17,9 @@ BASIC_CHALLENGE = {'WWW-Authenticate': 'Basic realm="messenger", charset="UTF-8"
|
||||
def get_store(request: Request) -> PostgresStore:
|
||||
return request.app.state.store
|
||||
|
||||
def get_history_cache(request: Request) -> HistoryCache:
|
||||
return request.app.state.history_cache
|
||||
|
||||
async def get_current_user(authorization: str | None = Header(default=None), store: PostgresStore = Depends(get_store)) -> dict:
|
||||
if authorization is None or not authorization.startswith("Bearer "):
|
||||
raise ApiError(401, "unauthorized", "Требуется Bearer-сессия", BEARER_CHALLENGE)
|
||||
@@ -99,10 +103,11 @@ async def get_chat(chat_id: UUID, user: dict = Depends(get_current_user), store:
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
|
||||
async def create_message(chat_id: UUID, payload: CreateMessageRequest, user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store)) -> dict:
|
||||
return await store.create_message(chat_id, user["id"], payload.text)
|
||||
message, _version = await store.create_message(chat_id, user["id"], payload.text)
|
||||
return message
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePageResponse)
|
||||
async def list_messages(chat_id: UUID, user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store), limit: int = Query(default=50, ge=1, le=100), cursor: str | None = Query(default=None, min_length=1)) -> MessagePageResponse:
|
||||
async def list_messages(chat_id: UUID, user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store), cache: HistoryCache = Depends(get_history_cache), limit: int = Query(default=50, ge=1, le=100), cursor: str | None = Query(default=None, min_length=1)) -> MessagePageResponse:
|
||||
after: tuple[datetime, UUID] | None = None
|
||||
scope = "messages:" + str(chat_id)
|
||||
if cursor is not None:
|
||||
@@ -111,7 +116,14 @@ async def list_messages(chat_id: UUID, user: dict = Depends(get_current_user), s
|
||||
after = created_at, UUID(item_id)
|
||||
except (CursorError, ValueError) as error:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor") from error
|
||||
rows = await store.list_messages_for_member(chat_id, user["id"], after, limit)
|
||||
if cursor is None:
|
||||
version = await store.history_version_for_member(chat_id, user["id"])
|
||||
rows = await cache.get(chat_id, version, limit)
|
||||
if rows is None:
|
||||
rows = await store.list_messages_for_member(chat_id, user["id"], after, limit)
|
||||
await cache.set(chat_id, version, limit, rows)
|
||||
else:
|
||||
rows = await store.list_messages_for_member(chat_id, user["id"], after, limit)
|
||||
page = rows[:limit]
|
||||
next_cursor = encode_cursor(scope, page[-1]["created_at"], str(page[-1]["id"])) if len(rows) > limit else None
|
||||
return MessagePageResponse(items=page, next_cursor=next_cursor)
|
||||
|
||||
@@ -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