This commit is contained in:
2026-11-20 20:11:39 +03:00
parent 276dbdad8a
commit b4d667532f
116 changed files with 11777 additions and 40 deletions
+58
View File
@@ -0,0 +1,58 @@
"""Окружение Alembic: URL базы берётся из тех же переменных, что и у приложения."""
from __future__ import annotations
import asyncio
from logging.config import fileConfig
from alembic import context
from sqlalchemy import pool
from sqlalchemy.ext.asyncio import async_engine_from_config
from messenger.config import database_url_from_env
from messenger.schema import METADATA
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# Сравнение идёт ровно с теми объектами, по которым работает приложение:
# расхождение между схемой и миграциями ловится на `alembic check`.
target_metadata = METADATA
def run_migrations_offline() -> None:
"""Режим без подключения: печатает SQL миграции, удобен для ревью."""
context.configure(
url=database_url_from_env(),
target_metadata=target_metadata,
literal_binds=True,
compare_type=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def _run_migrations(connection) -> None:
context.configure(connection=connection, target_metadata=target_metadata, compare_type=True)
with context.begin_transaction():
context.run_migrations()
async def run_migrations_online() -> None:
"""Драйвер асинхронный (asyncpg), поэтому миграции идут через run_sync."""
section = config.get_section(config.config_ini_section, {})
section["sqlalchemy.url"] = database_url_from_env()
engine = async_engine_from_config(section, prefix="sqlalchemy.", poolclass=pool.NullPool)
try:
async with engine.connect() as connection:
await connection.run_sync(_run_migrations)
finally:
await engine.dispose()
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_migrations_online())
+24
View File
@@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
+103
View File
@@ -0,0 +1,103 @@
"""Начальная схема: пользователи, чаты, участники и сообщения
Revision ID: 0001_initial_schema
Revises:
Create Date: 2026-10-11
DDL написан вручную и повторяет src/messenger/schema.py: имена ограничений
и индексов совпадают, поэтому `alembic check` не находит расхождений между
схемой в базе и описанием, по которому работают запросы.
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision = "0001_initial_schema"
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"users",
sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("username", sa.Text(), nullable=False),
sa.Column("display_name", sa.Text(), nullable=False),
sa.Column("password_hash", sa.Text(), nullable=False),
sa.Column(
"created_at",
postgresql.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.CheckConstraint(
"char_length(display_name) BETWEEN 1 AND 100", name="ck_users_display_name_length"
),
sa.CheckConstraint(r"username ~ '^[a-z0-9_]{3,32}$'", name="ck_users_username_format"),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("username", name="uq_users_username"),
)
op.create_table(
"chats",
sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("title", sa.Text(), nullable=False),
sa.Column(
"created_at",
postgresql.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.CheckConstraint("char_length(title) BETWEEN 1 AND 100", name="ck_chats_title_length"),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"chat_members",
sa.Column("chat_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("user_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.ForeignKeyConstraint(
["chat_id"], ["chats.id"], name="fk_chat_members_chat", ondelete="CASCADE"
),
sa.ForeignKeyConstraint(
["user_id"], ["users.id"], name="fk_chat_members_user", ondelete="RESTRICT"
),
sa.PrimaryKeyConstraint("chat_id", "user_id"),
)
op.create_index("ix_chat_members_user_id_chat_id", "chat_members", ["user_id", "chat_id"])
op.create_table(
"messages",
sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("chat_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("sender_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("text", sa.Text(), nullable=False),
sa.Column(
"created_at",
postgresql.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.CheckConstraint(
"text <> '' AND char_length(text) <= 4000", name="ck_messages_text_length"
),
sa.ForeignKeyConstraint(["chat_id"], ["chats.id"], name="fk_messages_chat", ondelete="CASCADE"),
sa.ForeignKeyConstraint(
["sender_id"], ["users.id"], name="fk_messages_sender", ondelete="RESTRICT"
),
sa.PrimaryKeyConstraint("id"),
)
# Порядок истории (created_at, id) и keyset-предикат обслуживает один индекс.
op.create_index("ix_messages_chat_id_created_at_id", "messages", ["chat_id", "created_at", "id"])
def downgrade() -> None:
op.drop_index("ix_messages_chat_id_created_at_id", table_name="messages")
op.drop_table("messages")
op.drop_index("ix_chat_members_user_id_chat_id", table_name="chat_members")
op.drop_table("chat_members")
op.drop_table("chats")
op.drop_table("users")
@@ -0,0 +1,61 @@
"""Общая идемпотентность отправки сообщения
Revision ID: 0002_message_idempotency
Revises: 0001_initial_schema
Create Date: 2026-10-30
Таблица описана в src/messenger/schema.py; DDL повторяет имена ограничений и
индексов, чтобы alembic check не находил расхождений.
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision = "0002_message_idempotency"
down_revision = "0001_initial_schema"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"message_idempotency",
sa.Column("user_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("chat_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("idempotency_key", sa.Text(), nullable=False),
sa.Column("request_hash", sa.Text(), nullable=False),
sa.Column("message_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column(
"created_at",
postgresql.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.CheckConstraint(
"char_length(idempotency_key) BETWEEN 1 AND 128",
name="ck_message_idempotency_key_length",
),
sa.ForeignKeyConstraint(
["chat_id"], ["chats.id"], name="fk_message_idempotency_chat", ondelete="CASCADE"
),
sa.ForeignKeyConstraint(
["message_id"],
["messages.id"],
name="fk_message_idempotency_message",
ondelete="CASCADE",
),
sa.ForeignKeyConstraint(
["user_id"], ["users.id"], name="fk_message_idempotency_user", ondelete="CASCADE"
),
sa.PrimaryKeyConstraint("user_id", "chat_id", "idempotency_key"),
)
op.create_index(
"ix_message_idempotency_created_at", "message_idempotency", ["created_at"]
)
def downgrade() -> None:
op.drop_index("ix_message_idempotency_created_at", table_name="message_idempotency")
op.drop_table("message_idempotency")
+128
View File
@@ -0,0 +1,128 @@
"""Вложения и связь сообщений с вложениями
Revision ID: 0003_attachments
Revises: 0002_message_idempotency
Create Date: 2026-11-06
DDL повторяет src/messenger/schema.py, включая имена ограничений и индексов,
поэтому `alembic check` не находит расхождений. Отдельно ослабляется CHECK
текста сообщения: пустая строка теперь допустима только вместе с вложением,
а это правило проверяет API (CHECK не может ссылаться на другую таблицу).
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision = "0003_attachments"
down_revision = "0002_message_idempotency"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"attachments",
sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("chat_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("owner_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("object_key", sa.Text(), nullable=False),
sa.Column("filename", sa.Text(), nullable=False),
sa.Column("content_type", sa.Text(), nullable=False),
sa.Column("size_bytes", sa.BigInteger(), nullable=False),
sa.Column("sha256", sa.Text(), nullable=False),
sa.Column("status", sa.Text(), server_default=sa.text("'pending'"), nullable=False),
sa.Column("error_code", sa.Text(), nullable=True),
sa.Column(
"created_at",
postgresql.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.Column(
"updated_at",
postgresql.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.CheckConstraint(
"char_length(filename) BETWEEN 1 AND 255", name="ck_attachments_filename_length"
),
sa.CheckConstraint(
"content_type IN ('image/png','image/jpeg')", name="ck_attachments_content_type"
),
sa.CheckConstraint(
"size_bytes > 0 AND size_bytes <= 10485760", name="ck_attachments_size_bytes"
),
sa.CheckConstraint("sha256 ~ '^[a-f0-9]{64}$'", name="ck_attachments_sha256"),
sa.CheckConstraint(
"status IN ('pending','ready','failed')", name="ck_attachments_status"
),
sa.CheckConstraint(
"error_code IS NULL OR char_length(error_code) BETWEEN 1 AND 64",
name="ck_attachments_error_code",
),
sa.ForeignKeyConstraint(
["chat_id"], ["chats.id"], name="fk_attachments_chat", ondelete="CASCADE"
),
sa.ForeignKeyConstraint(
["owner_id"], ["users.id"], name="fk_attachments_owner", ondelete="RESTRICT"
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("object_key", name="uq_attachments_object_key"),
)
op.create_index(
"ix_attachments_chat_id_created_at_id",
"attachments",
["chat_id", "created_at", "id"],
)
op.create_index("ix_attachments_status_updated_at", "attachments", ["status", "updated_at"])
op.create_table(
"message_attachments",
sa.Column("message_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("attachment_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("position", sa.SmallInteger(), nullable=False),
sa.CheckConstraint(
"position >= 0 AND position < 10", name="ck_message_attachments_position"
),
sa.ForeignKeyConstraint(
["attachment_id"],
["attachments.id"],
name="fk_message_attachments_attachment",
ondelete="RESTRICT",
),
sa.ForeignKeyConstraint(
["message_id"],
["messages.id"],
name="fk_message_attachments_message",
ondelete="CASCADE",
),
sa.PrimaryKeyConstraint("message_id", "attachment_id"),
sa.UniqueConstraint(
"message_id", "position", name="uq_message_attachments_position"
),
)
op.create_index(
"ix_message_attachments_attachment_id",
"message_attachments",
["attachment_id"],
)
op.drop_constraint("ck_messages_text_length", "messages", type_="check")
op.create_check_constraint(
"ck_messages_text_length", "messages", "char_length(text) <= 4000"
)
def downgrade() -> None:
op.drop_constraint("ck_messages_text_length", "messages", type_="check")
op.create_check_constraint(
"ck_messages_text_length", "messages", "text <> '' AND char_length(text) <= 4000"
)
op.drop_index("ix_message_attachments_attachment_id", table_name="message_attachments")
op.drop_table("message_attachments")
op.drop_index("ix_attachments_status_updated_at", table_name="attachments")
op.drop_index("ix_attachments_chat_id_created_at_id", table_name="attachments")
op.drop_table("attachments")
+292
View File
@@ -0,0 +1,292 @@
"""Асинхронный pipeline: staging, jobs, outbox, варианты и аудит
Revision ID: 0004_async_pipeline
Revises: 0003_attachments
Create Date: 2026-11-20
DDL повторяет src/messenger/schema.py, включая имена ограничений и индексов.
Существующие lab4-вложения трактуются консервативно: staging_key сбрасывается
в прежний object_key, завершённые ready-строки сохраняются, а незавершённые
pending-строки помечаются failed с безопасным error_code.
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision = "0004_async_pipeline"
down_revision = "0003_attachments"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("attachments", sa.Column("staging_key", sa.Text(), nullable=True))
op.add_column(
"attachments",
sa.Column("pipeline_version", sa.Integer(), server_default=sa.text("0"), nullable=False),
)
op.add_column(
"attachments",
sa.Column("ready_at", postgresql.TIMESTAMP(timezone=True), nullable=True),
)
op.execute("UPDATE attachments SET staging_key = object_key WHERE staging_key IS NULL")
op.alter_column("attachments", "staging_key", nullable=False)
op.create_unique_constraint("uq_attachments_staging_key", "attachments", ["staging_key"])
op.drop_constraint("ck_attachments_status", "attachments", type_="check")
op.execute(
"UPDATE attachments SET status = 'failed', error_code = 'legacy_pending' "
"WHERE status = 'pending'"
)
op.alter_column(
"attachments", "status", server_default=sa.text("'queued'"), existing_type=sa.Text()
)
op.create_check_constraint(
"ck_attachments_status",
"attachments",
"status IN ('queued','processing','ready','failed')",
)
op.create_check_constraint(
"ck_attachments_pipeline_version", "attachments", "pipeline_version >= 0"
)
op.create_table(
"jobs",
sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("attachment_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("pipeline_version", sa.Integer(), nullable=False),
sa.Column(
"type",
sa.Text(),
server_default=sa.text("'attachment.process.v1'"),
nullable=False,
),
sa.Column("state", sa.Text(), server_default=sa.text("'queued'"), nullable=False),
sa.Column("attempts", sa.Integer(), server_default=sa.text("0"), nullable=False),
sa.Column("max_attempts", sa.Integer(), nullable=False),
sa.Column("lease_token", postgresql.UUID(as_uuid=True), nullable=True),
sa.Column("worker_id", sa.Text(), nullable=True),
sa.Column(
"lease_expires_at", postgresql.TIMESTAMP(timezone=True), nullable=True
),
sa.Column("next_attempt_at", postgresql.TIMESTAMP(timezone=True), nullable=True),
sa.Column("last_error_code", sa.Text(), nullable=True),
sa.Column("replay_of", postgresql.UUID(as_uuid=True), nullable=True),
sa.Column(
"created_at",
postgresql.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.Column(
"updated_at",
postgresql.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.Column("finished_at", postgresql.TIMESTAMP(timezone=True), nullable=True),
sa.CheckConstraint("pipeline_version >= 1", name="ck_jobs_pipeline_version"),
sa.CheckConstraint(
"state IN ('queued','processing','ready','failed','superseded')",
name="ck_jobs_state",
),
sa.CheckConstraint("attempts >= 0", name="ck_jobs_attempts"),
sa.CheckConstraint("max_attempts >= 1", name="ck_jobs_max_attempts"),
sa.CheckConstraint(
"last_error_code IS NULL OR char_length(last_error_code) BETWEEN 1 AND 64",
name="ck_jobs_last_error_code",
),
sa.ForeignKeyConstraint(
["attachment_id"], ["attachments.id"], name="fk_jobs_attachment", ondelete="CASCADE"
),
sa.ForeignKeyConstraint(
["replay_of"], ["jobs.id"], name="fk_jobs_replay_of", ondelete="SET NULL"
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index("ix_jobs_attachment_id", "jobs", ["attachment_id"])
op.create_index("ix_jobs_state_next_attempt_at", "jobs", ["state", "next_attempt_at"])
op.create_index("ix_jobs_lease_expires_at", "jobs", ["lease_expires_at"])
op.create_index(
"uq_jobs_initial_attachment_version",
"jobs",
["attachment_id", "pipeline_version"],
unique=True,
postgresql_where=sa.text("replay_of IS NULL"),
)
op.create_table(
"outbox",
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
sa.Column("job_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column(
"available_at",
postgresql.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.Column("published_at", postgresql.TIMESTAMP(timezone=True), nullable=True),
sa.Column("attempts", sa.Integer(), server_default=sa.text("0"), nullable=False),
sa.Column("last_error", sa.Text(), nullable=True),
sa.Column(
"created_at",
postgresql.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.ForeignKeyConstraint(
["job_id"], ["jobs.id"], name="fk_outbox_job", ondelete="CASCADE"
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index("ix_outbox_due", "outbox", ["published_at", "available_at"])
op.create_index(
"uq_outbox_pending_job",
"outbox",
["job_id"],
unique=True,
postgresql_where=sa.text("published_at IS NULL"),
)
op.create_table(
"variants",
sa.Column("attachment_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("pipeline_version", sa.Integer(), nullable=False),
sa.Column("name", sa.Text(), nullable=False),
sa.Column("content_type", sa.Text(), nullable=False),
sa.Column("object_key", sa.Text(), nullable=False),
sa.Column("size_bytes", sa.BigInteger(), nullable=False),
sa.Column("sha256", sa.Text(), nullable=False),
sa.Column("width", sa.Integer(), nullable=False),
sa.Column("height", sa.Integer(), nullable=False),
sa.Column(
"created_at",
postgresql.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.CheckConstraint("pipeline_version >= 1", name="ck_variants_pipeline_version"),
sa.CheckConstraint("name IN ('thumbnail','crop','optimized')", name="ck_variants_name"),
sa.CheckConstraint(
"content_type IN ('image/jpeg','image/png','image/webp')",
name="ck_variants_content_type",
),
sa.CheckConstraint("size_bytes > 0", name="ck_variants_size_bytes"),
sa.CheckConstraint("width > 0 AND height > 0", name="ck_variants_dimensions"),
sa.CheckConstraint("sha256 ~ '^[a-f0-9]{64}$'", name="ck_variants_sha256"),
sa.ForeignKeyConstraint(
["attachment_id"],
["attachments.id"],
name="fk_variants_attachment",
ondelete="CASCADE",
),
sa.PrimaryKeyConstraint("attachment_id", "pipeline_version", "name"),
sa.UniqueConstraint("object_key", name="uq_variants_object_key"),
)
op.create_index("ix_variants_attachment_id", "variants", ["attachment_id"])
op.create_table(
"job_events",
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
sa.Column("job_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("from_state", sa.Text(), nullable=True),
sa.Column("to_state", sa.Text(), nullable=False),
sa.Column("attempt", sa.Integer(), nullable=True),
sa.Column("error_code", sa.Text(), nullable=True),
sa.Column("worker_id", sa.Text(), nullable=True),
sa.Column("detail", sa.Text(), nullable=True),
sa.Column(
"created_at",
postgresql.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.ForeignKeyConstraint(
["job_id"], ["jobs.id"], name="fk_job_events_job", ondelete="CASCADE"
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index("ix_job_events_job_id_created_at", "job_events", ["job_id", "created_at"])
op.create_table(
"job_replays",
sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("source_job_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("replay_job_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("requested_by", sa.Text(), nullable=False),
sa.Column("reason", sa.Text(), nullable=False),
sa.Column(
"created_at",
postgresql.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.CheckConstraint(
"char_length(requested_by) BETWEEN 1 AND 128",
name="ck_job_replays_requested_by",
),
sa.CheckConstraint("char_length(reason) BETWEEN 1 AND 512", name="ck_job_replays_reason"),
sa.ForeignKeyConstraint(
["replay_job_id"],
["jobs.id"],
name="fk_job_replays_replay",
ondelete="CASCADE",
),
sa.ForeignKeyConstraint(
["source_job_id"],
["jobs.id"],
name="fk_job_replays_source",
ondelete="CASCADE",
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("replay_job_id", name="uq_job_replays_replay_job"),
)
op.create_table(
"fault_flags",
sa.Column("kind", sa.Text(), nullable=False),
sa.Column("remaining", sa.Integer(), nullable=False),
sa.Column(
"updated_at",
postgresql.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.CheckConstraint("remaining >= 0", name="ck_fault_flags_remaining"),
sa.PrimaryKeyConstraint("kind"),
)
def downgrade() -> None:
op.drop_table("fault_flags")
op.drop_table("job_replays")
op.drop_index("ix_job_events_job_id_created_at", table_name="job_events")
op.drop_table("job_events")
op.drop_index("ix_variants_attachment_id", table_name="variants")
op.drop_table("variants")
op.drop_index("uq_outbox_pending_job", table_name="outbox")
op.drop_index("ix_outbox_due", table_name="outbox")
op.drop_table("outbox")
op.drop_index("uq_jobs_initial_attachment_version", table_name="jobs")
op.drop_index("ix_jobs_lease_expires_at", table_name="jobs")
op.drop_index("ix_jobs_state_next_attempt_at", table_name="jobs")
op.drop_index("ix_jobs_attachment_id", table_name="jobs")
op.drop_table("jobs")
op.drop_constraint("ck_attachments_pipeline_version", "attachments", type_="check")
op.drop_constraint("ck_attachments_status", "attachments", type_="check")
op.execute("UPDATE attachments SET status = 'pending' WHERE status = 'failed'")
op.create_check_constraint(
"ck_attachments_status",
"attachments",
"status IN ('pending','ready','failed')",
)
op.alter_column(
"attachments", "status", server_default=sa.text("'pending'"), existing_type=sa.Text()
)
op.drop_constraint("uq_attachments_staging_key", "attachments", type_="unique")
op.drop_column("attachments", "ready_at")
op.drop_column("attachments", "pipeline_version")
op.drop_column("attachments", "staging_key")