feat: add PostgreSQL fallback for sessions and graceful degradation on Redis failure
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-10-22 16:49:19 +03:00
parent cca293dcb1
commit 566b02d850
9 changed files with 479 additions and 128 deletions
+92
View File
@@ -52,8 +52,23 @@ docker compose up -d --build
# Ожидаемый результат: {"status":"ok"} # Ожидаемый результат: {"status":"ok"}
curl -s http://localhost:8080/health/ready curl -s http://localhost:8080/health/ready
# Миграции
# 1. Генерация файла миграции (сравнивает модели с текущей схемой БД)
docker compose run --rm api alembic revision --autogenerate -m "Initial tables"
# 2. Применение миграции к БД
docker compose run --rm api alembic upgrade head
# Показать таблицы и ключи
docker compose exec postgres psql -U app_user -d messenger_db -c "\dt"
docker compose exec postgres psql -U app_user -d messenger_db -c "\d users"
docker compose exec postgres psql -U app_user -d messenger_db -c "\d chat_members"
# 4. Smoke test # 4. Smoke test
python3 tests/smoke.py --base-url http://localhost:8080 python3 tests/smoke.py --base-url http://localhost:8080
# 2. Запустить тест перезапуска
python3 tests/resilience.py --base-url http://localhost:8080 \
--mode persistence --action-script scripts/restart.sh
#5. Persistemce #5. Persistemce
python3 tests/resilience.py --base-url http://localhost:8080 --mode persistence --action-script scripts/restart.sh python3 tests/resilience.py --base-url http://localhost:8080 --mode persistence --action-script scripts/restart.sh
@@ -76,3 +91,80 @@ curl -s -X POST http://localhost:8080/api/v1/users -H "Content-Type: application
# Второй запрос (ошибка 409) # Второй запрос (ошибка 409)
curl -s -X POST http://localhost:8080/api/v1/users -H "Content-Type: application/json" -d '{"username":"raceuser", "display_name":"Test", "password":"supersecretpass123"}' | python3 -m json.tool curl -s -X POST http://localhost:8080/api/v1/users -H "Content-Type: application/json" -d '{"username":"raceuser", "display_name":"Test", "password":"supersecretpass123"}' | python3 -m json.tool
# Ожидаемый результат в поле error.code: "conflict" # Ожидаемый результат в поле error.code: "conflict"
# 1. Basic Auth работает только для сессий
curl -X POST http://localhost:8080/api/v1/auth/sessions -u "user:pass" # 201
# 2. Bearer для бизнес-запросов
curl -H "Authorization: Bearer TOKEN" http://localhost:8080/api/v1/users/me # 200
# 3. X-User-Id не работает
curl -H "X-User-Id: UUID" http://localhost:8080/api/v1/users/me # 401
# 4. Logout
curl -X DELETE -H "Authorization: Bearer TOKEN" http://localhost:8080/api/v1/auth/sessions/current # 204
curl -H "Authorization: Bearer TOKEN" http://localhost:8080/api/v1/users/me # 401 (токен недействителен)
# Показать, что Valkey используется
docker compose exec redis valkey-cli CONFIG GET appendonly
# Посмотреть сессии в Redis
docker compose exec redis valkey-cli KEYS "session:*"
# Посмотреть кэш сообщений
docker compose exec redis valkey-cli KEYS "messages:*"
# Показать гонку регистрации
curl -X POST http://localhost:8080/api/v1/users -H "Content-Type: application/json" \
-d '{"username":"raceuser","display_name":"Test","password":"supersecretpass123"}'
# 201 Created
curl -X POST http://localhost:8080/api/v1/users -H "Content-Type: application/json" \
-d '{"username":"raceuser","display_name":"Test","password":"supersecretpass123"}'
# 409 Conflict (не 500!)
# Показать connection pool в логах
docker compose logs api | grep "pool"
#1. Неверный пароль
curl -X POST http://localhost:8080/api/v1/auth/sessions -u "user:wrong-password"
# 401 Unauthorized
# 2. Короткий TTL (изменить в .env)
SESSION_TTL_SECONDS=5
docker compose down && docker compose up -d --build
# Войти, подождать 5 секунд, попробовать запрос — 401
# 3. Недоступность Redis
docker compose stop redis
curl -H "Authorization: Bearer TOKEN" http://localhost:8080/api/v1/users/me
# 500 Internal Server Error (корректная ошибка, не зависание)
docker compose start redis
# Показать индекс
docker compose exec postgres psql -U app_user -d messenger_db -c "\d messages"
# Искать: "ix_messages_chat_history" btree (chat_id, created_at, id)
# EXPLAIN ANALYZE на реальном запросе
docker compose exec postgres psql -U app_user -d messenger_db -c "
EXPLAIN ANALYZE BUFFERS
SELECT * FROM messages
WHERE chat_id = 'UUID'
ORDER BY created_at ASC, id ASC
LIMIT 50;
"
# Ожидаемый вывод: Index Scan using ix_messages_chat_history
# 1. Неверный пароль
curl -X POST http://localhost:8080/api/v1/auth/sessions -u "user:wrong-password"
# 401 Unauthorized
# 2. Короткий TTL (изменить в .env)
SESSION_TTL_SECONDS=5
docker compose down && docker compose up -d --build
# Войти, подождать 5 секунд, попробовать запрос — 401
# 3. Недоступность Redis
docker compose stop redis
curl -H "Authorization: Bearer TOKEN" http://localhost:8080/api/v1/users/me
# 500 Internal Server Error (корректная ошибка, не зависание)
docker compose start redis
@@ -0,0 +1,27 @@
"""Add sessions table for Redis fallback
Revision ID: a1c1f7f5dd0e
Revises: 77be690803c9
Create Date: 2026-10-22 10:53:56.768429
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
revision: str = 'a1c1f7f5dd0e'
down_revision: Union[str, None] = '77be690803c9'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
'sessions',
sa.Column('token', sa.String(length=255), primary_key=True),
sa.Column('user_id', postgresql.UUID(as_uuid=True), sa.ForeignKey('users.id', ondelete='CASCADE'), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('expires_at', sa.DateTime(timezone=True), nullable=False),
)
def downgrade() -> None:
op.drop_table('sessions')
+4 -4
View File
@@ -17,10 +17,10 @@ settings = Settings()
engine = create_async_engine( engine = create_async_engine(
settings.DATABASE_URL, settings.DATABASE_URL,
echo=False, echo=False,
pool_size=10, pool_size=10, # Максимум 10 постоянных соединений
max_overflow=20, max_overflow=20, # Допускается до 20 дополнительных при пике
pool_timeout=30, pool_timeout=30, # Таймаут ожидания соединения (сек)
pool_recycle=1800 pool_recycle=1800 # Пересоздавать соединения каждые 30 минут
) )
async_session_maker = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async_session_maker = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
+77 -9
View File
@@ -1,29 +1,97 @@
import uuid
import logging
from datetime import datetime, timezone
from fastapi import Depends, HTTPException, status, Security from fastapi import Depends, HTTPException, status, Security
from fastapi.security import HTTPBearer, HTTPBasic, HTTPBasicCredentials from fastapi.security import HTTPBearer, HTTPBasic, HTTPBasicCredentials
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select from sqlalchemy import select
import uuid from sqlalchemy.exc import SQLAlchemyError
from app.database import get_db from app.database import get_db
from app.models import User as UserModel from app.models import User as UserModel, UserSession
from app.redis_client import get_redis from app.redis_client import get_redis
logger = logging.getLogger(__name__)
security_bearer = HTTPBearer(auto_error=False) security_bearer = HTTPBearer(auto_error=False)
security_basic = HTTPBasic(auto_error=False) security_basic = HTTPBasic(auto_error=False)
async def get_current_user(credentials = Security(security_bearer), db: AsyncSession = Depends(get_db), redis_client = Depends(get_redis)) -> UserModel: async def get_current_user(
credentials = Security(security_bearer),
db: AsyncSession = Depends(get_db),
redis_client = Depends(get_redis)
) -> UserModel:
if not credentials: if not credentials:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail={"code": "unauthorized", "message": "Missing Bearer token"}, headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}) raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail={"code": "unauthorized", "message": "Missing Bearer token"},
headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}
)
user_id_str = await redis_client.get(f"session:{credentials.credentials}") token = credentials.credentials
user_id_str = None
# 1. Пытаемся получить сессию из Redis
try:
user_id_str = await redis_client.get(f"session:{token}")
except Exception as e:
logger.warning(f"Redis unavailable for session lookup, falling back to PostgreSQL: {e}")
# 2. Если Redis недоступен или сессия не найдена — проверяем PostgreSQL
if not user_id_str: if not user_id_str:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail={"code": "unauthorized", "message": "Invalid or expired session"}, headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}) try:
result = await db.execute(
select(UserSession)
.where(UserSession.token == token)
.where(UserSession.expires_at > datetime.now(timezone.utc))
)
session = result.scalar_one_or_none()
if session:
user_id_str = str(session.user_id)
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail={"code": "unauthorized", "message": "Invalid or expired session"},
headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}
)
except HTTPException:
raise
except SQLAlchemyError as e:
logger.error(f"PostgreSQL error during session check: {e}")
# Возвращаем 500, так как этот код описан в контракте как internal_error
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail={"code": "internal_error", "message": "Session store unavailable"}
)
# 3. Получаем пользователя из БД
try:
user_id = uuid.UUID(user_id_str)
except (ValueError, TypeError):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail={"code": "unauthorized", "message": "Invalid session data"},
headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}
)
result = await db.execute(select(UserModel).where(UserModel.id == user_id))
user = result.scalar_one_or_none()
user = (await db.execute(select(UserModel).where(UserModel.id == uuid.UUID(user_id_str)))).scalar_one_or_none()
if not user: if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail={"code": "unauthorized", "message": "User not found"}, headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}) raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail={"code": "unauthorized", "message": "User not found"},
headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}
)
return user return user
def get_basic_auth(credentials: HTTPBasicCredentials = Security(security_basic)): def get_basic_auth(credentials: HTTPBasicCredentials = Security(security_basic)):
if not credentials: if not credentials:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail={"code": "unauthorized", "message": "Missing Basic auth"}, headers={"WWW-Authenticate": "Basic realm=\"messenger\", charset=\"UTF-8\""}) raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail={"code": "unauthorized", "message": "Missing Basic auth"},
headers={"WWW-Authenticate": "Basic realm=\"messenger\", charset=\"UTF-8\""}
)
return credentials return credentials
+35 -24
View File
@@ -1,37 +1,22 @@
import uuid import uuid
from fastapi import FastAPI, Request, HTTPException import logging
from fastapi import FastAPI, Request, HTTPException, Depends
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError from fastapi.exceptions import RequestValidationError
from app.routers import auth, chats from app.routers import auth, chats
from app.redis_client import get_redis
logger = logging.getLogger(__name__)
app = FastAPI() app = FastAPI()
app.include_router(auth.router) app.include_router(auth.router)
app.include_router(chats.router) app.include_router(chats.router)
@app.middleware("http")
async def add_request_id(request: Request, call_next):
# Генерируем или берем request_id один раз и сохраняем в state запроса
request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
request.state.request_id = request_id
try:
response = await call_next(request)
except Exception:
# Fallback для совершенно необработанных исключений
return JSONResponse(
status_code=500,
content={"error": {"code": "internal_error", "message": "Unexpected error", "request_id": request_id}},
headers={"X-Request-Id": request_id}
)
# Гарантируем наличие заголовка в успешном ответе
response.headers["X-Request-Id"] = request.state.request_id
return response
@app.exception_handler(RequestValidationError) @app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError): async def validation_exception_handler(request: Request, exc: RequestValidationError):
# Берем тот же request_id, что был создан в middleware
request_id = getattr(request.state, "request_id", str(uuid.uuid4())) request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
first_error = exc.errors()[0] if exc.errors() else {"msg": "Invalid request"} first_error = exc.errors()[0] if exc.errors() else {"msg": "Invalid request"}
@@ -49,7 +34,6 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
@app.exception_handler(HTTPException) @app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException): async def http_exception_handler(request: Request, exc: HTTPException):
# Берем тот же request_id, что был создан в middleware
request_id = getattr(request.state, "request_id", str(uuid.uuid4())) request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
detail = exc.detail if isinstance(exc.detail, dict) else {"code": "internal_error", "message": str(exc.detail)} detail = exc.detail if isinstance(exc.detail, dict) else {"code": "internal_error", "message": str(exc.detail)}
@@ -70,10 +54,37 @@ async def http_exception_handler(request: Request, exc: HTTPException):
headers=headers headers=headers
) )
@app.middleware("http")
async def add_request_id(request: Request, call_next):
request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
request.state.request_id = request_id
try:
response = await call_next(request)
except Exception:
return JSONResponse(
status_code=500,
content={"error": {"code": "internal_error", "message": "Unexpected error", "request_id": request_id}},
headers={"X-Request-Id": request_id}
)
response.headers["X-Request-Id"] = request.state.request_id
return response
@app.get("/health/live") @app.get("/health/live")
async def liveness(): async def liveness():
return {"status": "ok"} return {"status": "ok"}
@app.get("/health/ready") @app.get("/health/ready")
async def readiness(): async def readiness(redis_client = Depends(get_redis)):
"""
Контракт строго требует {"status": "ok"}.
Если Redis недоступен, мы логируем это, но возвращаем "ok",
так как приложение работает (используется fallback в PostgreSQL).
"""
try:
await redis_client.ping()
except Exception as e:
logger.warning(f"Redis health check failed, but PostgreSQL fallback is active: {e}")
return {"status": "ok"} return {"status": "ok"}
+19 -2
View File
@@ -1,4 +1,4 @@
from sqlalchemy import Column, String, Integer, DateTime, ForeignKey, Index, text from sqlalchemy import Column, String, Integer, DateTime, ForeignKey, Index
from sqlalchemy.orm import declarative_base, relationship from sqlalchemy.orm import declarative_base, relationship
from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.dialects.postgresql import UUID
import uuid import uuid
@@ -18,6 +18,8 @@ class User(Base):
password_hash = Column(String(255), nullable=False) password_hash = Column(String(255), nullable=False)
created_at = Column(DateTime(timezone=True), default=utc_now) created_at = Column(DateTime(timezone=True), default=utc_now)
sessions = relationship("UserSession", back_populates="user", cascade="all, delete-orphan")
class Chat(Base): class Chat(Base):
__tablename__ = "chats" __tablename__ = "chats"
@@ -47,7 +49,22 @@ class Message(Base):
chat = relationship("Chat", back_populates="messages") chat = relationship("Chat", back_populates="messages")
# ТРЕБОВАНИЕ GRADE 4: Индекс для эффективной пагинации по курсору (created_at, id) # Составной индекс для пагинации
__table_args__ = ( __table_args__ = (
Index("ix_messages_chat_history", "chat_id", "created_at", "id"), Index("ix_messages_chat_history", "chat_id", "created_at", "id"),
) )
class UserSession(Base):
"""
Fallback-хранилище сессий в PostgreSQL.
Используется, когда Redis/Valkey недоступен.
Источник истины для сессий — Redis (быстрый доступ), PostgreSQL — резерв.
"""
__tablename__ = "sessions"
token = Column(String(255), primary_key=True)
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
created_at = Column(DateTime(timezone=True), default=utc_now, nullable=False)
expires_at = Column(DateTime(timezone=True), nullable=False)
user = relationship("User", back_populates="sessions")
+135 -30
View File
@@ -1,32 +1,49 @@
from fastapi import APIRouter, Depends, HTTPException, status, Response
from fastapi.security import HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
import asyncpg
import secrets import secrets
import bcrypt import logging
from datetime import datetime, timezone, timedelta from datetime import datetime, timezone, timedelta
import bcrypt
import asyncpg
from fastapi import APIRouter, Depends, HTTPException, status, Response
from fastapi.security import HTTPBearer
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.exc import SQLAlchemyError
from app.database import get_db, settings from app.database import get_db, settings
from app.models import User as UserModel from app.models import User as UserModel, UserSession
from app.schemas import CreateUser, User, Session, ErrorResponse from app.schemas import CreateUser, User, Session, ErrorResponse
from app.dependencies import get_basic_auth, get_current_user from app.dependencies import get_basic_auth, get_current_user
from app.redis_client import get_redis from app.redis_client import get_redis
logger = logging.getLogger(__name__)
router = APIRouter() router = APIRouter()
def verify_password(plain_password: str, hashed_password: str) -> bool: def verify_password(plain_password: str, hashed_password: str) -> bool:
return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8')) return bcrypt.checkpw(
plain_password.encode('utf-8'),
hashed_password.encode('utf-8')
)
def get_password_hash(password: str) -> str: def get_password_hash(password: str) -> str:
salt = bcrypt.gensalt() salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password.encode('utf-8'), salt) hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
return hashed.decode('utf-8') return hashed.decode('utf-8')
@router.post("/api/v1/users", response_model=User, status_code=status.HTTP_201_CREATED, responses={409: {"model": ErrorResponse}}) @router.post(
"/api/v1/users",
response_model=User,
status_code=status.HTTP_201_CREATED,
responses={409: {"model": ErrorResponse}}
)
async def register_user(user_in: CreateUser, db: AsyncSession = Depends(get_db)): async def register_user(user_in: CreateUser, db: AsyncSession = Depends(get_db)):
hashed_password = get_password_hash(user_in.password) hashed_password = get_password_hash(user_in.password)
new_user = UserModel(username=user_in.username, display_name=user_in.display_name, password_hash=hashed_password) new_user = UserModel(
username=user_in.username,
display_name=user_in.display_name,
password_hash=hashed_password
)
db.add(new_user) db.add(new_user)
try: try:
await db.commit() await db.commit()
@@ -35,11 +52,30 @@ async def register_user(user_in: CreateUser, db: AsyncSession = Depends(get_db))
except Exception as e: except Exception as e:
await db.rollback() await db.rollback()
if isinstance(e.__cause__, asyncpg.exceptions.UniqueViolationError) or "unique constraint" in str(e).lower(): if isinstance(e.__cause__, asyncpg.exceptions.UniqueViolationError) or "unique constraint" in str(e).lower():
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail={"code": "conflict", "message": "Username already exists"}) raise HTTPException(
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail={"code": "internal_error", "message": "Database error"}) status_code=status.HTTP_409_CONFLICT,
detail={"code": "conflict", "message": "Username already exists"}
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail={"code": "internal_error", "message": "Database error"}
)
@router.post("/api/v1/auth/sessions", response_model=Session, status_code=status.HTTP_201_CREATED, responses={401: {"model": ErrorResponse}}) @router.post(
async def create_session(credentials = Depends(get_basic_auth), db: AsyncSession = Depends(get_db), redis_client = Depends(get_redis)): "/api/v1/auth/sessions",
response_model=Session,
status_code=status.HTTP_201_CREATED,
responses={401: {"model": ErrorResponse}}
)
async def create_session(
credentials = Depends(get_basic_auth),
db: AsyncSession = Depends(get_db),
redis_client = Depends(get_redis)
):
"""
Создаёт сессию. Записывает в Redis (основное хранилище) и PostgreSQL (fallback).
Если Redis недоступен — сессия всё равно создаётся в PostgreSQL.
"""
result = await db.execute(select(UserModel).where(UserModel.username == credentials.username)) result = await db.execute(select(UserModel).where(UserModel.username == credentials.username))
user = result.scalar_one_or_none() user = result.scalar_one_or_none()
@@ -52,28 +88,97 @@ async def create_session(credentials = Depends(get_basic_auth), db: AsyncSession
token = secrets.token_urlsafe(32) token = secrets.token_urlsafe(32)
expires_at = datetime.now(timezone.utc) + timedelta(seconds=settings.SESSION_TTL_SECONDS) expires_at = datetime.now(timezone.utc) + timedelta(seconds=settings.SESSION_TTL_SECONDS)
await redis_client.setex(f"session:{token}", settings.SESSION_TTL_SECONDS, str(user.id))
return Session( # 1. Пытаемся записать в Redis (не критично, если не получится)
token=token, token_type="Bearer", expires_at=expires_at, try:
user=User(id=str(user.id), username=user.username, display_name=user.display_name, created_at=user.created_at.isoformat().replace('+00:00', 'Z')) await redis_client.setex(
) f"session:{token}",
settings.SESSION_TTL_SECONDS,
str(user.id)
)
except Exception as e:
logger.warning(f"Redis unavailable during session creation, session saved to PostgreSQL only: {e}")
@router.delete("/api/v1/auth/sessions/current", status_code=status.HTTP_204_NO_CONTENT, responses={401: {"model": ErrorResponse}}) # 2. Всегда записываем в PostgreSQL (fallback-хранилище)
async def revoke_session(credentials = Depends(HTTPBearer()), redis_client = Depends(get_redis)): try:
token = credentials.credentials session_record = UserSession(
# Проверяем, существует ли сессия в Redis token=token,
exists = await redis_client.exists(f"session:{token}") user_id=user.id,
if not exists: expires_at=expires_at
)
db.add(session_record)
await db.commit()
except SQLAlchemyError as e:
await db.rollback()
logger.error(f"Failed to save session to PostgreSQL: {e}")
raise HTTPException( raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail={"code": "unauthorized", "message": "Invalid or expired session"}, detail={"code": "internal_error", "message": "Failed to create session"}
headers={"WWW-Authenticate": "Bearer realm=\"messenger\""} )
return Session(
token=token,
token_type="Bearer",
expires_at=expires_at,
user=User(
id=str(user.id),
username=user.username,
display_name=user.display_name,
created_at=user.created_at.isoformat().replace('+00:00', 'Z')
)
)
@router.delete(
"/api/v1/auth/sessions/current",
status_code=status.HTTP_204_NO_CONTENT,
responses={401: {"model": ErrorResponse}}
)
async def revoke_session(
credentials = Depends(HTTPBearer()),
db: AsyncSession = Depends(get_db),
redis_client = Depends(get_redis)
):
"""
Отзывает сессию. Удаляет из Redis и PostgreSQL.
Если Redis недоступен — удаляет только из PostgreSQL.
"""
token = credentials.credentials
# 1. Пытаемся удалить из Redis
try:
await redis_client.delete(f"session:{token}")
except Exception as e:
logger.warning(f"Redis unavailable during session revocation: {e}")
# 2. Удаляем из PostgreSQL
try:
result = await db.execute(select(UserSession).where(UserSession.token == token))
session = result.scalar_one_or_none()
if session:
await db.delete(session)
await db.commit()
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail={"code": "unauthorized", "message": "Invalid or expired session"},
headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}
)
except HTTPException:
raise
except SQLAlchemyError as e:
await db.rollback()
logger.error(f"Failed to revoke session from PostgreSQL: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail={"code": "internal_error", "message": "Failed to revoke session"}
) )
await redis_client.delete(f"session:{token}")
return Response(status_code=status.HTTP_204_NO_CONTENT) return Response(status_code=status.HTTP_204_NO_CONTENT)
@router.get("/api/v1/users/me", response_model=User, responses={401: {"model": ErrorResponse}}) @router.get(
"/api/v1/users/me",
response_model=User,
responses={401: {"model": ErrorResponse}}
)
async def current_user(current_user: UserModel = Depends(get_current_user)): async def current_user(current_user: UserModel = Depends(get_current_user)):
return current_user return current_user
+83 -48
View File
@@ -1,16 +1,28 @@
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from sqlalchemy.orm import selectinload
import uuid import uuid
import logging
from datetime import datetime, timezone from datetime import datetime, timezone
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from app.database import get_db from app.database import get_db
from app.models import Chat as ChatModel, ChatMember as ChatMemberModel, Message as MessageModel, User as UserModel from app.models import (
from app.schemas import Chat, CreateChat, Message, CreateMessage, ChatPage, MessagePage, ErrorResponse Chat as ChatModel,
ChatMember as ChatMemberModel,
Message as MessageModel,
User as UserModel,
)
from app.schemas import (
Chat, CreateChat, Message, CreateMessage,
ChatPage, MessagePage, ErrorResponse,
)
from app.dependencies import get_current_user from app.dependencies import get_current_user
from app.redis_client import get_redis from app.redis_client import get_redis
logger = logging.getLogger(__name__)
router = APIRouter() router = APIRouter()
@router.post( @router.post(
@@ -27,7 +39,7 @@ async def create_chat(
if current_user.id not in chat_in.member_ids: if current_user.id not in chat_in.member_ids:
raise HTTPException( raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, status_code=status.HTTP_400_BAD_REQUEST,
detail={"code": "invalid_request", "message": "Creator must be in member_ids", } detail={"code": "invalid_request", "message": "Creator must be in member_ids"}
) )
user_ids = list(set(chat_in.member_ids)) user_ids = list(set(chat_in.member_ids))
@@ -35,7 +47,7 @@ async def create_chat(
if len(result.scalars().all()) != len(user_ids): if len(result.scalars().all()) != len(user_ids):
raise HTTPException( raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, status_code=status.HTTP_400_BAD_REQUEST,
detail={"code": "invalid_request", "message": "One or more member_ids do not exist", } detail={"code": "invalid_request", "message": "One or more member_ids do not exist"}
) )
new_chat = ChatModel(title=chat_in.title) new_chat = ChatModel(title=chat_in.title)
@@ -86,7 +98,7 @@ async def list_chats(
except (ValueError, TypeError): except (ValueError, TypeError):
raise HTTPException( raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, status_code=status.HTTP_400_BAD_REQUEST,
detail={"code": "invalid_request", "message": "Invalid cursor", } detail={"code": "invalid_request", "message": "Invalid cursor"}
) )
stmt = stmt.limit(limit + 1) stmt = stmt.limit(limit + 1)
@@ -100,16 +112,15 @@ async def list_chats(
else: else:
next_cursor = None next_cursor = None
items = [] items = [
for c in chats: Chat(
member_ids = [str(m.user_id) for m in c.members]
items.append(Chat(
id=str(c.id), id=str(c.id),
title=c.title, title=c.title,
member_ids=member_ids, member_ids=[str(m.user_id) for m in c.members],
created_at=c.created_at.isoformat().replace('+00:00', 'Z') created_at=c.created_at.isoformat().replace('+00:00', 'Z')
)) )
for c in chats
]
return ChatPage(items=items, next_cursor=next_cursor) return ChatPage(items=items, next_cursor=next_cursor)
@router.get( @router.get(
@@ -133,14 +144,13 @@ async def get_chat(
if not chat: if not chat:
raise HTTPException( raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, status_code=status.HTTP_404_NOT_FOUND,
detail={"code": "not_found", "message": "Chat not found or access denied", } detail={"code": "not_found", "message": "Chat not found or access denied"}
) )
member_ids = [str(m.user_id) for m in chat.members]
return Chat( return Chat(
id=str(chat.id), id=str(chat.id),
title=chat.title, title=chat.title,
member_ids=member_ids, member_ids=[str(m.user_id) for m in chat.members],
created_at=chat.created_at.isoformat().replace('+00:00', 'Z') created_at=chat.created_at.isoformat().replace('+00:00', 'Z')
) )
@@ -163,7 +173,7 @@ async def create_message(
if not (await db.execute(stmt)).scalar_one_or_none(): if not (await db.execute(stmt)).scalar_one_or_none():
raise HTTPException( raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, status_code=status.HTTP_404_NOT_FOUND,
detail={"code": "not_found", "message": "Chat not found or access denied", } detail={"code": "not_found", "message": "Chat not found or access denied"}
) )
new_message = MessageModel(chat_id=chat_id, sender_id=current_user.id, text=message_in.text) new_message = MessageModel(chat_id=chat_id, sender_id=current_user.id, text=message_in.text)
@@ -171,8 +181,12 @@ async def create_message(
await db.commit() await db.commit()
await db.refresh(new_message) await db.refresh(new_message)
# GRADE 5: Инвалидация кэша при записи (Read-After-Write consistency) # Инвалидация кэша при записи (Read-After-Write consistency)
await redis_client.delete(f"messages:{chat_id}:*") # Если Redis недоступен — кэш всё равно истечёт по TTL, это не критично
try:
await redis_client.delete(f"messages:{chat_id}:*")
except Exception as e:
logger.warning(f"Redis unavailable for cache invalidation: {e}")
return Message( return Message(
id=str(new_message.id), id=str(new_message.id),
@@ -195,32 +209,47 @@ async def list_messages(
db: AsyncSession = Depends(get_db), db: AsyncSession = Depends(get_db),
redis_client = Depends(get_redis) redis_client = Depends(get_redis)
): ):
"""
Чтение истории сообщений с кэшированием в Redis.
При недоступности Redis — graceful degradation: запрос идёт напрямую в PostgreSQL.
"""
if not (await db.execute(select(ChatMemberModel).where( if not (await db.execute(select(ChatMemberModel).where(
ChatMemberModel.chat_id == chat_id, ChatMemberModel.user_id == current_user.id ChatMemberModel.chat_id == chat_id, ChatMemberModel.user_id == current_user.id
))).scalar_one_or_none(): ))).scalar_one_or_none():
raise HTTPException( raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, status_code=status.HTTP_404_NOT_FOUND,
detail={"code": "not_found", "message": "Chat not found or access denied", } detail={"code": "not_found", "message": "Chat not found or access denied"}
) )
cache_key = f"messages:{chat_id}:{limit}:{cursor or 'null'}" cache_key = f"messages:{chat_id}:{limit}:{cursor or 'null'}"
redis_available = True
# 1. Проверяем основной кэш # 1. Пытаемся проверить кэш
cached_data = await redis_client.get(cache_key) try:
if cached_data: cached_data = await redis_client.get(cache_key)
await redis_client.expire(cache_key, 60) if cached_data:
return MessagePage.model_validate_json(cached_data) await redis_client.expire(cache_key, 60)
return MessagePage.model_validate_json(cached_data)
except Exception as e:
logger.warning(f"Redis unavailable for cache read, falling back to PostgreSQL: {e}")
redis_available = False
# 2. GRADE 5: Защита от Cache Stampede (Request Coalescing) # 2. Request Coalescing (только если Redis доступен)
lock_key = f"lock:{cache_key}" lock_acquired = False
acquired = await redis_client.set(lock_key, "1", nx=True, ex=5) if redis_available:
lock_key = f"lock:{cache_key}"
try:
lock_acquired = await redis_client.set(lock_key, "1", nx=True, ex=5)
if not acquired: if not lock_acquired:
stale_data = await redis_client.get(f"stale:{cache_key}") stale_data = await redis_client.get(f"stale:{cache_key}")
if stale_data: if stale_data:
return MessagePage.model_validate_json(stale_data) return MessagePage.model_validate_json(stale_data)
except Exception as e:
logger.warning(f"Redis unavailable for lock acquisition: {e}")
redis_available = False
# 3. Выполняем запрос к БД # 3. Выполняем запрос к БД (всегда, если кэш miss)
stmt = ( stmt = (
select(MessageModel) select(MessageModel)
.where(MessageModel.chat_id == chat_id) .where(MessageModel.chat_id == chat_id)
@@ -239,7 +268,7 @@ async def list_messages(
except (ValueError, TypeError): except (ValueError, TypeError):
raise HTTPException( raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, status_code=status.HTTP_400_BAD_REQUEST,
detail={"code": "invalid_request", "message": "Invalid cursor", } detail={"code": "invalid_request", "message": "Invalid cursor"}
) )
stmt = stmt.limit(limit + 1) stmt = stmt.limit(limit + 1)
@@ -252,24 +281,30 @@ async def list_messages(
else: else:
next_cursor = None next_cursor = None
items = [] items = [
for m in messages: Message(
items.append(Message(
id=str(m.id), id=str(m.id),
chat_id=str(m.chat_id), chat_id=str(m.chat_id),
sender_id=str(m.sender_id), sender_id=str(m.sender_id),
text=m.text, text=m.text,
created_at=m.created_at.isoformat().replace('+00:00', 'Z') created_at=m.created_at.isoformat().replace('+00:00', 'Z')
)) )
for m in messages
]
page = MessagePage(items=items, next_cursor=next_cursor) page = MessagePage(items=items, next_cursor=next_cursor)
# 4. GRADE 5: Сохраняем старые данные как stale перед обновлением основного кэша # 4. Пытаемся обновить кэш (если Redis доступен)
old_cache = await redis_client.get(cache_key) if redis_available:
if old_cache: try:
await redis_client.setex(f"stale:{cache_key}", 120, old_cache) old_cache = await redis_client.get(cache_key)
if old_cache:
await redis_client.setex(f"stale:{cache_key}", 120, old_cache)
await redis_client.setex(cache_key, 60, page.model_dump_json()) await redis_client.setex(cache_key, 60, page.model_dump_json())
await redis_client.delete(lock_key)
if lock_acquired:
await redis_client.delete(f"lock:{cache_key}")
except Exception as e:
logger.warning(f"Redis unavailable for cache write: {e}")
return page return page
+1 -5
View File
@@ -12,10 +12,9 @@ services:
interval: 5s interval: 5s
timeout: 5s timeout: 5s
retries: 5 retries: 5
restart: unless-stopped
redis: redis:
image: valkey/valkey:8.0-alpine # Используем Valkey как современный форк Redis image: valkey/valkey:8.0-alpine
command: valkey-server --appendonly yes --save 60 1 command: valkey-server --appendonly yes --save 60 1
volumes: volumes:
- redis_data:/data - redis_data:/data
@@ -24,7 +23,6 @@ services:
interval: 5s interval: 5s
timeout: 5s timeout: 5s
retries: 5 retries: 5
restart: unless-stopped
api: api:
build: build:
@@ -37,8 +35,6 @@ services:
- SESSION_TTL_SECONDS=${SESSION_TTL_SECONDS} - SESSION_TTL_SECONDS=${SESSION_TTL_SECONDS}
ports: ports:
- "8080:8080" - "8080:8080"
volumes:
- ./alembic/versions:/app/alembic/versions # <-- ДОБАВИТЬ ЭТУ СТРОКУ
depends_on: depends_on:
postgres: postgres:
condition: service_healthy condition: service_healthy