forked from mtusi2026/mtusi2026lab4
Bring the application, own tests, Dockerfile, toolchain, compose stack, HAProxy and k6 configuration, migrations, hooks, evidence and level 4 scripts and the CI job from the lab 3 solution commit 61c0c28, merge the lab 3 Makefile targets into the lab 4 skeleton Makefile without touching its targets, and append the lab 3 solution variables to the skeleton .env.example. The package and the application follow the contract version 1.4.0, and the image and the throwaway test containers are tagged lab4 so they do not collide with a lab 3 stand on the same host. This is the starting point of the lab 4 cycle: lint, own tests and the offline skeleton check pass before any lab 4 change. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
71 lines
2.3 KiB
Python
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()
|