+ добавила функционал на 4 + тесты

This commit is contained in:
vasyukova
2026-10-02 01:06:35 +03:00
parent 6aed50419f
commit afd49a3515
9 changed files with 328 additions and 61 deletions
+18 -3
View File
@@ -1,5 +1,7 @@
from fastapi import APIRouter
from fastapi import APIRouter, Response
from ..models.schemas import Health
from ..storage import db as _db
from ..storage.sessions import _redis_client, _store
router = APIRouter(tags=["health"])
@@ -20,6 +22,19 @@ def liveness() -> Health:
summary="Проверка готовности принимать трафик",
response_model=Health,
)
def readiness() -> Health:
"""Готов принимать трафик. В lab1 критичных зависимостей нет."""
def readiness(response: Response) -> Health:
"""200, если PostgreSQL и (в режиме redis) Redis доступны; иначе 503."""
try:
with _db.connection() as conn, conn.cursor() as cur:
cur.execute("SELECT 1")
cur.fetchone()
except Exception:
response.status_code = 503
return Health(status="ok")
if _store() == "redis":
try:
_redis_client().ping()
except Exception:
response.status_code = 503
return Health(status="ok")
return Health(status="ok")
+10 -10
View File
@@ -1,5 +1,6 @@
import base64
import json
from datetime import datetime
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Query
from ..models.schemas import CreateMessage, Message, MessagePage, User
@@ -27,7 +28,7 @@ def _decode_cursor(chat_id: UUID, cursor: str) -> tuple:
data = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode())
if data.get("chat_id") != str(chat_id):
raise ValueError("cursor_chat_mismatch")
return UUID(data["id"]), data["created_at"]
return datetime.fromisoformat(data["created_at"]), UUID(data["id"])
except Exception:
raise HTTPException(status_code=400, detail="invalid_request")
@@ -60,13 +61,12 @@ def list_messages(
limit: int = Query(50, ge=1, le=100),
cursor: str | None = None,
) -> MessagePage:
"""Реализована курсорная пагинация"""
"""Keyset-пагинация в SQL: (created_at, id) по возрастанию, без полного scan истории."""
_require_member(chat_id, user.id)
messages = storage.list_messages(chat_id)
if cursor:
mid, mcreated = _decode_cursor(chat_id, cursor)
messages = [m for m in messages if (m.created_at.isoformat(), str(m.id)) > (mcreated, str(mid))]
page = messages[:limit]
next_cursor = _encode_cursor(chat_id, page[-1]) if len(messages) > limit else None
return MessagePage(items=page, next_cursor=next_cursor)
after = _decode_cursor(chat_id, cursor) if cursor else None
# Берём limit+1, чтобы понять, есть ли следующая страница
rows = storage.list_messages_page(chat_id, limit + 1, after=after)
has_more = len(rows) > limit
items = rows[:limit]
next_cursor = _encode_cursor(chat_id, items[-1]) if has_more and items else None
return MessagePage(items=items, next_cursor=next_cursor)