Adopt async SQLAlchemy storage and verified Alembic migrations

Keep the message and idempotency receipt in one Core CTE statement with chat-first locking. Preserve rollback, bounded dependency failures, and domain ports.

Replace the SQL runner with Alembic. Adopt legacy databases only after validating their journal and PostgreSQL schema, retain all data, and verify migrations on fresh and populated databases.
This commit is contained in:
Artyom
2026-11-05 21:38:12 +03:00
parent c376882ce8
commit 71c643c6d1
29 changed files with 1542 additions and 409 deletions
+51 -12
View File
@@ -1,5 +1,6 @@
import asyncio
import re
import socket
import subprocess
import time
from base64 import b64encode
@@ -9,15 +10,19 @@ from pathlib import Path
from typing import Any
from uuid import uuid4
import asyncpg
import pytest
from alembic import command
from alembic.config import Config
from fastapi import FastAPI
from httpx import ASGITransport, AsyncClient
from sqlalchemy import make_url
from sqlalchemy.exc import DBAPIError
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
from sqlalchemy.pool import NullPool
from messenger.identity.config import IdentitySettings
from messenger.main import create_app
from messenger.messaging.config import MessagingSettings
from messenger.migrate import migrate
from messenger.shared.config import PlatformSettings
from messenger.shared.entrypoints.config import TransportSettings
@@ -36,18 +41,53 @@ def docker(*args: str) -> str:
return done.stdout.strip()
def migration_config(dsn: str) -> Config:
config = Config(str(ROOT / "alembic.ini"))
config.attributes["database_url"] = dsn
return config
async def upgrade(dsn: str, revision: str = "head") -> None:
await asyncio.to_thread(command.upgrade, migration_config(dsn), revision)
async def migrated(dsn: str) -> None:
deadline = time.monotonic() + STARTUP_SECONDS
while True:
try:
await migrate(dsn)
await upgrade(dsn)
return
except OSError, asyncpg.PostgresError, asyncpg.InterfaceError:
except OSError, DBAPIError:
if time.monotonic() > deadline:
raise
await asyncio.sleep(0.5)
@asynccontextmanager
async def sql_connection(dsn: str | None = None) -> AsyncIterator[AsyncConnection]:
engine = create_async_engine(
make_url(dsn or DATABASE["url"]).set(drivername="postgresql+asyncpg"),
poolclass=NullPool,
hide_parameters=True,
)
try:
async with engine.begin() as connection:
yield connection
finally:
await engine.dispose()
def free_port() -> int:
for port in range(23000, 24000):
with socket.socket() as probe:
try:
probe.bind(("127.0.0.1", port))
return port
except OSError:
continue
raise RuntimeError("No free test port in 23000–23999")
@pytest.fixture(autouse=True)
def database_for_api(request: pytest.FixtureRequest) -> None:
if "api" in request.node.path.parts:
@@ -76,7 +116,7 @@ def answering(name: str, *probe: str) -> bool:
@pytest.fixture(scope="session")
def valkey() -> Iterator[dict[str, str]]:
name = f"mtusi-lab3-test-valkey-{uuid4().hex[:8]}"
container(name, "-p", "127.0.0.1::6379", image(VALKEY_IMAGE))
container(name, "-p", f"127.0.0.1:{free_port()}:6379", image(VALKEY_IMAGE))
try:
deadline = time.monotonic() + STARTUP_SECONDS
while not answering(name, "valkey-cli", "ping"):
@@ -92,7 +132,9 @@ def database() -> Iterator[str]:
name = f"mtusi-lab3-test-{uuid4().hex[:8]}"
tuning = ["-c", "fsync=off", "-c", "synchronous_commit=off", "-c", "full_page_writes=off"]
environment = ["-e", "POSTGRES_PASSWORD=test", "-e", "POSTGRES_DB=messenger"]
container(name, *environment, "-p", "127.0.0.1::5432", image(POSTGRES_IMAGE), *tuning)
container(
name, *environment, "-p", f"127.0.0.1:{free_port()}:5432", image(POSTGRES_IMAGE), *tuning
)
try:
dsn = f"postgresql://postgres:test@127.0.0.1:{published(name, 5432)}/messenger"
asyncio.run(migrated(dsn))
@@ -147,12 +189,9 @@ async def client() -> AsyncIterator[AsyncClient]:
yield http
async def scalar(sql: str, *args: Any) -> Any:
connection = await asyncpg.connect(DATABASE["url"])
try:
return await connection.fetchval(sql, *args)
finally:
await connection.close()
async def scalar(statement: Any) -> Any:
async with sql_connection() as connection:
return await connection.scalar(statement)
def basic(username: str, password: str) -> dict[str, str]: