223 lines
9.0 KiB
Python
223 lines
9.0 KiB
Python
"""attachment jobs, variants and replays
|
||
|
||
Revision ID: 0004
|
||
Revises: 0003
|
||
Create Date: 2026-11-05
|
||
|
||
Лаба 5: загрузка отвечает 202, обработку делает worker.
|
||
|
||
Что добавляется (только expand):
|
||
|
||
- у `attachments` — колонки `staging_key` и `error_code` (NULL),
|
||
статусы `queued`, `processing`, `failed`; оба CHECK заменяются с
|
||
`NOT VALID`: старые строки (`pending`, `ready`, без кода) новому условию
|
||
и так удовлетворяют;
|
||
- `attachment_jobs` — задание: outbox для relay, попытка, аренда,
|
||
backoff; `attachment_variants` — результат, первичный ключ = ключ
|
||
эффекта; `attachment_job_replays` — журнал ручных replay. Таблицы новые
|
||
и пустые: индексы на них — в той же транзакции;
|
||
- индекс уборки staging на `attachments` — `CONCURRENTLY` отдельным
|
||
шагом вне транзакции: таблица рабочая и может быть большой.
|
||
|
||
Реплики лабы 4 на этой схеме продолжают отвечать 201: заданий они не
|
||
пишут, их вложения сразу `ready` (KNOWN_ISSUES.md, «Смесь версий»).
|
||
"""
|
||
|
||
from collections.abc import Sequence
|
||
|
||
import sqlalchemy as sa
|
||
from alembic import op
|
||
|
||
revision: str = "0004"
|
||
down_revision: str | Sequence[str] | None = "0003"
|
||
branch_labels: str | Sequence[str] | None = None
|
||
depends_on: str | Sequence[str] | None = None
|
||
|
||
|
||
def upgrade() -> None:
|
||
op.execute("SET LOCAL lock_timeout = '2s'")
|
||
op.add_column("attachments", sa.Column("staging_key", sa.Text(), nullable=True))
|
||
op.add_column("attachments", sa.Column("error_code", sa.Text(), nullable=True))
|
||
op.drop_constraint("ck_attachments_status", "attachments", type_="check")
|
||
op.execute(
|
||
"ALTER TABLE attachments ADD CONSTRAINT ck_attachments_status CHECK "
|
||
"(status IN ('pending', 'queued', 'processing', 'ready', 'failed')) "
|
||
"NOT VALID",
|
||
)
|
||
op.execute(
|
||
"ALTER TABLE attachments ADD CONSTRAINT ck_attachments_error_code CHECK "
|
||
"((status = 'failed') = (error_code IS NOT NULL)) NOT VALID",
|
||
)
|
||
|
||
op.create_table(
|
||
"attachment_jobs",
|
||
sa.Column("id", sa.Uuid(), nullable=False),
|
||
sa.Column("attachment_id", sa.Uuid(), nullable=False),
|
||
sa.Column("pipeline_version", sa.SmallInteger(), nullable=False),
|
||
sa.Column("state", sa.Text(), nullable=False),
|
||
sa.Column("attempt", sa.Integer(), nullable=False),
|
||
sa.Column("attempt_base", sa.Integer(), nullable=False),
|
||
sa.Column("next_attempt_at", sa.DateTime(timezone=True), nullable=False),
|
||
sa.Column("published_at", sa.DateTime(timezone=True), nullable=True),
|
||
sa.Column("lease_until", sa.DateTime(timezone=True), nullable=True),
|
||
sa.Column("last_error", sa.Text(), nullable=True),
|
||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||
sa.PrimaryKeyConstraint("id", name="pk_attachment_jobs"),
|
||
sa.ForeignKeyConstraint(
|
||
["attachment_id"],
|
||
["attachments.id"],
|
||
name="fk_attachment_jobs_attachment_id_attachments",
|
||
),
|
||
sa.UniqueConstraint(
|
||
"attachment_id",
|
||
"pipeline_version",
|
||
name="uq_attachment_jobs_attachment_id_pipeline_version",
|
||
),
|
||
sa.CheckConstraint(
|
||
"state IN ('queued', 'processing', 'ready', 'failed')",
|
||
name="ck_attachment_jobs_state",
|
||
),
|
||
sa.CheckConstraint(
|
||
"attempt_base >= 0 AND attempt >= attempt_base",
|
||
name="ck_attachment_jobs_attempts",
|
||
),
|
||
sa.CheckConstraint(
|
||
"(state = 'processing') = (lease_until IS NOT NULL)",
|
||
name="ck_attachment_jobs_lease",
|
||
),
|
||
)
|
||
op.create_index(
|
||
"ix_attachment_jobs_outbox",
|
||
"attachment_jobs",
|
||
["next_attempt_at"],
|
||
postgresql_where=sa.text("state = 'queued' AND published_at IS NULL"),
|
||
)
|
||
op.create_index(
|
||
"ix_attachment_jobs_published",
|
||
"attachment_jobs",
|
||
["published_at"],
|
||
postgresql_where=sa.text("state = 'queued' AND published_at IS NOT NULL"),
|
||
)
|
||
op.create_index(
|
||
"ix_attachment_jobs_lease",
|
||
"attachment_jobs",
|
||
["lease_until"],
|
||
postgresql_where=sa.text("state = 'processing'"),
|
||
)
|
||
op.create_index(
|
||
"ix_attachment_jobs_unfinished",
|
||
"attachment_jobs",
|
||
["created_at"],
|
||
postgresql_where=sa.text("state IN ('queued', 'processing')"),
|
||
)
|
||
op.create_index(
|
||
"ix_attachment_jobs_failed",
|
||
"attachment_jobs",
|
||
["updated_at", "id"],
|
||
postgresql_where=sa.text("state = 'failed'"),
|
||
)
|
||
|
||
op.create_table(
|
||
"attachment_variants",
|
||
sa.Column("attachment_id", sa.Uuid(), nullable=False),
|
||
sa.Column("pipeline_version", sa.SmallInteger(), nullable=False),
|
||
sa.Column("name", sa.Text(), nullable=False),
|
||
sa.Column("content_type", sa.Text(), nullable=False),
|
||
sa.Column("size_bytes", sa.Integer(), nullable=False),
|
||
sa.Column("width", sa.Integer(), nullable=False),
|
||
sa.Column("height", sa.Integer(), nullable=False),
|
||
sa.Column("sha256", sa.LargeBinary(), nullable=False),
|
||
sa.Column("object_key", sa.Text(), nullable=False),
|
||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||
sa.PrimaryKeyConstraint(
|
||
"attachment_id",
|
||
"pipeline_version",
|
||
"name",
|
||
name="pk_attachment_variants",
|
||
),
|
||
sa.ForeignKeyConstraint(
|
||
["attachment_id"],
|
||
["attachments.id"],
|
||
name="fk_attachment_variants_attachment_id_attachments",
|
||
),
|
||
sa.UniqueConstraint("object_key", name="uq_attachment_variants_object_key"),
|
||
sa.CheckConstraint(
|
||
"name IN ('thumbnail', 'crop', 'optimized')",
|
||
name="ck_attachment_variants_name",
|
||
),
|
||
sa.CheckConstraint(
|
||
"content_type IN ('image/jpeg', 'image/png', 'image/webp')",
|
||
name="ck_attachment_variants_content_type",
|
||
),
|
||
sa.CheckConstraint(
|
||
"size_bytes >= 1 AND width >= 1 AND height >= 1",
|
||
name="ck_attachment_variants_dimensions",
|
||
),
|
||
sa.CheckConstraint(
|
||
"octet_length(sha256) = 32",
|
||
name="ck_attachment_variants_sha256_length",
|
||
),
|
||
)
|
||
|
||
op.create_table(
|
||
"attachment_job_replays",
|
||
sa.Column("id", sa.Uuid(), nullable=False),
|
||
sa.Column("job_id", sa.Uuid(), nullable=False),
|
||
sa.Column("operator", sa.Text(), nullable=False),
|
||
sa.Column("reason", sa.Text(), nullable=False),
|
||
sa.Column("previous_error", sa.Text(), nullable=True),
|
||
sa.Column("previous_attempt", sa.Integer(), nullable=False),
|
||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||
sa.PrimaryKeyConstraint("id", name="pk_attachment_job_replays"),
|
||
sa.ForeignKeyConstraint(
|
||
["job_id"],
|
||
["attachment_jobs.id"],
|
||
name="fk_attachment_job_replays_job_id_attachment_jobs",
|
||
),
|
||
sa.CheckConstraint(
|
||
"char_length(operator) BETWEEN 1 AND 64 AND "
|
||
"char_length(reason) BETWEEN 1 AND 500",
|
||
name="ck_attachment_job_replays_text",
|
||
),
|
||
)
|
||
op.create_index(
|
||
"ix_attachment_job_replays_job_id", "attachment_job_replays", ["job_id"]
|
||
)
|
||
|
||
# индекс на рабочей таблице — без блокировки записи
|
||
with op.get_context().autocommit_block():
|
||
op.create_index(
|
||
"ix_attachments_staging_done",
|
||
"attachments",
|
||
["updated_at", "id"],
|
||
postgresql_where=sa.text(
|
||
"staging_key IS NOT NULL AND status IN ('ready', 'failed')"
|
||
),
|
||
postgresql_concurrently=True,
|
||
if_not_exists=True,
|
||
)
|
||
|
||
|
||
def downgrade() -> None:
|
||
with op.get_context().autocommit_block():
|
||
op.drop_index(
|
||
"ix_attachments_staging_done",
|
||
table_name="attachments",
|
||
postgresql_concurrently=True,
|
||
if_exists=True,
|
||
)
|
||
op.execute("SET LOCAL lock_timeout = '2s'")
|
||
op.drop_table("attachment_job_replays")
|
||
op.drop_table("attachment_variants")
|
||
op.drop_table("attachment_jobs")
|
||
op.drop_constraint("ck_attachments_error_code", "attachments", type_="check")
|
||
op.drop_constraint("ck_attachments_status", "attachments", type_="check")
|
||
# строки новых статусов откат не переписывает: прежнее условие NOT VALID
|
||
op.execute(
|
||
"ALTER TABLE attachments ADD CONSTRAINT ck_attachments_status CHECK "
|
||
"(status IN ('pending', 'ready')) NOT VALID",
|
||
)
|
||
op.drop_column("attachments", "error_code")
|
||
op.drop_column("attachments", "staging_key")
|