Files
mtusi2026lab7-safronov/migrations/env.py
T
ricoromaandClaude Opus 5.5 8bca5543fd feat: require TLS to PostgreSQL, Valkey and S3
Storage servers accept only TLS 1.3 (pg_hba hostssl / hostnossl reject,
Valkey port 0, S3 gateway HTTPS only) with stand identities postgres,
valkey and s3. Clients trust only the stand CA from [client_tls] ca_file
and check the host name; no switch to disable verification. Processes
exit with code 2 without a CA or with an IP storage address. Temporary
stands, CI and bench/ run on TLS storages; make storage_tls_check adds
negative checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:17:49 +03:00

85 lines
3.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Окружение 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
from src.infra.tls import (
MIGRATION_STORAGES,
build_client_context,
client_tls_problems,
)
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
# TLS к PostgreSQL (change storage-tls, design, решение 5): CA стенда и
# имя хоста — до подключения; поля без значений, ненулевой код — реплики
# ждут миграций и не стартуют
problems = client_tls_problems(settings, MIGRATION_STORAGES)
if problems:
logger.error("Invalid client TLS settings", fields=problems)
raise SystemExit(2)
# адрес и имя базы — чтобы по журналу было видно, какую базу мигрировали
logger.info(
"Running alembic",
host=database.host,
port=database.port,
database=database.name,
)
engine = create_async_engine(
database.url,
poolclass=pool.NullPool,
# с SSLContext asyncpg требует TLS (verify-full по CA стенда и имени)
connect_args={
"timeout": database.connect_timeout_seconds,
"ssl": build_client_context(settings.client_tls.ca_file),
},
)
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())