Forward the lab 4 foundation and migrate the lab 5 pipeline to SQLAlchemy

This commit is contained in:
Artyom
2026-11-06 09:12:25 +03:00
parent ae9f60fe1f
commit 1217da5f5e
134 changed files with 8243 additions and 1409 deletions
+57 -15
View File
@@ -1,5 +1,6 @@
import asyncio
import re
import socket
import subprocess
import time
from base64 import b64encode
@@ -9,19 +10,23 @@ 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.ext.asyncio import AsyncConnection, create_async_engine
from sqlalchemy.pool import NullPool
from fakes import MemoryStorageProvider
from messenger.attachments.config import AttachmentsSettings
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
from messenger.shared.infrastructure.postgres import unavailable
ROOT = Path(__file__).resolve().parents[1]
POSTGRES_IMAGE = re.compile(r"image: (postgres:\S+)")
@@ -38,18 +43,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:
if time.monotonic() > deadline:
except Exception as error:
if not unavailable(error) or 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(25000, 26000):
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 25000–25999")
@pytest.fixture(autouse=True)
def database_for_api(request: pytest.FixtureRequest) -> None:
if "api" in request.node.path.parts:
@@ -78,7 +118,7 @@ def answering(name: str, *probe: str) -> bool:
@pytest.fixture(scope="session")
def valkey() -> Iterator[dict[str, str]]:
name = f"mtusi-lab5-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"):
@@ -86,7 +126,7 @@ def valkey() -> Iterator[dict[str, str]]:
time.sleep(0.2)
yield {"name": name, "url": f"redis://127.0.0.1:{published(name, 6379)}/0"}
finally:
subprocess.run(["docker", "rm", "-f", name], capture_output=True, check=False)
subprocess.run(["docker", "rm", "-fv", name], capture_output=True, check=False)
@pytest.fixture(scope="session")
@@ -94,14 +134,16 @@ def database() -> Iterator[str]:
name = f"mtusi-lab5-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))
DATABASE["url"] = dsn
yield dsn
finally:
subprocess.run(["docker", "rm", "-f", name], capture_output=True, check=False)
subprocess.run(["docker", "rm", "-fv", name], capture_output=True, check=False)
def split_settings(**overrides: Any) -> dict[str, Any]:
@@ -152,12 +194,12 @@ 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, *args: Any) -> Any:
async with sql_connection() as connection:
if isinstance(statement, str):
result = await connection.exec_driver_sql(statement, args)
return result.scalar() if result.returns_rows else None
return await connection.scalar(statement)
def basic(username: str, password: str) -> dict[str, str]: