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
+53 -17
View File
@@ -30,15 +30,18 @@ test-persistence:
# Приложение на хосте (свои цели; цели skeleton выше не менять)
# -------------------------
# Postgres из compose и миграции, затем сервис на хосте:
# 127.0.0.1:APP__PORT, reload по src/
.PHONY: run_dev
run_dev:
run_dev: upgrade
APP__RUN_MODE=console uv run python -m src
# шаблоны копируются только если файла ещё нет: локальные значения
# не затираются
# не затираются. В новый .env подставляется случайный пароль Postgres:
# в шаблоне он пустой, общего пароля стенда в git нет
.PHONY: env_setup
env_setup:
@test -f .env || cp .env.example .env
@test -f .env || sed "s/^POSTGRES_PASSWORD=$$/POSTGRES_PASSWORD=$$(openssl rand -hex 16)/" .env.example > .env
@test -f config.toml || cp config_example.toml config.toml
@echo "env ready: .env, config.toml"
@@ -52,21 +55,10 @@ env_setup:
APP__PORT ?= 8080
APP_OUT_PORT ?= 8080
DC=docker compose
DOCKER_IMAGE=mtusi-messenger:lab2
DOCKER_CONTAINER=mtusi-messenger-lab2
# без compose: команды README, контейнер на переднем плане;
# стоп — Ctrl+C или docker stop mtusi-messenger-lab2.
# env_setup создаёт недостающий .env: без него --env-file падает
.PHONY: run_no_compose
run_no_compose: env_setup
DOCKER_BUILDKIT=1 docker build -t $(DOCKER_IMAGE) .
docker run --rm --name $(DOCKER_CONTAINER) \
-p 127.0.0.1:$(APP_OUT_PORT):$(APP__PORT) \
--env-file .env $(DOCKER_IMAGE)
# env_setup создаёт недостающие .env и config.toml из шаблонов: без
# config.toml compose не запустится (bind с create_host_path: false)
# стенд: postgres -> migrate -> api. env_setup создаёт недостающие .env
# и config.toml из шаблонов: без config.toml compose не запустится
# (bind с create_host_path: false), без пароля — тоже
.PHONY: run_docker
run_docker: env_setup
DOCKER_BUILDKIT=1 $(DC) build
@@ -76,6 +68,7 @@ run_docker: env_setup
stop:
$(DC) stop
# контейнеры удаляются, volume с данными остаётся (удаление — wipe_data)
.PHONY: down
down:
$(DC) down
@@ -86,6 +79,42 @@ logs:
$(DC) logs -f --no-log-prefix api
# -------------------------
# PostgreSQL и миграции
# -------------------------
# Postgres стенда; --wait ждёт его healthcheck
.PHONY: start_db
start_db: env_setup
$(DC) up -d --wait postgres
.PHONY: stop_db
stop_db:
$(DC) stop postgres
# миграции с хоста: 127.0.0.1:POSTGRES_OUT_PORT из .env
.PHONY: upgrade
upgrade: start_db
uv run alembic upgrade head
# новая ревизия autogenerate; база сначала доводится до head, иначе
# autogenerate сравнит модели не с той схемой
.PHONY: revision
revision: upgrade
@read -p "Сообщение миграции (англ., прошедшее время): " msg; \
uv run alembic revision --autogenerate -m "$$msg"
# удалить контейнеры стенда и volume с данными: только после ввода yes
.PHONY: wipe_data
wipe_data:
@read -p "Удалить все данные стенда (volume Postgres)? Введите yes: " answer; \
if [ "$$answer" = "yes" ]; then \
$(DC) down -v --remove-orphans; \
else \
echo "cancelled, nothing removed"; exit 1; \
fi
# -------------------------
# Load benchmark (трек 1)
# -------------------------
@@ -135,6 +164,13 @@ bench_ab:
student_test:
BASE_URL=$(BASE_URL) uv run pytest
# образ на временной базе test_<POSTGRES_DB>: сборка, миграции, отдельный
# контейнер api на 127.0.0.1:TEST_APP_PORT, make test и make student_test,
# затем уборка при любом исходе. KEEP_TEST_DB=1 оставляет базу для разбора
.PHONY: test_isolated
test_isolated: env_setup start_db
uv run python student-tests/run_isolated.py $(if $(KEEP_TEST_DB),--keep-db,)
.PHONY: lint
lint:
@ruff format .