feat: store messenger data in PostgreSQL

Replace the in-memory store with PostgreSQL 18.6: SQLAlchemy 2.1 async
engine on asyncpg, alembic migrations with an async env.py, repos on
AsyncSession and services that own the transaction. Username
uniqueness is enforced by the database (ON CONFLICT), a chat and its
members are created in one transaction, member order is kept in
chat_members.position, and a composite foreign key makes the sender a
member of the chat. History and chat lists use keyset pagination on
(chat_id, created_at, id) and (user_id, created_at, chat_id).

The compose stand runs postgres, a one-shot migrate service on the
API image and the API. All Postgres addresses come from .env without
literals; only the 127.0.0.1 publish address stays literal. make
run_dev starts Postgres and applies migrations before the server, and
make env_setup generates a random Postgres password.

Unavailable PostgreSQL yields 503: get_db_session bounds the request
with asyncio and classifies driver errors. BoundedCloseConnection
limits asyncpg's graceful close, which otherwise waited without limit
on a frozen server and held the request until it was resumed.

Add scripts/restart.sh for make test-persistence and make
test_isolated, which runs the image on a throwaway test database.
Remove make run_no_compose. X-User-Id identification is unchanged
until the session-auth change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-01 15:33:49 +03:00
co-authored by Claude Opus 5.5
parent 93b699a478
commit 4921afa39d
47 changed files with 2648 additions and 169 deletions
+67 -15
View File
@@ -1,45 +1,97 @@
"""Зависимости ручек: хранилище, сервисы, текущий пользователь, страница."""
"""Зависимости ручек: сессия БД, сервисы, текущий пользователь, страница."""
import asyncio
from collections.abc import AsyncIterator
from dataclasses import dataclass
from typing import Annotated
from fastapi import Depends, Query, Request, Security
from fastapi.security import APIKeyHeader
from sqlalchemy.ext.asyncio import (
AsyncEngine,
AsyncSession,
async_sessionmaker,
)
from src.config import settings
from src.core import exceptions
from src.core.services import ChatService, MessageService, UserService
from src.infra.logger import current_user_id
from src.infra.memory import MemoryStore
from src.infra.db import is_db_unavailable, ping
from src.infra.logger import AbstractLogger, current_user_id, get_logger
from src.schemas import dataclasses
from src.utils.constants import (
PAGE_LIMIT_DEFAULT,
PAGE_LIMIT_MAX,
PAGE_LIMIT_MIN,
READINESS_DB_TIMEOUT_SECONDS,
USER_ID_HEADER,
)
logger: AbstractLogger = get_logger().bind(module="api_dependencies")
async def get_store(request: Request) -> MemoryStore:
"""Хранилище из lifespan; до его создания — 503."""
store: MemoryStore | None = getattr(request.app.state, "store", None)
if store is None:
async def get_db_session(request: Request) -> AsyncIterator[AsyncSession]:
"""Одна сессия БД на запрос; commit делает сервис.
Незакоммиченное при выходе откатывается. Вся работа запроса с БД
ограничена `[database] request_timeout_seconds`: зависший Postgres не
держит запрос бесконечно. Недоступность БД (`is_db_unavailable`) —
503 `unavailable`, а соединение не возвращается в пул: его состояние
неизвестно, а откат на зависшем сервере повис бы.
"""
session_factory: async_sessionmaker[AsyncSession] | None = getattr(
request.app.state,
"session_factory",
None,
)
if session_factory is None:
raise exceptions.ServiceUnavailable
return store
async with session_factory() as db_session:
try:
async with asyncio.timeout(
settings.database.request_timeout_seconds,
):
yield db_session
except Exception as e:
if not is_db_unavailable(e):
raise
await db_session.invalidate()
logger.warning(
"Database is unavailable",
error_type=type(e).__name__,
error=str(e),
)
raise exceptions.ServiceUnavailable from e
StoreDep = Annotated[MemoryStore, Depends(get_store)]
DbSessionDep = Annotated[AsyncSession, Depends(get_db_session)]
async def get_user_service(store: StoreDep) -> UserService:
return UserService(store=store)
async def require_database(request: Request) -> None:
"""Readiness: Postgres отвечает на `SELECT 1` за отведённое время.
Любая ошибка — 503: готовность не должна отвечать 500. Не логирует:
healthcheck спрашивает каждые несколько секунд.
"""
engine: AsyncEngine | None = getattr(request.app.state, "engine", None)
if engine is None:
raise exceptions.ServiceUnavailable
try:
await ping(engine, timeout=READINESS_DB_TIMEOUT_SECONDS)
except Exception as e:
raise exceptions.ServiceUnavailable from e
async def get_chat_service(store: StoreDep) -> ChatService:
return ChatService(store=store)
async def get_user_service(db_session: DbSessionDep) -> UserService:
return UserService(db_session=db_session)
async def get_message_service(store: StoreDep) -> MessageService:
return MessageService(store=store)
async def get_chat_service(db_session: DbSessionDep) -> ChatService:
return ChatService(db_session=db_session)
async def get_message_service(db_session: DbSessionDep) -> MessageService:
return MessageService(db_session=db_session)
UserServiceDep = Annotated[UserService, Depends(get_user_service)]
+3 -3
View File
@@ -1,6 +1,6 @@
from fastapi import APIRouter, Depends
from src.api.dependencies import get_store
from src.api.dependencies import require_database
from src.api.schemas import Error, Health
from src.utils.constants import HEALTH_LIVE_PATH, HEALTH_READY_PATH
@@ -18,8 +18,8 @@ async def liveness() -> Health:
HEALTH_READY_PATH,
response_model=Health,
responses={503: {"model": Error}},
dependencies=[Depends(get_store)],
dependencies=[Depends(require_database)],
)
async def readiness() -> Health:
"""Хранилище создано — можно обслуживать запросы; иначе 503."""
"""Postgres отвечает — можно обслуживать запросы; иначе 503."""
return Health(status="ok")