-- Async attachment processing. Bytes stay in S3. The broker message carries only ids. -- 202 is returned after the staging object and this job row commit. Publish is a -- later step: published_at stays null until the broker confirms, so a crash -- between COMMIT and publish is recovered by the outbox loop. ALTER TABLE attachments DROP CONSTRAINT attachments_status; ALTER TABLE attachments ADD CONSTRAINT attachments_status CHECK (status IN ('queued', 'processing', 'ready', 'failed')); ALTER TABLE attachments DROP CONSTRAINT attachments_ready_error; ALTER TABLE attachments ADD CONSTRAINT attachments_error CHECK ( (status = 'failed' AND error_code IS NOT NULL AND error_code ~ '^[a-z0-9_]{1,64}$') OR (status <> 'failed' AND error_code IS NULL) ); CREATE TABLE attachment_variants ( attachment_id UUID NOT NULL REFERENCES attachments (id) ON DELETE CASCADE, pipeline_version INTEGER NOT NULL CHECK (pipeline_version >= 1), name TEXT NOT NULL, content_type TEXT NOT NULL, size_bytes INTEGER NOT NULL CHECK (size_bytes >= 1), width INTEGER NOT NULL CHECK (width >= 1), height INTEGER NOT NULL CHECK (height >= 1), sha256 TEXT NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'), object_key TEXT NOT NULL UNIQUE, PRIMARY KEY (attachment_id, pipeline_version, name), CONSTRAINT attachment_variants_name CHECK (name IN ('thumbnail', 'crop', 'optimized')) ); CREATE TABLE attachment_jobs ( job_id UUID PRIMARY KEY, attachment_id UUID NOT NULL REFERENCES attachments (id) ON DELETE CASCADE, pipeline_version INTEGER NOT NULL CHECK (pipeline_version >= 1), attempt INTEGER NOT NULL CHECK (attempt >= 1), status TEXT NOT NULL, error_code TEXT, lease_until TIMESTAMPTZ, lease_token UUID, next_attempt_at TIMESTAMPTZ, published_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), UNIQUE (attachment_id, pipeline_version), CONSTRAINT attachment_jobs_status CHECK (status IN ('queued', 'processing', 'ready', 'failed')), CONSTRAINT attachment_jobs_error CHECK ( error_code IS NULL OR error_code ~ '^[a-z0-9_]{1,64}$' ), CONSTRAINT attachment_jobs_failed_error CHECK (status <> 'failed' OR error_code IS NOT NULL) ); CREATE INDEX attachment_jobs_outbox_idx ON attachment_jobs (created_at) WHERE published_at IS NULL AND status = 'queued'; CREATE INDEX attachment_jobs_lease_idx ON attachment_jobs (lease_until) WHERE status = 'processing'; CREATE TABLE attachment_job_events ( id BIGSERIAL PRIMARY KEY, job_id UUID NOT NULL, attachment_id UUID NOT NULL, kind TEXT NOT NULL, detail TEXT, created_at TIMESTAMPTZ NOT NULL DEFAULT now() );