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
+6 -1
View File
@@ -1,7 +1,7 @@
[project]
name = "mtusi-messenger"
version = "0.1.0"
description = "Lab 1: Docker and in-memory messenger"
description = "Lab 2: PostgreSQL storage, sessions and Redis/Valkey"
requires-python = "==3.12.*"
dependencies = [
@@ -11,6 +11,11 @@ dependencies = [
"fastapi[all]>=0.137.2,<1.0.0",
"uvicorn>=0.29.0,<1.0.0",
"structlog>=24.1.0,<25.0.0",
# asyncio-extra ставит greenlet: без него асинхронный engine 2.1 не работает
"sqlalchemy[asyncio]>=2.1.1,<2.2",
"asyncpg>=0.31.0,<0.32",
# в основной группе: сервис миграций работает в runtime-образе (--no-dev)
"alembic>=1.20.0,<2",
]
[project.optional-dependencies]