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:
+80
-13
@@ -1,24 +1,91 @@
|
||||
# Стенд лабы 1: один процесс API, состояние в памяти. Правила —
|
||||
# .claude/rules/docker.md. Переменные — из .env (шаблон .env.example).
|
||||
# Стенд лабы 2: PostgreSQL, одноразовые миграции и API. Правила —
|
||||
# .claude/rules/docker.md. Значения — из .env (шаблон .env.example);
|
||||
# литералы только у адреса публикации 127.0.0.1 и у режима docker.
|
||||
name: mtusi-lab2
|
||||
|
||||
# окружение приложения: одно для api и migrate, чтобы они не разъехались
|
||||
x-app-env: &app-env
|
||||
APP__RUN_MODE: docker
|
||||
APP__PORT: ${APP__PORT:-8080}
|
||||
DATABASE__HOST: ${POSTGRES_HOST:-postgres}
|
||||
DATABASE__PORT: ${POSTGRES_PORT:-5432}
|
||||
DATABASE__USER: ${POSTGRES_USER:?POSTGRES_USER is not set, run make env_setup}
|
||||
DATABASE__PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is empty, run make env_setup}
|
||||
DATABASE__NAME: ${POSTGRES_DB:?POSTGRES_DB is not set, run make env_setup}
|
||||
|
||||
# config.toml только на чтение, длинной записью: без файла запуск падает,
|
||||
# а не создаёт на хосте каталог config.toml/
|
||||
x-config-toml: &config-toml
|
||||
type: bind
|
||||
source: ./config.toml
|
||||
target: /app/config.toml
|
||||
read_only: true
|
||||
bind:
|
||||
create_host_path: false
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:18.6-trixie@sha256:5a5a84b19854a9ffaa54082c166ff4ec27473a361e496e5ea167f298f2da9722
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:?POSTGRES_USER is not set, run make env_setup}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is empty, run make env_setup}
|
||||
POSTGRES_DB: ${POSTGRES_DB:?POSTGRES_DB is not set, run make env_setup}
|
||||
# порт самого сервера; его же берут pg_isready и psql в контейнере
|
||||
PGPORT: ${POSTGRES_PORT:-5432}
|
||||
ports:
|
||||
# только localhost: к нему подключается приложение в console
|
||||
- "127.0.0.1:${POSTGRES_OUT_PORT:-5433}:${POSTGRES_PORT:-5432}"
|
||||
volumes:
|
||||
# с 18.x данные в /var/lib/postgresql/18/docker, volume образа —
|
||||
# весь /var/lib/postgresql (Config.Volumes)
|
||||
- postgres_data:/var/lib/postgresql
|
||||
networks:
|
||||
default:
|
||||
# любое значение POSTGRES_HOST указывает на этот сервис
|
||||
aliases:
|
||||
- ${POSTGRES_HOST:-postgres}
|
||||
healthcheck:
|
||||
# по TCP, а не через сокет: при инициализации образ поднимает
|
||||
# временный сервер только на сокете, и проверка через сокет
|
||||
# сказала бы «готов» раньше времени. $$ — переменная контейнера
|
||||
test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U \"$$POSTGRES_USER\" -d \"$$POSTGRES_DB\""]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
start_period: 30s
|
||||
start_interval: 1s
|
||||
|
||||
migrate:
|
||||
# образ собирает сервис api (make run_docker, make test_isolated)
|
||||
image: mtusi-messenger:lab2
|
||||
pull_policy: never
|
||||
command: ["alembic", "upgrade", "head"]
|
||||
restart: "no"
|
||||
environment: *app-env
|
||||
volumes:
|
||||
- *config-toml
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
api:
|
||||
build: .
|
||||
# тот же тег, что у docker build из README и make run_no_compose
|
||||
image: mtusi-messenger:lab2
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
# только localhost: стенд учебный
|
||||
- "127.0.0.1:${APP_OUT_PORT:-8080}:${APP__PORT:-8080}"
|
||||
environment:
|
||||
- APP__RUN_MODE=docker
|
||||
- APP__PORT=${APP__PORT:-8080}
|
||||
environment: *app-env
|
||||
volumes:
|
||||
# длинная запись: без файла запуск падает, а не создаёт каталог
|
||||
- type: bind
|
||||
source: ./config.toml
|
||||
target: /app/config.toml
|
||||
read_only: true
|
||||
bind:
|
||||
create_host_path: false
|
||||
- *config-toml
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
# healthcheck — из образа; SIGKILL не раньше, чем через 10 с
|
||||
stop_grace_period: 10s
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
|
||||
Reference in New Issue
Block a user