-- Lab5: asynchronous attachment processing. -- -- * attachments gains a staging pointer (the durable upload) and a pipeline -- version; s3_key becomes the FINAL original and is set by the worker, so it -- must be nullable while the attachment is queued. -- * attachment_variants holds one row per (attachment, pipeline_version, name) -- so reprocessing is idempotent and an older version can never overwrite a -- newer result. -- * attachment_jobs is both the job registry and the transactional outbox: -- the API writes a row in the same transaction as the attachment, and a -- publisher thread moves rows to the broker (published_at) closing the -- COMMIT -> publish gap. alter table attachments alter column s3_key drop not null; alter table attachments add column if not exists staging_key text; alter table attachments add column if not exists pipeline_version integer not null default 1; create table if not exists attachment_variants ( id uuid primary key, attachment_id uuid not null references attachments (id) on delete cascade, pipeline_version integer not null, name text not null, content_type text not null, size_bytes bigint not null, width integer not null, height integer not null, sha256 text not null, s3_key text not null, created_at timestamptz not null, unique (attachment_id, pipeline_version, name) ); create table if not exists attachment_jobs ( job_id uuid primary key, attachment_id uuid not null references attachments (id) on delete cascade, pipeline_version integer not null, attempt integer not null default 1, status text not null default 'pending', -- pending|processing|done|failed available_at timestamptz not null default now(), lease_until timestamptz, published_at timestamptz, last_error text, created_at timestamptz not null default now(), updated_at timestamptz not null default now() ); create index if not exists attachment_jobs_outbox_idx on attachment_jobs (published_at, available_at); create index if not exists attachment_jobs_lease_idx on attachment_jobs (status, lease_until);