included rabbitmq as broker

This commit is contained in:
2026-11-10 07:01:17 +03:00
parent 0a70358829
commit 2b9fb3f375
49 changed files with 3072 additions and 287 deletions
@@ -0,0 +1,21 @@
"""Offline cutover: повторно опубликовать queued jobs в RabbitMQ."""
from alembic import op
revision = "a62c950e18b3"
down_revision = "f9183d27a640"
branch_labels = None
depends_on = None
def upgrade() -> None:
# Старые publisher/worker остановлены. Processing восстановится по lease.
op.execute("""
UPDATE attachment_jobs j SET published_attempt = attempt
FROM attachments a WHERE a.id = j.attachment_id AND a.status = 'queued'
""")
def downgrade() -> None:
# При обратном переключении требуется такая же повторная публикация.
upgrade()
@@ -0,0 +1,62 @@
"""Lab5: состояния, варианты и устойчивые jobs с намерением публикации."""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
revision = "c35e91a2f706"
down_revision = "8f31b94a2d10"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.drop_constraint(op.f("ck_attachments_status"), "attachments", type_="check")
op.create_check_constraint(op.f("ck_attachments_status"), "attachments", "status IN ('queued', 'processing', 'ready', 'failed')")
op.alter_column("attachments", "status", server_default="queued")
op.add_column("attachments", sa.Column("error_code", sa.String(64), nullable=True))
op.add_column("attachments", sa.Column("thumbnail_key", sa.String(128), nullable=True))
op.add_column("attachments", sa.Column("variants", postgresql.JSONB(), nullable=False, server_default=sa.text("'[]'::jsonb")))
op.create_check_constraint(op.f("ck_attachments_error_code"), "attachments", "(status = 'failed' AND error_code IS NOT NULL) OR (status <> 'failed' AND error_code IS NULL)")
op.create_table(
"attachment_jobs",
sa.Column("id", sa.UUID(), nullable=False),
sa.Column("attachment_id", sa.UUID(), nullable=False),
sa.Column("staging_key", sa.String(128), nullable=True),
sa.Column("pipeline_version", sa.Integer(), server_default="1", nullable=False),
sa.Column("attempt", sa.Integer(), server_default="0", nullable=False),
sa.Column("published_attempt", sa.Integer(), server_default="0", nullable=False),
sa.Column("next_attempt_at", sa.DateTime(timezone=True), server_default=sa.text("clock_timestamp()"), nullable=False),
sa.Column("lease_token", sa.UUID(), nullable=True),
sa.Column("lease_until", sa.DateTime(timezone=True), nullable=True),
sa.Column("last_error_code", sa.String(64), nullable=True),
sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("clock_timestamp()"), nullable=False),
sa.PrimaryKeyConstraint("id", name=op.f("pk_attachment_jobs")),
sa.ForeignKeyConstraint(["attachment_id"], ["attachments.id"], name=op.f("fk_attachment_jobs_attachment_id_attachments")),
sa.UniqueConstraint("attachment_id", name=op.f("uq_attachment_jobs_attachment_id")),
sa.CheckConstraint("pipeline_version = 1", name=op.f("ck_attachment_jobs_pipeline_version")),
sa.CheckConstraint("attempt >= 0 AND published_attempt >= 0", name=op.f("ck_attachment_jobs_attempt")),
)
op.create_index("ix_attachment_jobs_due", "attachment_jobs", ["next_attempt_at"])
op.create_index("ix_attachment_jobs_lease", "attachment_jobs", ["lease_until"])
# Прежние оригиналы остаются источником; worker создаст отсутствующий thumbnail.
op.execute("INSERT INTO attachment_jobs (id, attachment_id, staging_key) SELECT id, id, object_key FROM attachments")
op.execute("UPDATE attachments SET status = 'queued', updated_at = clock_timestamp()")
def downgrade() -> None:
connection = op.get_bind()
unfinished = connection.scalar(sa.text("SELECT count(*) FROM attachments WHERE status <> 'ready'"))
if unfinished:
raise RuntimeError("Перед downgrade нужно завершить или вручную разобрать все queued/processing/failed вложения")
op.drop_index("ix_attachment_jobs_lease", table_name="attachment_jobs")
op.drop_index("ix_attachment_jobs_due", table_name="attachment_jobs")
op.drop_table("attachment_jobs")
op.drop_constraint(op.f("ck_attachments_error_code"), "attachments", type_="check")
op.drop_column("attachments", "variants")
op.drop_column("attachments", "thumbnail_key")
op.drop_column("attachments", "error_code")
op.drop_constraint(op.f("ck_attachments_status"), "attachments", type_="check")
op.create_check_constraint(op.f("ck_attachments_status"), "attachments", "status = 'ready'")
op.alter_column("attachments", "status", server_default="ready")
@@ -0,0 +1,49 @@
"""Уровень 4: ключи crop/WebP и дообработка старых ready-вложений."""
from alembic import op
import sqlalchemy as sa
revision = "e7048b6da913"
down_revision = "c35e91a2f706"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("attachments", sa.Column("crop_key", sa.String(128), nullable=True))
op.add_column("attachments", sa.Column("optimized_key", sa.String(128), nullable=True))
# Старый staging сменяется надёжным ready-оригиналом, но не теряется из журнала cleanup.
op.execute("""
INSERT INTO upload_intents (id, object_key)
SELECT gen_random_uuid(), j.staging_key
FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id
WHERE a.status = 'ready' AND j.staging_key IS NOT NULL
AND j.staging_key <> a.object_key
ON CONFLICT (object_key) DO NOTHING
""")
op.execute("""
UPDATE attachment_jobs j
SET staging_key = a.object_key, attempt = 0, published_attempt = 0,
next_attempt_at = clock_timestamp(), lease_token = NULL, lease_until = NULL,
last_error_code = NULL, finished_at = NULL
FROM attachments a
WHERE a.id = j.attachment_id AND a.status = 'ready'
""")
op.execute("""
UPDATE attachments SET status = 'queued', variants = '[]'::jsonb,
updated_at = clock_timestamp()
WHERE status = 'ready'
""")
def downgrade() -> None:
active = op.get_bind().scalar(sa.text("SELECT count(*) FROM attachments WHERE status IN ('queued', 'processing')"))
if active:
raise RuntimeError("Перед downgrade необходимо завершить активные задания")
op.execute("""
UPDATE attachments a SET variants = COALESCE(
(SELECT jsonb_agg(v) FROM jsonb_array_elements(a.variants) v
WHERE v->>'name' = 'thumbnail'), '[]'::jsonb)
""")
op.drop_column("attachments", "optimized_key")
op.drop_column("attachments", "crop_key")
@@ -0,0 +1,34 @@
"""Бюджет повторов и аудит операторского replay."""
from alembic import op
import sqlalchemy as sa
revision = "f9183d27a640"
down_revision = "e7048b6da913"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("attachment_jobs", sa.Column("cycle_start_attempt", sa.Integer(), nullable=False, server_default="0"))
op.add_column("attachment_jobs", sa.Column("attempt_limit", sa.Integer(), nullable=True))
op.add_column("attachment_jobs", sa.Column("last_error_permanent", sa.Boolean(), nullable=True))
op.create_table(
"job_replays",
sa.Column("id", sa.Uuid(), primary_key=True),
sa.Column("job_id", sa.Uuid(), sa.ForeignKey("attachment_jobs.id"), nullable=False),
sa.Column("actor", sa.String(64), nullable=False),
sa.Column("reason", sa.String(32), nullable=False),
sa.Column("previous_attempt", sa.Integer(), nullable=False),
sa.Column("attempt_limit", sa.Integer(), nullable=False),
sa.Column("previous_error_code", sa.String(64), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.clock_timestamp()),
)
op.create_index("ix_job_replays_job_id", "job_replays", ["job_id"])
def downgrade() -> None:
op.drop_table("job_replays")
op.drop_column("attachment_jobs", "last_error_permanent")
op.drop_column("attachment_jobs", "attempt_limit")
op.drop_column("attachment_jobs", "cycle_start_attempt")