Files
mtusi2026lab5/migrations/versions/0004_async_pipeline.py
T
2026-11-20 20:11:39 +03:00

293 lines
12 KiB
Python

"""Асинхронный 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")