create schema if not exists "workflows"; create table if not exists "workflows"."workflows" ( "id" uuid primary key default gen_random_uuid(), "name" text not null, "description" text, "state_machine" jsonb not null, "trigger" jsonb not null, "execution_order" text not null default 'sequence' check ("execution_order" in ('sequence', 'data')), "connections" jsonb, "trace" text check ("trace" in ('all', 'failed', 'none')), "version" integer, "tenant_id" text, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now() ); create table if not exists "workflows"."versions" ( "workflow_id" uuid not null references "workflows"."workflows" ("id") on delete cascade, "version" integer not null, "state_machine" jsonb not null, "trigger" jsonb not null, "execution_order" text not null default 'sequence' check ("execution_order" in ('sequence', 'data')), "connections" jsonb, "trace" text check ("trace" in ('all', 'failed', 'none')), "saved_by" text, "tenant_id" text, "saved_at" timestamptz not null default now(), primary key ("workflow_id", "version") ); create table if not exists "workflows"."runs" ( "id" uuid primary key default gen_random_uuid(), "workflow_id" uuid not null references "workflows"."workflows" ("id") on delete cascade, "version" integer, "input" jsonb, "key" text, "status" text not null default 'queued' check ("status" in ('queued', 'running', 'waiting', 'succeeded', 'failed')), "output" jsonb, "error" text, "cause" text, "resume_at" timestamptz, "started_by" text, "rerun_of" uuid references "workflows"."runs" ("id") on delete set null, "replay" boolean, "rerun_from" text, "tenant_id" text, "created_at" timestamptz not null default now(), "finished_at" timestamptz, "duration_ms" bigint generated always as ((floor(extract(epoch from ("finished_at" - "created_at")) * 1000)::bigint)) stored, foreign key ("workflow_id", "version") references "workflows"."versions" ("workflow_id", "version") ); do $$ begin if exists (select 1 from information_schema.columns where table_schema = 'workflows' and table_name = 'workflows' and column_name = 'definition' and is_generated = 'NEVER') then alter table "workflows"."workflows" add column "state_machine" jsonb, add column "trigger" jsonb, add column "execution_order" text not null default 'sequence' check ("execution_order" in ('sequence', 'data')), add column "connections" jsonb, add column "trace" text check ("trace" in ('all', 'failed', 'none')); update "workflows"."workflows" set "state_machine" = "definition" -> 'stateMachine', "trigger" = "definition" -> 'trigger', "execution_order" = coalesce("definition" ->> 'order', 'sequence'), "connections" = "definition" -> 'connections', "trace" = "definition" ->> 'trace'; alter table "workflows"."workflows" alter column "state_machine" set not null, alter column "trigger" set not null, drop column "definition"; end if; end $$; -- The definition the database once put together from the parts, which nothing reads now alter table "workflows"."workflows" drop column if exists "definition"; do $$ begin if exists (select 1 from information_schema.columns where table_schema = 'workflows' and table_name = 'versions' and column_name = 'definition' and is_generated = 'NEVER') then alter table "workflows"."versions" add column "state_machine" jsonb, add column "trigger" jsonb, add column "execution_order" text not null default 'sequence' check ("execution_order" in ('sequence', 'data')), add column "connections" jsonb, add column "trace" text check ("trace" in ('all', 'failed', 'none')); update "workflows"."versions" set "state_machine" = "definition" -> 'stateMachine', "trigger" = "definition" -> 'trigger', "execution_order" = coalesce("definition" ->> 'order', 'sequence'), "connections" = "definition" -> 'connections', "trace" = "definition" ->> 'trace'; alter table "workflows"."versions" alter column "state_machine" set not null, alter column "trigger" set not null, drop column "definition"; end if; end $$; -- The definition the database once put together from the parts, which nothing reads now alter table "workflows"."versions" drop column if exists "definition"; alter table "workflows"."workflows" add column if not exists "layout" jsonb not null default '{}'::jsonb; alter table "workflows"."versions" add column if not exists "layout" jsonb not null default '{}'::jsonb; create table if not exists "workflows"."checkpoints" ( "run_id" uuid not null references "workflows"."runs" ("id") on delete cascade, "scope" text not null, "seq" integer not null, "follows" integer not null, "state" text not null, "type" text not null, "status" text not null check ("status" in ('succeeded', 'retrying', 'caught')), "fetched_at" timestamptz not null, "next" text, "value" jsonb, "variables" jsonb not null, "attempt" integer not null, "failures" jsonb not null, "visits" jsonb not null, "resume_at" timestamptz, "clock" timestamptz not null, primary key ("run_id", "scope") ); alter table "workflows"."runs" add column if not exists "trace" text check ("trace" in ('all', 'failed', 'none')); alter table "workflows"."runs" add column if not exists "trace_file" text; drop table if exists "workflows"."steps"; alter table "workflows"."workflows" add column if not exists "enabled_version" integer; do $$ begin if not exists (select 1 from pg_constraint where conname = 'workflows_enabled_version' and connamespace = 'workflows'::regnamespace) then alter table "workflows"."workflows" add constraint "workflows_enabled_version" foreign key ("id", "enabled_version") references "workflows"."versions" ("workflow_id", "version") deferrable initially deferred; end if; end $$; -- Who turned the version on, signed in as themselves: the consent its runs sign in through their connections with. alter table "workflows"."versions" add column if not exists "enabled_by" text; create table if not exists "workflows"."triggers" ( "id" uuid primary key default gen_random_uuid(), "workflow_id" uuid references "workflows"."workflows" ("id") on delete set null, "version" integer not null, "tenant_id" text, "type" text not null, "input" jsonb not null, "connection_id" text, "status" text not null check ("status" in ('active', 'failing', 'needs_sign_in', 'stopping')), "generation" integer not null, "cursor" jsonb check (octet_length("cursor"::text) <= 65536), "store" jsonb check (octet_length("store"::text) <= 65536), "poll_job_id" text, "poll_attempt" integer, "consecutive_failures" integer not null, "last_error" jsonb, "next_poll_at" timestamptz, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now() ); alter table "workflows"."triggers" add column if not exists "poll_attempt" integer; -- Who turned the trigger's version on: the only person whose account its stop job ends the subscription through. alter table "workflows"."triggers" add column if not exists "enabled_by" text; -- A deleted workflow's trigger stays, without its workflow, until its stop job unsubscribed it at its provider. alter table "workflows"."triggers" alter column "workflow_id" drop not null; do $$ begin if exists (select 1 from pg_constraint where conname = 'triggers_workflow_id_fkey' and confdeltype = 'c' and connamespace = 'workflows'::regnamespace) then alter table "workflows"."triggers" drop constraint "triggers_workflow_id_fkey"; alter table "workflows"."triggers" add constraint "triggers_workflow_id_fkey" foreign key ("workflow_id") references "workflows"."workflows" ("id") on delete set null; end if; end $$; create unique index if not exists "triggers_workflow" on "workflows"."triggers" ("workflow_id") where "status" <> 'stopping'; create index if not exists "triggers_workflow_id" on "workflows"."triggers" ("workflow_id"); create index if not exists "triggers_updated_at" on "workflows"."triggers" ("updated_at"); create index if not exists "triggers_status_type" on "workflows"."triggers" ("status", "type"); create index if not exists "triggers_connection" on "workflows"."triggers" ("connection_id"); create index if not exists "triggers_tenant" on "workflows"."triggers" ("tenant_id"); create table if not exists "workflows"."effects" ( "run_id" uuid not null references "workflows"."runs" ("id") on delete cascade, "key" text not null, "result" jsonb, primary key ("run_id", "key") ); create table if not exists "workflows"."connection_revocations" ( "id" uuid primary key default gen_random_uuid(), "provider" text not null, "hint" text not null check ("hint" in ('refresh_token', 'access_token')), "token" text not null, "created_at" timestamptz not null default now() ); create table if not exists "workflows"."hooks" ( "workflow_id" uuid primary key references "workflows"."workflows" ("id") on delete cascade, "key_hash" text not null unique, "secret" text, "secret_hash" text not null, "tenant_id" text, "created_at" timestamptz not null default now() ); create table if not exists "workflows"."step_cache" ( "type" text not null, "key" text not null, "who" jsonb not null, "tenant_id" text, "output" jsonb, "secrets" jsonb not null, "cached_at" timestamptz not null default now(), "expires_at" timestamptz not null, primary key ("type", "key", "who") ); create index if not exists "step_cache_expires" on "workflows"."step_cache" ("type", "tenant_id", "expires_at"); create table if not exists "workflows"."step_cache_shapes" ( "type" text not null, "shape" jsonb not null, primary key ("type", "shape") ); create extension if not exists pg_trgm; create index if not exists "workflows_tenant" on "workflows"."workflows" ("tenant_id"); create index if not exists "workflows_name" on "workflows"."workflows" ("name"); create index if not exists "workflows_updated_at" on "workflows"."workflows" ("updated_at"); create index if not exists "workflows_execution_order" on "workflows"."workflows" ("execution_order"); create index if not exists "workflows_name_search" on "workflows"."workflows" using gin ("name" gin_trgm_ops); create index if not exists "versions_tenant" on "workflows"."versions" ("tenant_id"); create index if not exists "versions_version" on "workflows"."versions" ("version"); create index if not exists "versions_enabled_by" on "workflows"."versions" ("enabled_by"); alter table "workflows"."runs" add column if not exists "key" text; create unique index if not exists "runs_key" on "workflows"."runs" ("workflow_id", "key"); alter table "workflows"."runs" add column if not exists "rerun_of" uuid references "workflows"."runs" ("id") on delete set null; create index if not exists "runs_rerun_of" on "workflows"."runs" ("rerun_of"); alter table "workflows"."runs" add column if not exists "replay" boolean; create index if not exists "runs_workflow" on "workflows"."runs" ("workflow_id", "created_at"); create index if not exists "runs_tenant" on "workflows"."runs" ("tenant_id"); create index if not exists "runs_status" on "workflows"."runs" ("status"); create index if not exists "runs_created_at" on "workflows"."runs" ("created_at"); alter table "workflows"."runs" add column if not exists "block_of" uuid references "workflows"."runs" ("id") on delete set null; alter table "workflows"."runs" add column if not exists "block_state" text; alter table "workflows"."runs" add column if not exists "block_visit" text; alter table "workflows"."runs" add column if not exists "output_blanked" boolean; create index if not exists "runs_block_of" on "workflows"."runs" ("block_of"); create unique index if not exists "runs_block_visit" on "workflows"."runs" ("block_of", "block_visit") where "block_of" is not null; alter table "workflows"."runs" add column if not exists "block_key" text; alter table "workflows"."runs" add column if not exists "block_who" text; alter table "workflows"."runs" drop constraint if exists "runs_block_shared"; alter table "workflows"."runs" add constraint "runs_block_shared" check (("block_key" is null) = ("block_who" is null)); create unique index if not exists "runs_block_in_flight" on "workflows"."runs" ("block_key", "block_who") where "block_key" is not null and "block_who" is not null and "status" in ('queued', 'running', 'waiting'); create table if not exists "workflows"."block_waiters" ( "parent" uuid not null references "workflows"."runs" ("id") on delete cascade, "visit" text not null, "run_id" uuid not null references "workflows"."runs" ("id") on delete cascade, primary key ("parent", "visit") ); create index if not exists "block_waiters_run" on "workflows"."block_waiters" ("run_id"); create table if not exists "workflows"."task_tokens" ( "run_id" uuid not null references "workflows"."runs" ("id") on delete cascade, "visit" text not null, "state" text not null, "token_hash" text not null unique, "status" text not null default 'waiting' check ("status" in ('waiting', 'succeeded', 'failed')), "started_at" timestamptz not null, "handed_off_at" timestamptz, "deadline" timestamptz not null, "heartbeat_seconds" integer, "heartbeat_at" timestamptz, "input" jsonb, "logs" jsonb not null default '[]'::jsonb, "output" jsonb, "error" text, "cause" text, "answered_at" timestamptz, primary key ("run_id", "visit") ); alter table "workflows"."runs" add column if not exists "test_step" text; alter table "workflows"."runs" alter column "workflow_id" drop not null; alter table "workflows"."runs" drop constraint if exists "runs_workflow_or_test"; alter table "workflows"."runs" add constraint "runs_workflow_or_test" check (("workflow_id" is null) = ("test_step" is not null)); create table if not exists "workflows"."storage_configurations" ( "id" uuid primary key default gen_random_uuid(), "name" text not null, "kind" text not null check ("kind" in ('local', 's3')), "dir" text, "bucket" text, "region" text, "endpoint" text, "access_key_id" text, "secret_access_key" text, "tenant_id" text, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now() ); create unique index if not exists "storage_configurations_name" on "workflows"."storage_configurations" (coalesce("tenant_id", ''), "name"); create index if not exists "storage_configurations_tenant" on "workflows"."storage_configurations" ("tenant_id"); create index if not exists "storage_configurations_name_order" on "workflows"."storage_configurations" ("name"); create index if not exists "storage_configurations_name_search" on "workflows"."storage_configurations" using gin ("name" gin_trgm_ops); create index if not exists "storage_configurations_updated_at" on "workflows"."storage_configurations" ("updated_at"); create or replace function "workflows"."storage_configuration_updated"() returns trigger language plpgsql as $$ begin new.updated_at := greatest(clock_timestamp(), old.updated_at + interval '1 microsecond'); return new; end $$; drop trigger if exists "storage_configuration_updated" on "workflows"."storage_configurations"; create trigger "storage_configuration_updated" before update on "workflows"."storage_configurations" for each row execute function "workflows"."storage_configuration_updated"(); create table if not exists "workflows"."custom_steps" ( "id" uuid primary key default gen_random_uuid(), "name" text not null, "version" integer not null default 1, "label" text not null, "description" text, "kind" text not null default 'container' check ("kind" in ('container')), "container" jsonb not null, "input" jsonb not null, "output" jsonb not null, "error_prefix" text not null default 'Custom', "errors" jsonb not null default '{}'::jsonb, "tenant_id" text, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now() ); create unique index if not exists "custom_steps_name" on "workflows"."custom_steps" (coalesce("tenant_id", ''), "name"); create index if not exists "custom_steps_tenant" on "workflows"."custom_steps" ("tenant_id"); create index if not exists "custom_steps_name_order" on "workflows"."custom_steps" ("name"); create index if not exists "custom_steps_name_search" on "workflows"."custom_steps" using gin ("name" gin_trgm_ops); create index if not exists "custom_steps_updated_at" on "workflows"."custom_steps" ("updated_at"); create table if not exists "workflows"."custom_step_versions" ( "id" uuid primary key default gen_random_uuid(), -- None once its step is deleted: the version stays, as what its name and number meant "custom_step_id" uuid references "workflows"."custom_steps" ("id") on delete set null, "version" integer not null, "tenant_id" text, "name" text not null, "label" text not null, "description" text, "kind" text not null default 'container' check ("kind" in ('container')), "container" jsonb not null, "input" jsonb not null, "output" jsonb not null, "error_prefix" text not null default 'Custom', "errors" jsonb not null default '{}'::jsonb, "saved_by" text, "saved_at" timestamptz not null default now() ); create unique index if not exists "custom_step_versions_name" on "workflows"."custom_step_versions" (coalesce("tenant_id", ''), "name", "version"); create index if not exists "custom_step_versions_step" on "workflows"."custom_step_versions" ("custom_step_id", "version"); create index if not exists "custom_step_versions_version" on "workflows"."custom_step_versions" ("version"); create or replace function "workflows"."custom_step_version"() returns trigger language plpgsql as $$ begin if tg_op = 'INSERT' then -- After every version a step of this name had, a deleted one's included new.version := coalesce((select max(v.version) from "workflows"."custom_step_versions" v where coalesce(v.tenant_id, '') = coalesce(new.tenant_id, '') and v.name = new.name), 0) + 1; return new; end if; -- The write holds the row, so a save in another transaction numbers its version after this one. new.version := case when (new.label, new.description, new.kind, new.container, new.input, new.output, new.error_prefix, new.errors) is distinct from (old.label, old.description, old.kind, old.container, old.input, old.output, old.error_prefix, old.errors) then old.version + 1 else old.version end; -- Never the same twice, nor now(): two writes in one transaction are two ETags. new.updated_at := greatest(clock_timestamp(), old.updated_at + interval '1 microsecond'); return new; end $$; drop trigger if exists "custom_step_version" on "workflows"."custom_steps"; create trigger "custom_step_version" before insert or update on "workflows"."custom_steps" for each row execute function "workflows"."custom_step_version"(); create table if not exists "workflows"."runners" ( "id" uuid primary key default gen_random_uuid(), "name" text not null, "labels" jsonb not null default '[]'::jsonb, "revoked" boolean not null default false, "revoked_at" timestamptz, "registration_hash" text unique, "registration_expires_at" timestamptz, "registered_at" timestamptz, "token_hash" text unique, "platform" text, "kinds" jsonb not null default '[]'::jsonb, "state" jsonb, "polled_at" timestamptz, "polling_until" timestamptz, "tenant_id" text, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now() ); create index if not exists "runners_tenant" on "workflows"."runners" ("tenant_id"); create index if not exists "runners_tenant_key" on "workflows"."runners" (coalesce("tenant_id", '')); create index if not exists "runners_name" on "workflows"."runners" ("name"); create index if not exists "runners_name_search" on "workflows"."runners" using gin ("name" gin_trgm_ops); create index if not exists "runners_updated_at" on "workflows"."runners" ("updated_at"); create index if not exists "runners_polling" on "workflows"."runners" ("polling_until") where "polling_until" is not null; -- What its last claim said, as columns a list shows: its free slots, and the custom step versions whose images it holds alter table "workflows"."runners" add column if not exists "free_slots" integer generated always as (("state" -> 'capacity' ->> 'slots')::integer) stored; alter table "workflows"."runners" add column if not exists "images" jsonb generated always as (coalesce(jsonb_path_query_array("state", '$.images[*].step'), '[]'::jsonb)) stored; create table if not exists "workflows"."custom_step_jobs" ( "id" uuid primary key default gen_random_uuid(), "run_id" uuid not null references "workflows"."runs" ("id") on delete cascade, "visit" text not null, "state" text not null, "step" text not null, "version_id" uuid not null references "workflows"."custom_step_versions" ("id") on delete cascade, "input" jsonb, -- Sealed with the app's secret; only the claim answer opens them, for the runner holding the job, and they go once it ends "arguments" text, "token_hash" text not null, "status" text not null default 'queued' check ("status" in ('queued', 'running', 'succeeded', 'failed', 'timed_out')), "runner_id" uuid references "workflows"."runners" ("id") on delete set null, "requeues" integer not null default 0, "lease_until" timestamptz, "queued_at" timestamptz not null default now(), "passed_over_at" timestamptz, "claimed_at" timestamptz, "sent_at" timestamptz, "finished_at" timestamptz, "output" jsonb, "error" text, "cause" text, "logs" jsonb not null default '[]'::jsonb, "tenant_id" text, unique ("run_id", "visit") ); create index if not exists "custom_step_jobs_tenant" on "workflows"."custom_step_jobs" ("tenant_id"); create index if not exists "custom_step_jobs_queued_at" on "workflows"."custom_step_jobs" ("queued_at"); create index if not exists "custom_step_jobs_status" on "workflows"."custom_step_jobs" ("status", "queued_at"); create index if not exists "custom_step_jobs_runner" on "workflows"."custom_step_jobs" ("runner_id", "queued_at"); create index if not exists "custom_step_jobs_token" on "workflows"."custom_step_jobs" ("token_hash"); create index if not exists "custom_step_jobs_version" on "workflows"."custom_step_jobs" ("version_id", "queued_at"); create table if not exists "workflows"."custom_step_builds" ( "id" uuid primary key default gen_random_uuid(), "runner_id" uuid references "workflows"."runners" ("id") on delete set null, "version_id" uuid not null references "workflows"."custom_step_versions" ("id") on delete cascade, "step" text not null, "status" text not null default 'building' check ("status" in ('building', 'ready', 'failed')), "digest" text, "log" text, "started_at" timestamptz not null default now(), "finished_at" timestamptz, "tenant_id" text ); create index if not exists "custom_step_builds_tenant" on "workflows"."custom_step_builds" ("tenant_id"); create index if not exists "custom_step_builds_version" on "workflows"."custom_step_builds" ("version_id", "started_at"); create index if not exists "custom_step_builds_runner" on "workflows"."custom_step_builds" ("runner_id", "version_id"); create index if not exists "custom_step_builds_started_at" on "workflows"."custom_step_builds" ("started_at"); create index if not exists "custom_step_builds_status" on "workflows"."custom_step_builds" ("status", "started_at"); create table if not exists "workflows"."custom_step_wanted" ( "workflow_id" uuid not null references "workflows"."workflows" ("id") on delete cascade, "version_id" uuid not null references "workflows"."custom_step_versions" ("id") on delete cascade, "tenant_id" text, primary key ("workflow_id", "version_id") ); create index if not exists "custom_step_wanted_version" on "workflows"."custom_step_wanted" ("version_id"); create index if not exists "custom_step_wanted_tenant" on "workflows"."custom_step_wanted" ("tenant_id"); create or replace function "workflows"."runner_written"() returns trigger language plpgsql as $$ begin if tg_op = 'DELETE' or (new.revoked and not old.revoked) then update "workflows"."custom_step_jobs" set "status" = 'queued', "runner_id" = null, "lease_until" = null, "claimed_at" = null, "sent_at" = null, "passed_over_at" = null, "queued_at" = now() where "runner_id" = old.id and "status" = 'running'; end if; if tg_op = 'DELETE' then return old; end if; if new.revoked and not old.revoked then new.revoked_at := now(); new.polling_until := null; end if; if (new.name, new.labels, new.revoked) is distinct from (old.name, old.labels, old.revoked) then -- Never the same twice, nor now(): two writes in one transaction are two ETags. new.updated_at := greatest(clock_timestamp(), old.updated_at + interval '1 microsecond'); end if; return new; end $$; drop trigger if exists "runner_written" on "workflows"."runners"; create trigger "runner_written" before update or delete on "workflows"."runners" for each row execute function "workflows"."runner_written"(); create or replace function "workflows"."custom_step_job_answered"() returns trigger language plpgsql as $$ begin update "workflows"."custom_step_jobs" set "finished_at" = now(), "arguments" = null, "lease_until" = null, "status" = case when new.status = 'succeeded' then 'succeeded' when new.error in ('States.Timeout', 'States.HeartbeatTimeout') then 'timed_out' else 'failed' end, "output" = new.output, "error" = new.error, "cause" = new.cause where "token_hash" = new.token_hash and "status" in ('queued', 'running'); return null; end $$; drop trigger if exists "custom_step_job_answered" on "workflows"."task_tokens"; create trigger "custom_step_job_answered" after update of "status" on "workflows"."task_tokens" for each row when (old.status = 'waiting' and new.status <> 'waiting') execute function "workflows"."custom_step_job_answered"(); create or replace function "workflows"."custom_step_run_ended"() returns trigger language plpgsql as $$ begin update "workflows"."custom_step_jobs" set "finished_at" = now(), "arguments" = null, "lease_until" = null, "status" = 'timed_out', "cause" = 'Its run ended' where "run_id" = new.id and "status" in ('queued', 'running'); return null; end $$; drop trigger if exists "custom_step_run_ended" on "workflows"."runs"; create trigger "custom_step_run_ended" after update of "status" on "workflows"."runs" for each row when (new.status in ('succeeded', 'failed') and old.status is distinct from new.status) execute function "workflows"."custom_step_run_ended"(); alter table "workflows"."runs" add column if not exists "rerun_from" text; alter table "workflows"."workflows" alter column "state_machine" set default '{"QueryLanguage":"JSONata","StartAt":"","States":{}}'::jsonb; alter table "workflows"."workflows" alter column "trigger" set default '{"manual":{}}'::jsonb; -- The layout a definition keeps: each view's own positions, Pins' and Simple's, of the views it knows alone. In each, a -- position only under the trigger's key or a state's name as keys write it ('%', '.' and a leading '#' or '$' escaped), -- and in Pins also before a dot, as a Break or a Make of that state is kept, so a state removed takes its positions -- along; a layout or a view that is no object is none. create or replace function "workflows"."kept_layout"(layout jsonb, machine jsonb) returns jsonb language sql immutable as $$ with recursive machines(states) as ( select case when jsonb_typeof(machine -> 'States') = 'object' then machine -> 'States' else '{}'::jsonb end union all select case when jsonb_typeof(inner_machine -> 'States') = 'object' then inner_machine -> 'States' else '{}'::jsonb end from machines, jsonb_each(machines.states) as state(name, value), lateral (select case state.value ->> 'Type' when 'Map' then state.value -> 'ItemProcessor' else state.value -> 'Processor' end as inner_machine) as held where jsonb_typeof(state.value) = 'object' and state.value ->> 'Type' in ('Map', 'Block') ), names(name) as ( select regexp_replace(regexp_replace(replace(replace(state.name, '%', '%25'), '.', '%2E'), '^#', '%23'), '^\$', '%24') from machines, jsonb_object_keys(machines.states) as state(name) union select '$trigger' ), views(view, positions) as ( select key, case when jsonb_typeof(value) = 'object' then value else '{}'::jsonb end from jsonb_each(case when jsonb_typeof(layout) = 'object' then layout else '{}'::jsonb end) where key in ('pins', 'simple') ) select coalesce(jsonb_object_agg(views.view, ( select coalesce(jsonb_object_agg(kept.key, kept.value), '{}'::jsonb) from jsonb_each(views.positions) as kept where exists (select from names where kept.key = names.name or (views.view = 'pins' and starts_with(kept.key, names.name || '.'))) )), '{}'::jsonb) from views $$; create or replace function "workflows"."workflow_version"() returns trigger language plpgsql as $$ begin if tg_op = 'INSERT' then new.version := 1; new.layout := "workflows"."kept_layout"(new.layout, new.state_machine); return new; end if; -- Where nodes were moved is no part of the definition: it makes no new version if (new.layout, new.state_machine) is distinct from (old.layout, old.state_machine) then new.layout := "workflows"."kept_layout"(new.layout, new.state_machine); end if; -- The write holds the row, so a save in another transaction numbers its version after this one. new.version := case when (new.state_machine, new.trigger, new.execution_order, new.connections, new.trace) is distinct from (old.state_machine, old.trigger, old.execution_order, old.connections, old.trace) then coalesce(old.version, 0) + 1 else old.version end; -- Its status, which runs ending and marks as resolved write, is no change to the workflow itself. -- Otherwise never the same twice, nor now(): two writes in one transaction, as a batch that saves and publishes, are two ETags. if to_jsonb(new) - array['run_status', 'status_run_id', 'status_run_at', 'unresolved_failures', 'resolved_at', 'resolved_by', 'updated_at'] is distinct from to_jsonb(old) - array['run_status', 'status_run_id', 'status_run_at', 'unresolved_failures', 'resolved_at', 'resolved_by', 'updated_at'] then new.updated_at := greatest(clock_timestamp(), old.updated_at + interval '1 microsecond'); end if; return new; end $$; drop trigger if exists "workflow_version" on "workflows"."workflows"; create trigger "workflow_version" before insert or update on "workflows"."workflows" for each row execute function "workflows"."workflow_version"(); create or replace function "workflows"."run_version"() returns trigger language plpgsql as $$ declare found record; begin -- A custom step's test run, which only the engine starts, runs that step alone and has no workflow. if new.test_step is not null then return new; end if; select w.id, w.version, w.enabled_version, w.tenant_id into found from "workflows"."workflows" w where w.id = new.workflow_id; -- Another tenant's workflow is refused as one that is not there, so a start tells nothing of other tenants. if found.id is null or new.tenant_id is distinct from found.tenant_id then raise exception 'There is no workflow % here', new.workflow_id using errcode = '23503'; end if; if found.version is null then raise exception 'Workflow % has no saved version', new.workflow_id using errcode = '23503'; end if; if new.version is not null and not exists (select from "workflows"."versions" v where v.workflow_id = new.workflow_id and v.version = new.version) then raise exception 'Workflow % has no version %', new.workflow_id, new.version using errcode = '23503'; end if; -- A replay replays a run of this workflow and tenant. if new.replay then if not exists (select from "workflows"."runs" r where r.id = new.rerun_of and r.workflow_id = new.workflow_id and r.tenant_id is not distinct from new.tenant_id) then raise exception 'There is no run % of workflow % here to replay', new.rerun_of, new.workflow_id using errcode = '23503'; end if; end if; -- A re-run or a replay tries a fix, so it runs the version saved last. Any other start not naming its version runs -- what is published, so a saved change stays out of production until it is, or the version saved last on a workflow that is off. if new.version is null then new.version := case when new.rerun_of is null then coalesce(found.enabled_version, found.version) else found.version end; end if; -- Checked on the version the run takes, which a re-run or a replay takes otherwise than a start if exists (select from "workflows"."versions" v where v.workflow_id = new.workflow_id and v.version = new.version and v.state_machine -> 'States' = '{}'::jsonb) then raise exception 'Workflow % has no steps to run', new.workflow_id using errcode = '23503'; end if; -- A re-run or a replay of a block's run runs that Block's processor again, alone. if new.rerun_of is not null then select r.input, r.block_state into new.input, new.block_state from "workflows"."runs" r where r.id = new.rerun_of and r.workflow_id = new.workflow_id; end if; return new; end $$; comment on function "workflows"."run_version"() is 'Protobase workflows 28'; drop trigger if exists "run_version" on "workflows"."runs"; create trigger "run_version" before insert on "workflows"."runs" for each row execute function "workflows"."run_version"(); alter table "workflows"."workflows" add column if not exists "run_status" text not null default 'no_runs'; alter table "workflows"."workflows" add column if not exists "status_run_id" uuid; alter table "workflows"."workflows" add column if not exists "status_run_at" timestamptz; alter table "workflows"."workflows" add column if not exists "unresolved_failures" integer not null default 0; alter table "workflows"."workflows" add column if not exists "resolved_at" timestamptz; alter table "workflows"."workflows" add column if not exists "resolved_by" text; do $$ begin if not exists (select 1 from pg_constraint where conname = 'workflows_run_status' and connamespace = 'workflows'::regnamespace) then alter table "workflows"."workflows" add constraint "workflows_run_status" check ("run_status" in ('failing', 'unresolved', 'healthy', 'no_runs', 'resolved', 'new_version')); end if; end $$; create table if not exists "workflows"."resolutions" ( "id" uuid primary key default gen_random_uuid(), "workflow_id" uuid not null references "workflows"."workflows" ("id") on delete cascade, "resolved_by" text, "tenant_id" text, "resolved_at" timestamptz not null default now() ); create index if not exists "resolutions_workflow" on "workflows"."resolutions" ("workflow_id", "resolved_at"); create index if not exists "resolutions_tenant" on "workflows"."resolutions" ("tenant_id"); create index if not exists "resolutions_resolved_at" on "workflows"."resolutions" ("resolved_at"); create index if not exists "runs_ended" on "workflows"."runs" ("workflow_id", "finished_at" desc, "id" desc) where "status" in ('succeeded', 'failed'); -- The runs a workflow's status counts, so its status skips no blocks' runs, of which a run starts many, to find them. create index if not exists "runs_ended_top" on "workflows"."runs" ("workflow_id", "finished_at" desc, "id" desc) where "status" in ('succeeded', 'failed') and "block_of" is null; -- The status of a workflow at its version and last mark as resolved, from its last 10 ended runs, blocks' runs left out -- (a block's failure is its run's): the run its -- reason names is the latest for failing and healthy, the latest failure that counts for unresolved, none for the gray ones. create or replace function "workflows"."workflow_status"(workflow uuid, current_version integer, resolved timestamptz) returns table ("run_status" text, "status_run_id" uuid, "status_run_at" timestamptz, "unresolved_failures" integer) language sql stable as $$ with ended as ( select r.id, r.finished_at, r.version, r.status = 'failed' as failed, r.status = 'failed' and r.version = current_version and (resolved is null or r.finished_at > resolved) as counts, row_number() over (order by r.finished_at desc, r.id desc) as n from (select * from "workflows"."runs" where workflow_id = workflow and block_of is null and status in ('succeeded', 'failed') order by finished_at desc, id desc limit 10) r ), latest as (select * from ended where n = 1), failure as (select * from ended where counts order by n limit 1), shown as ( select case when l.id is null then 'no_runs' when l.counts then 'failing' when l.failed and l.version is distinct from current_version then 'new_version' when l.failed then 'resolved' when f.id is not null then 'unresolved' else 'healthy' end as status, l.id as latest_id, l.finished_at as latest_at, f.id as failure_id, f.finished_at as failure_at from (select) one left join latest l on true left join failure f on true ) select status, case status when 'unresolved' then failure_id when 'failing' then latest_id when 'healthy' then latest_id end, case status when 'unresolved' then failure_at when 'failing' then latest_at when 'healthy' then latest_at end, (select count(*)::integer from ended where counts) from shown $$; -- A new version or a mark as resolved counts the failures again. Named to run after "workflow_version", which numbers the version. create or replace function "workflows"."workflow_version_status"() returns trigger language plpgsql as $$ begin if new.version is distinct from old.version or new.resolved_at is distinct from old.resolved_at then select st.run_status, st.status_run_id, st.status_run_at, st.unresolved_failures into new.run_status, new.status_run_id, new.status_run_at, new.unresolved_failures from "workflows"."workflow_status"(new.id, new.version, new.resolved_at) st; end if; return new; end $$; drop trigger if exists "workflow_version_status" on "workflows"."workflows"; create trigger "workflow_version_status" before update on "workflows"."workflows" for each row execute function "workflows"."workflow_version_status"(); -- A run that ends computes its workflow's status again. The workflow is locked first, in a statement of its own, so a -- run of it ending at the same time has committed before the update's snapshot is taken, and the status counts both. create or replace function "workflows"."run_status"() returns trigger language plpgsql as $$ begin perform 1 from "workflows"."workflows" where id = new.workflow_id for no key update; update "workflows"."workflows" w set ("run_status", "status_run_id", "status_run_at", "unresolved_failures") = (select st.run_status, st.status_run_id, st.status_run_at, st.unresolved_failures from "workflows"."workflow_status"(w.id, w.version, w.resolved_at) st) where w.id = new.workflow_id; return null; end $$; drop trigger if exists "run_status" on "workflows"."runs"; create trigger "run_status" after update of "status" on "workflows"."runs" for each row when (new.status in ('succeeded', 'failed') and old.status is distinct from new.status and new.block_of is null) execute function "workflows"."run_status"(); -- Marking a workflow resolved: refused for another tenant's workflow as one that is not there, then copied onto it. create or replace function "workflows"."resolution"() returns trigger language plpgsql as $$ begin if not exists (select from "workflows"."workflows" w where w.id = new.workflow_id and w.tenant_id is not distinct from new.tenant_id) then raise exception 'There is no workflow % here', new.workflow_id using errcode = '23503'; end if; update "workflows"."workflows" set "resolved_at" = new.resolved_at, "resolved_by" = new.resolved_by where id = new.workflow_id; return null; end $$; drop trigger if exists "resolution" on "workflows"."resolutions"; create trigger "resolution" after insert on "workflows"."resolutions" for each row execute function "workflows"."resolution"(); update "workflows"."workflows" w set ("run_status", "status_run_id", "status_run_at", "unresolved_failures") = (select st.run_status, st.status_run_id, st.status_run_at, st.unresolved_failures from "workflows"."workflow_status"(w.id, w.version, w.resolved_at) st);