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
+68
View File
@@ -0,0 +1,68 @@
"""Окружение alembic: асинхронный шаблон, URL и журнал — из приложения.
URL берётся из `settings.database.url` и не проходит через ConfigParser
alembic, поэтому `%` в пароле ничего не ломает. Журнал — JSON через
`src/infra/logger.py`, как у сервиса. Асинхронное здесь только
подключение: ревизии остаются синхронным кодом `op.*`.
"""
import asyncio
from alembic import context
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import create_async_engine
from src.config import settings
from src.infra.db.models import Base
from src.infra.logger import AbstractLogger, get_logger
logger: AbstractLogger = get_logger().bind(module="migrations")
target_metadata = Base.metadata
def run_migrations_offline() -> None:
"""SQL без подключения: `alembic upgrade head --sql`."""
context.configure(
url=settings.database.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:
database = settings.database
# адрес и имя базы — чтобы по журналу было видно, какую базу мигрировали
logger.info(
"Running alembic",
host=database.host,
port=database.port,
database=database.name,
)
engine = create_async_engine(
database.url,
poolclass=pool.NullPool,
connect_args={"timeout": database.connect_timeout_seconds},
)
try:
async with engine.connect() as connection:
await connection.run_sync(do_run_migrations)
finally:
await engine.dispose()
logger.info("Finished alembic", database=database.name)
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_async_migrations())
+27
View File
@@ -0,0 +1,27 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: str | Sequence[str] | None = ${repr(down_revision)}
branch_labels: str | Sequence[str] | None = ${repr(branch_labels)}
depends_on: 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,127 @@
"""added messenger tables
Revision ID: 16c279725564
Revises:
Create Date: 2026-10-01 01:35:56.145855
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "16c279725564"
down_revision: str | Sequence[str] | None = None
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
# CHECK записаны литералами, а не константами src: применённая
# ревизия не должна меняться вместе с кодом
op.create_table(
"chats",
sa.Column("id", sa.Uuid(), nullable=False),
sa.Column("title", sa.Text(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.CheckConstraint(
"char_length(title) BETWEEN 1 AND 100",
name=op.f("ck_chats_title_length"),
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_chats")),
)
op.create_table(
"users",
sa.Column("id", sa.Uuid(), nullable=False),
sa.Column("username", sa.Text(), nullable=False),
sa.Column("display_name", sa.Text(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.CheckConstraint(
"username ~ '^[a-z0-9_]{3,32}$'",
name=op.f("ck_users_username_format"),
),
sa.CheckConstraint(
"char_length(display_name) BETWEEN 1 AND 100",
name=op.f("ck_users_display_name_length"),
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_users")),
sa.UniqueConstraint("username", name=op.f("uq_users_username")),
)
op.create_table(
"chat_members",
sa.Column("chat_id", sa.Uuid(), nullable=False),
sa.Column("user_id", sa.Uuid(), nullable=False),
sa.Column("position", sa.SmallInteger(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.CheckConstraint(
"position >= 0",
name=op.f("ck_chat_members_position_non_negative"),
),
sa.ForeignKeyConstraint(
["chat_id"],
["chats.id"],
name=op.f("fk_chat_members_chat_id_chats"),
),
sa.ForeignKeyConstraint(
["user_id"],
["users.id"],
name=op.f("fk_chat_members_user_id_users"),
),
sa.PrimaryKeyConstraint(
"chat_id",
"user_id",
name=op.f("pk_chat_members"),
),
sa.UniqueConstraint(
"chat_id",
"position",
name=op.f("uq_chat_members_chat_id_position"),
),
)
op.create_index(
op.f("ix_chat_members_user_id_created_at_chat_id"),
"chat_members",
["user_id", "created_at", "chat_id"],
unique=False,
)
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.Text(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.CheckConstraint(
"char_length(text) BETWEEN 1 AND 4000",
name=op.f("ck_messages_text_length"),
),
sa.ForeignKeyConstraint(
["chat_id", "sender_id"],
["chat_members.chat_id", "chat_members.user_id"],
name=op.f("fk_messages_chat_id_sender_id_chat_members"),
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_messages")),
)
op.create_index(
op.f("ix_messages_chat_id_created_at_id"),
"messages",
["chat_id", "created_at", "id"],
unique=False,
)
def downgrade() -> None:
op.drop_index(
op.f("ix_messages_chat_id_created_at_id"),
table_name="messages",
)
op.drop_table("messages")
op.drop_index(
op.f("ix_chat_members_user_id_created_at_chat_id"),
table_name="chat_members",
)
op.drop_table("chat_members")
op.drop_table("users")
op.drop_table("chats")