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>
69 lines
2.3 KiB
Python
69 lines
2.3 KiB
Python
"""Окружение 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())
|