-- Schedules leave the schedules control-plane resource for their own tables: -- running a schedule records a run row and never rewrites the definition, so -- an operator's edit and a firing cannot conflict. A run is unique by schedule -- and slot, which is what stops two schedulers firing the same slot twice. -- +goose Up CREATE TABLE schedules ( id text PRIMARY KEY CHECK (id <> ''), owner_kind text NOT NULL CHECK (owner_kind IN ('instance', 'org')), owner_id text NOT NULL DEFAULT '', name text NOT NULL CHECK (name <> ''), enabled boolean NOT NULL DEFAULT true, built_in boolean NOT NULL DEFAULT false, timing_kind text NOT NULL CHECK (timing_kind IN ('interval', 'cron', 'once')), interval_seconds bigint NOT NULL DEFAULT 0, cron text NOT NULL DEFAULT '', run_at timestamptz, anchor timestamptz NOT NULL, next_run timestamptz, -- The zone next_run was computed in, so a cron schedule is recomputed -- when the instance zone changes. zone text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), CHECK ((owner_kind = 'instance') = (owner_id = '')) ); CREATE INDEX idx_schedules_due ON schedules (next_run) WHERE enabled AND next_run IS NOT NULL; CREATE TABLE schedule_runs ( id bigserial PRIMARY KEY, schedule_id text NOT NULL REFERENCES schedules (id) ON DELETE CASCADE, scheduled_for timestamptz NOT NULL, started_at timestamptz, finished_at timestamptz, result text NOT NULL CHECK (result IN ('pending', 'running', 'succeeded', 'failed', 'skipped')), error text NOT NULL DEFAULT '', -- capture_id is the schedule-fired capture the run recorded; the tasks it -- started are the binding dispatches against that capture. capture_id text NOT NULL DEFAULT '', UNIQUE (schedule_id, scheduled_for) ); CREATE INDEX idx_schedule_runs_latest ON schedule_runs (schedule_id, scheduled_for DESC); CREATE INDEX idx_schedule_runs_open ON schedule_runs (result) WHERE result IN ('pending', 'running'); DELETE FROM resources WHERE kind = 'schedules'; -- +goose Down DROP TABLE schedule_runs; DROP TABLE schedules;