forked from mtusi2026/mtusi2026lab5
59 lines
2.6 KiB
SQL
59 lines
2.6 KiB
SQL
-- Lab5: stage durably, then transact job and outbox atomically.
|
|
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS status TEXT NOT NULL DEFAULT 'ready'
|
|
CHECK (status IN ('queued','processing','ready','failed'));
|
|
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS error_code TEXT;
|
|
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 UNIQUE INDEX IF NOT EXISTS idx_attachments_staging ON attachments(staging_key) WHERE staging_key IS NOT NULL;
|
|
CREATE INDEX IF NOT EXISTS idx_attachments_status ON attachments(status);
|
|
|
|
CREATE TABLE IF NOT EXISTS attachment_variants (
|
|
attachment_id UUID NOT NULL REFERENCES attachments(id),
|
|
pipeline_version INTEGER NOT NULL CHECK (pipeline_version >= 1),
|
|
name TEXT NOT NULL CHECK (name IN ('thumbnail','crop','optimized')),
|
|
object_key TEXT NOT NULL UNIQUE,
|
|
content_type TEXT NOT NULL,
|
|
size_bytes BIGINT NOT NULL CHECK (size_bytes > 0),
|
|
sha256 CHAR(64) NOT NULL,
|
|
width INTEGER NOT NULL CHECK (width > 0),
|
|
height INTEGER NOT NULL CHECK (height > 0),
|
|
PRIMARY KEY (attachment_id,pipeline_version,name)
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS processing_jobs (
|
|
id UUID PRIMARY KEY,
|
|
attachment_id UUID NOT NULL UNIQUE REFERENCES attachments(id),
|
|
pipeline_version INTEGER NOT NULL DEFAULT 1,
|
|
status TEXT NOT NULL DEFAULT 'queued' CHECK (status IN ('queued','processing','ready','failed')),
|
|
attempt INTEGER NOT NULL DEFAULT 1 CHECK (attempt >= 1),
|
|
next_run_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
lease_token UUID,
|
|
leased_until TIMESTAMPTZ,
|
|
error_code TEXT,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_jobs_leases ON processing_jobs(status, leased_until);
|
|
|
|
CREATE TABLE IF NOT EXISTS job_outbox (
|
|
id UUID PRIMARY KEY,
|
|
job_id UUID NOT NULL REFERENCES processing_jobs(id),
|
|
payload JSONB NOT NULL,
|
|
available_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
published_at TIMESTAMPTZ,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_outbox_due ON job_outbox(available_at, created_at) WHERE published_at IS NULL;
|
|
|
|
CREATE TABLE IF NOT EXISTS job_replay_audit (
|
|
id UUID PRIMARY KEY,
|
|
job_id UUID NOT NULL REFERENCES processing_jobs(id),
|
|
replayed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
action TEXT NOT NULL DEFAULT 'operator_replay'
|
|
);
|
|
CREATE TABLE IF NOT EXISTS job_fault_once (
|
|
job_id UUID NOT NULL REFERENCES processing_jobs(id),
|
|
fault TEXT NOT NULL,
|
|
PRIMARY KEY (job_id,fault)
|
|
);
|