Files
mtusi2026lab5/migrations/0006_jobs.sql
T
RainakandClaude Opus 5.5 0a221b0675 ЛР5 БВТ2304 Запорожец на 5
RabbitMQ (quorum queue, publisher confirms, manual ack, DLX) + отдельный worker:
staging в S3 + вложение/job/outbox одной транзакцией -> 202 queued; relay outbox,
lease с heartbeat и fencing (worker_id, attempt), retry с backoff+jitter, failed-реестр,
безопасный replay с audit; thumbnail/crop/WebP в изолированном процессе с лимитами.
Тесты окон отказа (fault injection), трек 1 «Очередь под перегрузкой» с backpressure.
Перенесено исправление замечания lab3 PR #99 (U+0000 в тексте).

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

82 lines
5.7 KiB
SQL
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.
-- 0006: асинхронная обработка вложений (lab5): состояния, задания, варианты, transactional outbox, audit.
-- Только expand: новые таблицы и столбцы; прежняя (lab4) версия видит ready-вложения как раньше.
-- Вложение: queued -> processing -> ready | failed (contracts/attachment-states.md).
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check
CHECK (status IN ('queued', 'processing', 'ready', 'failed'));
ALTER TABLE attachments ALTER COLUMN status SET DEFAULT 'queued';
-- Безопасный машинный код для failed (invalid_image, retry_exhausted, ...); у ready всегда NULL.
ALTER TABLE attachments ADD COLUMN error_code text CHECK (error_code ~ '^[a-z_]{1,64}$');
ALTER TABLE attachments ADD CONSTRAINT attachments_error_only_failed
CHECK ((status = 'failed') = (error_code IS NOT NULL));
-- Устойчивый staging: приватный prefix staging/<id> того же bucket. object_key — конечный ключ оригинала
-- (originals/<id>); он появляется в S3, когда worker публикует результат.
ALTER TABLE attachments ADD COLUMN staging_key text UNIQUE;
ALTER TABLE attachments ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1 CHECK (pipeline_version >= 1);
-- Варианты. Ключ эффекта контракта: (attachment_id, pipeline_version, variant) — повтор не создаёт второй набор.
CREATE TABLE attachment_variants (
attachment_id uuid NOT NULL REFERENCES attachments (id),
pipeline_version integer NOT NULL,
name text NOT NULL CHECK (name IN ('thumbnail', 'crop', 'optimized')),
content_type text NOT NULL CHECK (content_type IN ('image/jpeg', 'image/png', 'image/webp')),
size_bytes bigint NOT NULL CHECK (size_bytes > 0),
width integer NOT NULL CHECK (width > 0),
height integer NOT NULL CHECK (height > 0),
sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
object_key text NOT NULL UNIQUE, -- variants/<id>/v<pipeline>/<name>: детерминирован
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY (attachment_id, pipeline_version, name)
);
-- Одна логическая работа на (вложение, версия pipeline). job_id не меняется при redelivery и retry.
CREATE TABLE attachment_jobs (
job_id uuid PRIMARY KEY,
attachment_id uuid NOT NULL REFERENCES attachments (id),
pipeline_version integer NOT NULL DEFAULT 1,
status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'processing', 'done', 'failed')),
attempt integer NOT NULL DEFAULT 0 CHECK (attempt >= 0), -- число начатых попыток
max_attempts integer NOT NULL CHECK (max_attempts BETWEEN 1 AND 50),
next_attempt_at timestamptz NOT NULL DEFAULT clock_timestamp(),
lease_until timestamptz, -- аренда processing; продлевается heartbeat-ом worker
worker_id text, -- владелец аренды (fencing при фиксации результата)
error_code text,
last_error text, -- краткая причина без секретов и stack trace
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
started_at timestamptz,
finished_at timestamptz,
UNIQUE (attachment_id, pipeline_version),
CONSTRAINT jobs_lease_when_processing CHECK ((status = 'processing') = (lease_until IS NOT NULL))
);
-- Backpressure считает незавершённую работу; reaper ищет просроченные аренды.
CREATE INDEX attachment_jobs_pending_idx ON attachment_jobs (status) WHERE status IN ('queued', 'processing');
CREATE INDEX attachment_jobs_lease_idx ON attachment_jobs (lease_until) WHERE status = 'processing';
-- Transactional outbox: намерение опубликовать job фиксируется в той же транзакции, что и вложение.
-- Relay публикует с publisher confirm и только потом ставит published_at. available_at > now() —
-- отложенная публикация (retry с backoff) без плагинов брокера.
CREATE TABLE outbox (
id bigserial PRIMARY KEY,
job_id uuid NOT NULL REFERENCES attachment_jobs (job_id),
payload jsonb NOT NULL, -- contracts/jobs.schema.json: только ID и служебные поля
available_at timestamptz NOT NULL DEFAULT clock_timestamp(),
published_at timestamptz,
publish_attempts integer NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX outbox_unpublished_idx ON outbox (available_at, id) WHERE published_at IS NULL;
-- Audit операторских действий (явный replay failed-задания).
CREATE TABLE job_audit (
id bigserial PRIMARY KEY,
job_id uuid NOT NULL REFERENCES attachment_jobs (job_id),
action text NOT NULL CHECK (action IN ('replay')),
previous_status text NOT NULL,
previous_error text,
actor text NOT NULL,
reason text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);