+ добавила функционал на 4 + тесты
This commit is contained in:
+18
-3
@@ -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
@@ -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)
|
||||
+43
-3
@@ -10,9 +10,10 @@ from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.openapi.utils import get_openapi
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
import psycopg
|
||||
import uvicorn
|
||||
from .api import auth, chats, health, messages, users
|
||||
from .storage.db import init_schema
|
||||
from .storage.db import init_schema, init_pool, close_pool
|
||||
|
||||
|
||||
# --- Логирование: структурированный stdout, без содержимого сообщений ---
|
||||
@@ -26,9 +27,15 @@ logger = logging.getLogger("app")
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
init_schema() # создать таблицы в БД если их ещё нет
|
||||
logger.info("event=startup app_env=%s", os.environ.get("APP_ENV", "lab"))
|
||||
init_pool() # пул соединений PostgreSQL с таймаутами (уровень 4)
|
||||
init_schema() # создать таблицы в БД если их ещё нет
|
||||
logger.info(
|
||||
"event=startup app_env=%s session_store=%s",
|
||||
os.environ.get("APP_ENV", "lab"),
|
||||
os.environ.get("SESSION_STORE", "postgres"),
|
||||
)
|
||||
yield
|
||||
close_pool()
|
||||
logger.info("event=shutdown_complete")
|
||||
|
||||
|
||||
@@ -121,6 +128,39 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
|
||||
return _error_response(400, "Неверный запрос", request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(psycopg.OperationalError)
|
||||
async def db_unavailable_handler(request: Request, exc: psycopg.OperationalError):
|
||||
"""PostgreSQL недоступен → 503 unavailable, без внутренних деталей."""
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
logger.error(
|
||||
"event=db_unavailable type=%s request_id=%s",
|
||||
type(exc).__name__,
|
||||
request_id,
|
||||
)
|
||||
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(RuntimeError)
|
||||
async def runtime_error_handler(request: Request, exc: RuntimeError):
|
||||
"""Redis недоступен или конфигурация битая.
|
||||
|
||||
sessions.py поднимает RuntimeError("redis_unavailable") при ошибке Redis.
|
||||
Отдаём 503, чтобы смоук/resilience видели корректный unavailable,
|
||||
а не внутреннюю 500.
|
||||
"""
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
text = str(exc)
|
||||
if "redis_unavailable" in text:
|
||||
logger.error("event=redis_unavailable request_id=%s", request_id)
|
||||
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||
logger.error(
|
||||
"event=runtime_error type=%s request_id=%s",
|
||||
type(exc).__name__,
|
||||
request_id,
|
||||
)
|
||||
return _error_response(500, "Внутренняя ошибка", request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_exception_handler(request: Request, exc: Exception):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
|
||||
+33
-5
@@ -3,6 +3,10 @@ from contextlib import contextmanager
|
||||
from typing import Iterator
|
||||
|
||||
import psycopg
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
|
||||
_pool: ConnectionPool | None = None
|
||||
|
||||
|
||||
def _dsn() -> str:
|
||||
@@ -12,14 +16,37 @@ def _dsn() -> str:
|
||||
return dsn
|
||||
|
||||
|
||||
def init_pool() -> None:
|
||||
"""Ограниченный пул соединений с таймаутами. Вызывается один раз на старте."""
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
return
|
||||
_pool = ConnectionPool(
|
||||
conninfo=_dsn(),
|
||||
min_size=2,
|
||||
max_size=10,
|
||||
timeout=5.0,
|
||||
max_idle=300.0,
|
||||
kwargs={"options": "-c statement_timeout=5000"},
|
||||
open=True,
|
||||
)
|
||||
|
||||
|
||||
def close_pool() -> None:
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
_pool.close()
|
||||
_pool = None
|
||||
|
||||
|
||||
@contextmanager
|
||||
def connection() -> Iterator[psycopg.Connection]:
|
||||
"""Одно соединение на запрос; autocommit=False для явных транзакций."""
|
||||
conn = psycopg.connect(_dsn())
|
||||
try:
|
||||
"""Соединение из пула; autocommit=False для явных транзакций."""
|
||||
if _pool is None:
|
||||
init_pool()
|
||||
assert _pool is not None
|
||||
with _pool.connection() as conn:
|
||||
yield conn
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
SCHEMA_SQL = """
|
||||
@@ -53,6 +80,7 @@ CREATE TABLE IF NOT EXISTS messages (
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_chat_created
|
||||
ON messages (chat_id, created_at, id);
|
||||
|
||||
-- sessions остаются как fallback, если SESSION_STORE=postgres.
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token TEXT PRIMARY KEY,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
|
||||
+56
-38
@@ -2,12 +2,17 @@ import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from ..models.schemas import Chat, Message, User
|
||||
from .db import connection
|
||||
from .sessions import (
|
||||
create_session as _sess_create,
|
||||
get_session_user as _sess_get,
|
||||
revoke_session as _sess_revoke,
|
||||
)
|
||||
|
||||
|
||||
def now_utc() -> datetime:
|
||||
@@ -74,6 +79,8 @@ class PostgresStorage:
|
||||
def create_user(self, username: str, display_name: str, password: str) -> User:
|
||||
with self._lock, connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
# SELECT-проверка + INSERT в одной транзакции; уникальный индекс
|
||||
# users.username отсекает гонку на уровне БД (UniqueViolation).
|
||||
cur.execute("SELECT 1 FROM users WHERE username = %s", (username,))
|
||||
if cur.fetchone() is not None:
|
||||
raise ValueError("username_taken")
|
||||
@@ -81,12 +88,19 @@ class PostgresStorage:
|
||||
id=uuid4(), username=username,
|
||||
display_name=display_name, created_at=now_utc(),
|
||||
)
|
||||
cur.execute(
|
||||
"INSERT INTO users (id, username, display_name, password_hash, created_at)"
|
||||
" VALUES (%s, %s, %s, %s, %s)",
|
||||
(user.id, user.username, user.display_name,
|
||||
_hash_password(password), user.created_at),
|
||||
)
|
||||
try:
|
||||
cur.execute(
|
||||
"INSERT INTO users (id, username, display_name, password_hash, created_at)"
|
||||
" VALUES (%s, %s, %s, %s, %s)",
|
||||
(user.id, user.username, user.display_name,
|
||||
_hash_password(password), user.created_at),
|
||||
)
|
||||
except Exception as exc:
|
||||
# Параллельная регистрация того же username: уникальный индекс
|
||||
# выбросил UniqueViolation — превращаем в доменную ошибку.
|
||||
if exc.__class__.__name__ == "UniqueViolation":
|
||||
raise ValueError("username_taken")
|
||||
raise
|
||||
conn.commit()
|
||||
return user
|
||||
|
||||
@@ -122,42 +136,17 @@ class PostgresStorage:
|
||||
return None
|
||||
return _row_to_user(row[:4])
|
||||
|
||||
# ---------- Сессии ----------
|
||||
# ---------- Сессии (Redis или PostgreSQL — см. storage/sessions.py) ----------
|
||||
# Тонкие делегаты: роутеры продолжают вызывать storage.create_session(...),
|
||||
# storage.get_session_user(...), storage.revoke_session(...) без изменений.
|
||||
def create_session(self, user_id: UUID, ttl_seconds: int) -> tuple:
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = now_utc() + timedelta(seconds=ttl_seconds)
|
||||
with self._lock, connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO sessions (token, user_id, expires_at) VALUES (%s, %s, %s)",
|
||||
(token, user_id, expires_at),
|
||||
)
|
||||
conn.commit()
|
||||
return token, expires_at
|
||||
return _sess_create(user_id, ttl_seconds)
|
||||
|
||||
def get_session_user(self, token: str) -> Optional[User]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at"
|
||||
" FROM sessions s JOIN users u ON u.id = s.user_id"
|
||||
" WHERE s.token = %s",
|
||||
(token,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
if row[4] <= now_utc():
|
||||
with conn.cursor() as cur2:
|
||||
cur2.execute("DELETE FROM sessions WHERE token = %s", (token,))
|
||||
conn.commit()
|
||||
return None
|
||||
return _row_to_user(row[:4])
|
||||
return _sess_get(token)
|
||||
|
||||
def revoke_session(self, token: str) -> None:
|
||||
with self._lock, connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("DELETE FROM sessions WHERE token = %s", (token,))
|
||||
conn.commit()
|
||||
_sess_revoke(token)
|
||||
|
||||
# ---------- Чаты ----------
|
||||
def create_chat(self, title: str, member_ids: List[UUID]) -> Chat:
|
||||
@@ -245,5 +234,34 @@ class PostgresStorage:
|
||||
)
|
||||
return [_row_to_message(r) for r in cur.fetchall()]
|
||||
|
||||
def list_messages_page(
|
||||
self,
|
||||
chat_id: UUID,
|
||||
limit: int,
|
||||
after: Optional[tuple] = None,
|
||||
) -> List[Message]:
|
||||
"""Keyset-пагинация в SQL
|
||||
|
||||
after = (created_at, id) последней записи предыдущей страницы или None.
|
||||
Запрос использует индекс idx_messages_chat_created (chat_id, created_at, id)
|
||||
и не делает полный scan всей истории на каждую страницу.
|
||||
"""
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
if after is None:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
||||
" WHERE chat_id = %s ORDER BY created_at, id LIMIT %s",
|
||||
(chat_id, limit),
|
||||
)
|
||||
else:
|
||||
after_ts, after_id = after
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
||||
" WHERE chat_id = %s AND (created_at, id) > (%s, %s)"
|
||||
" ORDER BY created_at, id LIMIT %s",
|
||||
(chat_id, after_ts, after_id, limit),
|
||||
)
|
||||
return [_row_to_message(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
storage = PostgresStorage() # единственный экземпляр на процесс
|
||||
Reference in New Issue
Block a user