Files
mtusi2026labs/src/messenger/migrate.py
T
ArtyomandClaude Opus 5.5 5ae3d77152 Carry over the lab 5 solution
Bring the application, own tests, Dockerfile, toolchain, compose stack,
HAProxy, k6, RustFS and RabbitMQ configuration, migrations, hooks,
scenario scripts and the CI job from the lab 5 solution commit 64d5c67,
keep the lab 5 Makefile targets on top of the unchanged skeleton
targets, and append the lab 5 solution variables to the skeleton
.env.example. The package and the application follow the contract
version 1.6.0, and the image, the throwaway test containers and the
broker vhost description are tagged lab6 so they do not collide with a
lab 5 stand on the same host.

This is the starting point of the lab 6 cycle: lint, own tests and the
offline skeleton check pass before any lab 6 change.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-29 03:51:58 +03:00

71 lines
2.3 KiB
Python

import asyncio
import hashlib
from importlib import resources
import asyncpg
from messenger.shared.config import PlatformSettings
from messenger.shared.infrastructure.logging import PLATFORM_FIELDS, StructlogLogger
LOCK_KEY = 20_260_002
JOURNAL = """
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
checksum text NOT NULL,
applied_at timestamptz NOT NULL DEFAULT now()
)
"""
class MigrationChangedError(Exception):
pass
def migrations() -> list[tuple[str, str]]:
folder = resources.files("messenger") / "migrations"
found = (item for item in folder.iterdir() if item.name.endswith(".sql"))
return sorted((item.name.removesuffix(".sql"), item.read_text()) for item in found)
async def migrate(dsn: str) -> list[str]:
connection = await asyncpg.connect(dsn, timeout=10)
try:
await connection.execute("SELECT pg_advisory_lock($1)", LOCK_KEY)
await connection.execute(JOURNAL)
applied = dict(await connection.fetch("SELECT version, checksum FROM schema_migrations"))
done: list[str] = []
for version, sql in migrations():
checksum = hashlib.sha256(sql.encode()).hexdigest()
if version in applied:
if applied[version] != checksum:
raise MigrationChangedError(version)
continue
async with connection.transaction():
await connection.execute(sql)
await connection.execute(
"INSERT INTO schema_migrations (version, checksum) VALUES ($1, $2)",
version,
checksum,
)
done.append(version)
return done
finally:
await connection.close()
def main() -> None:
settings = PlatformSettings()
logger = StructlogLogger(level=settings.log_level, allowed_fields=PLATFORM_FIELDS | {"version"})
try:
done = asyncio.run(migrate(settings.database_url.get_secret_value()))
except MigrationChangedError as error:
logger.error("migration.changed", version=str(error))
raise SystemExit(1) from None
for version in done:
logger.info("migration.applied", version=version)
logger.info("migration.completed", reason="up to date" if not done else "applied")
if __name__ == "__main__":
main()