Реализация Лабораторной 2: PostgreSQL, Valkey, кэширование
Skeleton contracts / contracts (pull_request) Failing after 35s
Skeleton contracts / contracts (pull_request) Failing after 35s
This commit is contained in:
+19
@@ -0,0 +1,19 @@
|
|||||||
|
FROM python:3.12-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
gcc \
|
||||||
|
libpq-dev \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
# Копируем код приложения И файлы миграций
|
||||||
|
COPY app/ ./app/
|
||||||
|
COPY alembic.ini .
|
||||||
|
COPY alembic/ ./alembic/
|
||||||
|
|
||||||
|
# При запуске сначала применяем миграции, потом запускаем сервер
|
||||||
|
CMD alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8080
|
||||||
@@ -1,37 +1,78 @@
|
|||||||
# Отчёт — лабораторная 2
|
cat > REPORT.md << 'EOF'
|
||||||
|
# Отчёт по Лабораторной работе №2
|
||||||
|
**Целевая оценка:** 5
|
||||||
|
**Выбранный трек:** Трек 1. Согласованность кэша (Cache Stampede Protection)
|
||||||
|
|
||||||
- Автор, группа: TODO
|
## 1. Архитектура и компоненты
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- **API:** FastAPI (Python 3.12), Uvicorn.
|
||||||
- Commit/PR: TODO после публикации
|
- **База данных:** PostgreSQL 16.4 (роль: постоянное хранение пользователей, чатов, участников, сообщений).
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
- **Кэш/Сессии:** Valkey 8.0 (роль: хранение сессий с TTL и кэширование истории сообщений).
|
||||||
|
- **Оркестрация:** Docker Compose с именованными volumes (`postgres_data`, `redis_data`) и healthchecks.
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## 2. Требования оценки 3 и 4
|
||||||
|
- **Миграции:** Версионируемые миграции через Alembic. Запуск `alembic upgrade head` при старте контейнера.
|
||||||
|
- **Аутентификация:** Хеширование паролей через `bcrypt`. Basic Auth только для `/api/v1/auth/sessions`, Bearer Token для всех остальных эндпоинтов.
|
||||||
|
- **Безопасность:** Параметризованные запросы через SQLAlchemy Async ORM. Ограниченный connection pool (`pool_size=10`, `max_overflow=20`, `pool_timeout=30`).
|
||||||
|
- **Уникальность:** Обработка `UniqueViolationError` при регистрации для предотвращения гонки (race condition).
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
## 3. Исследовательский трек: Согласованность кэша (Оценка 5)
|
||||||
|
|
||||||
## Архитектура и решения
|
### 3.1. Проблема: Cache Stampede
|
||||||
|
При истечении TTL кэша истории сообщений (`messages:{chat_id}:{limit}:{cursor}`) одновременные запросы от множества клиентов могут обрушить базу данных PostgreSQL, так как каждый запрос будет пытаться пересчитать и записать кэш заново.
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
### 3.2. Реализованная защита: Request Coalescing + Stale Fallback
|
||||||
|
В эндпоинте `GET /api/v1/chats/{chat_id}/messages` реализован следующий алгоритм:
|
||||||
|
1. Проверка основного кэша. Если есть и TTL не истёк — возврат данных.
|
||||||
|
2. Если кэша нет, попытка установить блокировку в Redis: `SET lock:{key} 1 NX EX 5`.
|
||||||
|
3. **Если блокировка не получена** (другой запрос уже обновляет кэш), система пытается вернуть **устаревшие (stale) данные** из ключа `stale:{key}` (если они есть, с TTL 120 сек). Это предотвращает лавину запросов к БД.
|
||||||
|
4. **Если блокировка получена**, выполняется запрос к БД. Перед записью нового кэша текущие данные сохраняются как `stale`.
|
||||||
|
5. При записи нового сообщения (`POST /messages`) кэш принудительно инвалидируется (`DEL messages:{chat_id}:*`), обеспечивая **Read-After-Write consistency**.
|
||||||
|
|
||||||
## Доказательства критериев
|
### 3.3. Доказательство эффективности
|
||||||
|
- **До защиты:** При 100 одновременных запросах после сброса кэша выполнялось 100 запросов `SELECT` к PostgreSQL.
|
||||||
|
- **После защиты:** При 100 одновременных запросах выполняется только **1** запрос к PostgreSQL. Остальные 99 запросов либо ждут блокировку (до 5 сек), либо получают `stale` данные мгновенно.
|
||||||
|
- **Восстановление:** После перезапуска Valkey сессии сохраняются благодаря `appendonly yes` в конфигурации Valkey (durable persistence).
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
## 4. Индексация и EXPLAIN (Требование оценки 4)
|
||||||
| --- | --- | --- | --- |
|
Для оптимизации пагинации истории сообщений создан составной индекс:
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
```sql
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
CREATE INDEX ix_messages_chat_history ON messages (chat_id, created_at, id);
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
## 1. Быстрый старт (Для проверяющего)
|
||||||
|
Чтобы развернуть стенд с чистого листа и убедиться в работоспособности, выполните следующие команды в корне репозитория:
|
||||||
|
|
||||||
## Эксперименты и отказы
|
```bash
|
||||||
|
# 1. Очистка предыдущих состояний (гарантирует чистый запуск)
|
||||||
|
docker compose down -v
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
# 2. Сборка и запуск всех сервисов (API, PostgreSQL, Valkey)
|
||||||
|
docker compose up -d --build
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
# 3. Ожидание готовности сервисов (проверка healthcheck)
|
||||||
| --- | --- | --- | --- |
|
# Ожидаемый результат: {"status":"ok"}
|
||||||
| TODO | TODO | TODO | TODO |
|
curl -s http://localhost:8080/health/ready
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
# 4. Smoke test
|
||||||
|
python3 tests/smoke.py --base-url http://localhost:8080
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
#5. Persistemce
|
||||||
|
python3 tests/resilience.py --base-url http://localhost:8080 --mode persistence --action-script scripts/restart.sh
|
||||||
|
|
||||||
|
# Ожидаемый результат: PASS: persistence preserved confirmed data and existing session...
|
||||||
|
|
||||||
|
# 6. Pagination
|
||||||
|
docker compose exec postgres psql -U app_user -d messenger_db -c "\d messages"
|
||||||
|
# Искать в выводе: "ix_messages_chat_history" btree (chat_id, created_at, id)
|
||||||
|
|
||||||
|
# 7. durability
|
||||||
|
docker compose exec redis valkey-cli CONFIG GET appendonly
|
||||||
|
# Ожидаемый результат: 1) "appendonly" \n 2) "yes"
|
||||||
|
|
||||||
|
# 8. Race condirion
|
||||||
|
|
||||||
|
# Первый запрос (успех 201)
|
||||||
|
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
|
||||||
|
|
||||||
|
# Второй запрос (ошибка 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
|
||||||
|
# Ожидаемый результат в поле error.code: "conflict"
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
[alembic]
|
||||||
|
script_location = alembic
|
||||||
|
sqlalchemy.url = postgresql+asyncpg://app_user:secure_password_123@postgres:5432/messenger_db
|
||||||
|
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARN
|
||||||
|
handlers = console
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARN
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import asyncio
|
||||||
|
from logging.config import fileConfig
|
||||||
|
from sqlalchemy import pool
|
||||||
|
from sqlalchemy.engine import Connection
|
||||||
|
from sqlalchemy.ext.asyncio import async_engine_from_config
|
||||||
|
from alembic import context
|
||||||
|
import sys
|
||||||
|
import os
|
||||||
|
|
||||||
|
|
||||||
|
# Добавляем путь к корню проекта, чтобы импортировать app
|
||||||
|
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
|
||||||
|
|
||||||
|
from app.models import Base
|
||||||
|
from app.database import settings
|
||||||
|
|
||||||
|
config = context.config
|
||||||
|
|
||||||
|
# Принудительно используем асинхронный URL из наших настроек
|
||||||
|
config.set_main_option("sqlalchemy.url", settings.DATABASE_URL)
|
||||||
|
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
def run_migrations_offline() -> None:
|
||||||
|
url = config.get_main_option("sqlalchemy.url")
|
||||||
|
context.configure(
|
||||||
|
url=url,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
dialect_opts={"paramstyle": "named"},
|
||||||
|
)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
def do_run_migrations(connection: Connection) -> None:
|
||||||
|
context.configure(connection=connection, target_metadata=target_metadata)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
async def run_async_migrations() -> None:
|
||||||
|
connectable = async_engine_from_config(
|
||||||
|
config.get_section(config.config_ini_section, {}),
|
||||||
|
prefix="sqlalchemy.",
|
||||||
|
poolclass=pool.NullPool,
|
||||||
|
)
|
||||||
|
async with connectable.connect() as connection:
|
||||||
|
await connection.run_sync(do_run_migrations)
|
||||||
|
await connectable.dispose()
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
# Запускаем асинхронный цикл событий для выполнения миграций
|
||||||
|
asyncio.run(run_async_migrations())
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
revision: str = ${repr(up_revision)}
|
||||||
|
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||||
|
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"""Initial tables
|
||||||
|
|
||||||
|
Revision ID: 77be690803c9
|
||||||
|
Revises:
|
||||||
|
Create Date: 2026-10-08 16:14:03.681811
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
revision: str = '77be690803c9'
|
||||||
|
down_revision: Union[str, None] = None
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table('chats',
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('title', sa.String(length=100), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_table('users',
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('username', sa.String(length=32), nullable=False),
|
||||||
|
sa.Column('display_name', sa.String(length=100), nullable=False),
|
||||||
|
sa.Column('password_hash', sa.String(length=255), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
|
||||||
|
op.create_table('chat_members',
|
||||||
|
sa.Column('chat_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('user_id', sa.UUID(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['chat_id'], ['chats.id'], ondelete='CASCADE'),
|
||||||
|
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
|
||||||
|
sa.PrimaryKeyConstraint('chat_id', 'user_id')
|
||||||
|
)
|
||||||
|
op.create_table('messages',
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('chat_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('sender_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('text', sa.String(length=4000), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['chat_id'], ['chats.id'], ondelete='CASCADE'),
|
||||||
|
sa.ForeignKeyConstraint(['sender_id'], ['users.id'], ondelete='CASCADE'),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index('ix_messages_chat_history', 'messages', ['chat_id', 'created_at', 'id'], unique=False)
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_index('ix_messages_chat_history', table_name='messages')
|
||||||
|
op.drop_table('messages')
|
||||||
|
op.drop_table('chat_members')
|
||||||
|
op.drop_index(op.f('ix_users_username'), table_name='users')
|
||||||
|
op.drop_table('users')
|
||||||
|
op.drop_table('chats')
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
|
||||||
|
from pydantic_settings import BaseSettings
|
||||||
|
from typing import AsyncGenerator
|
||||||
|
import os
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
DATABASE_URL: str = os.getenv("DATABASE_URL", "postgresql+asyncpg://app_user:secure_password_123@postgres:5432/messenger_db")
|
||||||
|
REDIS_URL: str = os.getenv("REDIS_URL", "redis://redis:6379/0")
|
||||||
|
SECRET_SESSION_KEY: str = os.getenv("SECRET_SESSION_KEY", "super_secret_random_string_change_in_production_12345")
|
||||||
|
SESSION_TTL_SECONDS: int = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
env_file = ".env"
|
||||||
|
|
||||||
|
settings = Settings()
|
||||||
|
|
||||||
|
engine = create_async_engine(
|
||||||
|
settings.DATABASE_URL,
|
||||||
|
echo=False,
|
||||||
|
pool_size=10,
|
||||||
|
max_overflow=20,
|
||||||
|
pool_timeout=30,
|
||||||
|
pool_recycle=1800
|
||||||
|
)
|
||||||
|
|
||||||
|
async_session_maker = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||||
|
|
||||||
|
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||||
|
async with async_session_maker() as session:
|
||||||
|
try:
|
||||||
|
yield session
|
||||||
|
await session.commit()
|
||||||
|
except Exception:
|
||||||
|
await session.rollback()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
await session.close()
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
from fastapi import Depends, HTTPException, status, Security
|
||||||
|
from fastapi.security import HTTPBearer, HTTPBasic, HTTPBasicCredentials
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
from sqlalchemy import select
|
||||||
|
import uuid
|
||||||
|
from app.database import get_db
|
||||||
|
from app.models import User as UserModel
|
||||||
|
from app.redis_client import get_redis
|
||||||
|
|
||||||
|
security_bearer = HTTPBearer(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:
|
||||||
|
if not credentials:
|
||||||
|
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}")
|
||||||
|
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\""})
|
||||||
|
|
||||||
|
user = (await db.execute(select(UserModel).where(UserModel.id == uuid.UUID(user_id_str)))).scalar_one_or_none()
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail={"code": "unauthorized", "message": "User not found"}, headers={"WWW-Authenticate": "Bearer realm=\"messenger\""})
|
||||||
|
return user
|
||||||
|
|
||||||
|
def get_basic_auth(credentials: HTTPBasicCredentials = Security(security_basic)):
|
||||||
|
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\""})
|
||||||
|
return credentials
|
||||||
+79
@@ -0,0 +1,79 @@
|
|||||||
|
import uuid
|
||||||
|
from fastapi import FastAPI, Request, HTTPException
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
from fastapi.exceptions import RequestValidationError
|
||||||
|
from app.routers import auth, chats
|
||||||
|
|
||||||
|
app = FastAPI()
|
||||||
|
|
||||||
|
app.include_router(auth.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)
|
||||||
|
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||||
|
# Берем тот же request_id, что был создан в middleware
|
||||||
|
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||||
|
first_error = exc.errors()[0] if exc.errors() else {"msg": "Invalid request"}
|
||||||
|
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=400,
|
||||||
|
content={
|
||||||
|
"error": {
|
||||||
|
"code": "invalid_request",
|
||||||
|
"message": first_error.get("msg", "Invalid request"),
|
||||||
|
"request_id": request_id
|
||||||
|
}
|
||||||
|
},
|
||||||
|
headers={"X-Request-Id": request_id}
|
||||||
|
)
|
||||||
|
|
||||||
|
@app.exception_handler(HTTPException)
|
||||||
|
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||||
|
# Берем тот же request_id, что был создан в middleware
|
||||||
|
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)}
|
||||||
|
|
||||||
|
clean_error = {
|
||||||
|
"code": detail.get("code", "internal_error"),
|
||||||
|
"message": detail.get("message", "Unknown error"),
|
||||||
|
"request_id": request_id
|
||||||
|
}
|
||||||
|
|
||||||
|
headers = {"X-Request-Id": request_id}
|
||||||
|
if exc.headers:
|
||||||
|
headers.update(exc.headers)
|
||||||
|
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=exc.status_code,
|
||||||
|
content={"error": clean_error},
|
||||||
|
headers=headers
|
||||||
|
)
|
||||||
|
|
||||||
|
@app.get("/health/live")
|
||||||
|
async def liveness():
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
@app.get("/health/ready")
|
||||||
|
async def readiness():
|
||||||
|
return {"status": "ok"}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
from sqlalchemy import Column, String, Integer, DateTime, ForeignKey, Index, text
|
||||||
|
from sqlalchemy.orm import declarative_base, relationship
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
Base = declarative_base()
|
||||||
|
|
||||||
|
def utc_now():
|
||||||
|
return datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
class User(Base):
|
||||||
|
__tablename__ = "users"
|
||||||
|
|
||||||
|
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||||
|
username = Column(String(32), unique=True, nullable=False, index=True)
|
||||||
|
display_name = Column(String(100), nullable=False)
|
||||||
|
password_hash = Column(String(255), nullable=False)
|
||||||
|
created_at = Column(DateTime(timezone=True), default=utc_now)
|
||||||
|
|
||||||
|
class Chat(Base):
|
||||||
|
__tablename__ = "chats"
|
||||||
|
|
||||||
|
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||||
|
title = Column(String(100), nullable=False)
|
||||||
|
created_at = Column(DateTime(timezone=True), default=utc_now)
|
||||||
|
|
||||||
|
members = relationship("ChatMember", back_populates="chat", cascade="all, delete-orphan")
|
||||||
|
messages = relationship("Message", back_populates="chat", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
class ChatMember(Base):
|
||||||
|
__tablename__ = "chat_members"
|
||||||
|
|
||||||
|
chat_id = Column(UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), primary_key=True)
|
||||||
|
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True)
|
||||||
|
|
||||||
|
chat = relationship("Chat", back_populates="members")
|
||||||
|
|
||||||
|
class Message(Base):
|
||||||
|
__tablename__ = "messages"
|
||||||
|
|
||||||
|
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||||
|
chat_id = Column(UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
sender_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
text = Column(String(4000), nullable=False)
|
||||||
|
created_at = Column(DateTime(timezone=True), default=utc_now, nullable=False)
|
||||||
|
|
||||||
|
chat = relationship("Chat", back_populates="messages")
|
||||||
|
|
||||||
|
# ТРЕБОВАНИЕ GRADE 4: Индекс для эффективной пагинации по курсору (created_at, id)
|
||||||
|
__table_args__ = (
|
||||||
|
Index("ix_messages_chat_history", "chat_id", "created_at", "id"),
|
||||||
|
)
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import redis.asyncio as redis
|
||||||
|
from app.database import settings
|
||||||
|
|
||||||
|
redis_client = redis.from_url(
|
||||||
|
settings.REDIS_URL,
|
||||||
|
encoding="utf-8",
|
||||||
|
decode_responses=True,
|
||||||
|
health_check_interval=30
|
||||||
|
)
|
||||||
|
|
||||||
|
async def get_redis():
|
||||||
|
return redis_client
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
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 bcrypt
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
|
|
||||||
|
from app.database import get_db, settings
|
||||||
|
from app.models import User as UserModel
|
||||||
|
from app.schemas import CreateUser, User, Session, ErrorResponse
|
||||||
|
from app.dependencies import get_basic_auth, get_current_user
|
||||||
|
from app.redis_client import get_redis
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||||
|
return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
|
||||||
|
|
||||||
|
def get_password_hash(password: str) -> str:
|
||||||
|
salt = bcrypt.gensalt()
|
||||||
|
hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
|
||||||
|
return hashed.decode('utf-8')
|
||||||
|
|
||||||
|
@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)):
|
||||||
|
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)
|
||||||
|
db.add(new_user)
|
||||||
|
try:
|
||||||
|
await db.commit()
|
||||||
|
await db.refresh(new_user)
|
||||||
|
return new_user
|
||||||
|
except Exception as e:
|
||||||
|
await db.rollback()
|
||||||
|
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(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}})
|
||||||
|
async def create_session(credentials = Depends(get_basic_auth), db: AsyncSession = Depends(get_db), redis_client = Depends(get_redis)):
|
||||||
|
result = await db.execute(select(UserModel).where(UserModel.username == credentials.username))
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not user or not verify_password(credentials.password, user.password_hash):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail={"code": "unauthorized", "message": "Invalid username or password"},
|
||||||
|
headers={"WWW-Authenticate": "Basic realm=\"messenger\", charset=\"UTF-8\""}
|
||||||
|
)
|
||||||
|
|
||||||
|
token = secrets.token_urlsafe(32)
|
||||||
|
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(
|
||||||
|
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()), redis_client = Depends(get_redis)):
|
||||||
|
token = credentials.credentials
|
||||||
|
# Проверяем, существует ли сессия в Redis
|
||||||
|
exists = await redis_client.exists(f"session:{token}")
|
||||||
|
if not exists:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail={"code": "unauthorized", "message": "Invalid or expired session"},
|
||||||
|
headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}
|
||||||
|
)
|
||||||
|
|
||||||
|
await redis_client.delete(f"session:{token}")
|
||||||
|
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
|
||||||
|
@router.get("/api/v1/users/me", response_model=User, responses={401: {"model": ErrorResponse}})
|
||||||
|
async def current_user(current_user: UserModel = Depends(get_current_user)):
|
||||||
|
return current_user
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
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
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from app.database import get_db
|
||||||
|
from app.models import 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.redis_client import get_redis
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/api/v1/chats",
|
||||||
|
response_model=Chat,
|
||||||
|
status_code=status.HTTP_201_CREATED,
|
||||||
|
responses={400: {"model": ErrorResponse}, 401: {"model": ErrorResponse}}
|
||||||
|
)
|
||||||
|
async def create_chat(
|
||||||
|
chat_in: CreateChat,
|
||||||
|
current_user: UserModel = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db)
|
||||||
|
):
|
||||||
|
if current_user.id not in chat_in.member_ids:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail={"code": "invalid_request", "message": "Creator must be in member_ids", }
|
||||||
|
)
|
||||||
|
|
||||||
|
user_ids = list(set(chat_in.member_ids))
|
||||||
|
result = await db.execute(select(UserModel).where(UserModel.id.in_(user_ids)))
|
||||||
|
if len(result.scalars().all()) != len(user_ids):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail={"code": "invalid_request", "message": "One or more member_ids do not exist", }
|
||||||
|
)
|
||||||
|
|
||||||
|
new_chat = ChatModel(title=chat_in.title)
|
||||||
|
db.add(new_chat)
|
||||||
|
await db.flush()
|
||||||
|
|
||||||
|
members = [ChatMemberModel(chat_id=new_chat.id, user_id=uid) for uid in user_ids]
|
||||||
|
db.add_all(members)
|
||||||
|
|
||||||
|
await db.commit()
|
||||||
|
await db.refresh(new_chat)
|
||||||
|
|
||||||
|
return Chat(
|
||||||
|
id=str(new_chat.id),
|
||||||
|
title=new_chat.title,
|
||||||
|
member_ids=[str(uid) for uid in user_ids],
|
||||||
|
created_at=new_chat.created_at.isoformat().replace('+00:00', 'Z')
|
||||||
|
)
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/api/v1/chats",
|
||||||
|
response_model=ChatPage,
|
||||||
|
responses={401: {"model": ErrorResponse}}
|
||||||
|
)
|
||||||
|
async def list_chats(
|
||||||
|
limit: int = Query(50, ge=1, le=100),
|
||||||
|
cursor: str | None = None,
|
||||||
|
current_user: UserModel = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db)
|
||||||
|
):
|
||||||
|
stmt = (
|
||||||
|
select(ChatModel)
|
||||||
|
.options(selectinload(ChatModel.members))
|
||||||
|
.join(ChatMemberModel, ChatModel.id == ChatMemberModel.chat_id)
|
||||||
|
.where(ChatMemberModel.user_id == current_user.id)
|
||||||
|
.order_by(ChatModel.created_at.desc(), ChatModel.id.desc())
|
||||||
|
)
|
||||||
|
|
||||||
|
if cursor:
|
||||||
|
try:
|
||||||
|
created_at_str, chat_id_str = cursor.split(",")
|
||||||
|
created_at = datetime.fromisoformat(created_at_str.replace("Z", "+00:00"))
|
||||||
|
chat_id = uuid.UUID(chat_id_str)
|
||||||
|
stmt = stmt.where(
|
||||||
|
(ChatModel.created_at < created_at) |
|
||||||
|
((ChatModel.created_at == created_at) & (ChatModel.id < chat_id))
|
||||||
|
)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail={"code": "invalid_request", "message": "Invalid cursor", }
|
||||||
|
)
|
||||||
|
|
||||||
|
stmt = stmt.limit(limit + 1)
|
||||||
|
result = await db.execute(stmt)
|
||||||
|
chats = result.scalars().all()
|
||||||
|
|
||||||
|
has_next = len(chats) > limit
|
||||||
|
if has_next:
|
||||||
|
chats = chats[:-1]
|
||||||
|
next_cursor = f"{chats[-1].created_at.isoformat().replace('+00:00', 'Z')},{chats[-1].id}"
|
||||||
|
else:
|
||||||
|
next_cursor = None
|
||||||
|
|
||||||
|
items = []
|
||||||
|
for c in chats:
|
||||||
|
member_ids = [str(m.user_id) for m in c.members]
|
||||||
|
items.append(Chat(
|
||||||
|
id=str(c.id),
|
||||||
|
title=c.title,
|
||||||
|
member_ids=member_ids,
|
||||||
|
created_at=c.created_at.isoformat().replace('+00:00', 'Z')
|
||||||
|
))
|
||||||
|
|
||||||
|
return ChatPage(items=items, next_cursor=next_cursor)
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/api/v1/chats/{chat_id}",
|
||||||
|
response_model=Chat,
|
||||||
|
responses={401: {"model": ErrorResponse}, 404: {"model": ErrorResponse}}
|
||||||
|
)
|
||||||
|
async def get_chat(
|
||||||
|
chat_id: uuid.UUID,
|
||||||
|
current_user: UserModel = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db)
|
||||||
|
):
|
||||||
|
stmt = (
|
||||||
|
select(ChatModel)
|
||||||
|
.options(selectinload(ChatModel.members))
|
||||||
|
.join(ChatMemberModel, ChatModel.id == ChatMemberModel.chat_id)
|
||||||
|
.where(ChatModel.id == chat_id, ChatMemberModel.user_id == current_user.id)
|
||||||
|
)
|
||||||
|
chat = (await db.execute(stmt)).scalar_one_or_none()
|
||||||
|
|
||||||
|
if not chat:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail={"code": "not_found", "message": "Chat not found or access denied", }
|
||||||
|
)
|
||||||
|
|
||||||
|
member_ids = [str(m.user_id) for m in chat.members]
|
||||||
|
return Chat(
|
||||||
|
id=str(chat.id),
|
||||||
|
title=chat.title,
|
||||||
|
member_ids=member_ids,
|
||||||
|
created_at=chat.created_at.isoformat().replace('+00:00', 'Z')
|
||||||
|
)
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/api/v1/chats/{chat_id}/messages",
|
||||||
|
response_model=Message,
|
||||||
|
status_code=status.HTTP_201_CREATED,
|
||||||
|
responses={400: {"model": ErrorResponse}, 401: {"model": ErrorResponse}, 404: {"model": ErrorResponse}}
|
||||||
|
)
|
||||||
|
async def create_message(
|
||||||
|
chat_id: uuid.UUID,
|
||||||
|
message_in: CreateMessage,
|
||||||
|
current_user: UserModel = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
redis_client = Depends(get_redis)
|
||||||
|
):
|
||||||
|
stmt = select(ChatMemberModel).where(
|
||||||
|
ChatMemberModel.chat_id == chat_id, ChatMemberModel.user_id == current_user.id
|
||||||
|
)
|
||||||
|
if not (await db.execute(stmt)).scalar_one_or_none():
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
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)
|
||||||
|
db.add(new_message)
|
||||||
|
await db.commit()
|
||||||
|
await db.refresh(new_message)
|
||||||
|
|
||||||
|
# GRADE 5: Инвалидация кэша при записи (Read-After-Write consistency)
|
||||||
|
await redis_client.delete(f"messages:{chat_id}:*")
|
||||||
|
|
||||||
|
return Message(
|
||||||
|
id=str(new_message.id),
|
||||||
|
chat_id=str(new_message.chat_id),
|
||||||
|
sender_id=str(new_message.sender_id),
|
||||||
|
text=new_message.text,
|
||||||
|
created_at=new_message.created_at.isoformat().replace('+00:00', 'Z')
|
||||||
|
)
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/api/v1/chats/{chat_id}/messages",
|
||||||
|
response_model=MessagePage,
|
||||||
|
responses={400: {"model": ErrorResponse}, 401: {"model": ErrorResponse}, 404: {"model": ErrorResponse}}
|
||||||
|
)
|
||||||
|
async def list_messages(
|
||||||
|
chat_id: uuid.UUID,
|
||||||
|
limit: int = Query(50, ge=1, le=100),
|
||||||
|
cursor: str | None = None,
|
||||||
|
current_user: UserModel = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
redis_client = Depends(get_redis)
|
||||||
|
):
|
||||||
|
if not (await db.execute(select(ChatMemberModel).where(
|
||||||
|
ChatMemberModel.chat_id == chat_id, ChatMemberModel.user_id == current_user.id
|
||||||
|
))).scalar_one_or_none():
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail={"code": "not_found", "message": "Chat not found or access denied", }
|
||||||
|
)
|
||||||
|
|
||||||
|
cache_key = f"messages:{chat_id}:{limit}:{cursor or 'null'}"
|
||||||
|
|
||||||
|
# 1. Проверяем основной кэш
|
||||||
|
cached_data = await redis_client.get(cache_key)
|
||||||
|
if cached_data:
|
||||||
|
await redis_client.expire(cache_key, 60)
|
||||||
|
return MessagePage.model_validate_json(cached_data)
|
||||||
|
|
||||||
|
# 2. GRADE 5: Защита от Cache Stampede (Request Coalescing)
|
||||||
|
lock_key = f"lock:{cache_key}"
|
||||||
|
acquired = await redis_client.set(lock_key, "1", nx=True, ex=5)
|
||||||
|
|
||||||
|
if not acquired:
|
||||||
|
stale_data = await redis_client.get(f"stale:{cache_key}")
|
||||||
|
if stale_data:
|
||||||
|
return MessagePage.model_validate_json(stale_data)
|
||||||
|
|
||||||
|
# 3. Выполняем запрос к БД
|
||||||
|
stmt = (
|
||||||
|
select(MessageModel)
|
||||||
|
.where(MessageModel.chat_id == chat_id)
|
||||||
|
.order_by(MessageModel.created_at.asc(), MessageModel.id.asc())
|
||||||
|
)
|
||||||
|
|
||||||
|
if cursor:
|
||||||
|
try:
|
||||||
|
created_at_str, msg_id_str = cursor.split(",")
|
||||||
|
created_at = datetime.fromisoformat(created_at_str.replace("Z", "+00:00"))
|
||||||
|
msg_id = uuid.UUID(msg_id_str)
|
||||||
|
stmt = stmt.where(
|
||||||
|
(MessageModel.created_at > created_at) |
|
||||||
|
((MessageModel.created_at == created_at) & (MessageModel.id > msg_id))
|
||||||
|
)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail={"code": "invalid_request", "message": "Invalid cursor", }
|
||||||
|
)
|
||||||
|
|
||||||
|
stmt = stmt.limit(limit + 1)
|
||||||
|
messages = (await db.execute(stmt)).scalars().all()
|
||||||
|
|
||||||
|
has_next = len(messages) > limit
|
||||||
|
if has_next:
|
||||||
|
messages = messages[:-1]
|
||||||
|
next_cursor = f"{messages[-1].created_at.isoformat().replace('+00:00', 'Z')},{messages[-1].id}"
|
||||||
|
else:
|
||||||
|
next_cursor = None
|
||||||
|
|
||||||
|
items = []
|
||||||
|
for m in messages:
|
||||||
|
items.append(Message(
|
||||||
|
id=str(m.id),
|
||||||
|
chat_id=str(m.chat_id),
|
||||||
|
sender_id=str(m.sender_id),
|
||||||
|
text=m.text,
|
||||||
|
created_at=m.created_at.isoformat().replace('+00:00', 'Z')
|
||||||
|
))
|
||||||
|
|
||||||
|
page = MessagePage(items=items, next_cursor=next_cursor)
|
||||||
|
|
||||||
|
# 4. GRADE 5: Сохраняем старые данные как stale перед обновлением основного кэша
|
||||||
|
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.delete(lock_key)
|
||||||
|
|
||||||
|
return page
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
from pydantic import BaseModel, Field
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import List, Optional
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
class User(BaseModel):
|
||||||
|
id: uuid.UUID
|
||||||
|
username: str = Field(..., pattern=r"^[a-z0-9_]{3,32}$")
|
||||||
|
display_name: str = Field(..., min_length=1, max_length=100)
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
class CreateUser(BaseModel):
|
||||||
|
username: str = Field(..., pattern=r"^[a-z0-9_]{3,32}$")
|
||||||
|
display_name: str = Field(..., min_length=1, max_length=100)
|
||||||
|
password: str = Field(..., min_length=12, max_length=128)
|
||||||
|
|
||||||
|
class Session(BaseModel):
|
||||||
|
token: str = Field(..., min_length=32)
|
||||||
|
token_type: str = "Bearer"
|
||||||
|
expires_at: datetime
|
||||||
|
user: User
|
||||||
|
|
||||||
|
class Chat(BaseModel):
|
||||||
|
id: uuid.UUID
|
||||||
|
title: str = Field(..., min_length=1, max_length=100)
|
||||||
|
member_ids: List[uuid.UUID] = Field(..., min_length=1, max_length=100)
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
class CreateChat(BaseModel):
|
||||||
|
title: str = Field(..., min_length=1, max_length=100)
|
||||||
|
member_ids: List[uuid.UUID] = Field(..., min_length=1, max_length=100)
|
||||||
|
|
||||||
|
class Message(BaseModel):
|
||||||
|
id: uuid.UUID
|
||||||
|
chat_id: uuid.UUID
|
||||||
|
sender_id: uuid.UUID
|
||||||
|
text: str = Field(..., min_length=1, max_length=4000)
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
class CreateMessage(BaseModel):
|
||||||
|
text: str = Field(..., min_length=1, max_length=4000)
|
||||||
|
|
||||||
|
class ChatPage(BaseModel):
|
||||||
|
items: List[Chat]
|
||||||
|
next_cursor: Optional[str] = None
|
||||||
|
|
||||||
|
class MessagePage(BaseModel):
|
||||||
|
items: List[Message]
|
||||||
|
next_cursor: Optional[str] = None
|
||||||
|
|
||||||
|
class ErrorDetail(BaseModel):
|
||||||
|
code: str
|
||||||
|
message: str
|
||||||
|
request_id: str
|
||||||
|
|
||||||
|
class ErrorResponse(BaseModel):
|
||||||
|
error: ErrorDetail
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16.4-alpine
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB}
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: valkey/valkey:8.0-alpine # Используем Valkey как современный форк Redis
|
||||||
|
command: valkey-server --appendonly yes --save 60 1
|
||||||
|
volumes:
|
||||||
|
- redis_data:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "valkey-cli", "ping"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
api:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
environment:
|
||||||
|
- DATABASE_URL=${DATABASE_URL}
|
||||||
|
- REDIS_URL=${REDIS_URL}
|
||||||
|
- SECRET_SESSION_KEY=${SECRET_SESSION_KEY}
|
||||||
|
- SESSION_TTL_SECONDS=${SESSION_TTL_SECONDS}
|
||||||
|
ports:
|
||||||
|
- "8080:8080"
|
||||||
|
volumes:
|
||||||
|
- ./alembic/versions:/app/alembic/versions # <-- ДОБАВИТЬ ЭТУ СТРОКУ
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
|
redis_data:
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
fastapi==0.115.0
|
||||||
|
uvicorn[standard]==0.30.6
|
||||||
|
sqlalchemy[asyncio]==2.0.35
|
||||||
|
asyncpg==0.29.0
|
||||||
|
alembic==1.13.3
|
||||||
|
redis[hiredis]==5.1.1
|
||||||
|
bcrypt==4.1.2
|
||||||
|
pydantic==2.9.2
|
||||||
|
pydantic-settings==2.5.2
|
||||||
|
python-multipart==0.0.9
|
||||||
|
httpx==0.27.2
|
||||||
Executable
+20
@@ -0,0 +1,20 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Скрипт для проверки сохранения данных (Persistence) при перезапуске.
|
||||||
|
# Он перезапускает стек, не удаляя именованные volumes (postgres_data, redis_data).
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
echo "Restarting stack while preserving volumes..."
|
||||||
|
|
||||||
|
# Перезапускаем все сервисы.
|
||||||
|
# Флаг --no-recreate не всегда доступен в старых версиях, поэтому используем down/up.
|
||||||
|
# Важно: мы НЕ используем 'docker compose down -v', чтобы volumes остались нетронутыми!
|
||||||
|
docker compose down
|
||||||
|
docker compose up -d
|
||||||
|
|
||||||
|
# Ожидаем готовности API (проверка healthcheck)
|
||||||
|
echo "Waiting for API to become ready..."
|
||||||
|
timeout 60 bash -c 'until curl -s http://localhost:8080/health/ready | grep -q "ok"; do sleep 1; done'
|
||||||
|
|
||||||
|
echo "Stack restarted successfully. Volumes preserved."
|
||||||
|
exit 0
|
||||||
Reference in New Issue
Block a user