feat(runs,events,ui): identify workflows by immutable UUID (#2125)
This commit is contained in:
46 files changed
+1284
-512
No files matched your search
+143
-29
@@ -1258,6 +1258,18 @@ components:
|
||||
required:
|
||||
- name
|
||||
type: object
|
||||
CreateWorkflowInputBody:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
body:
|
||||
description: The first version's workflow document, as YAML; the workflow is created unpublished without one
|
||||
type: string
|
||||
name:
|
||||
description: Lowercase letters and digits, joined by dots or hyphens
|
||||
type: string
|
||||
required:
|
||||
- name
|
||||
type: object
|
||||
CreateWorkspaceInputBody:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
@@ -1735,14 +1747,11 @@ components:
|
||||
type: string
|
||||
source_id:
|
||||
type: string
|
||||
workflow:
|
||||
type: string
|
||||
required:
|
||||
- source_id
|
||||
- source
|
||||
- event_type
|
||||
- filter
|
||||
- workflow
|
||||
type: object
|
||||
EventsSavedID:
|
||||
additionalProperties: false
|
||||
@@ -1915,10 +1924,13 @@ components:
|
||||
type: boolean
|
||||
workflow:
|
||||
type: string
|
||||
workflow_id:
|
||||
type: string
|
||||
required:
|
||||
- name
|
||||
- event_type
|
||||
- filter
|
||||
- workflow_id
|
||||
- workflow
|
||||
- enabled
|
||||
- status
|
||||
@@ -3726,11 +3738,12 @@ components:
|
||||
description: The source whose events fire it; none when every is set
|
||||
format: uuid
|
||||
type: string
|
||||
workflow:
|
||||
workflow_id:
|
||||
description: The workflow each match runs
|
||||
format: uuid
|
||||
type: string
|
||||
required:
|
||||
- workflow
|
||||
- workflow_id
|
||||
type: object
|
||||
PutWorkflowInputBody:
|
||||
additionalProperties: false
|
||||
@@ -3739,7 +3752,7 @@ components:
|
||||
description: The workflow document, as YAML
|
||||
type: string
|
||||
expected_version:
|
||||
description: The latest version the document was edited from, 0 for a new workflow; the save is refused with 409 when another is stored
|
||||
description: The latest version the document was edited from, 0 for a workflow not yet published; the save is refused with 409 when another is stored
|
||||
format: int64
|
||||
minimum: 0
|
||||
type: integer
|
||||
@@ -3792,6 +3805,15 @@ components:
|
||||
- expected_version
|
||||
type: object
|
||||
RenameInputBody1:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
name:
|
||||
description: Lowercase letters and digits, joined by dots or hyphens
|
||||
type: string
|
||||
required:
|
||||
- name
|
||||
type: object
|
||||
RenameInputBody2:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
title:
|
||||
@@ -3883,7 +3905,10 @@ components:
|
||||
type: string
|
||||
updated_by:
|
||||
type: string
|
||||
workflow_id:
|
||||
type: string
|
||||
required:
|
||||
- workflow_id
|
||||
- name
|
||||
- body
|
||||
- base_version
|
||||
@@ -4068,11 +4093,14 @@ components:
|
||||
type: string
|
||||
workflow:
|
||||
type: string
|
||||
workflow_id:
|
||||
type: string
|
||||
workflow_version:
|
||||
format: int64
|
||||
type: integer
|
||||
required:
|
||||
- id
|
||||
- workflow_id
|
||||
- workflow
|
||||
- workflow_version
|
||||
- state
|
||||
@@ -4229,6 +4257,24 @@ components:
|
||||
- at
|
||||
- kind
|
||||
type: object
|
||||
RunsWorkflowIdentity:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
enabled:
|
||||
type: boolean
|
||||
id:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
version:
|
||||
format: int64
|
||||
type: integer
|
||||
required:
|
||||
- id
|
||||
- name
|
||||
- enabled
|
||||
- version
|
||||
type: object
|
||||
RunsWorkflowStats:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
@@ -4253,7 +4299,10 @@ components:
|
||||
type: integer
|
||||
workflow:
|
||||
type: string
|
||||
workflow_id:
|
||||
type: string
|
||||
required:
|
||||
- workflow_id
|
||||
- workflow
|
||||
- total
|
||||
- succeeded
|
||||
@@ -4273,6 +4322,8 @@ components:
|
||||
type: string
|
||||
enabled:
|
||||
type: boolean
|
||||
id:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
steps:
|
||||
@@ -4285,6 +4336,7 @@ components:
|
||||
format: int64
|
||||
type: integer
|
||||
required:
|
||||
- id
|
||||
- name
|
||||
- version
|
||||
- body
|
||||
@@ -5747,7 +5799,7 @@ paths:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/RenameInputBody1"
|
||||
$ref: "#/components/schemas/RenameInputBody2"
|
||||
required: true
|
||||
responses:
|
||||
"200":
|
||||
@@ -8338,9 +8390,10 @@ paths:
|
||||
- description: Only this workflow's runs
|
||||
explode: false
|
||||
in: query
|
||||
name: workflow
|
||||
name: workflow_id
|
||||
schema:
|
||||
description: Only this workflow's runs
|
||||
format: uuid
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
@@ -9629,14 +9682,39 @@ paths:
|
||||
summary: List every workflow at its latest version
|
||||
tags:
|
||||
- Workflows
|
||||
/api/workflows/{name}:
|
||||
post:
|
||||
operationId: create-workflow
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/CreateWorkflowInputBody"
|
||||
required: true
|
||||
responses:
|
||||
"201":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/RunsWorkflowIdentity"
|
||||
description: Created
|
||||
default:
|
||||
content:
|
||||
application/problem+json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorModel"
|
||||
description: Error
|
||||
summary: Create a workflow, and publish its first version when a document is given
|
||||
tags:
|
||||
- Workflows
|
||||
/api/workflows/{id}:
|
||||
delete:
|
||||
operationId: delete-workflow
|
||||
parameters:
|
||||
- in: path
|
||||
name: name
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
format: uuid
|
||||
type: string
|
||||
responses:
|
||||
"204":
|
||||
@@ -9647,16 +9725,17 @@ paths:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorModel"
|
||||
description: Error
|
||||
summary: Delete a workflow, unless a trigger or another workflow still names it
|
||||
summary: Delete a workflow, unless a trigger or another workflow still refers to it
|
||||
tags:
|
||||
- Workflows
|
||||
get:
|
||||
operationId: get-workflow
|
||||
parameters:
|
||||
- in: path
|
||||
name: name
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
format: uuid
|
||||
type: string
|
||||
- description: A past version; the latest by default
|
||||
explode: false
|
||||
@@ -9686,12 +9765,11 @@ paths:
|
||||
put:
|
||||
operationId: put-workflow
|
||||
parameters:
|
||||
- description: Lowercase letters and digits, joined by dots or hyphens
|
||||
in: path
|
||||
name: name
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
description: Lowercase letters and digits, joined by dots or hyphens
|
||||
format: uuid
|
||||
type: string
|
||||
requestBody:
|
||||
content:
|
||||
@@ -9715,14 +9793,15 @@ paths:
|
||||
summary: Publish a workflow document as its next version
|
||||
tags:
|
||||
- Workflows
|
||||
/api/workflows/{name}/draft:
|
||||
/api/workflows/{id}/draft:
|
||||
delete:
|
||||
operationId: discard-workflow-draft
|
||||
parameters:
|
||||
- in: path
|
||||
name: name
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
format: uuid
|
||||
type: string
|
||||
responses:
|
||||
"204":
|
||||
@@ -9740,9 +9819,10 @@ paths:
|
||||
operationId: get-workflow-draft
|
||||
parameters:
|
||||
- in: path
|
||||
name: name
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
format: uuid
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
@@ -9763,12 +9843,11 @@ paths:
|
||||
put:
|
||||
operationId: put-workflow-draft
|
||||
parameters:
|
||||
- description: Lowercase letters and digits, joined by dots or hyphens
|
||||
in: path
|
||||
name: name
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
description: Lowercase letters and digits, joined by dots or hyphens
|
||||
format: uuid
|
||||
type: string
|
||||
requestBody:
|
||||
content:
|
||||
@@ -9792,14 +9871,15 @@ paths:
|
||||
summary: Save a workflow's draft, which no run uses until it is published
|
||||
tags:
|
||||
- Workflows
|
||||
/api/workflows/{name}/draft/test-run:
|
||||
/api/workflows/{id}/draft/test-run:
|
||||
post:
|
||||
operationId: test-workflow-draft
|
||||
parameters:
|
||||
- in: path
|
||||
name: name
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
format: uuid
|
||||
type: string
|
||||
requestBody:
|
||||
content:
|
||||
@@ -9823,14 +9903,15 @@ paths:
|
||||
summary: "Test-run a workflow's draft: every action is judged and none that changes something runs"
|
||||
tags:
|
||||
- Workflows
|
||||
/api/workflows/{name}/enabled:
|
||||
/api/workflows/{id}/enabled:
|
||||
put:
|
||||
operationId: set-workflow-enabled
|
||||
parameters:
|
||||
- in: path
|
||||
name: name
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
format: uuid
|
||||
type: string
|
||||
requestBody:
|
||||
content:
|
||||
@@ -9854,14 +9935,47 @@ paths:
|
||||
summary: Enable or disable a workflow
|
||||
tags:
|
||||
- Workflows
|
||||
/api/workflows/{name}/runs:
|
||||
/api/workflows/{id}/name:
|
||||
put:
|
||||
operationId: rename-workflow
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
format: uuid
|
||||
type: string
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/RenameInputBody1"
|
||||
required: true
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/RunsWorkflowIdentity"
|
||||
description: OK
|
||||
default:
|
||||
content:
|
||||
application/problem+json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorModel"
|
||||
description: Error
|
||||
summary: Rename a workflow; its runs, triggers and callers refer to it by id and are unchanged
|
||||
tags:
|
||||
- Workflows
|
||||
/api/workflows/{id}/runs:
|
||||
post:
|
||||
operationId: run-workflow
|
||||
parameters:
|
||||
- in: path
|
||||
name: name
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
format: uuid
|
||||
type: string
|
||||
requestBody:
|
||||
content:
|
||||
|
||||
@@ -144,10 +144,10 @@ func (o *operations) Wait() {
|
||||
// installStarter puts the workflow that ships with the binary in place. It
|
||||
// belongs to the organisation, so it waits until setup has created one.
|
||||
func installStarter(ctx context.Context, engine *runs.Engine) error {
|
||||
if _, err := engine.Install(ctx, orgID, "investigate", runs.InvestigateDocument(), string(governance.SystemID)); err != nil {
|
||||
if _, err := engine.InstallShipped(ctx, orgID, "investigate", runs.InvestigateDocument(), string(governance.SystemID)); err != nil {
|
||||
return fmt.Errorf("install the investigate workflow: %w", err)
|
||||
}
|
||||
if _, err := engine.Install(ctx, orgID, runs.ProposalWorkflow, runs.ProposalDocument(), string(governance.SystemID)); err != nil {
|
||||
if _, err := engine.InstallShipped(ctx, orgID, runs.ProposalWorkflow, runs.ProposalDocument(), string(governance.SystemID)); err != nil {
|
||||
return fmt.Errorf("install the proposal workflow: %w", err)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -98,7 +98,7 @@ CREATE TABLE events.triggers (
|
||||
source_id uuid REFERENCES events.sources (id),
|
||||
event_type text NOT NULL,
|
||||
filter jsonb NOT NULL DEFAULT '{}',
|
||||
workflow text NOT NULL,
|
||||
workflow_id uuid NOT NULL,
|
||||
enabled boolean NOT NULL DEFAULT true,
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
schedule_every_s integer CHECK (schedule_every_s >= 60),
|
||||
|
||||
@@ -4,7 +4,7 @@ CREATE SCHEMA runs;
|
||||
CREATE TABLE runs.runs (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
workflow text NOT NULL,
|
||||
workflow_id uuid,
|
||||
start_key text,
|
||||
input jsonb NOT NULL,
|
||||
state text NOT NULL CHECK (state IN ('queued', 'running', 'waiting', 'succeeded', 'failed', 'cancelled', 'parked', 'waiting_approval', 'declined')),
|
||||
@@ -27,7 +27,9 @@ CREATE TABLE runs.runs (
|
||||
parent_run_id uuid REFERENCES runs.runs (id) ON DELETE CASCADE,
|
||||
parent_signal text,
|
||||
call_depth integer NOT NULL DEFAULT 0,
|
||||
UNIQUE (org_id, start_key)
|
||||
UNIQUE (org_id, start_key),
|
||||
-- Only a test run of a document that isn't a workflow yet has no workflow.
|
||||
CHECK (dry OR workflow_id IS NOT NULL)
|
||||
);
|
||||
CREATE INDEX runs_claimable ON runs.runs (created_at) WHERE (state IN ('queued', 'waiting', 'running'));
|
||||
CREATE INDEX runs_runs_parent ON runs.runs (parent_run_id) WHERE (parent_run_id IS NOT NULL);
|
||||
@@ -51,16 +53,33 @@ CREATE TABLE runs.signals (
|
||||
PRIMARY KEY (run_id, key)
|
||||
);
|
||||
|
||||
-- A workflow is a document, stored by name and version. A run records the
|
||||
-- version it started with and executes that version.
|
||||
-- A workflow is identified by its id, fixed when it is created; its name is a
|
||||
-- label that can change. A deleted workflow keeps its row and versions, so its
|
||||
-- runs still show what they ran, and its name can be given to a new workflow.
|
||||
-- A disabled workflow can't be started by a trigger, by another workflow or
|
||||
-- manually.
|
||||
CREATE TABLE runs.workflows (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
name text NOT NULL,
|
||||
version integer NOT NULL,
|
||||
body text NOT NULL,
|
||||
created_by text NOT NULL,
|
||||
enabled boolean NOT NULL DEFAULT true,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (org_id, name, version)
|
||||
deleted_at timestamptz
|
||||
);
|
||||
CREATE UNIQUE INDEX workflows_live_name ON runs.workflows (org_id, name) WHERE (deleted_at IS NULL);
|
||||
|
||||
-- A version is one published workflow document. A run records the version it
|
||||
-- started with and executes that version. calls maps each workflow name the
|
||||
-- document calls or hands off to onto the id it resolved to when the version
|
||||
-- was published, so renaming the called workflow doesn't change what runs.
|
||||
CREATE TABLE runs.workflow_versions (
|
||||
workflow_id uuid NOT NULL REFERENCES runs.workflows (id),
|
||||
version integer NOT NULL,
|
||||
body text NOT NULL,
|
||||
calls jsonb NOT NULL DEFAULT '{}',
|
||||
created_by text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (workflow_id, version)
|
||||
);
|
||||
|
||||
-- A draft is the unpublished edit of a workflow. It is stored so the edit
|
||||
@@ -68,25 +87,14 @@ CREATE TABLE runs.workflows (
|
||||
-- version. revision increments on every write, and a write that specifies an
|
||||
-- older revision is refused, so two editors can't overwrite each other's
|
||||
-- changes. base_version is the published version the draft started from, or 0
|
||||
-- for a new workflow.
|
||||
-- for a workflow not yet published.
|
||||
CREATE TABLE runs.workflow_drafts (
|
||||
org_id text NOT NULL,
|
||||
name text NOT NULL,
|
||||
workflow_id uuid PRIMARY KEY REFERENCES runs.workflows (id),
|
||||
body text NOT NULL,
|
||||
base_version integer NOT NULL,
|
||||
revision integer NOT NULL DEFAULT 1,
|
||||
updated_by text NOT NULL,
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (org_id, name)
|
||||
);
|
||||
|
||||
-- A workflow with no row here is enabled. A disabled workflow can't be started
|
||||
-- by a trigger, by another workflow or manually.
|
||||
CREATE TABLE runs.workflow_settings (
|
||||
org_id text NOT NULL,
|
||||
name text NOT NULL,
|
||||
enabled boolean NOT NULL,
|
||||
PRIMARY KEY (org_id, name)
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
@@ -128,7 +128,11 @@ func (s *startRecorder) Start(ctx context.Context, _ runs.StartRequest) (uuid.UU
|
||||
return uuid.New(), s.err
|
||||
}
|
||||
|
||||
func (*startRecorder) CheckTrigger(context.Context, string, string) error { return nil }
|
||||
func (*startRecorder) CheckTrigger(context.Context, string, uuid.UUID) error { return nil }
|
||||
|
||||
func (*startRecorder) WorkflowName(context.Context, string, uuid.UUID) (string, error) {
|
||||
return "triage", nil
|
||||
}
|
||||
|
||||
// TestTriggersStartRunsAsTheWorkload guards that dispatching an event never
|
||||
// starts a run without a principal: the workload principal acts, a policy
|
||||
@@ -152,7 +156,7 @@ func TestTriggersStartRunsAsTheWorkload(t *testing.T) {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
starts := &startRecorder{err: tt.err}
|
||||
m := &Module{runs: starts, log: slog.New(slog.DiscardHandler)}
|
||||
_, why, err := m.startRun(t.Context(), store.Event{ID: uuid.New(), OrgID: "default"}, store.Trigger{Name: "t", Workflow: "triage"}, nil)
|
||||
_, why, err := m.startRun(t.Context(), store.Event{ID: uuid.New(), OrgID: "default"}, store.Trigger{Name: "t", WorkflowID: uuid.New()}, nil)
|
||||
var outcome string
|
||||
if why != nil {
|
||||
outcome = why.outcome
|
||||
|
||||
+23
-16
@@ -241,12 +241,12 @@ func (m *Module) setHMAC(src *store.Source, set SourceSettings, stored *store.So
|
||||
type putTriggerInput struct {
|
||||
Name string `path:"name" doc:"Lowercase letters, digits and hyphens"`
|
||||
Body struct {
|
||||
SourceID string `json:"source_id,omitzero" format:"uuid" doc:"The source whose events fire it; none when every is set"`
|
||||
EventType string `json:"event_type,omitzero" doc:"The event type that fires it; fixed when every is set"`
|
||||
Filter map[string]string `json:"filter,omitzero" doc:"Event fields that must match exactly"`
|
||||
Workflow string `json:"workflow" doc:"The workflow each match runs"`
|
||||
Disabled bool `json:"disabled,omitzero"`
|
||||
Every string `json:"every,omitzero" doc:"Fire on an interval instead of on events, such as 1h" example:"1h"`
|
||||
SourceID string `json:"source_id,omitzero" format:"uuid" doc:"The source whose events fire it; none when every is set"`
|
||||
EventType string `json:"event_type,omitzero" doc:"The event type that fires it; fixed when every is set"`
|
||||
Filter map[string]string `json:"filter,omitzero" doc:"Event fields that must match exactly"`
|
||||
WorkflowID string `json:"workflow_id" format:"uuid" doc:"The workflow each match runs"`
|
||||
Disabled bool `json:"disabled,omitzero"`
|
||||
Every string `json:"every,omitzero" doc:"Fire on an interval instead of on events, such as 1h" example:"1h"`
|
||||
// EventTypeID restricts the trigger to events identified as that event
|
||||
// type, and MappingID reads their payload for the run.
|
||||
EventTypeID string `json:"event_type_id,omitzero" format:"uuid" doc:"Fire only for events identified as this event type of the source"`
|
||||
@@ -283,14 +283,18 @@ func (m *Module) putTrigger(ctx context.Context, in *putTriggerInput) (*httpapi.
|
||||
// this trigger to its own.
|
||||
req.Filter = map[string]string{"trigger": in.Name}
|
||||
}
|
||||
if !validName.MatchString(in.Name) || (req.SourceID == "" && !every.Valid) || (req.EventType == "" && req.EventTypeID == "") || req.Workflow == "" {
|
||||
if !validName.MatchString(in.Name) || (req.SourceID == "" && !every.Valid) || (req.EventType == "" && req.EventTypeID == "") || req.WorkflowID == "" {
|
||||
return nil, huma.Error400BadRequest("a trigger needs a lowercase name, a workflow, and either a source and event type or an every interval")
|
||||
}
|
||||
sourceID, err := m.triggerSource(ctx, req.SourceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
typeID, mappingID, err := m.checkTargets(ctx, sourceID, req.EventType, req.Workflow, req.EventTypeID, req.MappingID)
|
||||
workflow, err := uuid.Parse(req.WorkflowID)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("a workflow id is a UUID", &huma.ErrorDetail{Location: "body.workflow_id", Message: "a workflow id is a UUID"})
|
||||
}
|
||||
typeID, mappingID, err := m.checkTargets(ctx, sourceID, req.EventType, workflow, req.EventTypeID, req.MappingID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -304,7 +308,7 @@ func (m *Module) putTrigger(ctx context.Context, in *putTriggerInput) (*httpapi.
|
||||
}
|
||||
if err := m.store.UpsertTrigger(ctx, store.Trigger{
|
||||
OrgID: m.orgID, Name: in.Name, SourceID: sourceID, EventType: req.EventType,
|
||||
Filter: filter, Workflow: req.Workflow, Enabled: !req.Disabled, Approved: approved,
|
||||
Filter: filter, WorkflowID: workflow, Enabled: !req.Disabled, Approved: approved,
|
||||
EventTypeID: typeID, MappingID: mappingID, ScheduleEverySeconds: every,
|
||||
}); err != nil {
|
||||
return nil, huma.Error500InternalServerError("couldn't save the trigger", err)
|
||||
@@ -337,13 +341,13 @@ func (m *Module) triggerSource(ctx context.Context, raw string) (uuid.NullUUID,
|
||||
|
||||
// checkTargets refuses a trigger whose workflow can't be started or whose
|
||||
// event type, mapping or connector event type doesn't exist.
|
||||
func (m *Module) checkTargets(ctx context.Context, sourceID uuid.NullUUID, eventType, workflow, eventTypeID, mappingID string) (typeID, mapID uuid.NullUUID, err error) {
|
||||
func (m *Module) checkTargets(ctx context.Context, sourceID uuid.NullUUID, eventType string, workflow uuid.UUID, eventTypeID, mappingID string) (typeID, mapID uuid.NullUUID, err error) {
|
||||
if typeID, mapID, err = m.checkBinding(ctx, sourceID, eventTypeID, mappingID); err != nil {
|
||||
return typeID, mapID, err
|
||||
}
|
||||
if err := m.runs.CheckTrigger(ctx, m.orgID, workflow); err != nil {
|
||||
if refused, ok := errors.AsType[*runs.InvalidError](err); ok {
|
||||
return typeID, mapID, huma.Error400BadRequest(refused.Problems[0].Message, &huma.ErrorDetail{Location: "body.workflow", Message: refused.Problems[0].Message})
|
||||
return typeID, mapID, huma.Error400BadRequest(refused.Problems[0].Message, &huma.ErrorDetail{Location: "body.workflow_id", Message: refused.Problems[0].Message})
|
||||
}
|
||||
return typeID, mapID, huma.Error500InternalServerError("couldn't check the workflow", err)
|
||||
}
|
||||
@@ -489,7 +493,6 @@ type proposedTrigger struct {
|
||||
Source string `json:"source" doc:"The source's label"`
|
||||
EventType string `json:"event_type"`
|
||||
Filter jsontext.Value `json:"filter"`
|
||||
Workflow string `json:"workflow"`
|
||||
}
|
||||
|
||||
func (m *Module) groups(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]groupView], error) {
|
||||
@@ -583,9 +586,11 @@ type triggerView struct {
|
||||
Source string `json:"source,omitempty"`
|
||||
EventType string `json:"event_type"`
|
||||
Filter map[string]string `json:"filter"`
|
||||
Workflow string `json:"workflow"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Every string `json:"every,omitempty"`
|
||||
// WorkflowID is the workflow the trigger starts, and Workflow its name.
|
||||
WorkflowID uuid.UUID `json:"workflow_id"`
|
||||
Workflow string `json:"workflow"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Every string `json:"every,omitempty"`
|
||||
// Status is pending_approval, armed or paused.
|
||||
Status string `json:"status" enum:"pending_approval,armed,paused"`
|
||||
EventTypeID string `json:"event_type_id,omitempty"`
|
||||
@@ -608,7 +613,7 @@ func statusOf(t store.Trigger) string {
|
||||
// viewOfTrigger is the API's form of a stored trigger. Unsigned is set by the
|
||||
// caller, which knows the sources.
|
||||
func viewOfTrigger(t store.Trigger) (triggerView, error) {
|
||||
view := triggerView{Name: t.Name, EventType: t.EventType, Workflow: t.Workflow, Enabled: t.Enabled, Filter: map[string]string{}, Status: statusOf(t)}
|
||||
view := triggerView{Name: t.Name, EventType: t.EventType, WorkflowID: t.WorkflowID, Enabled: t.Enabled, Filter: map[string]string{}, Status: statusOf(t)}
|
||||
if len(t.Filter) > 0 {
|
||||
if err := json.Unmarshal(t.Filter, &view.Filter); err != nil {
|
||||
return view, fmt.Errorf("filter of %s: %w", t.Name, err)
|
||||
@@ -635,6 +640,7 @@ func (m *Module) viewOfTrigger(ctx context.Context, t store.Trigger) (triggerVie
|
||||
if err != nil {
|
||||
return view, err
|
||||
}
|
||||
view.Workflow = m.workflowName(ctx, t.WorkflowID)
|
||||
if t.SourceID.Valid {
|
||||
if src, err := m.store.Source(ctx, m.orgID, t.SourceID.UUID); err == nil {
|
||||
view.Source, view.Unsigned = src.Label, src.Verification == store.None
|
||||
@@ -670,6 +676,7 @@ func (m *Module) triggers(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]tr
|
||||
return nil, huma.Error500InternalServerError("couldn't read the filter of " + t.Name)
|
||||
}
|
||||
view.Source, view.Unsigned = src.Label, src.Verification == store.None
|
||||
view.Workflow = m.workflowName(ctx, t.WorkflowID)
|
||||
out = append(out, view)
|
||||
}
|
||||
return httpapi.OK(out), nil
|
||||
|
||||
@@ -80,15 +80,16 @@ type TriggerSpec struct {
|
||||
SourceID uuid.UUID
|
||||
EventType string
|
||||
Filter map[string]string
|
||||
Workflow string
|
||||
// WorkflowID is the workflow the trigger starts.
|
||||
WorkflowID uuid.UUID
|
||||
}
|
||||
|
||||
// SaveTrigger creates or replaces an event trigger.
|
||||
func (m *Module) SaveTrigger(ctx context.Context, t TriggerSpec) error {
|
||||
if !validName.MatchString(t.Name) || t.SourceID == uuid.Nil || t.EventType == "" || t.Workflow == "" {
|
||||
if !validName.MatchString(t.Name) || t.SourceID == uuid.Nil || t.EventType == "" || t.WorkflowID == uuid.Nil {
|
||||
return fmt.Errorf("a trigger needs a lowercase name, a source, an event type and a workflow")
|
||||
}
|
||||
if err := m.runs.CheckTrigger(ctx, m.orgID, t.Workflow); err != nil {
|
||||
if err := m.runs.CheckTrigger(ctx, m.orgID, t.WorkflowID); err != nil {
|
||||
return err
|
||||
}
|
||||
filter, err := json.Marshal(t.Filter)
|
||||
@@ -97,6 +98,6 @@ func (m *Module) SaveTrigger(ctx context.Context, t TriggerSpec) error {
|
||||
}
|
||||
return m.store.UpsertTrigger(ctx, store.Trigger{
|
||||
OrgID: m.orgID, Name: t.Name, SourceID: uuid.NullUUID{UUID: t.SourceID, Valid: true}, EventType: t.EventType,
|
||||
Filter: filter, Workflow: t.Workflow, Enabled: true, Approved: true,
|
||||
Filter: filter, WorkflowID: t.WorkflowID, Enabled: true, Approved: true,
|
||||
})
|
||||
}
|
||||
@@ -51,7 +51,8 @@ type Connectors interface {
|
||||
// start its workflow.
|
||||
type Runs interface {
|
||||
Start(ctx context.Context, req runs.StartRequest) (uuid.UUID, error)
|
||||
CheckTrigger(ctx context.Context, orgID, workflow string) error
|
||||
CheckTrigger(ctx context.Context, orgID string, workflow uuid.UUID) error
|
||||
WorkflowName(ctx context.Context, orgID string, workflow uuid.UUID) (string, error)
|
||||
}
|
||||
|
||||
// Deliveries recognises the echo of a message Archie sent. It returns the run
|
||||
@@ -716,15 +717,15 @@ func (m *Module) noteUnmatched(ctx context.Context, tx *sqlx.Tx, e store.Event)
|
||||
func (m *Module) startRun(ctx context.Context, e store.Event, t store.Trigger, input jsontext.Value) (uuid.UUID, *noRunReason, error) {
|
||||
ctx = governance.WithPrincipal(ctx, governance.WorkloadPrincipal(governance.DefaultOrgID))
|
||||
runID, err := m.runs.Start(ctx, runs.StartRequest{
|
||||
OrgID: e.OrgID, Workflow: t.Workflow, Key: e.ID.String() + ":" + t.Name, Input: input,
|
||||
OrgID: e.OrgID, WorkflowID: t.WorkflowID, Key: e.ID.String() + ":" + t.Name, Input: input,
|
||||
})
|
||||
if errors.Is(err, governance.ErrDenied) {
|
||||
m.log.WarnContext(ctx, "trigger not permitted to start its workflow", "event", e.ID, "trigger", t.Name, "error", err)
|
||||
return uuid.Nil, &noRunReason{outcome: store.OutcomeDenied, Code: reasonAccessDenied, Workflow: t.Workflow, Detail: err.Error()}, nil
|
||||
return uuid.Nil, &noRunReason{outcome: store.OutcomeDenied, Code: reasonAccessDenied, WorkflowID: t.WorkflowID, Workflow: m.workflowName(ctx, t.WorkflowID), Detail: err.Error()}, nil
|
||||
}
|
||||
if errors.Is(err, runs.ErrDisabled) {
|
||||
m.log.InfoContext(ctx, "trigger started no run: the workflow is disabled", "event", e.ID, "trigger", t.Name, "workflow", t.Workflow)
|
||||
return uuid.Nil, &noRunReason{outcome: store.OutcomeDisabled, Code: reasonWorkflowDisabled, Workflow: t.Workflow}, nil
|
||||
m.log.InfoContext(ctx, "trigger started no run: the workflow is disabled", "event", e.ID, "trigger", t.Name, "workflow", t.WorkflowID)
|
||||
return uuid.Nil, &noRunReason{outcome: store.OutcomeDisabled, Code: reasonWorkflowDisabled, WorkflowID: t.WorkflowID, Workflow: m.workflowName(ctx, t.WorkflowID)}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.Nil, nil, fmt.Errorf("start run for trigger %q: %w", t.Name, err)
|
||||
@@ -780,8 +781,21 @@ type noRunReason struct {
|
||||
Code string `json:"code"`
|
||||
Mapping string `json:"mapping,omitempty"`
|
||||
Failures []mapping.Failure `json:"failures,omitempty"`
|
||||
Workflow string `json:"workflow,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
// WorkflowID is the workflow the trigger starts, and Workflow its name
|
||||
// when the dispatch was refused.
|
||||
WorkflowID uuid.UUID `json:"workflow_id,omitzero"`
|
||||
Workflow string `json:"workflow,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
// workflowName returns the name of a workflow, or its id when the name can't
|
||||
// be read.
|
||||
func (m *Module) workflowName(ctx context.Context, id uuid.UUID) string {
|
||||
name, err := m.runs.WorkflowName(ctx, m.orgID, id)
|
||||
if err != nil {
|
||||
return id.String()
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// inputFor builds the run input for trigger t. For a trigger with a mapping,
|
||||
|
||||
@@ -400,7 +400,7 @@ func (s *Store) SetTriggerState(ctx context.Context, orgID, name string, approve
|
||||
func (s *Store) Trigger(ctx context.Context, orgID, name string) (Trigger, error) {
|
||||
var t Trigger
|
||||
err := s.db.GetContext(ctx, &t, `
|
||||
SELECT org_id, name, source, event_type, filter, workflow, enabled, approved, event_type_id, mapping_id,
|
||||
SELECT org_id, name, source_id, event_type, filter, workflow_id, enabled, approved, event_type_id, mapping_id,
|
||||
schedule_every_s, schedule_since
|
||||
FROM events.triggers WHERE org_id = $1 AND name = $2`, orgID, name)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
|
||||
@@ -127,11 +127,11 @@ type Trigger struct {
|
||||
OrgID string `db:"org_id"`
|
||||
Name string `db:"name"`
|
||||
// SourceID is null for a scheduled trigger, which has no source.
|
||||
SourceID uuid.NullUUID `db:"source_id"`
|
||||
EventType string `db:"event_type"`
|
||||
Filter jsontext.Value `db:"filter"`
|
||||
Workflow string `db:"workflow"`
|
||||
Enabled bool `db:"enabled"`
|
||||
SourceID uuid.NullUUID `db:"source_id"`
|
||||
EventType string `db:"event_type"`
|
||||
Filter jsontext.Value `db:"filter"`
|
||||
WorkflowID uuid.UUID `db:"workflow_id"`
|
||||
Enabled bool `db:"enabled"`
|
||||
// ScheduleEverySeconds is the interval a scheduled trigger fires on; it
|
||||
// is null for a trigger that fires on events.
|
||||
ScheduleEverySeconds sql.NullInt64 `db:"schedule_every_s"`
|
||||
@@ -344,7 +344,7 @@ func SetEventPayload(ctx context.Context, tx *sqlx.Tx, e Event) error {
|
||||
func Triggers(ctx context.Context, tx *sqlx.Tx, orgID string, sourceID uuid.NullUUID, eventType string, typeID uuid.NullUUID) ([]Trigger, error) {
|
||||
var out []Trigger
|
||||
if err := tx.SelectContext(ctx, &out, `
|
||||
SELECT org_id, name, source_id, event_type, filter, workflow, enabled, approved, event_type_id, mapping_id
|
||||
SELECT org_id, name, source_id, event_type, filter, workflow_id, enabled, approved, event_type_id, mapping_id
|
||||
FROM events.triggers
|
||||
WHERE org_id = $1 AND source_id IS NOT DISTINCT FROM $2 AND (event_type = $3 OR event_type = '') AND enabled AND approved
|
||||
AND (event_type_id IS NULL OR event_type_id = $4)
|
||||
@@ -395,14 +395,14 @@ func RecordNoRun(ctx context.Context, tx *sqlx.Tx, eventID uuid.UUID, trigger, o
|
||||
// UpsertTrigger creates or replaces a trigger.
|
||||
func (s *Store) UpsertTrigger(ctx context.Context, t Trigger) error {
|
||||
if _, err := s.db.NamedExecContext(ctx, `
|
||||
INSERT INTO events.triggers (org_id, name, source_id, event_type, filter, workflow, enabled, approved,
|
||||
INSERT INTO events.triggers (org_id, name, source_id, event_type, filter, workflow_id, enabled, approved,
|
||||
event_type_id, mapping_id, schedule_every_s, schedule_since)
|
||||
VALUES (:org_id, :name, :source_id, :event_type, :filter, :workflow, :enabled, :approved,
|
||||
VALUES (:org_id, :name, :source_id, :event_type, :filter, :workflow_id, :enabled, :approved,
|
||||
:event_type_id, :mapping_id,
|
||||
CAST(:schedule_every_s AS integer), CASE WHEN CAST(:schedule_every_s AS integer) IS NULL THEN NULL ELSE now() END)
|
||||
ON CONFLICT (org_id, name) DO UPDATE
|
||||
SET source_id = EXCLUDED.source_id, event_type = EXCLUDED.event_type, filter = EXCLUDED.filter,
|
||||
workflow = EXCLUDED.workflow, enabled = EXCLUDED.enabled, approved = EXCLUDED.approved,
|
||||
workflow_id = EXCLUDED.workflow_id, enabled = EXCLUDED.enabled, approved = EXCLUDED.approved,
|
||||
event_type_id = EXCLUDED.event_type_id, mapping_id = EXCLUDED.mapping_id,
|
||||
schedule_since = CASE
|
||||
WHEN EXCLUDED.schedule_every_s IS NULL THEN NULL
|
||||
@@ -419,7 +419,7 @@ func (s *Store) UpsertTrigger(ctx context.Context, t Trigger) error {
|
||||
func (s *Store) ScheduledTriggers(ctx context.Context, orgID string) ([]Trigger, error) {
|
||||
var out []Trigger
|
||||
if err := s.db.SelectContext(ctx, &out, `
|
||||
SELECT org_id, name, source_id, event_type, filter, workflow, enabled, approved, event_type_id, mapping_id,
|
||||
SELECT org_id, name, source_id, event_type, filter, workflow_id, enabled, approved, event_type_id, mapping_id,
|
||||
schedule_every_s, schedule_since
|
||||
FROM events.triggers
|
||||
WHERE org_id = $1 AND enabled AND approved AND schedule_every_s IS NOT NULL ORDER BY name`, orgID); err != nil {
|
||||
@@ -503,7 +503,7 @@ func (s *Store) RunsForEvent(ctx context.Context, orgID string, id uuid.UUID) ([
|
||||
func (s *Store) AllTriggers(ctx context.Context, orgID string) ([]Trigger, error) {
|
||||
var out []Trigger
|
||||
if err := s.db.SelectContext(ctx, &out, `
|
||||
SELECT org_id, name, source_id, event_type, filter, workflow, enabled, approved, event_type_id, mapping_id,
|
||||
SELECT org_id, name, source_id, event_type, filter, workflow_id, enabled, approved, event_type_id, mapping_id,
|
||||
schedule_every_s, schedule_since
|
||||
FROM events.triggers WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
|
||||
return nil, fmt.Errorf("list triggers: %w", err)
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
package events
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
|
||||
// WorkflowTriggers names the triggers that start workflow.
|
||||
func (m *Module) WorkflowTriggers(ctx context.Context, workflow string) ([]string, error) {
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// WorkflowTriggers returns the names of the triggers that start the workflow.
|
||||
func (m *Module) WorkflowTriggers(ctx context.Context, workflow uuid.UUID) ([]string, error) {
|
||||
triggers, err := m.store.AllTriggers(ctx, m.orgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var names []string
|
||||
for _, t := range triggers {
|
||||
if t.Workflow == workflow {
|
||||
if t.WorkflowID == workflow {
|
||||
names = append(names, t.Name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,8 +90,8 @@ type Groups interface {
|
||||
|
||||
// Workflows installs workflow documents, starts runs and manages dry runs.
|
||||
type Workflows interface {
|
||||
Install(ctx context.Context, orgID, name, body, by string) (int, error)
|
||||
Has(ctx context.Context, orgID, name string) (bool, error)
|
||||
Install(ctx context.Context, orgID, name, body, by string) (uuid.UUID, int, error)
|
||||
WorkflowNamed(ctx context.Context, orgID, name string) (uuid.UUID, error)
|
||||
Start(ctx context.Context, req runs.StartRequest) (uuid.UUID, error)
|
||||
StartDry(ctx context.Context, req runs.DryRequest) (uuid.UUID, error)
|
||||
DryReport(ctx context.Context, orgID string, id uuid.UUID) (runs.DryReport, bool, error)
|
||||
@@ -405,11 +405,11 @@ func (m *Module) readyToApprove(ctx context.Context, p store.Proposal, actions [
|
||||
if err := m.check(ctx, c.Name, c.Workflow, c.PolicyKind, c.Policy); err != nil {
|
||||
return err
|
||||
}
|
||||
taken, err := m.workflows.Has(ctx, m.orgID, c.Name)
|
||||
if err != nil {
|
||||
switch _, err := m.workflows.WorkflowNamed(ctx, m.orgID, c.Name); {
|
||||
case errors.Is(err, runs.ErrNoWorkflow):
|
||||
case err != nil:
|
||||
return fmt.Errorf("check the workflow name: %w", err)
|
||||
}
|
||||
if taken {
|
||||
default:
|
||||
return fmt.Errorf("%w: a workflow named %s already exists; rename the proposal", ErrTaken, c.Name)
|
||||
}
|
||||
}
|
||||
@@ -521,7 +521,7 @@ func (m *Module) apply(ctx context.Context, p store.Proposal) error {
|
||||
}
|
||||
if len(actions) > 0 {
|
||||
runID, err := m.workflows.Start(workloadContext(ctx), runs.StartRequest{
|
||||
OrgID: m.orgID, Workflow: runs.ProposalWorkflow, Key: "proposal:" + p.ID.String(),
|
||||
OrgID: m.orgID, WorkflowID: runs.ShippedID(m.orgID, runs.ProposalWorkflow), Key: "proposal:" + p.ID.String(),
|
||||
Input: jsontext.Value(`{"proposal_id":"` + p.ID.String() + `"}`),
|
||||
})
|
||||
if err != nil {
|
||||
@@ -543,7 +543,7 @@ func (m *Module) publishWorkflow(ctx context.Context, p store.Proposal) error {
|
||||
if err := json.Unmarshal(p.Change, &c); err != nil {
|
||||
return fmt.Errorf("read the workflow change: %w", err)
|
||||
}
|
||||
if _, err := m.workflows.Install(ctx, m.orgID, c.Name, c.Workflow, p.AnsweredByID.String); err != nil {
|
||||
if _, _, err := m.workflows.Install(ctx, m.orgID, c.Name, c.Workflow, p.AnsweredByID.String); err != nil {
|
||||
return fmt.Errorf("install the workflow: %w", err)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -252,7 +252,7 @@ func (m *Module) dryRun(ctx context.Context, p store.Proposal, eventID uuid.UUID
|
||||
return errNoEvent
|
||||
}
|
||||
runID, err := m.workflows.StartDry(ctx, runs.DryRequest{
|
||||
OrgID: m.orgID, Workflow: c.Name, Document: c.Workflow, PolicyKind: c.PolicyKind, Policy: c.Policy, Input: event.Input,
|
||||
OrgID: m.orgID, Name: c.Name, Document: c.Workflow, PolicyKind: c.PolicyKind, Policy: c.Policy, Input: event.Input,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("start the dry run: %w", err)
|
||||
@@ -280,7 +280,7 @@ func (m *Module) publishTrigger(ctx context.Context, p store.Proposal) error {
|
||||
return fmt.Errorf("add the policy: %w", err)
|
||||
}
|
||||
}
|
||||
version, err := m.workflows.Install(ctx, m.orgID, c.Name, c.Workflow, by)
|
||||
workflow, version, err := m.workflows.Install(ctx, m.orgID, c.Name, c.Workflow, by)
|
||||
if err != nil {
|
||||
return fmt.Errorf("install the workflow: %w", err)
|
||||
}
|
||||
@@ -288,16 +288,16 @@ func (m *Module) publishTrigger(ctx context.Context, p store.Proposal) error {
|
||||
return err
|
||||
}
|
||||
if err := m.groups.SaveTrigger(ctx, events.TriggerSpec{
|
||||
Name: c.Name, SourceID: c.SourceID, EventType: c.EventType, Filter: c.Filter, Workflow: c.Name,
|
||||
Name: c.Name, SourceID: c.SourceID, EventType: c.EventType, Filter: c.Filter, WorkflowID: workflow,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("save the trigger: %w", err)
|
||||
}
|
||||
return m.runPrompting(ctx, p, c)
|
||||
return m.runPrompting(ctx, p, c, workflow)
|
||||
}
|
||||
|
||||
// runPrompting starts the new trigger's workflow for each stored event that
|
||||
// prompted the proposal, keyed so a retry starts none twice.
|
||||
func (m *Module) runPrompting(ctx context.Context, p store.Proposal, c triggerChange) error {
|
||||
func (m *Module) runPrompting(ctx context.Context, p store.Proposal, c triggerChange, workflow uuid.UUID) error {
|
||||
var prompted []uuid.UUID
|
||||
if err := json.Unmarshal(p.PromptedBy, &prompted); err != nil {
|
||||
return fmt.Errorf("read the prompting events: %w", err)
|
||||
@@ -315,7 +315,7 @@ func (m *Module) runPrompting(ctx context.Context, p store.Proposal, c triggerCh
|
||||
continue
|
||||
}
|
||||
runID, err := m.workflows.Start(ctx, runs.StartRequest{
|
||||
OrgID: m.orgID, Workflow: c.Name, Key: "proposal:" + p.ID.String() + ":" + e.ID.String(), Input: e.Input,
|
||||
OrgID: m.orgID, WorkflowID: workflow, Key: "proposal:" + p.ID.String() + ":" + e.ID.String(), Input: e.Input,
|
||||
})
|
||||
switch {
|
||||
case err == nil:
|
||||
|
||||
@@ -65,7 +65,7 @@ func (c claimsOne) Claim(context.Context, string, uuid.UUID, time.Duration) (sto
|
||||
// and leaves the run for another attempt. Without it a revoked grant would
|
||||
// keep running queued work.
|
||||
func TestRunsAreAuthorizedAtStartAndAtEveryClaim(t *testing.T) {
|
||||
workload := asked{governance.WorkloadID, governance.ActionRun, governance.KindWorkflow, "triage"}
|
||||
workload := asked{governance.WorkloadID, governance.ActionRun, governance.KindWorkflow, wid("triage").String()}
|
||||
tests := []struct {
|
||||
name string
|
||||
decision governance.Decision
|
||||
@@ -100,14 +100,14 @@ func TestRunsAreAuthorizedAtStartAndAtEveryClaim(t *testing.T) {
|
||||
|
||||
var err error
|
||||
if tt.claim {
|
||||
engine.work = claimsOne{work, store.Run{ID: uuid.New(), OrgID: "org", Workflow: "triage", Version: 1, Input: jsontext.Value(`null`)}}
|
||||
engine.work = claimsOne{work, store.Run{ID: uuid.New(), OrgID: "org", WorkflowID: wid("triage"), Workflow: "triage", Version: 1, Input: jsontext.Value(`null`)}}
|
||||
_, err = engine.claimAndExecute(t.Context())
|
||||
} else {
|
||||
ctx := t.Context()
|
||||
if !tt.noPrincipal {
|
||||
ctx = governance.WithPrincipal(ctx, governance.WorkloadPrincipal(governance.DefaultOrgID))
|
||||
}
|
||||
_, err = engine.Start(ctx, StartRequest{OrgID: "org", Workflow: "triage", Key: "event:trigger"})
|
||||
_, err = engine.Start(ctx, StartRequest{OrgID: "org", WorkflowID: wid("triage"), Key: "event:trigger"})
|
||||
}
|
||||
|
||||
if !errors.Is(err, tt.wantErr) {
|
||||
|
||||
@@ -74,7 +74,7 @@ func TestTriageClassificationUsesPinnedModel(t *testing.T) {
|
||||
}
|
||||
engine := newEngine(nil, &fakeWork{}, slog.New(slog.DiscardHandler), Options{})
|
||||
engine.Use(Deps{Settings: modelSettings{}})
|
||||
_, err = engine.Install(t.Context(), "org", "triage", strings.Replace(body, "model: fast", "model: missing", 1), "operator")
|
||||
_, err = engine.Publish(t.Context(), "org", wid("triage"), strings.Replace(body, "model: fast", "model: missing", 1), "operator", nil)
|
||||
var invalid *InvalidError
|
||||
if !errors.As(err, &invalid) || len(invalid.Problems) != 1 || invalid.Problems[0].Path != "steps[0].settings.model" {
|
||||
t.Fatalf("saving an unknown alias returned %v, want a model setting error", err)
|
||||
|
||||
+149
-52
@@ -4,28 +4,33 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/runs/internal/store"
|
||||
)
|
||||
|
||||
// definitions is the stored workflows and drafts the catalogue operations read
|
||||
// and change.
|
||||
type definitions interface {
|
||||
Workflow(ctx context.Context, orgID, name string, version int) (store.Workflow, error)
|
||||
Named(ctx context.Context, orgID, name string) (store.Identity, error)
|
||||
Workflow(ctx context.Context, orgID string, id uuid.UUID, version int) (store.Workflow, error)
|
||||
Workflows(ctx context.Context, orgID string) ([]store.Workflow, error)
|
||||
AddWorkflow(ctx context.Context, orgID, name, body, by string, expected *int) (store.Workflow, error)
|
||||
SetEnabled(ctx context.Context, orgID, name string, enabled bool) error
|
||||
DeleteWorkflow(ctx context.Context, orgID, name string) error
|
||||
DeleteDraft(ctx context.Context, orgID, name string) (bool, error)
|
||||
ActiveRuns(ctx context.Context, orgID, name string) (int, error)
|
||||
AddWorkflow(ctx context.Context, orgID string, id uuid.UUID, body string, calls store.Calls, by string, expected *int) (store.Workflow, error)
|
||||
SetEnabled(ctx context.Context, orgID string, id uuid.UUID, enabled bool) error
|
||||
DeleteWorkflow(ctx context.Context, orgID string, id uuid.UUID) error
|
||||
DeleteDraft(ctx context.Context, orgID string, id uuid.UUID) (bool, error)
|
||||
ActiveRuns(ctx context.Context, orgID string, id uuid.UUID) (int, error)
|
||||
}
|
||||
|
||||
// Referrers finds what outside the runs module names a workflow.
|
||||
// Referrers finds what outside the runs module refers to a workflow.
|
||||
type Referrers interface {
|
||||
// WorkflowTriggers names the triggers that start the workflow.
|
||||
WorkflowTriggers(ctx context.Context, workflow string) ([]string, error)
|
||||
// WorkflowTriggers returns the names of the triggers that start the
|
||||
// workflow.
|
||||
WorkflowTriggers(ctx context.Context, workflow uuid.UUID) ([]string, error)
|
||||
}
|
||||
|
||||
// UseReferrers tells the engine where to look for the triggers that start a
|
||||
@@ -42,8 +47,10 @@ var (
|
||||
ErrVersionConflict = store.ErrVersionConflict
|
||||
// ErrDisabled is returned when a start names a disabled workflow.
|
||||
ErrDisabled = errors.New("the workflow is disabled")
|
||||
// ErrNoWorkflow is returned when no workflow has the name.
|
||||
// ErrNoWorkflow is returned when no workflow has the id or name.
|
||||
ErrNoWorkflow = store.ErrNoWorkflow
|
||||
// ErrNameTaken is returned when another workflow has the name.
|
||||
ErrNameTaken = store.ErrNameTaken
|
||||
)
|
||||
|
||||
// refusal is a start the workflow can't take as asked: its inputs are wrong or
|
||||
@@ -69,19 +76,103 @@ func (e *ReferencedError) Error() string {
|
||||
return fmt.Sprintf("workflow %q is still used by %s", e.Workflow, strings.Join(e.By, ", "))
|
||||
}
|
||||
|
||||
// Publish stores body as the next version of the workflow name and discards
|
||||
// its draft. When expected is set, the latest version must be that one (zero
|
||||
// for a workflow not yet published), or the body is not stored. A body that
|
||||
// doesn't validate is stored as nothing.
|
||||
func (e *Engine) Publish(ctx context.Context, orgID, name, body, by string, expected *int) (int, error) {
|
||||
if _, err := e.validateDocument(ctx, body); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return e.publish(ctx, orgID, name, body, by, expected)
|
||||
// Create adds a workflow called name, with no versions, and returns its id.
|
||||
func (e *Engine) Create(ctx context.Context, orgID, name string) (uuid.UUID, error) {
|
||||
return e.db.CreateWorkflow(ctx, orgID, name)
|
||||
}
|
||||
|
||||
func (e *Engine) publish(ctx context.Context, orgID, name, body, by string, expected *int) (int, error) {
|
||||
latest, err := e.defs.Workflow(ctx, orgID, name, 0)
|
||||
// shippedNamespace derives the ids of the workflows that ship with the binary.
|
||||
var shippedNamespace = uuid.MustParse("f0682f0e-30fc-4e00-885e-e803e53803f6")
|
||||
|
||||
// ShippedID is the id of the workflow the binary ships as name in an
|
||||
// organisation. It is the same on every boot, so a shipped workflow that was
|
||||
// renamed is updated in place rather than installed again under its first
|
||||
// name.
|
||||
func ShippedID(orgID, name string) uuid.UUID {
|
||||
return uuid.NewSHA1(shippedNamespace, []byte(orgID+"\x00"+name))
|
||||
}
|
||||
|
||||
// InstallShipped puts a workflow that ships with the binary in place under its
|
||||
// fixed id, and publishes body as its next version unless the latest version
|
||||
// already is body. A shipped workflow that was deleted stays deleted. It
|
||||
// returns the version in force, 0 for a deleted workflow.
|
||||
func (e *Engine) InstallShipped(ctx context.Context, orgID, name, body, by string) (int, error) {
|
||||
id := ShippedID(orgID, name)
|
||||
if err := e.db.EnsureWorkflow(ctx, orgID, id, name); err != nil {
|
||||
return 0, fmt.Errorf("create shipped workflow %q: %w", name, err)
|
||||
}
|
||||
w, err := e.db.Identity(ctx, orgID, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if w.Deleted {
|
||||
return 0, nil
|
||||
}
|
||||
return e.Publish(ctx, orgID, id, body, by, nil)
|
||||
}
|
||||
|
||||
// Rename gives a workflow a new name. Its runs, triggers and the versions of
|
||||
// other workflows that call it refer to it by id, so they are unchanged.
|
||||
func (e *Engine) Rename(ctx context.Context, orgID string, id uuid.UUID, name string) error {
|
||||
return e.db.Rename(ctx, orgID, id, name)
|
||||
}
|
||||
|
||||
// Publish stores body as the next version of a workflow and discards its
|
||||
// draft. When expected is set, the latest version must be that one (zero for a
|
||||
// workflow not yet published), or the body is not stored. A body that doesn't
|
||||
// validate, or that calls a workflow no workflow is named, is stored as
|
||||
// nothing.
|
||||
func (e *Engine) Publish(ctx context.Context, orgID string, id uuid.UUID, body, by string, expected *int) (int, error) {
|
||||
doc, err := e.validateDocument(ctx, body)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
calls, err := e.resolveCalls(ctx, orgID, doc)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return e.publish(ctx, orgID, id, body, calls, by, expected)
|
||||
}
|
||||
|
||||
// checkDocument reports what Publish would refuse in body before anything is
|
||||
// stored: a document that doesn't validate, or one that calls a workflow no
|
||||
// workflow is named.
|
||||
func (e *Engine) checkDocument(ctx context.Context, orgID, body string) error {
|
||||
doc, err := e.validateDocument(ctx, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = e.resolveCalls(ctx, orgID, doc)
|
||||
return err
|
||||
}
|
||||
|
||||
// resolveCalls maps each workflow name the document calls, hands off to or
|
||||
// runs after an approval onto that workflow's id.
|
||||
func (e *Engine) resolveCalls(ctx context.Context, orgID string, doc Document) (store.Calls, error) {
|
||||
calls := store.Calls{}
|
||||
var problems []Problem
|
||||
for _, name := range workflowsNamedIn(doc.Steps) {
|
||||
if _, done := calls[name]; done {
|
||||
continue
|
||||
}
|
||||
w, err := e.defs.Named(ctx, orgID, name)
|
||||
if errors.Is(err, store.ErrNoWorkflow) {
|
||||
problems = append(problems, Problem{Path: "steps", Message: fmt.Sprintf("no workflow is named %q", name)})
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
calls[name] = w.ID
|
||||
}
|
||||
if len(problems) > 0 {
|
||||
return nil, &InvalidError{Problems: problems}
|
||||
}
|
||||
return calls, nil
|
||||
}
|
||||
|
||||
func (e *Engine) publish(ctx context.Context, orgID string, id uuid.UUID, body string, calls store.Calls, by string, expected *int) (int, error) {
|
||||
latest, err := e.defs.Workflow(ctx, orgID, id, 0)
|
||||
if err != nil && !errors.Is(err, store.ErrNoWorkflow) {
|
||||
return 0, err
|
||||
}
|
||||
@@ -89,51 +180,59 @@ func (e *Engine) publish(ctx context.Context, orgID, name, body, by string, expe
|
||||
return 0, ErrVersionConflict
|
||||
}
|
||||
version := latest.Version
|
||||
if version == 0 || normalise(latest.Body) != normalise(body) {
|
||||
w, err := e.defs.AddWorkflow(ctx, orgID, name, body, by, expected)
|
||||
if version == 0 || normalise(latest.Body) != normalise(body) || !maps.Equal(latest.Calls, calls) {
|
||||
w, err := e.defs.AddWorkflow(ctx, orgID, id, body, calls, by, expected)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
version = w.Version
|
||||
}
|
||||
if _, err := e.defs.DeleteDraft(ctx, orgID, name); err != nil {
|
||||
e.log.WarnContext(ctx, "discard published draft", "workflow", name, "error", err)
|
||||
if _, err := e.defs.DeleteDraft(ctx, orgID, id); err != nil {
|
||||
e.log.WarnContext(ctx, "discard published draft", "workflow", id, "error", err)
|
||||
}
|
||||
return version, nil
|
||||
}
|
||||
|
||||
// SetEnabled enables or disables a workflow. A disabled workflow is not
|
||||
// started by a trigger, another workflow or a person.
|
||||
func (e *Engine) SetEnabled(ctx context.Context, orgID, name string, enabled bool) error {
|
||||
return e.defs.SetEnabled(ctx, orgID, name, enabled)
|
||||
func (e *Engine) SetEnabled(ctx context.Context, orgID string, id uuid.UUID, enabled bool) error {
|
||||
return e.defs.SetEnabled(ctx, orgID, id, enabled)
|
||||
}
|
||||
|
||||
// Delete removes a workflow with all its versions and its draft. It is refused,
|
||||
// naming what depends on the workflow, while a trigger or another workflow
|
||||
// names it or one of its runs is still going.
|
||||
func (e *Engine) Delete(ctx context.Context, orgID, name string) error {
|
||||
if _, err := e.defs.Workflow(ctx, orgID, name, 0); err != nil {
|
||||
// Delete deletes a workflow and discards its draft. It is refused, naming what
|
||||
// depends on the workflow, while a trigger or another workflow refers to it or
|
||||
// one of its runs is still going.
|
||||
func (e *Engine) Delete(ctx context.Context, orgID string, id uuid.UUID) error {
|
||||
w, err := e.defs.Workflow(ctx, orgID, id, 0)
|
||||
if errors.Is(err, store.ErrNoWorkflow) {
|
||||
// A workflow that was created and never published has no version.
|
||||
return e.defs.DeleteWorkflow(ctx, orgID, id)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
by, err := e.referencesTo(ctx, orgID, name)
|
||||
if w.Deleted {
|
||||
return ErrNoWorkflow
|
||||
}
|
||||
by, err := e.referencesTo(ctx, orgID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(by) > 0 {
|
||||
return &ReferencedError{Workflow: name, By: by}
|
||||
return &ReferencedError{Workflow: w.Name, By: by}
|
||||
}
|
||||
return e.defs.DeleteWorkflow(ctx, orgID, name)
|
||||
return e.defs.DeleteWorkflow(ctx, orgID, id)
|
||||
}
|
||||
|
||||
func (e *Engine) referencesTo(ctx context.Context, orgID, name string) ([]string, error) {
|
||||
func (e *Engine) referencesTo(ctx context.Context, orgID string, id uuid.UUID) ([]string, error) {
|
||||
var by []string
|
||||
e.mu.RLock()
|
||||
referrers := e.referrers
|
||||
e.mu.RUnlock()
|
||||
if referrers != nil {
|
||||
triggers, err := referrers.WorkflowTriggers(ctx, name)
|
||||
triggers, err := referrers.WorkflowTriggers(ctx, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("find triggers of %q: %w", name, err)
|
||||
return nil, fmt.Errorf("find triggers of workflow %s: %w", id, err)
|
||||
}
|
||||
for _, t := range triggers {
|
||||
by = append(by, "trigger "+t)
|
||||
@@ -144,18 +243,11 @@ func (e *Engine) referencesTo(ctx context.Context, orgID, name string) ([]string
|
||||
return nil, err
|
||||
}
|
||||
for _, w := range all {
|
||||
if w.Name == name {
|
||||
continue
|
||||
}
|
||||
doc, err := ParseDocument(w.Body)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if slices.Contains(workflowsNamedIn(doc.Steps), name) {
|
||||
if w.ID != id && slices.Contains(slices.Collect(maps.Values(w.Calls)), id) {
|
||||
by = append(by, "workflow "+w.Name)
|
||||
}
|
||||
}
|
||||
active, err := e.defs.ActiveRuns(ctx, orgID, name)
|
||||
active, err := e.defs.ActiveRuns(ctx, orgID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -165,17 +257,22 @@ func (e *Engine) referencesTo(ctx context.Context, orgID, name string) ([]string
|
||||
return by, nil
|
||||
}
|
||||
|
||||
// workflowsNamedIn lists the workflows steps call or hand off to, however
|
||||
// deeply the steps are nested.
|
||||
// workflowsNamedIn lists the workflows steps call, hand off to or run after an
|
||||
// approval, however deeply the steps are nested.
|
||||
func workflowsNamedIn(steps []Step) []string {
|
||||
var out []string
|
||||
for _, s := range steps {
|
||||
if s.Type == typeCall || s.Type == typeHandoff {
|
||||
if s.Type == typeCall || s.Type == typeHandoff || s.Type == typeApprove {
|
||||
var named struct {
|
||||
Workflow string `yaml:"workflow"`
|
||||
Then string `yaml:"then"`
|
||||
}
|
||||
if err := s.Settings.Decode(&named); err == nil && named.Workflow != "" {
|
||||
out = append(out, named.Workflow)
|
||||
if err := s.Settings.Decode(&named); err == nil {
|
||||
for _, name := range []string{named.Workflow, named.Then} {
|
||||
if name = strings.TrimSpace(name); name != "" {
|
||||
out = append(out, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, branch := range s.Parallel {
|
||||
|
||||
@@ -8,11 +8,14 @@ import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
"github.com/samcharles93/archie-core/modules/runs/internal/store"
|
||||
)
|
||||
|
||||
// shelf is an in-memory set of stored workflows, drafts and runs in progress.
|
||||
// shelf is an in-memory set of stored workflows, drafts and runs in progress,
|
||||
// keyed by name. A workflow's id is wid of its name.
|
||||
type shelf struct {
|
||||
versions map[string][]string
|
||||
drafts map[string]bool
|
||||
@@ -20,18 +23,42 @@ type shelf struct {
|
||||
deleted []string
|
||||
}
|
||||
|
||||
func (s *shelf) Workflow(_ context.Context, _, name string, _ int) (store.Workflow, error) {
|
||||
func (s *shelf) nameOf(id uuid.UUID) string {
|
||||
for name := range s.versions {
|
||||
if wid(name) == id {
|
||||
return name
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *shelf) Named(_ context.Context, _, name string) (store.Identity, error) {
|
||||
if _, ok := s.versions[name]; !ok {
|
||||
return store.Identity{}, store.ErrNoWorkflow
|
||||
}
|
||||
return store.Identity{ID: wid(name), Name: name}, nil
|
||||
}
|
||||
|
||||
// Workflow resolves the names the latest version calls as publishing would.
|
||||
func (s *shelf) Workflow(_ context.Context, _ string, id uuid.UUID, _ int) (store.Workflow, error) {
|
||||
name := s.nameOf(id)
|
||||
v := s.versions[name]
|
||||
if len(v) == 0 {
|
||||
return store.Workflow{}, store.ErrNoWorkflow
|
||||
}
|
||||
return store.Workflow{Name: name, Version: len(v), Body: v[len(v)-1]}, nil
|
||||
calls := store.Calls{}
|
||||
if doc, err := ParseDocument(v[len(v)-1]); err == nil {
|
||||
for _, called := range workflowsNamedIn(doc.Steps) {
|
||||
calls[called] = wid(called)
|
||||
}
|
||||
}
|
||||
return store.Workflow{ID: id, Name: name, Version: len(v), Body: v[len(v)-1], Calls: calls}, nil
|
||||
}
|
||||
|
||||
func (s *shelf) Workflows(ctx context.Context, org string) ([]store.Workflow, error) {
|
||||
var out []store.Workflow
|
||||
for name := range s.versions {
|
||||
w, _ := s.Workflow(ctx, org, name, 0)
|
||||
w, _ := s.Workflow(ctx, org, wid(name), 0)
|
||||
out = append(out, w)
|
||||
}
|
||||
return out, nil
|
||||
@@ -39,33 +66,42 @@ func (s *shelf) Workflows(ctx context.Context, org string) ([]store.Workflow, er
|
||||
|
||||
// AddWorkflow stores unconditionally: the store's own check is SQL, so what is
|
||||
// tested here is the check the engine makes before it.
|
||||
func (s *shelf) AddWorkflow(_ context.Context, _, name, body, _ string, _ *int) (store.Workflow, error) {
|
||||
func (s *shelf) AddWorkflow(_ context.Context, _ string, id uuid.UUID, body string, _ store.Calls, _ string, _ *int) (store.Workflow, error) {
|
||||
name := s.nameOf(id)
|
||||
s.versions[name] = append(s.versions[name], body)
|
||||
return store.Workflow{Name: name, Version: len(s.versions[name]), Body: body}, nil
|
||||
return store.Workflow{ID: id, Name: name, Version: len(s.versions[name]), Body: body}, nil
|
||||
}
|
||||
|
||||
func (s *shelf) SetEnabled(context.Context, string, string, bool) error { return nil }
|
||||
func (s *shelf) SetEnabled(context.Context, string, uuid.UUID, bool) error { return nil }
|
||||
|
||||
func (s *shelf) DeleteWorkflow(_ context.Context, _, name string) error {
|
||||
func (s *shelf) DeleteWorkflow(_ context.Context, _ string, id uuid.UUID) error {
|
||||
name := s.nameOf(id)
|
||||
delete(s.versions, name)
|
||||
s.deleted = append(s.deleted, name)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *shelf) DeleteDraft(_ context.Context, _, name string) (bool, error) {
|
||||
func (s *shelf) DeleteDraft(_ context.Context, _ string, id uuid.UUID) (bool, error) {
|
||||
name := s.nameOf(id)
|
||||
had := s.drafts[name]
|
||||
delete(s.drafts, name)
|
||||
return had, nil
|
||||
}
|
||||
|
||||
func (s *shelf) ActiveRuns(_ context.Context, _, name string) (int, error) {
|
||||
return s.active[name], nil
|
||||
func (s *shelf) ActiveRuns(_ context.Context, _ string, id uuid.UUID) (int, error) {
|
||||
return s.active[s.nameOf(id)], nil
|
||||
}
|
||||
|
||||
// triggerNames lists the triggers of each workflow by the workflow's name.
|
||||
type triggerNames map[string][]string
|
||||
|
||||
func (t triggerNames) WorkflowTriggers(_ context.Context, workflow string) ([]string, error) {
|
||||
return t[workflow], nil
|
||||
func (t triggerNames) WorkflowTriggers(_ context.Context, workflow uuid.UUID) ([]string, error) {
|
||||
for name, triggers := range t {
|
||||
if wid(name) == workflow {
|
||||
return triggers, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
const notifyDoc = "steps:\n - type: run.notify\n"
|
||||
@@ -94,12 +130,9 @@ func TestPublishRefusesAStaleVersion(t *testing.T) {
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := &shelf{versions: map[string][]string{}, drafts: map[string]bool{"triage": true}}
|
||||
if tt.stored != nil {
|
||||
s.versions["triage"] = tt.stored
|
||||
}
|
||||
s := &shelf{versions: map[string][]string{"triage": tt.stored}, drafts: map[string]bool{"triage": true}}
|
||||
e := &Engine{defs: s, log: slog.New(slog.DiscardHandler)}
|
||||
_, err := e.publish(t.Context(), "org", "triage", tt.body, "admin", tt.expected)
|
||||
_, err := e.publish(t.Context(), "org", wid("triage"), tt.body, nil, "admin", tt.expected)
|
||||
if !errors.Is(err, tt.wantErr) {
|
||||
t.Fatalf("error = %v, want %v", err, tt.wantErr)
|
||||
}
|
||||
@@ -136,7 +169,7 @@ func TestDisabledWorkflowIsNeverStarted(t *testing.T) {
|
||||
engine := newEngine(nil, work, slog.New(slog.DiscardHandler), Options{})
|
||||
engine.queue = work
|
||||
engine.Use(Deps{Access: &recordingAccess{decision: governance.Allowed()}})
|
||||
req := StartRequest{OrgID: "org", Workflow: "triage", Key: "event:trigger"}
|
||||
req := StartRequest{OrgID: "org", WorkflowID: wid("triage"), Key: "event:trigger"}
|
||||
|
||||
var err error
|
||||
if tt.viaCall {
|
||||
@@ -183,7 +216,7 @@ func TestDeleteIsRefusedWhileReferenced(t *testing.T) {
|
||||
maps.Copy(s.versions, tt.others)
|
||||
e := &Engine{defs: s, log: slog.New(slog.DiscardHandler), referrers: tt.triggers}
|
||||
|
||||
err := e.Delete(t.Context(), "org", "triage")
|
||||
err := e.Delete(t.Context(), "org", wid("triage"))
|
||||
var refs *ReferencedError
|
||||
if len(tt.wantBy) == 0 {
|
||||
if err != nil || !slices.Equal(s.deleted, []string{"triage"}) {
|
||||
|
||||
@@ -175,7 +175,7 @@ type Ending struct {
|
||||
func (rc *Context) RunID() uuid.UUID { return rc.run.ID }
|
||||
|
||||
// Workflow is the name of the workflow this run executes.
|
||||
func (rc *Context) Workflow() string { return rc.run.Workflow }
|
||||
func (rc *Context) Workflow() string { return rc.workflowName() }
|
||||
|
||||
// OrgID is the organisation the run belongs to.
|
||||
func (rc *Context) OrgID() string { return rc.run.OrgID }
|
||||
|
||||
+25
-9
@@ -20,7 +20,10 @@ import (
|
||||
// dryOverlay contains the workflow document and policy a dry run tests as
|
||||
// if they were published.
|
||||
type dryOverlay struct {
|
||||
Document string `json:"document"`
|
||||
Document string `json:"document"`
|
||||
// Name is the name hard rules see for a document that isn't a workflow
|
||||
// yet.
|
||||
Name string `json:"name,omitzero"`
|
||||
PolicyKind string `json:"policy_kind,omitzero"`
|
||||
Policy string `json:"policy,omitzero"`
|
||||
}
|
||||
@@ -60,17 +63,30 @@ func (rc *Context) request(key, connector, action string, input jsontext.Value)
|
||||
diagnosis, evidence := rc.Rationale()
|
||||
return judgement.Request{
|
||||
RunID: rc.run.ID, Key: key, Connector: connector, Action: action, Input: input,
|
||||
Workflow: rc.run.Workflow, Dry: rc.run.Dry, Overlay: rc.overlay.policy(),
|
||||
Workflow: rc.workflowName(), Dry: rc.run.Dry, Overlay: rc.overlay.policy(),
|
||||
Diagnosis: diagnosis, Evidence: evidence,
|
||||
}
|
||||
}
|
||||
|
||||
// workflowName is the name hard rules see for this run: its workflow's name,
|
||||
// or for a test run of a document that isn't a workflow yet the name it would
|
||||
// be published under.
|
||||
func (rc *Context) workflowName() string {
|
||||
if rc.run.Workflow == "" && rc.overlay != nil {
|
||||
return rc.overlay.Name
|
||||
}
|
||||
return rc.run.Workflow
|
||||
}
|
||||
|
||||
// DryRequest starts a dry run of a document that is not yet published.
|
||||
type DryRequest struct {
|
||||
OrgID string
|
||||
// Workflow is the name the document would be published under; hard rules
|
||||
// see it as the principal.
|
||||
Workflow string
|
||||
// WorkflowID is the workflow the document would be published as. It is
|
||||
// uuid.Nil for a document that isn't a workflow yet, and Name is then the
|
||||
// name it would be published under. Hard rules see the name as the
|
||||
// principal.
|
||||
WorkflowID uuid.UUID
|
||||
Name string
|
||||
Document string
|
||||
PolicyKind string
|
||||
Policy string
|
||||
@@ -80,7 +96,7 @@ type DryRequest struct {
|
||||
// StartDry queues a dry run of a document and returns its run's id. A document
|
||||
// that doesn't validate starts nothing.
|
||||
func (e *Engine) StartDry(ctx context.Context, req DryRequest) (uuid.UUID, error) {
|
||||
if err := e.mayStart(ctx, req.Workflow); err != nil {
|
||||
if err := e.mayStart(ctx, req.WorkflowID); err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
doc, err := e.validateDocument(ctx, req.Document)
|
||||
@@ -92,7 +108,7 @@ func (e *Engine) StartDry(ctx context.Context, req DryRequest) (uuid.UUID, error
|
||||
if err := doc.unsupported(); err != nil {
|
||||
return uuid.Nil, refusal{err}
|
||||
}
|
||||
overlay, err := json.Marshal(dryOverlay{Document: req.Document, PolicyKind: req.PolicyKind, Policy: req.Policy})
|
||||
overlay, err := json.Marshal(dryOverlay{Document: req.Document, Name: req.Name, PolicyKind: req.PolicyKind, Policy: req.Policy})
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("encode overlay: %w", err)
|
||||
}
|
||||
@@ -101,10 +117,10 @@ func (e *Engine) StartDry(ctx context.Context, req DryRequest) (uuid.UUID, error
|
||||
input = jsontext.Value("null")
|
||||
}
|
||||
if err := doc.checkInputs(decodeInputs(input)); err != nil {
|
||||
return uuid.Nil, refusal{fmt.Errorf("workflow %q: %w", req.Workflow, err)}
|
||||
return uuid.Nil, refusal{fmt.Errorf("the document: %w", err)}
|
||||
}
|
||||
return e.queue.Start(ctx, store.NewRun{
|
||||
OrgID: req.OrgID, Workflow: req.Workflow, Input: input, Dry: true, Overlay: overlay,
|
||||
OrgID: req.OrgID, WorkflowID: req.WorkflowID, Input: input, Dry: true, Overlay: overlay,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ func TestStartDryRefusesWhatCannotStart(t *testing.T) {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := governance.WithPrincipal(context.Background(), governance.SharedTokenOwner())
|
||||
_, err := engine.StartDry(ctx, DryRequest{
|
||||
OrgID: "org", Workflow: "draft", Document: tt.doc,
|
||||
OrgID: "org", WorkflowID: wid("draft"), Document: tt.doc,
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), tt.want) {
|
||||
t.Fatalf("StartDry error = %v, want %q", err, tt.want)
|
||||
|
||||
@@ -163,7 +163,11 @@ func (rc *Context) startRun(ctx context.Context, key, workflow string, input map
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("encode input: %w", err)
|
||||
}
|
||||
n, err := rc.resolve(ctx, StartRequest{OrgID: rc.run.OrgID, Workflow: workflow, Input: raw})
|
||||
id, err := rc.callTarget(ctx, workflow)
|
||||
if err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
n, err := rc.resolve(ctx, StartRequest{OrgID: rc.run.OrgID, WorkflowID: id, Input: raw})
|
||||
if err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
@@ -171,6 +175,21 @@ func (rc *Context) startRun(ctx context.Context, key, workflow string, input map
|
||||
return rc.work.StartFor(ctx, rc.token, rc.run.ID, n)
|
||||
}
|
||||
|
||||
// callTarget returns the id the workflow name resolved to when the run's
|
||||
// version was published, so renaming the target after that doesn't change
|
||||
// what the run starts.
|
||||
func (rc *Context) callTarget(ctx context.Context, name string) (uuid.UUID, error) {
|
||||
w, err := rc.work.Workflow(ctx, rc.run.OrgID, rc.run.WorkflowID, rc.run.Version)
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("read version %d of the calling workflow: %w", rc.run.Version, err)
|
||||
}
|
||||
id, ok := w.Calls[name]
|
||||
if !ok {
|
||||
return uuid.Nil, fmt.Errorf("version %d resolved no workflow named %q when it was published", rc.run.Version, name)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// handoffSettings end the run and start another workflow with the same input.
|
||||
type handoffSettings struct {
|
||||
Workflow string `yaml:"workflow" json:"workflow" jsonschema:"the workflow the task is requeued under"`
|
||||
|
||||
@@ -62,9 +62,11 @@ var (
|
||||
|
||||
// Run is a claimed run.
|
||||
type Run struct {
|
||||
ID uuid.UUID `db:"id"`
|
||||
OrgID string `db:"org_id"`
|
||||
Workflow string `db:"workflow"`
|
||||
ID uuid.UUID `db:"id"`
|
||||
OrgID string `db:"org_id"`
|
||||
WorkflowID uuid.UUID `db:"workflow_id"`
|
||||
// Workflow is the workflow's name when the run was claimed.
|
||||
Workflow string `db:"workflow"`
|
||||
// Version is the workflow version the run started under.
|
||||
Version int `db:"workflow_version"`
|
||||
Input jsontext.Value `db:"input"`
|
||||
@@ -101,13 +103,15 @@ func New(db *sqlx.DB) *Store {
|
||||
|
||||
// NewRun is a run to queue.
|
||||
type NewRun struct {
|
||||
OrgID string
|
||||
Workflow string
|
||||
Version int
|
||||
StartKey string
|
||||
Input jsontext.Value
|
||||
Dry bool
|
||||
Overlay jsontext.Value
|
||||
OrgID string
|
||||
// WorkflowID is uuid.Nil only for a test run of a document that isn't a
|
||||
// workflow yet.
|
||||
WorkflowID uuid.UUID
|
||||
Version int
|
||||
StartKey string
|
||||
Input jsontext.Value
|
||||
Dry bool
|
||||
Overlay jsontext.Value
|
||||
// CallDepth is the depth of a run started by a call.
|
||||
CallDepth int
|
||||
// ParentSignal is the signal key to send the run that called this one
|
||||
@@ -121,10 +125,10 @@ func (s *Store) Start(ctx context.Context, n NewRun) (uuid.UUID, error) {
|
||||
key := sql.NullString{String: n.StartKey, Valid: n.StartKey != ""}
|
||||
var id uuid.UUID
|
||||
err := s.db.GetContext(ctx, &id, `
|
||||
INSERT INTO runs.runs (id, org_id, workflow, workflow_version, start_key, input, state, dry, overlay)
|
||||
INSERT INTO runs.runs (id, org_id, workflow_id, workflow_version, start_key, input, state, dry, overlay)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, 'queued', $7, $8)
|
||||
ON CONFLICT (org_id, start_key) DO NOTHING
|
||||
RETURNING id`, uuid.New(), n.OrgID, n.Workflow, n.Version, key, n.Input, n.Dry, nullJSON(n.Overlay))
|
||||
RETURNING id`, uuid.New(), n.OrgID, nullID(n.WorkflowID), n.Version, key, n.Input, n.Dry, nullJSON(n.Overlay))
|
||||
if errors.Is(err, sql.ErrNoRows) && key.Valid {
|
||||
err = s.db.GetContext(ctx, &id, `SELECT id FROM runs.runs WHERE org_id = $1 AND start_key = $2`, n.OrgID, n.StartKey)
|
||||
}
|
||||
@@ -148,11 +152,11 @@ func (s *Store) StartFor(ctx context.Context, token, parent uuid.UUID, n NewRun)
|
||||
}
|
||||
var id uuid.UUID
|
||||
err := s.db.GetContext(ctx, &id, `
|
||||
INSERT INTO runs.runs (id, org_id, workflow, workflow_version, start_key, input, state, parent_run_id, parent_signal, call_depth)
|
||||
INSERT INTO runs.runs (id, org_id, workflow_id, workflow_version, start_key, input, state, parent_run_id, parent_signal, call_depth)
|
||||
SELECT $1, $2, $3, $4, $5, $6, 'queued', $7, NULLIF($8, ''), $9
|
||||
WHERE EXISTS (SELECT 1 FROM runs.runs WHERE id = $10 AND lease_token = $11)
|
||||
ON CONFLICT (org_id, start_key) DO NOTHING
|
||||
RETURNING id`, uuid.New(), n.OrgID, n.Workflow, n.Version, n.StartKey, n.Input, link, n.ParentSignal, n.CallDepth, parent, token)
|
||||
RETURNING id`, uuid.New(), n.OrgID, n.WorkflowID, n.Version, n.StartKey, n.Input, link, n.ParentSignal, n.CallDepth, parent, token)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
err = s.db.GetContext(ctx, &id, `SELECT id FROM runs.runs WHERE org_id = $1 AND start_key = $2`, n.OrgID, n.StartKey)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
@@ -183,7 +187,7 @@ func (s *Store) Claim(ctx context.Context, owner string, token uuid.UUID, ttl ti
|
||||
ORDER BY created_at
|
||||
FOR UPDATE SKIP LOCKED
|
||||
LIMIT 1)
|
||||
RETURNING r.id, r.org_id, r.workflow, r.workflow_version, r.input, r.attempts, r.dry, r.overlay, r.call_depth`, token, owner, ttl.Seconds())
|
||||
RETURNING r.id, r.org_id, r.workflow_id, COALESCE((SELECT name FROM runs.workflows WHERE id = r.workflow_id), '') AS workflow, r.workflow_version, r.input, r.attempts, r.dry, r.overlay, r.call_depth`, token, owner, ttl.Seconds())
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Run{}, false, nil
|
||||
}
|
||||
@@ -493,6 +497,7 @@ func (s *Store) CancelRequested(ctx context.Context, id uuid.UUID) (bool, error)
|
||||
// Summary is a run as a list shows it.
|
||||
type Summary struct {
|
||||
ID uuid.UUID `db:"id"`
|
||||
WorkflowID uuid.UUID `db:"workflow_id"`
|
||||
Workflow string `db:"workflow"`
|
||||
Version int `db:"workflow_version"`
|
||||
State string `db:"state"`
|
||||
@@ -521,13 +526,13 @@ type Recorded struct {
|
||||
RecordedAt time.Time `db:"recorded_at"`
|
||||
}
|
||||
|
||||
// Recent returns an organisation's latest runs, newest first, of one workflow when
|
||||
// one is named.
|
||||
func (s *Store) Recent(ctx context.Context, orgID, workflow string, limit int) ([]Summary, error) {
|
||||
// Recent returns an organisation's latest runs, newest first, of one workflow
|
||||
// when workflow is valid.
|
||||
func (s *Store) Recent(ctx context.Context, orgID string, workflow uuid.NullUUID, limit int) ([]Summary, error) {
|
||||
var out []Summary
|
||||
if err := s.db.SelectContext(ctx, &out, `
|
||||
SELECT id, workflow, workflow_version, state, attempts, error, detail, created_at, finished_at, dry FROM runs.runs
|
||||
WHERE org_id = $1 AND NOT dry AND ($3 = '' OR workflow = $3) ORDER BY created_at DESC LIMIT $2`, orgID, limit, workflow); err != nil {
|
||||
SELECT r.id, r.workflow_id, COALESCE(w.name, '') AS workflow, r.workflow_version, r.state, r.attempts, r.error, r.detail, r.created_at, r.finished_at, r.dry FROM runs.runs r LEFT JOIN runs.workflows w ON w.id = r.workflow_id
|
||||
WHERE r.org_id = $1 AND NOT r.dry AND ($3::uuid IS NULL OR r.workflow_id = $3) ORDER BY r.created_at DESC LIMIT $2`, orgID, limit, workflow); err != nil {
|
||||
return nil, fmt.Errorf("list runs: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
@@ -538,9 +543,9 @@ func (s *Store) Recent(ctx context.Context, orgID, workflow string, limit int) (
|
||||
func (s *Store) Detail(ctx context.Context, orgID string, id uuid.UUID) (Detail, bool, error) {
|
||||
var d Detail
|
||||
err := s.db.GetContext(ctx, &d, `
|
||||
SELECT id, workflow, workflow_version, state, attempts, error, detail, created_at, finished_at, dry, input,
|
||||
coalesce(result, 'null') AS result, overlay
|
||||
FROM runs.runs WHERE org_id = $1 AND id = $2`, orgID, id)
|
||||
SELECT r.id, r.workflow_id, COALESCE(w.name, '') AS workflow, r.workflow_version, r.state, r.attempts, r.error, r.detail, r.created_at, r.finished_at, r.dry, r.input,
|
||||
coalesce(r.result, 'null') AS result, r.overlay
|
||||
FROM runs.runs r LEFT JOIN runs.workflows w ON w.id = r.workflow_id WHERE r.org_id = $1 AND r.id = $2`, orgID, id)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Detail{}, false, nil
|
||||
}
|
||||
@@ -582,6 +587,11 @@ func affected(res sql.Result) int64 {
|
||||
return n
|
||||
}
|
||||
|
||||
// nullID stores uuid.Nil as NULL.
|
||||
func nullID(id uuid.UUID) uuid.NullUUID {
|
||||
return uuid.NullUUID{UUID: id, Valid: id != uuid.Nil}
|
||||
}
|
||||
|
||||
func nullJSON(v jsontext.Value) any {
|
||||
if len(v) == 0 {
|
||||
return nil
|
||||
@@ -613,9 +623,9 @@ func (s *Store) Counts(ctx context.Context, orgID string) (map[string]int, error
|
||||
func (s *Store) LastFailed(ctx context.Context, orgID string) (Summary, bool, error) {
|
||||
var out Summary
|
||||
err := s.db.GetContext(ctx, &out, `
|
||||
SELECT id, workflow, workflow_version, state, attempts, error, detail, created_at, finished_at, dry FROM runs.runs
|
||||
WHERE org_id = $1 AND NOT dry AND state = 'failed'
|
||||
ORDER BY coalesce(finished_at, created_at) DESC LIMIT 1`, orgID)
|
||||
SELECT r.id, r.workflow_id, COALESCE(w.name, '') AS workflow, r.workflow_version, r.state, r.attempts, r.error, r.detail, r.created_at, r.finished_at, r.dry FROM runs.runs r LEFT JOIN runs.workflows w ON w.id = r.workflow_id
|
||||
WHERE r.org_id = $1 AND NOT r.dry AND r.state = 'failed'
|
||||
ORDER BY coalesce(r.finished_at, r.created_at) DESC LIMIT 1`, orgID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Summary{}, false, nil
|
||||
}
|
||||
|
||||
@@ -3,14 +3,21 @@ package store
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
json "encoding/json/v2"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrNoWorkflow means no workflow is stored under that name and version.
|
||||
// ErrNoWorkflow means no workflow has that id or name, or it has no such
|
||||
// version.
|
||||
ErrNoWorkflow = errors.New("no such workflow")
|
||||
// ErrNameTaken means another workflow in the organisation has the name.
|
||||
ErrNameTaken = errors.New("another workflow has that name")
|
||||
// ErrVersionConflict means the workflow's latest version is not the one
|
||||
// the writer expected.
|
||||
ErrVersionConflict = errors.New("the workflow has another version than expected")
|
||||
@@ -21,27 +28,129 @@ var (
|
||||
ErrNoDraft = errors.New("no such draft")
|
||||
)
|
||||
|
||||
// Workflow is one stored version of a workflow document.
|
||||
type Workflow struct {
|
||||
Name string `db:"name"`
|
||||
Version int `db:"version"`
|
||||
Body string `db:"body"`
|
||||
CreatedBy string `db:"created_by"`
|
||||
CreatedAt time.Time `db:"created_at"`
|
||||
// Identity is a workflow apart from its versions.
|
||||
type Identity struct {
|
||||
ID uuid.UUID `db:"id"`
|
||||
Name string `db:"name"`
|
||||
// Disabled is a workflow nothing may start. The zero value is enabled.
|
||||
Disabled bool `db:"disabled"`
|
||||
// Deleted is a workflow that was deleted; its runs still read it.
|
||||
Deleted bool `db:"deleted"`
|
||||
}
|
||||
|
||||
const workflowColumns = `w.name, w.version, w.body, w.created_by, w.created_at, COALESCE(NOT s.enabled, false) AS disabled`
|
||||
// Workflow is one stored version of a workflow document.
|
||||
type Workflow struct {
|
||||
Identity
|
||||
Version int `db:"version"`
|
||||
Body string `db:"body"`
|
||||
// Calls maps each workflow name the version calls, hands off to or runs
|
||||
// after an approval onto the id it resolved to when the version was
|
||||
// published.
|
||||
Calls Calls `db:"calls"`
|
||||
CreatedBy string `db:"created_by"`
|
||||
CreatedAt time.Time `db:"created_at"`
|
||||
}
|
||||
|
||||
// Workflow returns a version of a workflow, or its latest when version is zero.
|
||||
func (s *Store) Workflow(ctx context.Context, orgID, name string, version int) (Workflow, error) {
|
||||
// Calls maps workflow names onto workflow ids. It is stored as a JSON object.
|
||||
type Calls map[string]uuid.UUID
|
||||
|
||||
// Scan decodes a JSON object.
|
||||
func (c *Calls) Scan(src any) error {
|
||||
switch v := src.(type) {
|
||||
case []byte:
|
||||
return json.Unmarshal(v, c)
|
||||
case string:
|
||||
return json.Unmarshal([]byte(v), c)
|
||||
}
|
||||
return fmt.Errorf("scan calls: %T is not JSON text", src)
|
||||
}
|
||||
|
||||
const (
|
||||
identityColumns = `w.id, w.name, NOT w.enabled AS disabled, w.deleted_at IS NOT NULL AS deleted`
|
||||
workflowColumns = identityColumns + `, v.version, v.body, v.calls, v.created_by, v.created_at`
|
||||
)
|
||||
|
||||
// CreateWorkflow adds a workflow with no versions under a new id. The name must
|
||||
// not belong to another workflow of the organisation that isn't deleted.
|
||||
func (s *Store) CreateWorkflow(ctx context.Context, orgID, name string) (uuid.UUID, error) {
|
||||
id := uuid.New()
|
||||
_, err := s.db.ExecContext(ctx, `INSERT INTO runs.workflows (id, org_id, name) VALUES ($1, $2, $3)`, id, orgID, name)
|
||||
if isUniqueViolation(err) {
|
||||
return uuid.Nil, ErrNameTaken
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("create workflow: %w", err)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// EnsureWorkflow adds a workflow with no versions under id unless one has the
|
||||
// id already, deleted or not.
|
||||
func (s *Store) EnsureWorkflow(ctx context.Context, orgID string, id uuid.UUID, name string) error {
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO runs.workflows (id, org_id, name) VALUES ($1, $2, $3) ON CONFLICT (id) DO NOTHING`, id, orgID, name)
|
||||
if isUniqueViolation(err) {
|
||||
return ErrNameTaken
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("create workflow: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Rename changes the name of a workflow that isn't deleted.
|
||||
func (s *Store) Rename(ctx context.Context, orgID string, id uuid.UUID, name string) error {
|
||||
res, err := s.db.ExecContext(ctx, `
|
||||
UPDATE runs.workflows SET name = $3 WHERE org_id = $1 AND id = $2 AND deleted_at IS NULL`, orgID, id, name)
|
||||
if isUniqueViolation(err) {
|
||||
return ErrNameTaken
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("rename workflow: %w", err)
|
||||
}
|
||||
if affected(res) == 0 {
|
||||
return ErrNoWorkflow
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Identity returns a workflow apart from its versions, deleted or not.
|
||||
func (s *Store) Identity(ctx context.Context, orgID string, id uuid.UUID) (Identity, error) {
|
||||
var w Identity
|
||||
err := s.db.GetContext(ctx, &w, `SELECT `+identityColumns+` FROM runs.workflows w WHERE w.org_id = $1 AND w.id = $2`, orgID, id)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Identity{}, ErrNoWorkflow
|
||||
}
|
||||
if err != nil {
|
||||
return Identity{}, fmt.Errorf("read workflow: %w", err)
|
||||
}
|
||||
return w, nil
|
||||
}
|
||||
|
||||
// Named returns the workflow that isn't deleted and has the name.
|
||||
func (s *Store) Named(ctx context.Context, orgID, name string) (Identity, error) {
|
||||
var w Identity
|
||||
err := s.db.GetContext(ctx, &w, `
|
||||
SELECT `+identityColumns+` FROM runs.workflows w WHERE w.org_id = $1 AND w.name = $2 AND w.deleted_at IS NULL`, orgID, name)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Identity{}, ErrNoWorkflow
|
||||
}
|
||||
if err != nil {
|
||||
return Identity{}, fmt.Errorf("read workflow: %w", err)
|
||||
}
|
||||
return w, nil
|
||||
}
|
||||
|
||||
// Workflow returns a version of a workflow, or its latest when version is
|
||||
// zero. It reads a deleted workflow too, so its runs can still load what they
|
||||
// ran.
|
||||
func (s *Store) Workflow(ctx context.Context, orgID string, id uuid.UUID, version int) (Workflow, error) {
|
||||
var w Workflow
|
||||
err := s.db.GetContext(ctx, &w, `
|
||||
SELECT `+workflowColumns+` FROM runs.workflows w
|
||||
LEFT JOIN runs.workflow_settings s ON s.org_id = w.org_id AND s.name = w.name
|
||||
WHERE w.org_id = $1 AND w.name = $2 AND ($3 = 0 OR w.version = $3)
|
||||
ORDER BY w.version DESC LIMIT 1`, orgID, name, version)
|
||||
JOIN runs.workflow_versions v ON v.workflow_id = w.id
|
||||
WHERE w.org_id = $1 AND w.id = $2 AND ($3 = 0 OR v.version = $3)
|
||||
ORDER BY v.version DESC LIMIT 1`, orgID, id, version)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Workflow{}, ErrNoWorkflow
|
||||
}
|
||||
@@ -51,13 +160,14 @@ func (s *Store) Workflow(ctx context.Context, orgID, name string, version int) (
|
||||
return w, nil
|
||||
}
|
||||
|
||||
// Workflows returns the latest version of every workflow.
|
||||
// Workflows returns the latest version of every published workflow that isn't
|
||||
// deleted.
|
||||
func (s *Store) Workflows(ctx context.Context, orgID string) ([]Workflow, error) {
|
||||
var out []Workflow
|
||||
if err := s.db.SelectContext(ctx, &out, `
|
||||
SELECT DISTINCT ON (w.name) `+workflowColumns+` FROM runs.workflows w
|
||||
LEFT JOIN runs.workflow_settings s ON s.org_id = w.org_id AND s.name = w.name
|
||||
WHERE w.org_id = $1 ORDER BY w.name, w.version DESC`, orgID); err != nil {
|
||||
JOIN runs.workflow_versions v ON v.workflow_id = w.id
|
||||
WHERE w.org_id = $1 AND w.deleted_at IS NULL ORDER BY w.name, v.version DESC`, orgID); err != nil {
|
||||
return nil, fmt.Errorf("list workflows: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
@@ -66,32 +176,42 @@ func (s *Store) Workflows(ctx context.Context, orgID string) ([]Workflow, error)
|
||||
// AddWorkflow stores body as the next version of a workflow and returns it.
|
||||
// When expected is given, the workflow's latest version must be that one (zero
|
||||
// for a workflow with none), or nothing is stored.
|
||||
func (s *Store) AddWorkflow(ctx context.Context, orgID, name, body, by string, expected *int) (Workflow, error) {
|
||||
func (s *Store) AddWorkflow(ctx context.Context, orgID string, id uuid.UUID, body string, calls Calls, by string, expected *int) (Workflow, error) {
|
||||
var want sql.NullInt64
|
||||
if expected != nil {
|
||||
want = sql.NullInt64{Int64: int64(*expected), Valid: true}
|
||||
}
|
||||
var w Workflow
|
||||
err := s.db.GetContext(ctx, &w, `
|
||||
INSERT INTO runs.workflows (org_id, name, version, body, created_by)
|
||||
SELECT $1, $2, COALESCE(max(version), 0) + 1, $3, $4 FROM runs.workflows WHERE org_id = $1 AND name = $2
|
||||
HAVING $5::bigint IS NULL OR COALESCE(max(version), 0) = $5
|
||||
RETURNING name, version, body, created_by, created_at, false AS disabled`, orgID, name, body, by, want)
|
||||
if calls == nil {
|
||||
calls = Calls{}
|
||||
}
|
||||
resolved, err := json.Marshal(calls)
|
||||
if err != nil {
|
||||
return Workflow{}, fmt.Errorf("encode calls: %w", err)
|
||||
}
|
||||
var version int
|
||||
err = s.db.GetContext(ctx, &version, `
|
||||
INSERT INTO runs.workflow_versions (workflow_id, version, body, calls, created_by)
|
||||
SELECT w.id, COALESCE((SELECT max(version) FROM runs.workflow_versions WHERE workflow_id = w.id), 0) + 1, $3, $4, $5
|
||||
FROM runs.workflows w
|
||||
WHERE w.org_id = $1 AND w.id = $2 AND w.deleted_at IS NULL
|
||||
AND ($6::bigint IS NULL OR COALESCE((SELECT max(version) FROM runs.workflow_versions WHERE workflow_id = w.id), 0) = $6)
|
||||
RETURNING version`, orgID, id, body, resolved, by, want)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
if _, err := s.Identity(ctx, orgID, id); err != nil {
|
||||
return Workflow{}, err
|
||||
}
|
||||
return Workflow{}, ErrVersionConflict
|
||||
}
|
||||
if err != nil {
|
||||
return Workflow{}, fmt.Errorf("store workflow: %w", err)
|
||||
}
|
||||
return w, nil
|
||||
return s.Workflow(ctx, orgID, id, version)
|
||||
}
|
||||
|
||||
// SetEnabled enables or disables a stored workflow.
|
||||
func (s *Store) SetEnabled(ctx context.Context, orgID, name string, enabled bool) error {
|
||||
// SetEnabled enables or disables a workflow that isn't deleted.
|
||||
func (s *Store) SetEnabled(ctx context.Context, orgID string, id uuid.UUID, enabled bool) error {
|
||||
res, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO runs.workflow_settings (org_id, name, enabled)
|
||||
SELECT $1, $2, $3 WHERE EXISTS (SELECT 1 FROM runs.workflows WHERE org_id = $1 AND name = $2)
|
||||
ON CONFLICT (org_id, name) DO UPDATE SET enabled = EXCLUDED.enabled`, orgID, name, enabled)
|
||||
UPDATE runs.workflows SET enabled = $3 WHERE org_id = $1 AND id = $2 AND deleted_at IS NULL`, orgID, id, enabled)
|
||||
if err != nil {
|
||||
return fmt.Errorf("set workflow enabled: %w", err)
|
||||
}
|
||||
@@ -101,27 +221,25 @@ func (s *Store) SetEnabled(ctx context.Context, orgID, name string, enabled bool
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteWorkflow removes every version of a workflow with its draft and
|
||||
// settings. The runs it made keep their record.
|
||||
func (s *Store) DeleteWorkflow(ctx context.Context, orgID, name string) error {
|
||||
// DeleteWorkflow marks a workflow deleted and discards its draft. Its versions
|
||||
// stay, so the runs it made can still read what they ran.
|
||||
func (s *Store) DeleteWorkflow(ctx context.Context, orgID string, id uuid.UUID) error {
|
||||
tx, err := s.db.BeginTxx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete workflow: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
res, err := tx.ExecContext(ctx, `DELETE FROM runs.workflows WHERE org_id = $1 AND name = $2`, orgID, name)
|
||||
res, err := tx.ExecContext(ctx, `
|
||||
UPDATE runs.workflows SET deleted_at = now() WHERE org_id = $1 AND id = $2 AND deleted_at IS NULL`, orgID, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete workflow: %w", err)
|
||||
}
|
||||
if affected(res) == 0 {
|
||||
return ErrNoWorkflow
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM runs.workflow_drafts WHERE org_id = $1 AND name = $2`, orgID, name); err != nil {
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM runs.workflow_drafts WHERE workflow_id = $1`, id); err != nil {
|
||||
return fmt.Errorf("delete workflow draft: %w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM runs.workflow_settings WHERE org_id = $1 AND name = $2`, orgID, name); err != nil {
|
||||
return fmt.Errorf("delete workflow settings: %w", err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("delete workflow: %w", err)
|
||||
}
|
||||
@@ -130,6 +248,7 @@ func (s *Store) DeleteWorkflow(ctx context.Context, orgID, name string) error {
|
||||
|
||||
// Draft is the unpublished edit of a workflow.
|
||||
type Draft struct {
|
||||
WorkflowID uuid.UUID `db:"workflow_id"`
|
||||
Name string `db:"name"`
|
||||
Body string `db:"body"`
|
||||
BaseVersion int `db:"base_version"`
|
||||
@@ -138,12 +257,15 @@ type Draft struct {
|
||||
UpdatedAt time.Time `db:"updated_at"`
|
||||
}
|
||||
|
||||
const draftColumns = `name, body, base_version, revision, updated_by, updated_at`
|
||||
const draftQuery = `
|
||||
SELECT d.workflow_id, w.name, d.body, d.base_version, d.revision, d.updated_by, d.updated_at
|
||||
FROM runs.workflow_drafts d JOIN runs.workflows w ON w.id = d.workflow_id
|
||||
WHERE w.org_id = $1 AND w.deleted_at IS NULL`
|
||||
|
||||
// Draft returns a workflow's draft.
|
||||
func (s *Store) Draft(ctx context.Context, orgID, name string) (Draft, error) {
|
||||
func (s *Store) Draft(ctx context.Context, orgID string, id uuid.UUID) (Draft, error) {
|
||||
var d Draft
|
||||
err := s.db.GetContext(ctx, &d, `SELECT `+draftColumns+` FROM runs.workflow_drafts WHERE org_id = $1 AND name = $2`, orgID, name)
|
||||
err := s.db.GetContext(ctx, &d, draftQuery+` AND d.workflow_id = $2`, orgID, id)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Draft{}, ErrNoDraft
|
||||
}
|
||||
@@ -156,7 +278,7 @@ func (s *Store) Draft(ctx context.Context, orgID, name string) (Draft, error) {
|
||||
// Drafts returns every workflow's draft.
|
||||
func (s *Store) Drafts(ctx context.Context, orgID string) ([]Draft, error) {
|
||||
var out []Draft
|
||||
if err := s.db.SelectContext(ctx, &out, `SELECT `+draftColumns+` FROM runs.workflow_drafts WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
|
||||
if err := s.db.SelectContext(ctx, &out, draftQuery+` ORDER BY w.name`, orgID); err != nil {
|
||||
return nil, fmt.Errorf("list drafts: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
@@ -165,33 +287,38 @@ func (s *Store) Drafts(ctx context.Context, orgID string) ([]Draft, error) {
|
||||
// PutDraft writes a workflow's draft. revision is the one the writer last saw,
|
||||
// zero for a workflow with no draft; a draft at any other revision is not
|
||||
// overwritten.
|
||||
func (s *Store) PutDraft(ctx context.Context, orgID, name, body, by string, revision int) (Draft, error) {
|
||||
var d Draft
|
||||
func (s *Store) PutDraft(ctx context.Context, orgID string, id uuid.UUID, body, by string, revision int) (Draft, error) {
|
||||
if _, err := s.Identity(ctx, orgID, id); err != nil {
|
||||
return Draft{}, err
|
||||
}
|
||||
var res sql.Result
|
||||
var err error
|
||||
if revision == 0 {
|
||||
err = s.db.GetContext(ctx, &d, `
|
||||
INSERT INTO runs.workflow_drafts (org_id, name, body, base_version, updated_by)
|
||||
SELECT $1, $2, $3, COALESCE(max(version), 0), $4 FROM runs.workflows WHERE org_id = $1 AND name = $2
|
||||
ON CONFLICT (org_id, name) DO NOTHING
|
||||
RETURNING `+draftColumns, orgID, name, body, by)
|
||||
res, err = s.db.ExecContext(ctx, `
|
||||
INSERT INTO runs.workflow_drafts (workflow_id, body, base_version, updated_by)
|
||||
SELECT w.id, $3, COALESCE((SELECT max(version) FROM runs.workflow_versions WHERE workflow_id = w.id), 0), $4
|
||||
FROM runs.workflows w WHERE w.org_id = $1 AND w.id = $2 AND w.deleted_at IS NULL
|
||||
ON CONFLICT (workflow_id) DO NOTHING`, orgID, id, body, by)
|
||||
} else {
|
||||
err = s.db.GetContext(ctx, &d, `
|
||||
UPDATE runs.workflow_drafts SET body = $3, revision = revision + 1, updated_by = $4, updated_at = now()
|
||||
WHERE org_id = $1 AND name = $2 AND revision = $5
|
||||
RETURNING `+draftColumns, orgID, name, body, by, revision)
|
||||
}
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Draft{}, ErrDraftConflict
|
||||
res, err = s.db.ExecContext(ctx, `
|
||||
UPDATE runs.workflow_drafts d SET body = $3, revision = revision + 1, updated_by = $4, updated_at = now()
|
||||
FROM runs.workflows w
|
||||
WHERE w.id = d.workflow_id AND w.org_id = $1 AND d.workflow_id = $2 AND d.revision = $5`, orgID, id, body, by, revision)
|
||||
}
|
||||
if err != nil {
|
||||
return Draft{}, fmt.Errorf("write draft: %w", err)
|
||||
}
|
||||
return d, nil
|
||||
if affected(res) == 0 {
|
||||
return Draft{}, ErrDraftConflict
|
||||
}
|
||||
return s.Draft(ctx, orgID, id)
|
||||
}
|
||||
|
||||
// DeleteDraft discards a workflow's draft, and reports whether it had one.
|
||||
func (s *Store) DeleteDraft(ctx context.Context, orgID, name string) (bool, error) {
|
||||
res, err := s.db.ExecContext(ctx, `DELETE FROM runs.workflow_drafts WHERE org_id = $1 AND name = $2`, orgID, name)
|
||||
func (s *Store) DeleteDraft(ctx context.Context, orgID string, id uuid.UUID) (bool, error) {
|
||||
res, err := s.db.ExecContext(ctx, `
|
||||
DELETE FROM runs.workflow_drafts d USING runs.workflows w
|
||||
WHERE w.id = d.workflow_id AND w.org_id = $1 AND d.workflow_id = $2`, orgID, id)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("delete draft: %w", err)
|
||||
}
|
||||
@@ -200,9 +327,10 @@ func (s *Store) DeleteDraft(ctx context.Context, orgID, name string) (bool, erro
|
||||
|
||||
// Stats is what a workflow's runs add up to. Dry runs are not counted.
|
||||
type Stats struct {
|
||||
Workflow string `db:"workflow"`
|
||||
Total int `db:"total"`
|
||||
Succeeded int `db:"succeeded"`
|
||||
WorkflowID uuid.UUID `db:"workflow_id"`
|
||||
Workflow string `db:"workflow"`
|
||||
Total int `db:"total"`
|
||||
Succeeded int `db:"succeeded"`
|
||||
// Failed counts runs that failed, parked or were declined.
|
||||
Failed int `db:"failed"`
|
||||
// Active counts runs that haven't ended.
|
||||
@@ -216,28 +344,34 @@ type Stats struct {
|
||||
func (s *Store) Stats(ctx context.Context, orgID string) ([]Stats, error) {
|
||||
var out []Stats
|
||||
if err := s.db.SelectContext(ctx, &out, `
|
||||
SELECT workflow,
|
||||
SELECT r.workflow_id, w.name AS workflow,
|
||||
count(*) AS total,
|
||||
count(*) FILTER (WHERE state = 'succeeded') AS succeeded,
|
||||
count(*) FILTER (WHERE state IN ('failed', 'parked', 'declined')) AS failed,
|
||||
count(*) FILTER (WHERE state IN ('queued', 'running', 'waiting', 'waiting_approval')) AS active,
|
||||
(array_agg(id::text ORDER BY created_at DESC))[1] AS last_run_id,
|
||||
(array_agg(state ORDER BY created_at DESC))[1] AS last_state,
|
||||
max(created_at) AS last_run_at
|
||||
FROM runs.runs WHERE org_id = $1 AND NOT dry
|
||||
GROUP BY workflow ORDER BY workflow`, orgID); err != nil {
|
||||
count(*) FILTER (WHERE r.state = 'succeeded') AS succeeded,
|
||||
count(*) FILTER (WHERE r.state IN ('failed', 'parked', 'declined')) AS failed,
|
||||
count(*) FILTER (WHERE r.state IN ('queued', 'running', 'waiting', 'waiting_approval')) AS active,
|
||||
(array_agg(r.id::text ORDER BY r.created_at DESC))[1] AS last_run_id,
|
||||
(array_agg(r.state ORDER BY r.created_at DESC))[1] AS last_state,
|
||||
max(r.created_at) AS last_run_at
|
||||
FROM runs.runs r JOIN runs.workflows w ON w.id = r.workflow_id
|
||||
WHERE r.org_id = $1 AND NOT r.dry AND w.deleted_at IS NULL
|
||||
GROUP BY r.workflow_id, w.name ORDER BY w.name`, orgID); err != nil {
|
||||
return nil, fmt.Errorf("count workflow runs: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ActiveRuns counts a workflow's runs that haven't ended.
|
||||
func (s *Store) ActiveRuns(ctx context.Context, orgID, name string) (int, error) {
|
||||
func (s *Store) ActiveRuns(ctx context.Context, orgID string, id uuid.UUID) (int, error) {
|
||||
var n int
|
||||
if err := s.db.GetContext(ctx, &n, `
|
||||
SELECT count(*) FROM runs.runs
|
||||
WHERE org_id = $1 AND workflow = $2 AND NOT dry AND state IN ('queued', 'running', 'waiting', 'waiting_approval')`, orgID, name); err != nil {
|
||||
WHERE org_id = $1 AND workflow_id = $2 AND NOT dry AND state IN ('queued', 'running', 'waiting', 'waiting_approval')`, orgID, id); err != nil {
|
||||
return 0, fmt.Errorf("count active runs: %w", err)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
pgErr, ok := errors.AsType[*pgconn.PgError](err)
|
||||
return ok && pgErr.Code == "23505"
|
||||
}
|
||||
+64
-34
@@ -25,10 +25,10 @@ import (
|
||||
// StartRequest specifies the workflow and organisation for a new run.
|
||||
// A non-empty Key makes the start idempotent within the organisation.
|
||||
type StartRequest struct {
|
||||
OrgID string
|
||||
Workflow string
|
||||
Key string
|
||||
Input jsontext.Value
|
||||
OrgID string
|
||||
WorkflowID uuid.UUID
|
||||
Key string
|
||||
Input jsontext.Value
|
||||
}
|
||||
|
||||
// Options tune the engine. Zero values take the defaults.
|
||||
@@ -126,11 +126,20 @@ func (e *Engine) steps() (Deps, error) {
|
||||
return *e.deps, nil
|
||||
}
|
||||
|
||||
// Install stores body as the next version of the workflow name, unless it is
|
||||
// what the latest version already is, and returns the version in force. A body
|
||||
// that doesn't validate is stored as nothing.
|
||||
func (e *Engine) Install(ctx context.Context, orgID, name, body, by string) (int, error) {
|
||||
return e.Publish(ctx, orgID, name, body, by, nil)
|
||||
// Install stores body as the next version of the workflow called name,
|
||||
// creating the workflow when none has the name, unless body is what the latest
|
||||
// version already is. It returns the workflow's id and the version in force. A
|
||||
// body that doesn't validate is stored as nothing.
|
||||
func (e *Engine) Install(ctx context.Context, orgID, name, body, by string) (uuid.UUID, int, error) {
|
||||
id, err := e.WorkflowNamed(ctx, orgID, name)
|
||||
if errors.Is(err, ErrNoWorkflow) {
|
||||
id, err = e.Create(ctx, orgID, name)
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.Nil, 0, err
|
||||
}
|
||||
version, err := e.Publish(ctx, orgID, id, body, by, nil)
|
||||
return id, version, err
|
||||
}
|
||||
|
||||
func (e *Engine) validateDocument(ctx context.Context, body string) (Document, error) {
|
||||
@@ -192,13 +201,23 @@ func modelProblem(err error, alias string) (string, bool) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
// Has reports whether a workflow is stored under name.
|
||||
func (e *Engine) Has(ctx context.Context, orgID, name string) (bool, error) {
|
||||
_, err := e.db.Workflow(ctx, orgID, name, 0)
|
||||
if errors.Is(err, store.ErrNoWorkflow) {
|
||||
return false, nil
|
||||
// WorkflowNamed returns the id of the workflow called name. It returns
|
||||
// ErrNoWorkflow when no workflow that isn't deleted has the name.
|
||||
func (e *Engine) WorkflowNamed(ctx context.Context, orgID, name string) (uuid.UUID, error) {
|
||||
w, err := e.db.Named(ctx, orgID, name)
|
||||
if err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return err == nil, err
|
||||
return w.ID, nil
|
||||
}
|
||||
|
||||
// WorkflowName returns the name of a workflow, deleted or not.
|
||||
func (e *Engine) WorkflowName(ctx context.Context, orgID string, id uuid.UUID) (string, error) {
|
||||
w, err := e.db.Identity(ctx, orgID, id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return w.Name, nil
|
||||
}
|
||||
|
||||
// runQueue reads the workflow a run starts under and queues the run.
|
||||
@@ -213,7 +232,7 @@ type runQueue interface {
|
||||
// principal. A start the policy chain can't decide queues nothing, and the
|
||||
// error wraps governance.ErrChainUnavailable so the caller tries again.
|
||||
func (e *Engine) Start(ctx context.Context, req StartRequest) (uuid.UUID, error) {
|
||||
if err := e.mayStart(ctx, req.Workflow); err != nil {
|
||||
if err := e.mayStart(ctx, req.WorkflowID); err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
n, err := newRun(ctx, e.queue, req)
|
||||
@@ -223,9 +242,9 @@ func (e *Engine) Start(ctx context.Context, req StartRequest) (uuid.UUID, error)
|
||||
return e.queue.Start(ctx, n)
|
||||
}
|
||||
|
||||
// mayStart refuses a start by a caller who may not run workflow, or whose
|
||||
// mayStart refuses a start by a caller who may not run the workflow, or whose
|
||||
// right can't be checked.
|
||||
func (e *Engine) mayStart(ctx context.Context, workflow string) error {
|
||||
func (e *Engine) mayStart(ctx context.Context, workflow uuid.UUID) error {
|
||||
p, ok := governance.PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return fmt.Errorf("%w: no principal starts the run", governance.ErrDenied)
|
||||
@@ -235,31 +254,41 @@ func (e *Engine) mayStart(ctx context.Context, workflow string) error {
|
||||
return fmt.Errorf("%w: %w", governance.ErrChainUnavailable, err)
|
||||
}
|
||||
return governance.Require(ctx, deps.Access, p, governance.ActionRun, governance.Resource{
|
||||
Kind: governance.KindWorkflow, ID: workflow, Org: p.Org,
|
||||
Kind: governance.KindWorkflow, ID: resourceID(workflow), Org: p.Org,
|
||||
})
|
||||
}
|
||||
|
||||
// resourceID is a workflow's id as an access resource. A test run of a
|
||||
// document that isn't a workflow yet has none, and is checked against
|
||||
// workflows in general.
|
||||
func resourceID(workflow uuid.UUID) string {
|
||||
if workflow == uuid.Nil {
|
||||
return ""
|
||||
}
|
||||
return workflow.String()
|
||||
}
|
||||
|
||||
// workflowFinder reads stored workflow versions.
|
||||
type workflowFinder interface {
|
||||
Workflow(ctx context.Context, orgID, name string, version int) (store.Workflow, error)
|
||||
Workflow(ctx context.Context, orgID string, id uuid.UUID, version int) (store.Workflow, error)
|
||||
}
|
||||
|
||||
// newRun checks that the latest version of the workflow can start with the
|
||||
// request's input, and returns the run to queue.
|
||||
func newRun(ctx context.Context, finder workflowFinder, req StartRequest) (store.NewRun, error) {
|
||||
w, err := finder.Workflow(ctx, req.OrgID, req.Workflow, 0)
|
||||
if errors.Is(err, store.ErrNoWorkflow) {
|
||||
return store.NewRun{}, fmt.Errorf("no workflow named %q: %w", req.Workflow, ErrNoWorkflow)
|
||||
w, err := finder.Workflow(ctx, req.OrgID, req.WorkflowID, 0)
|
||||
if errors.Is(err, store.ErrNoWorkflow) || (err == nil && w.Deleted) {
|
||||
return store.NewRun{}, fmt.Errorf("no workflow %s: %w", req.WorkflowID, ErrNoWorkflow)
|
||||
}
|
||||
if err != nil {
|
||||
return store.NewRun{}, err
|
||||
}
|
||||
if w.Disabled {
|
||||
return store.NewRun{}, fmt.Errorf("workflow %q: %w", req.Workflow, ErrDisabled)
|
||||
return store.NewRun{}, fmt.Errorf("workflow %q: %w", w.Name, ErrDisabled)
|
||||
}
|
||||
doc, err := ParseDocument(w.Body)
|
||||
if err != nil {
|
||||
return store.NewRun{}, fmt.Errorf("workflow %q version %d: %w", req.Workflow, w.Version, err)
|
||||
return store.NewRun{}, fmt.Errorf("workflow %q version %d: %w", w.Name, w.Version, err)
|
||||
}
|
||||
if err := doc.unsupported(); err != nil {
|
||||
return store.NewRun{}, refusal{err}
|
||||
@@ -269,27 +298,28 @@ func newRun(ctx context.Context, finder workflowFinder, req StartRequest) (store
|
||||
input = jsontext.Value("null")
|
||||
}
|
||||
if err := doc.checkInputs(decodeInputs(input)); err != nil {
|
||||
return store.NewRun{}, refusal{fmt.Errorf("workflow %q: %w", req.Workflow, err)}
|
||||
return store.NewRun{}, refusal{fmt.Errorf("workflow %q: %w", w.Name, err)}
|
||||
}
|
||||
return store.NewRun{
|
||||
OrgID: req.OrgID, Workflow: req.Workflow, Version: w.Version, StartKey: req.Key, Input: input,
|
||||
OrgID: req.OrgID, WorkflowID: w.ID, Version: w.Version, StartKey: req.Key, Input: input,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CheckTrigger refuses a trigger for a workflow it couldn't start: one that
|
||||
// doesn't exist, or one that requires an input a trigger doesn't supply. A
|
||||
// trigger supplies only the event that fired it.
|
||||
func (e *Engine) CheckTrigger(ctx context.Context, orgID, workflow string) error {
|
||||
w, err := e.db.Workflow(ctx, orgID, workflow, 0)
|
||||
func (e *Engine) CheckTrigger(ctx context.Context, orgID string, id uuid.UUID) error {
|
||||
w, err := e.db.Workflow(ctx, orgID, id, 0)
|
||||
refuse := func(format string, args ...any) error {
|
||||
return &InvalidError{Problems: []Problem{{Path: "workflow", Message: fmt.Sprintf(format, args...)}}}
|
||||
return &InvalidError{Problems: []Problem{{Path: "workflow_id", Message: fmt.Sprintf(format, args...)}}}
|
||||
}
|
||||
if errors.Is(err, store.ErrNoWorkflow) {
|
||||
return refuse("no workflow named %q", workflow)
|
||||
if errors.Is(err, store.ErrNoWorkflow) || (err == nil && w.Deleted) {
|
||||
return refuse("no published workflow %s", id)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
workflow := w.Name
|
||||
doc, err := ParseDocument(w.Body)
|
||||
if err != nil {
|
||||
return refuse("workflow %q is not valid: %v", workflow, err)
|
||||
@@ -386,7 +416,7 @@ func (e *Engine) mayExecute(ctx context.Context, run store.Run) error {
|
||||
return fmt.Errorf("%w: %w", governance.ErrChainUnavailable, err)
|
||||
}
|
||||
return governance.RequireWorkload(ctx, deps.Access, governance.ActionRun, governance.Resource{
|
||||
Kind: governance.KindWorkflow, ID: run.Workflow,
|
||||
Kind: governance.KindWorkflow, ID: resourceID(run.WorkflowID),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -474,7 +504,7 @@ func (e *Engine) loadDocument(ctx context.Context, run store.Run) (Workflow, err
|
||||
}
|
||||
body = o.Document
|
||||
} else {
|
||||
w, err := e.db.Workflow(ctx, run.OrgID, run.Workflow, run.Version)
|
||||
w, err := e.db.Workflow(ctx, run.OrgID, run.WorkflowID, run.Version)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("workflow %q version %d: %w", run.Workflow, run.Version, err)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"encoding/json/jsontext"
|
||||
json "encoding/json/v2"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -93,14 +95,29 @@ func (f *fakeWork) Signalled(context.Context, uuid.UUID, string) (jsontext.Value
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
func (f *fakeWork) Workflow(_ context.Context, _, name string, _ int) (store.Workflow, error) {
|
||||
// Workflow returns the workflow whose id is wid of its name. Every version
|
||||
// resolves the names in bodies, so a step can call any of them.
|
||||
func (f *fakeWork) Workflow(_ context.Context, _ string, id uuid.UUID, _ int) (store.Workflow, error) {
|
||||
var name string
|
||||
for _, n := range slices.Concat(slices.Collect(maps.Keys(f.bodies)), slices.Collect(maps.Keys(f.disabled))) {
|
||||
if wid(n) == id {
|
||||
name = n
|
||||
}
|
||||
}
|
||||
body, ok := f.bodies[name]
|
||||
if !ok {
|
||||
body = "steps:\n - type: run.notify\n"
|
||||
}
|
||||
return store.Workflow{Name: name, Version: 1, Body: body, Disabled: f.disabled[name]}, nil
|
||||
calls := store.Calls{}
|
||||
for n := range f.bodies {
|
||||
calls[n] = wid(n)
|
||||
}
|
||||
return store.Workflow{ID: id, Name: name, Disabled: f.disabled[name], Version: 1, Body: body, Calls: calls}, nil
|
||||
}
|
||||
|
||||
// wid is the id the fakes give the workflow called name.
|
||||
func wid(name string) uuid.UUID { return uuid.NewSHA1(uuid.NameSpaceOID, []byte(name)) }
|
||||
|
||||
// StartFor starts a run once per start key, as the store does.
|
||||
func (f *fakeWork) StartFor(_ context.Context, _, _ uuid.UUID, n store.NewRun) (uuid.UUID, error) {
|
||||
f.mu.Lock()
|
||||
|
||||
@@ -428,6 +428,10 @@ steps:
|
||||
wf := Deps{Settings: onePersonPath{}, Toolbox: anyBox{}, Judge: judge, Approver: ask, Notifier: told, Messenger: sent}.Compile(doc)
|
||||
work := &callWork{arrives: 1}
|
||||
work.bodies = tt.bodies
|
||||
if work.bodies == nil {
|
||||
// The workflow every call in these documents starts.
|
||||
work.bodies = map[string]string{"remediate": "steps:\n - type: run.notify\n"}
|
||||
}
|
||||
run := store.Run{ID: uuid.New(), Dry: tt.dry}
|
||||
rc := newContext(t.Context(), work, run, uuid.New(), nil)
|
||||
restart := func() {
|
||||
|
||||
+22
-12
@@ -44,12 +44,14 @@ type Origins interface {
|
||||
|
||||
// RunView is a run as the API shows it.
|
||||
type RunView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Workflow string `json:"workflow"`
|
||||
Version int `json:"workflow_version"`
|
||||
State string `json:"state"`
|
||||
Attempts int `json:"attempts"`
|
||||
Error string `json:"error,omitzero"`
|
||||
ID uuid.UUID `json:"id"`
|
||||
WorkflowID uuid.UUID `json:"workflow_id"`
|
||||
// Workflow is the workflow's current name.
|
||||
Workflow string `json:"workflow"`
|
||||
Version int `json:"workflow_version"`
|
||||
State string `json:"state"`
|
||||
Attempts int `json:"attempts"`
|
||||
Error string `json:"error,omitzero"`
|
||||
// Detail explains how the run ended: a finish step's detail, or why a
|
||||
// step parked the run.
|
||||
Detail string `json:"detail,omitzero"`
|
||||
@@ -228,8 +230,8 @@ func (a *runAPI) cancel(ctx context.Context, in *cancelRunInput) (*httpapi.Reply
|
||||
}
|
||||
|
||||
type recentRunsInput struct {
|
||||
Limit int `query:"limit" minimum:"1" maximum:"200" default:"50"`
|
||||
Workflow string `query:"workflow" doc:"Only this workflow's runs"`
|
||||
Limit int `query:"limit" minimum:"1" maximum:"200" default:"50"`
|
||||
WorkflowID string `query:"workflow_id" format:"uuid" doc:"Only this workflow's runs"`
|
||||
}
|
||||
|
||||
type runInput struct {
|
||||
@@ -246,7 +248,15 @@ type runAPI struct {
|
||||
}
|
||||
|
||||
func (a *runAPI) recent(ctx context.Context, in *recentRunsInput) (*httpapi.Reply[[]RunView], error) {
|
||||
runs, err := a.db.Recent(ctx, a.orgID, in.Workflow, in.Limit)
|
||||
var workflow uuid.NullUUID
|
||||
if in.WorkflowID != "" {
|
||||
id, err := uuid.Parse(in.WorkflowID)
|
||||
if err != nil {
|
||||
return nil, huma.NewError(http.StatusBadRequest, "a workflow id is a UUID")
|
||||
}
|
||||
workflow = uuid.NullUUID{UUID: id, Valid: true}
|
||||
}
|
||||
runs, err := a.db.Recent(ctx, a.orgID, workflow, in.Limit)
|
||||
if err != nil {
|
||||
return nil, huma.NewError(http.StatusInternalServerError, "couldn't list runs")
|
||||
}
|
||||
@@ -315,7 +325,7 @@ func (a *runAPI) definition(ctx context.Context, d store.Detail) (string, bool)
|
||||
o, err := readOverlay(d.Overlay)
|
||||
return o.documentOr(), err == nil
|
||||
}
|
||||
w, err := a.db.Workflow(ctx, a.orgID, d.Workflow, d.Version)
|
||||
w, err := a.db.Workflow(ctx, a.orgID, d.WorkflowID, d.Version)
|
||||
return w.Body, err == nil
|
||||
}
|
||||
|
||||
@@ -416,7 +426,7 @@ func effectOf(s store.Recorded) *Effect {
|
||||
|
||||
func view(s store.Summary, result jsontext.Value) RunView {
|
||||
v := RunView{
|
||||
ID: s.ID, Workflow: s.Workflow, Version: s.Version, State: s.State, Attempts: s.Attempts,
|
||||
ID: s.ID, WorkflowID: s.WorkflowID, Workflow: s.Workflow, Version: s.Version, State: s.State, Attempts: s.Attempts,
|
||||
Error: s.Error.String, Detail: s.Detail.String, CreatedAt: s.CreatedAt, Result: result, Dry: s.Dry,
|
||||
}
|
||||
if s.FinishedAt.Valid {
|
||||
@@ -471,7 +481,7 @@ func entry(s store.Recorded) TrailEntry {
|
||||
|
||||
// Recent returns orgID's latest runs, newest first.
|
||||
func (e *Engine) Recent(ctx context.Context, orgID string, limit int) ([]RunView, error) {
|
||||
runs, err := e.db.Recent(ctx, orgID, "", limit)
|
||||
runs, err := e.db.Recent(ctx, orgID, uuid.NullUUID{}, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
+204
-53
@@ -19,6 +19,7 @@ import (
|
||||
|
||||
// WorkflowView is one stored version of a workflow.
|
||||
type WorkflowView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Version int `json:"version"`
|
||||
Body string `json:"body"`
|
||||
@@ -31,7 +32,7 @@ type WorkflowView struct {
|
||||
}
|
||||
|
||||
func workflowView(w store.Workflow) WorkflowView {
|
||||
v := WorkflowView{Name: w.Name, Version: w.Version, Body: w.Body, CreatedBy: w.CreatedBy, CreatedAt: w.CreatedAt, Steps: []string{}, Enabled: !w.Disabled}
|
||||
v := WorkflowView{ID: w.ID, Name: w.Name, Version: w.Version, Body: w.Body, CreatedBy: w.CreatedBy, CreatedAt: w.CreatedAt, Steps: []string{}, Enabled: !w.Disabled}
|
||||
if doc, err := ParseDocument(w.Body); err == nil {
|
||||
v.Steps = doc.Describe()
|
||||
}
|
||||
@@ -40,6 +41,8 @@ func workflowView(w store.Workflow) WorkflowView {
|
||||
|
||||
// DraftView is the unpublished edit of a workflow.
|
||||
type DraftView struct {
|
||||
WorkflowID uuid.UUID `json:"workflow_id"`
|
||||
// Name is the workflow's name.
|
||||
Name string `json:"name"`
|
||||
Body string `json:"body"`
|
||||
// BaseVersion is the published version the draft began from, 0 for a
|
||||
@@ -52,12 +55,14 @@ type DraftView struct {
|
||||
}
|
||||
|
||||
func draftView(d store.Draft) DraftView {
|
||||
return DraftView{Name: d.Name, Body: d.Body, BaseVersion: d.BaseVersion, Revision: d.Revision, UpdatedBy: d.UpdatedBy, UpdatedAt: d.UpdatedAt}
|
||||
return DraftView{WorkflowID: d.WorkflowID, Name: d.Name, Body: d.Body, BaseVersion: d.BaseVersion, Revision: d.Revision, UpdatedBy: d.UpdatedBy, UpdatedAt: d.UpdatedAt}
|
||||
}
|
||||
|
||||
// WorkflowStats is what one workflow's runs add up to. Test runs are not
|
||||
// counted.
|
||||
type WorkflowStats struct {
|
||||
WorkflowID uuid.UUID `json:"workflow_id"`
|
||||
// Workflow is the workflow's name.
|
||||
Workflow string `json:"workflow"`
|
||||
Total int `json:"total"`
|
||||
Succeeded int `json:"succeeded"`
|
||||
@@ -80,7 +85,7 @@ type LastRun struct {
|
||||
|
||||
func workflowStats(s store.Stats) WorkflowStats {
|
||||
out := WorkflowStats{
|
||||
Workflow: s.Workflow, Total: s.Total, Succeeded: s.Succeeded, Failed: s.Failed, Active: s.Active,
|
||||
WorkflowID: s.WorkflowID, Workflow: s.Workflow, Total: s.Total, Succeeded: s.Succeeded, Failed: s.Failed, Active: s.Active,
|
||||
LastRun: LastRun{ID: s.LastRunID, State: s.LastState, At: s.LastRunAt},
|
||||
}
|
||||
if ended := s.Succeeded + s.Failed; ended > 0 {
|
||||
@@ -102,24 +107,32 @@ func (e *Engine) registerWorkflows(api huma.API, orgID string) {
|
||||
OperationID: "list-workflows", Method: http.MethodGet, Path: "/api/workflows",
|
||||
Summary: "List every workflow at its latest version", Tags: tags,
|
||||
}, a.list)
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionCreate, governance.KindWorkflow), huma.Operation{
|
||||
OperationID: "create-workflow", Method: http.MethodPost, Path: "/api/workflows",
|
||||
Summary: "Create a workflow, and publish its first version when a document is given", Tags: tags, DefaultStatus: http.StatusCreated,
|
||||
}, a.create)
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindWorkflow), huma.Operation{
|
||||
OperationID: "rename-workflow", Method: http.MethodPut, Path: "/api/workflows/{id}/name",
|
||||
Summary: "Rename a workflow; its runs, triggers and callers refer to it by id and are unchanged", Tags: tags,
|
||||
}, a.rename)
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindWorkflow), huma.Operation{
|
||||
OperationID: "get-workflow", Method: http.MethodGet, Path: "/api/workflows/{name}",
|
||||
OperationID: "get-workflow", Method: http.MethodGet, Path: "/api/workflows/{id}",
|
||||
Summary: "Get a workflow", Tags: tags,
|
||||
}, a.get)
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindWorkflow), huma.Operation{
|
||||
OperationID: "put-workflow", Method: http.MethodPut, Path: "/api/workflows/{name}",
|
||||
OperationID: "put-workflow", Method: http.MethodPut, Path: "/api/workflows/{id}",
|
||||
Summary: "Publish a workflow document as its next version", Tags: tags,
|
||||
}, a.put)
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionDelete, governance.KindWorkflow), huma.Operation{
|
||||
OperationID: "delete-workflow", Method: http.MethodDelete, Path: "/api/workflows/{name}",
|
||||
Summary: "Delete a workflow, unless a trigger or another workflow still names it", Tags: tags,
|
||||
OperationID: "delete-workflow", Method: http.MethodDelete, Path: "/api/workflows/{id}",
|
||||
Summary: "Delete a workflow, unless a trigger or another workflow still refers to it", Tags: tags,
|
||||
}, a.remove)
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindWorkflow), huma.Operation{
|
||||
OperationID: "set-workflow-enabled", Method: http.MethodPut, Path: "/api/workflows/{name}/enabled",
|
||||
OperationID: "set-workflow-enabled", Method: http.MethodPut, Path: "/api/workflows/{id}/enabled",
|
||||
Summary: "Enable or disable a workflow", Tags: tags,
|
||||
}, a.setEnabled)
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRun, governance.KindWorkflow), huma.Operation{
|
||||
OperationID: "run-workflow", Method: http.MethodPost, Path: "/api/workflows/{name}/runs",
|
||||
OperationID: "run-workflow", Method: http.MethodPost, Path: "/api/workflows/{id}/runs",
|
||||
Summary: "Run a workflow now with an input", Tags: tags, DefaultStatus: http.StatusAccepted,
|
||||
}, a.run)
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindWorkflow), huma.Operation{
|
||||
@@ -127,19 +140,19 @@ func (e *Engine) registerWorkflows(api huma.API, orgID string) {
|
||||
Summary: "List every workflow's unpublished draft", Tags: tags,
|
||||
}, a.drafts)
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindWorkflow), huma.Operation{
|
||||
OperationID: "get-workflow-draft", Method: http.MethodGet, Path: "/api/workflows/{name}/draft",
|
||||
OperationID: "get-workflow-draft", Method: http.MethodGet, Path: "/api/workflows/{id}/draft",
|
||||
Summary: "Get a workflow's unpublished draft", Tags: tags,
|
||||
}, a.draft)
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindWorkflow), huma.Operation{
|
||||
OperationID: "put-workflow-draft", Method: http.MethodPut, Path: "/api/workflows/{name}/draft",
|
||||
OperationID: "put-workflow-draft", Method: http.MethodPut, Path: "/api/workflows/{id}/draft",
|
||||
Summary: "Save a workflow's draft, which no run uses until it is published", Tags: tags,
|
||||
}, a.putDraft)
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindWorkflow), huma.Operation{
|
||||
OperationID: "discard-workflow-draft", Method: http.MethodDelete, Path: "/api/workflows/{name}/draft",
|
||||
OperationID: "discard-workflow-draft", Method: http.MethodDelete, Path: "/api/workflows/{id}/draft",
|
||||
Summary: "Discard a workflow's draft", Tags: tags, DefaultStatus: http.StatusNoContent,
|
||||
}, a.discardDraft)
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRun, governance.KindWorkflow), huma.Operation{
|
||||
OperationID: "test-workflow-draft", Method: http.MethodPost, Path: "/api/workflows/{name}/draft/test-run",
|
||||
OperationID: "test-workflow-draft", Method: http.MethodPost, Path: "/api/workflows/{id}/draft/test-run",
|
||||
Summary: "Test-run a workflow's draft: every action is judged and none that changes something runs", Tags: tags, DefaultStatus: http.StatusAccepted,
|
||||
}, a.testDraft)
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindWorkflow), huma.Operation{
|
||||
@@ -171,15 +184,37 @@ func (a *workflowAPI) list(ctx context.Context, _ *emptyInput) (*httpapi.Reply[[
|
||||
return httpapi.OK(out), nil
|
||||
}
|
||||
|
||||
// idInput is a workflow's id in the path.
|
||||
type idInput struct {
|
||||
ID string `path:"id" format:"uuid"`
|
||||
}
|
||||
|
||||
// workflowID parses a workflow id from the path.
|
||||
func workflowID(raw string) (uuid.UUID, error) {
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
return uuid.Nil, huma.Error400BadRequest("a workflow id is a UUID")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
type workflowInput struct {
|
||||
Name string `path:"name"`
|
||||
ID string `path:"id" format:"uuid"`
|
||||
Version int `query:"version" minimum:"1" doc:"A past version; the latest by default"`
|
||||
}
|
||||
|
||||
func (a *workflowAPI) get(ctx context.Context, in *workflowInput) (*httpapi.Reply[WorkflowView], error) {
|
||||
w, err := a.e.db.Workflow(ctx, a.orgID, in.Name, in.Version)
|
||||
id, err := workflowID(in.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return a.view(ctx, id, in.Version)
|
||||
}
|
||||
|
||||
func (a *workflowAPI) view(ctx context.Context, id uuid.UUID, version int) (*httpapi.Reply[WorkflowView], error) {
|
||||
w, err := a.e.db.Workflow(ctx, a.orgID, id, version)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNoWorkflow):
|
||||
case errors.Is(err, store.ErrNoWorkflow), err == nil && w.Deleted:
|
||||
return nil, huma.Error404NotFound("no such workflow")
|
||||
case err != nil:
|
||||
return nil, a.fail(ctx, "read the workflow", err)
|
||||
@@ -187,43 +222,136 @@ func (a *workflowAPI) get(ctx context.Context, in *workflowInput) (*httpapi.Repl
|
||||
return httpapi.OK(workflowView(w)), nil
|
||||
}
|
||||
|
||||
// WorkflowIdentity is a workflow apart from its versions.
|
||||
type WorkflowIdentity struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Enabled bool `json:"enabled"`
|
||||
// Version is the version published with the workflow, 0 when none was.
|
||||
Version int `json:"version"`
|
||||
}
|
||||
|
||||
type createWorkflowInput struct {
|
||||
Body struct {
|
||||
Name string `json:"name" doc:"Lowercase letters and digits, joined by dots or hyphens"`
|
||||
Body string `json:"body,omitempty" doc:"The first version's workflow document, as YAML; the workflow is created unpublished without one"`
|
||||
}
|
||||
}
|
||||
|
||||
func (a *workflowAPI) create(ctx context.Context, in *createWorkflowInput) (*httpapi.Reply[WorkflowIdentity], error) {
|
||||
if !stableid.Valid(in.Body.Name) {
|
||||
return nil, huma.Error400BadRequest("a workflow name is lowercase letters and digits, joined by dots or hyphens")
|
||||
}
|
||||
if in.Body.Body != "" {
|
||||
// Check the document before creating anything, so a bad one leaves no
|
||||
// unpublished workflow behind.
|
||||
if err := a.e.checkDocument(ctx, a.orgID, in.Body.Body); err != nil {
|
||||
return nil, a.publishError(ctx, err)
|
||||
}
|
||||
}
|
||||
id, err := a.e.Create(ctx, a.orgID, in.Body.Name)
|
||||
switch {
|
||||
case errors.Is(err, ErrNameTaken):
|
||||
return nil, huma.Error409Conflict("another workflow has that name")
|
||||
case err != nil:
|
||||
return nil, a.fail(ctx, "create the workflow", err)
|
||||
}
|
||||
out := WorkflowIdentity{ID: id, Name: in.Body.Name, Enabled: true}
|
||||
if in.Body.Body != "" {
|
||||
zero := 0
|
||||
version, err := a.e.Publish(ctx, a.orgID, id, in.Body.Body, governance.CallerID(ctx), &zero)
|
||||
if err != nil {
|
||||
if derr := a.e.defs.DeleteWorkflow(ctx, a.orgID, id); derr != nil {
|
||||
a.e.log.WarnContext(ctx, "remove workflow whose first version was refused", "workflow", id, "error", derr)
|
||||
}
|
||||
return nil, a.publishError(ctx, err)
|
||||
}
|
||||
out.Version = version
|
||||
}
|
||||
return httpapi.OK(out), nil
|
||||
}
|
||||
|
||||
type renameInput struct {
|
||||
ID string `path:"id" format:"uuid"`
|
||||
Body struct {
|
||||
Name string `json:"name" doc:"Lowercase letters and digits, joined by dots or hyphens"`
|
||||
}
|
||||
}
|
||||
|
||||
func (a *workflowAPI) rename(ctx context.Context, in *renameInput) (*httpapi.Reply[WorkflowIdentity], error) {
|
||||
id, err := workflowID(in.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !stableid.Valid(in.Body.Name) {
|
||||
return nil, huma.Error400BadRequest("a workflow name is lowercase letters and digits, joined by dots or hyphens")
|
||||
}
|
||||
switch err := a.e.Rename(ctx, a.orgID, id, in.Body.Name); {
|
||||
case errors.Is(err, ErrNameTaken):
|
||||
return nil, huma.Error409Conflict("another workflow has that name")
|
||||
case errors.Is(err, store.ErrNoWorkflow):
|
||||
return nil, huma.Error404NotFound("no such workflow")
|
||||
case err != nil:
|
||||
return nil, a.fail(ctx, "rename the workflow", err)
|
||||
}
|
||||
return a.identity(ctx, id)
|
||||
}
|
||||
|
||||
func (a *workflowAPI) identity(ctx context.Context, id uuid.UUID) (*httpapi.Reply[WorkflowIdentity], error) {
|
||||
w, err := a.e.db.Identity(ctx, a.orgID, id)
|
||||
if err != nil {
|
||||
return nil, a.fail(ctx, "read the workflow", err)
|
||||
}
|
||||
out := WorkflowIdentity{ID: w.ID, Name: w.Name, Enabled: !w.Disabled}
|
||||
if latest, err := a.e.db.Workflow(ctx, a.orgID, id, 0); err == nil {
|
||||
out.Version = latest.Version
|
||||
}
|
||||
return httpapi.OK(out), nil
|
||||
}
|
||||
|
||||
type putWorkflowInput struct {
|
||||
Name string `path:"name" doc:"Lowercase letters and digits, joined by dots or hyphens"`
|
||||
ID string `path:"id" format:"uuid"`
|
||||
Body struct {
|
||||
Body string `json:"body" doc:"The workflow document, as YAML"`
|
||||
// ExpectedVersion makes the save refuse unless the latest version is
|
||||
// this one, so an editor can't publish over a version it never saw.
|
||||
ExpectedVersion *int `json:"expected_version,omitempty" minimum:"0" doc:"The latest version the document was edited from, 0 for a new workflow; the save is refused with 409 when another is stored"`
|
||||
ExpectedVersion *int `json:"expected_version,omitempty" minimum:"0" doc:"The latest version the document was edited from, 0 for a workflow not yet published; the save is refused with 409 when another is stored"`
|
||||
}
|
||||
}
|
||||
|
||||
func (a *workflowAPI) put(ctx context.Context, in *putWorkflowInput) (*httpapi.Reply[WorkflowView], error) {
|
||||
if !stableid.Valid(in.Name) {
|
||||
return nil, huma.Error400BadRequest("a workflow name is lowercase letters and digits, joined by dots or hyphens")
|
||||
}
|
||||
version, err := a.e.Publish(ctx, a.orgID, in.Name, in.Body.Body, governance.CallerID(ctx), in.Body.ExpectedVersion)
|
||||
id, err := workflowID(in.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrVersionConflict) {
|
||||
return nil, huma.Error409Conflict("the workflow has another version than the one this was edited from; reload it before publishing")
|
||||
}
|
||||
if invalid, ok := errors.AsType[*InvalidError](err); ok {
|
||||
return nil, Problems(invalid)
|
||||
}
|
||||
return nil, a.fail(ctx, "save the workflow", err)
|
||||
return nil, err
|
||||
}
|
||||
w, err := a.e.db.Workflow(ctx, a.orgID, in.Name, version)
|
||||
version, err := a.e.Publish(ctx, a.orgID, id, in.Body.Body, governance.CallerID(ctx), in.Body.ExpectedVersion)
|
||||
if err != nil {
|
||||
return nil, a.fail(ctx, "read the workflow", err)
|
||||
return nil, a.publishError(ctx, err)
|
||||
}
|
||||
return httpapi.OK(workflowView(w)), nil
|
||||
return a.view(ctx, id, version)
|
||||
}
|
||||
|
||||
type nameInput struct {
|
||||
Name string `path:"name"`
|
||||
// publishError turns why a document wasn't published into the response that
|
||||
// says what to do about it.
|
||||
func (a *workflowAPI) publishError(ctx context.Context, err error) error {
|
||||
if invalid, ok := errors.AsType[*InvalidError](err); ok {
|
||||
return Problems(invalid)
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, ErrVersionConflict):
|
||||
return huma.Error409Conflict("the workflow has another version than the one this was edited from; reload it before publishing")
|
||||
case errors.Is(err, store.ErrNoWorkflow):
|
||||
return huma.Error404NotFound("no such workflow")
|
||||
}
|
||||
return a.fail(ctx, "save the workflow", err)
|
||||
}
|
||||
|
||||
func (a *workflowAPI) remove(ctx context.Context, in *nameInput) (*struct{}, error) {
|
||||
switch err := a.e.Delete(ctx, a.orgID, in.Name); {
|
||||
func (a *workflowAPI) remove(ctx context.Context, in *idInput) (*struct{}, error) {
|
||||
id, err := workflowID(in.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch err := a.e.Delete(ctx, a.orgID, id); {
|
||||
case errors.Is(err, store.ErrNoWorkflow):
|
||||
return nil, huma.Error404NotFound("no such workflow")
|
||||
case err != nil:
|
||||
@@ -236,39 +364,47 @@ func (a *workflowAPI) remove(ctx context.Context, in *nameInput) (*struct{}, err
|
||||
}
|
||||
|
||||
type setEnabledInput struct {
|
||||
Name string `path:"name"`
|
||||
ID string `path:"id" format:"uuid"`
|
||||
Body struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
}
|
||||
|
||||
func (a *workflowAPI) setEnabled(ctx context.Context, in *setEnabledInput) (*httpapi.Reply[WorkflowView], error) {
|
||||
switch err := a.e.SetEnabled(ctx, a.orgID, in.Name, in.Body.Enabled); {
|
||||
id, err := workflowID(in.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch err := a.e.SetEnabled(ctx, a.orgID, id, in.Body.Enabled); {
|
||||
case errors.Is(err, store.ErrNoWorkflow):
|
||||
return nil, huma.Error404NotFound("no such workflow")
|
||||
case err != nil:
|
||||
return nil, a.fail(ctx, "change whether the workflow is enabled", err)
|
||||
}
|
||||
return a.get(ctx, &workflowInput{Name: in.Name})
|
||||
return a.view(ctx, id, 0)
|
||||
}
|
||||
|
||||
type runWorkflowInput struct {
|
||||
Name string `path:"name"`
|
||||
ID string `path:"id" format:"uuid"`
|
||||
Body struct {
|
||||
Input map[string]any `json:"input,omitempty" doc:"The workflow's inputs by name"`
|
||||
}
|
||||
}
|
||||
|
||||
func (a *workflowAPI) run(ctx context.Context, in *runWorkflowInput) (*httpapi.Reply[RunView], error) {
|
||||
id, err := workflowID(in.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
input, err := inputOf(in.Body.Input)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("the input isn't valid JSON")
|
||||
}
|
||||
id, err := a.e.Start(ctx, StartRequest{OrgID: a.orgID, Workflow: in.Name, Input: input})
|
||||
run, err := a.e.Start(ctx, StartRequest{OrgID: a.orgID, WorkflowID: id, Input: input})
|
||||
if err != nil {
|
||||
return nil, a.startError(ctx, err)
|
||||
}
|
||||
return a.started(ctx, id)
|
||||
return a.started(ctx, run)
|
||||
}
|
||||
|
||||
func (a *workflowAPI) started(ctx context.Context, id uuid.UUID) (*httpapi.Reply[RunView], error) {
|
||||
@@ -312,8 +448,12 @@ func (a *workflowAPI) drafts(ctx context.Context, _ *emptyInput) (*httpapi.Reply
|
||||
return httpapi.OK(out), nil
|
||||
}
|
||||
|
||||
func (a *workflowAPI) draft(ctx context.Context, in *nameInput) (*httpapi.Reply[DraftView], error) {
|
||||
d, err := a.e.db.Draft(ctx, a.orgID, in.Name)
|
||||
func (a *workflowAPI) draft(ctx context.Context, in *idInput) (*httpapi.Reply[DraftView], error) {
|
||||
id, err := workflowID(in.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d, err := a.e.db.Draft(ctx, a.orgID, id)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNoDraft):
|
||||
return nil, huma.Error404NotFound("the workflow has no draft")
|
||||
@@ -324,7 +464,7 @@ func (a *workflowAPI) draft(ctx context.Context, in *nameInput) (*httpapi.Reply[
|
||||
}
|
||||
|
||||
type putDraftInput struct {
|
||||
Name string `path:"name" doc:"Lowercase letters and digits, joined by dots or hyphens"`
|
||||
ID string `path:"id" format:"uuid"`
|
||||
Body struct {
|
||||
Body string `json:"body" doc:"The draft document, as YAML. It may be unfinished or invalid; publishing checks it."`
|
||||
// Revision is the draft's revision as last read, so a write can't
|
||||
@@ -334,11 +474,14 @@ type putDraftInput struct {
|
||||
}
|
||||
|
||||
func (a *workflowAPI) putDraft(ctx context.Context, in *putDraftInput) (*httpapi.Reply[DraftView], error) {
|
||||
if !stableid.Valid(in.Name) {
|
||||
return nil, huma.Error400BadRequest("a workflow name is lowercase letters and digits, joined by dots or hyphens")
|
||||
id, err := workflowID(in.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d, err := a.e.db.PutDraft(ctx, a.orgID, in.Name, in.Body.Body, governance.CallerID(ctx), in.Body.Revision)
|
||||
d, err := a.e.db.PutDraft(ctx, a.orgID, id, in.Body.Body, governance.CallerID(ctx), in.Body.Revision)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNoWorkflow):
|
||||
return nil, huma.Error404NotFound("no such workflow")
|
||||
case errors.Is(err, store.ErrDraftConflict):
|
||||
return nil, huma.Error409Conflict("the draft was changed elsewhere; load it before saving")
|
||||
case err != nil:
|
||||
@@ -347,8 +490,12 @@ func (a *workflowAPI) putDraft(ctx context.Context, in *putDraftInput) (*httpapi
|
||||
return httpapi.OK(draftView(d)), nil
|
||||
}
|
||||
|
||||
func (a *workflowAPI) discardDraft(ctx context.Context, in *nameInput) (*struct{}, error) {
|
||||
had, err := a.e.db.DeleteDraft(ctx, a.orgID, in.Name)
|
||||
func (a *workflowAPI) discardDraft(ctx context.Context, in *idInput) (*struct{}, error) {
|
||||
id, err := workflowID(in.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
had, err := a.e.db.DeleteDraft(ctx, a.orgID, id)
|
||||
switch {
|
||||
case err != nil:
|
||||
return nil, a.fail(ctx, "discard the draft", err)
|
||||
@@ -359,7 +506,11 @@ func (a *workflowAPI) discardDraft(ctx context.Context, in *nameInput) (*struct{
|
||||
}
|
||||
|
||||
func (a *workflowAPI) testDraft(ctx context.Context, in *runWorkflowInput) (*httpapi.Reply[RunView], error) {
|
||||
d, err := a.e.db.Draft(ctx, a.orgID, in.Name)
|
||||
id, err := workflowID(in.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d, err := a.e.db.Draft(ctx, a.orgID, id)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNoDraft):
|
||||
return nil, huma.Error404NotFound("the workflow has no draft to test")
|
||||
@@ -370,11 +521,11 @@ func (a *workflowAPI) testDraft(ctx context.Context, in *runWorkflowInput) (*htt
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("the input isn't valid JSON")
|
||||
}
|
||||
id, err := a.e.StartDry(ctx, DryRequest{OrgID: a.orgID, Workflow: in.Name, Document: d.Body, Input: input})
|
||||
run, err := a.e.StartDry(ctx, DryRequest{OrgID: a.orgID, WorkflowID: id, Document: d.Body, Input: input})
|
||||
if err != nil {
|
||||
return nil, a.startError(ctx, err)
|
||||
}
|
||||
return a.started(ctx, id)
|
||||
return a.started(ctx, run)
|
||||
}
|
||||
|
||||
func (a *workflowAPI) stats(ctx context.Context, _ *emptyInput) (*httpapi.Reply[[]WorkflowStats], error) {
|
||||
|
||||
@@ -14,6 +14,8 @@ export interface Binding {
|
||||
source: string;
|
||||
event_type_id?: string;
|
||||
mapping_id?: string;
|
||||
workflow_id?: string;
|
||||
/** The workflow's name. */
|
||||
workflow?: string;
|
||||
status?: string;
|
||||
/** The source takes deliveries with no verification. */
|
||||
@@ -27,6 +29,7 @@ export function bindingOfTrigger(trigger: Trigger): Binding {
|
||||
source: trigger.source ?? "",
|
||||
event_type_id: trigger.event_type_id,
|
||||
mapping_id: trigger.mapping_id,
|
||||
workflow_id: trigger.workflow_id,
|
||||
workflow: trigger.workflow,
|
||||
status: trigger.status,
|
||||
unsigned: trigger.unsigned,
|
||||
@@ -64,6 +67,7 @@ export interface BindingDraft {
|
||||
/** The event type the binding applies to; its source is the binding's. */
|
||||
eventTypeId: string;
|
||||
mappingId: string;
|
||||
/** The id of the workflow the binding starts. */
|
||||
workflow: string;
|
||||
}
|
||||
|
||||
@@ -77,7 +81,7 @@ export function draftFromBinding(binding: Binding): BindingDraft {
|
||||
name: binding.name,
|
||||
eventTypeId: binding.event_type_id || "",
|
||||
mappingId: binding.mapping_id || "",
|
||||
workflow: binding.workflow || "",
|
||||
workflow: binding.workflow_id || "",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -92,7 +96,7 @@ export function bindingPayload(
|
||||
source_id: eventType?.source_id ?? "",
|
||||
event_type_id: draft.eventTypeId,
|
||||
mapping_id: draft.mappingId || undefined,
|
||||
workflow: draft.workflow,
|
||||
workflow_id: draft.workflow,
|
||||
disabled: false,
|
||||
pending: true,
|
||||
};
|
||||
|
||||
@@ -63,7 +63,7 @@ export function useBindings() {
|
||||
bindings.value = triggers.filter((x) => x.event_type_id).map(bindingOfTrigger);
|
||||
mappings.value = m.mappings || [];
|
||||
eventTypes.value = t.event_types || [];
|
||||
workflows.value = w.map((d) => ({ id: d.name, name: d.name }));
|
||||
workflows.value = w.map((d) => ({ id: d.id, name: d.name }));
|
||||
} catch (err) {
|
||||
failure.value = failureFor(err);
|
||||
bindings.value = null;
|
||||
|
||||
@@ -43,7 +43,7 @@ interface TaskEntry {
|
||||
|
||||
const pages = computed(() => navEntries(props.hidden));
|
||||
const tasks = ref<TaskEntry[]>([]);
|
||||
const workflows = ref<string[]>([]);
|
||||
const workflows = ref<{ id: string; name: string }[]>([]);
|
||||
const shortcut = navigator.platform.startsWith("Mac") ? "⌘K" : "Ctrl K";
|
||||
const showWorkflows = computed(() => !props.hidden.includes("/workflows"));
|
||||
const showTasks = computed(() => !props.hidden.includes("/tasks"));
|
||||
@@ -63,7 +63,7 @@ async function loadEntries(): Promise<void> {
|
||||
tasksError.value = taskPage === null;
|
||||
tasks.value = taskPage?.tasks ?? [];
|
||||
workflowsError.value = workflowList === null;
|
||||
workflows.value = (workflowList ?? []).map(({ name }) => name);
|
||||
workflows.value = (workflowList ?? []).map(({ id, name }) => ({ id, name }));
|
||||
}
|
||||
|
||||
watch(open, (value) => {
|
||||
@@ -129,12 +129,12 @@ onUnmounted(() => document.removeEventListener("keydown", onGlobalKeydown));
|
||||
</CommandGroup>
|
||||
<CommandGroup v-else-if="workflows.length" heading="Workflows">
|
||||
<CommandItem
|
||||
v-for="id in workflows"
|
||||
:key="id"
|
||||
:value="`workflow:${id}`"
|
||||
@select="go(`/workflows/${encodeURIComponent(id)}`)"
|
||||
v-for="workflow in workflows"
|
||||
:key="workflow.id"
|
||||
:value="`workflow:${workflow.name}`"
|
||||
@select="go(`/workflows/${encodeURIComponent(workflow.id)}`)"
|
||||
>
|
||||
{{ id }}
|
||||
{{ workflow.name }}
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
<CommandGroup v-if="tasksError" heading="Tasks">
|
||||
|
||||
@@ -23,7 +23,8 @@ import { useRead } from "@/lib/use-read";
|
||||
import { interval } from "@/workflows/use-workflow-list";
|
||||
import { triggerInput } from "./trigger";
|
||||
|
||||
/** With `workflow`, only the triggers that run it, and new ones run it. */
|
||||
/** With `workflow`, a workflow's id, only the triggers that run it, and new
|
||||
* ones run it. */
|
||||
const props = defineProps<{ workflow?: string }>();
|
||||
|
||||
const { data, error, reload } = useRead(() => api.triggers());
|
||||
@@ -34,7 +35,7 @@ onMounted(() => {
|
||||
void sources.reload();
|
||||
if (!props.workflow) void workflows.reload();
|
||||
});
|
||||
const rows = computed(() => (data.value ?? []).filter((t) => !props.workflow || t.workflow === props.workflow));
|
||||
const rows = computed(() => (data.value ?? []).filter((t) => !props.workflow || t.workflow_id === props.workflow));
|
||||
|
||||
const columns = computed<DataTableColumn<Trigger>[]>(() => [
|
||||
{ id: "name", label: "Trigger", fixed: true, width: "auto", sort: (t) => t.name },
|
||||
@@ -73,7 +74,7 @@ function open(trigger?: Trigger): void {
|
||||
source_id: trigger?.every ? "" : (trigger?.source_id ?? ""),
|
||||
event_type: trigger?.every ? "" : (trigger?.event_type ?? ""),
|
||||
every: trigger?.every ?? "",
|
||||
workflow: trigger?.workflow ?? props.workflow ?? "",
|
||||
workflow: trigger?.workflow_id ?? props.workflow ?? "",
|
||||
filter: trigger?.every ? "" : toLines(trigger?.filter ?? {}),
|
||||
disabled: trigger ? !trigger.enabled : false,
|
||||
};
|
||||
@@ -84,8 +85,8 @@ async function submit(): Promise<void> {
|
||||
const filter = fromLines(f.filter);
|
||||
const input: TriggerInput =
|
||||
f.mode === "schedule"
|
||||
? { every: f.every.trim(), workflow: f.workflow, disabled: f.disabled }
|
||||
: { source_id: f.source_id, event_type: f.event_type.trim(), filter, workflow: f.workflow, disabled: f.disabled };
|
||||
? { every: f.every.trim(), workflow_id: f.workflow, disabled: f.disabled }
|
||||
: { source_id: f.source_id, event_type: f.event_type.trim(), filter, workflow_id: f.workflow, disabled: f.disabled };
|
||||
if (await save(f.name.trim(), input)) editing.value = false;
|
||||
}
|
||||
</script>
|
||||
@@ -105,7 +106,7 @@ async function submit(): Promise<void> {
|
||||
<template v-if="row.every">Every {{ interval(row.every) }}</template>
|
||||
<template v-else>{{ row.source }} <span class="font-mono text-caption text-fg-muted">{{ row.event_type }}</span></template>
|
||||
</template>
|
||||
<template #cell-workflow="{ row }"><RouterLink class="hover:underline" :to="`/workflows/${row.workflow}`">{{ row.workflow }}</RouterLink></template>
|
||||
<template #cell-workflow="{ row }"><RouterLink class="hover:underline" :to="`/workflows/${row.workflow_id}`">{{ row.workflow }}</RouterLink></template>
|
||||
<template #cell-filter="{ row }">
|
||||
<span v-if="!row.every" class="font-mono text-caption">{{ Object.entries(row.filter ?? {}).map(([k, v]) => `${k}=${v}`).join(", ") }}</span>
|
||||
</template>
|
||||
@@ -142,7 +143,7 @@ async function submit(): Promise<void> {
|
||||
<Select v-if="!workflow" v-model="form.workflow" required>
|
||||
<SelectTrigger class="w-full" aria-label="Workflow"><SelectValue placeholder="Workflow it runs" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="w in workflows.data.value ?? []" :key="w.name" :value="w.name">{{ w.name }}</SelectItem>
|
||||
<SelectItem v-for="w in workflows.data.value ?? []" :key="w.id" :value="w.id">{{ w.name }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p v-if="actionError" role="alert" class="text-caption text-danger">{{ actionError }}</p>
|
||||
|
||||
@@ -3,12 +3,12 @@ import type { Trigger, TriggerInput } from "@/lib/api";
|
||||
/** triggerInput is the put that keeps a listed trigger as it is. A schedule
|
||||
* sends only its interval: the server fixes its source, type and filter. */
|
||||
export function triggerInput(trigger: Trigger): TriggerInput {
|
||||
if (trigger.every) return { every: trigger.every, workflow: trigger.workflow, disabled: !trigger.enabled };
|
||||
if (trigger.every) return { every: trigger.every, workflow_id: trigger.workflow_id, disabled: !trigger.enabled };
|
||||
return {
|
||||
source_id: trigger.source_id,
|
||||
event_type: trigger.event_type,
|
||||
filter: trigger.filter,
|
||||
workflow: trigger.workflow,
|
||||
workflow_id: trigger.workflow_id,
|
||||
disabled: !trigger.enabled,
|
||||
};
|
||||
}
|
||||
+44
-19
@@ -185,7 +185,7 @@ async function request<T = unknown>(
|
||||
|
||||
export const api = {
|
||||
// The archie binary's module API; the wire types are below the object.
|
||||
runs: (limit = 200, workflow?: string) => request<Run[]>("/api/runs" + qs({ limit, workflow })),
|
||||
runs: (limit = 200, workflowId?: string) => request<Run[]>("/api/runs" + qs({ limit, workflow_id: workflowId })),
|
||||
run: (id: string) => request<RunTrail>(`/api/runs/${encodeURIComponent(id)}`),
|
||||
/** Queues a parked run again from the step that parked it, or from `from`. */
|
||||
retryRun: (id: string, from?: string) =>
|
||||
@@ -245,32 +245,36 @@ export const api = {
|
||||
putTrigger: (name: string, trigger: TriggerInput) =>
|
||||
request<{ trigger: string }>(`/api/triggers/${encodeURIComponent(name)}`, { method: "PUT", body: trigger }),
|
||||
workflowList: () => request<WorkflowVersion[]>("/api/workflows"),
|
||||
workflow: (name: string, version?: number) =>
|
||||
request<WorkflowVersion>(`/api/workflows/${encodeURIComponent(name)}` + qs({ version })),
|
||||
/** Publishes a document as the next version; `expectedVersion` makes the save fail with 409 when another is stored. */
|
||||
putWorkflow: (name: string, body: string, expectedVersion?: number) =>
|
||||
request<WorkflowVersion>(`/api/workflows/${encodeURIComponent(name)}`, { method: "PUT", body: { body, expected_version: expectedVersion } }),
|
||||
deleteWorkflow: (name: string) => request<void>(`/api/workflows/${encodeURIComponent(name)}`, { method: "DELETE", parse: false }),
|
||||
setWorkflowEnabled: (name: string, enabled: boolean) =>
|
||||
request<WorkflowVersion>(`/api/workflows/${encodeURIComponent(name)}/enabled`, { method: "PUT", body: { enabled } }),
|
||||
runWorkflow: (name: string, input?: Record<string, unknown>) =>
|
||||
request<Run>(`/api/workflows/${encodeURIComponent(name)}/runs`, { method: "POST", body: { input } }),
|
||||
/** Creates a workflow, publishing body as its first version when given. */
|
||||
createWorkflow: (name: string, body?: string) =>
|
||||
request<WorkflowIdentity>("/api/workflows", { method: "POST", body: body === undefined ? { name } : { name, body } }),
|
||||
renameWorkflow: (id: string, name: string) =>
|
||||
request<WorkflowIdentity>(`/api/workflows/${encodeURIComponent(id)}/name`, { method: "PUT", body: { name } }),
|
||||
workflow: (id: string, version?: number) =>
|
||||
request<WorkflowVersion>(`/api/workflows/${encodeURIComponent(id)}` + qs({ version })),
|
||||
putWorkflow: (id: string, body: string, expectedVersion?: number) =>
|
||||
request<WorkflowVersion>(`/api/workflows/${encodeURIComponent(id)}`, { method: "PUT", body: { body, expected_version: expectedVersion } }),
|
||||
deleteWorkflow: (id: string) => request<void>(`/api/workflows/${encodeURIComponent(id)}`, { method: "DELETE", parse: false }),
|
||||
setWorkflowEnabled: (id: string, enabled: boolean) =>
|
||||
request<WorkflowVersion>(`/api/workflows/${encodeURIComponent(id)}/enabled`, { method: "PUT", body: { enabled } }),
|
||||
runWorkflow: (id: string, input?: Record<string, unknown>) =>
|
||||
request<Run>(`/api/workflows/${encodeURIComponent(id)}/runs`, { method: "POST", body: { input } }),
|
||||
workflowDrafts: () => request<WorkflowDraft[]>("/api/workflow-drafts"),
|
||||
/** A workflow's draft, or null when it has none. */
|
||||
workflowDraft: async (name: string) => {
|
||||
workflowDraft: async (id: string) => {
|
||||
try {
|
||||
return await request<WorkflowDraft>(`/api/workflows/${encodeURIComponent(name)}/draft`);
|
||||
return await request<WorkflowDraft>(`/api/workflows/${encodeURIComponent(id)}/draft`);
|
||||
} catch (cause) {
|
||||
if (cause instanceof ApiError && cause.status === 404) return null;
|
||||
throw cause;
|
||||
}
|
||||
},
|
||||
/** Saves a draft; `revision` is the one last read, 0 for none, and a stale one fails with 409. */
|
||||
putWorkflowDraft: (name: string, body: string, revision: number) =>
|
||||
request<WorkflowDraft>(`/api/workflows/${encodeURIComponent(name)}/draft`, { method: "PUT", body: { body, revision } }),
|
||||
discardWorkflowDraft: (name: string) => request<void>(`/api/workflows/${encodeURIComponent(name)}/draft`, { method: "DELETE", parse: false }),
|
||||
testWorkflowDraft: (name: string, input?: Record<string, unknown>) =>
|
||||
request<Run>(`/api/workflows/${encodeURIComponent(name)}/draft/test-run`, { method: "POST", body: { input } }),
|
||||
putWorkflowDraft: (id: string, body: string, revision: number) =>
|
||||
request<WorkflowDraft>(`/api/workflows/${encodeURIComponent(id)}/draft`, { method: "PUT", body: { body, revision } }),
|
||||
discardWorkflowDraft: (id: string) => request<void>(`/api/workflows/${encodeURIComponent(id)}/draft`, { method: "DELETE", parse: false }),
|
||||
testWorkflowDraft: (id: string, input?: Record<string, unknown>) =>
|
||||
request<Run>(`/api/workflows/${encodeURIComponent(id)}/draft/test-run`, { method: "POST", body: { input } }),
|
||||
workflowStats: () => request<WorkflowStats[]>("/api/workflow-stats"),
|
||||
workflowStepTypes: () => request<StepType[]>("/api/workflow-step-types"),
|
||||
extensionKinds: () => request<ExtensionKindInfo[]>("/api/extension-kinds"),
|
||||
@@ -784,6 +788,9 @@ export interface ChatActionRecord {
|
||||
|
||||
export interface Run {
|
||||
id: string;
|
||||
/** Empty for a test run of a document that isn't a workflow yet. */
|
||||
workflow_id?: string;
|
||||
/** The workflow's current name. */
|
||||
workflow: string;
|
||||
workflow_version: number;
|
||||
state: string;
|
||||
@@ -1048,6 +1055,8 @@ export interface NoRunReason {
|
||||
code: "mapping_mismatch" | "access_denied" | "workflow_disabled" | string;
|
||||
mapping?: string;
|
||||
failures?: MappingFailure[];
|
||||
workflow_id?: string;
|
||||
/** The workflow's name when the dispatch was refused. */
|
||||
workflow?: string;
|
||||
detail?: string;
|
||||
}
|
||||
@@ -1118,6 +1127,8 @@ export interface Trigger {
|
||||
source?: string;
|
||||
event_type?: string;
|
||||
every?: string;
|
||||
workflow_id: string;
|
||||
/** The workflow's current name. */
|
||||
workflow: string;
|
||||
filter?: Record<string, string>;
|
||||
enabled: boolean;
|
||||
@@ -1132,7 +1143,7 @@ export interface TriggerInput {
|
||||
source_id?: string;
|
||||
event_type?: string;
|
||||
every?: string;
|
||||
workflow: string;
|
||||
workflow_id: string;
|
||||
filter?: Record<string, string>;
|
||||
disabled: boolean;
|
||||
event_type_id?: string;
|
||||
@@ -1141,7 +1152,17 @@ export interface TriggerInput {
|
||||
pending?: boolean;
|
||||
}
|
||||
|
||||
/** A workflow apart from its versions. */
|
||||
export interface WorkflowIdentity {
|
||||
id: string;
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
/** The version published with it, 0 when none was. */
|
||||
version: number;
|
||||
}
|
||||
|
||||
export interface WorkflowVersion {
|
||||
id: string;
|
||||
name: string;
|
||||
version: number;
|
||||
body: string;
|
||||
@@ -1154,6 +1175,8 @@ export interface WorkflowVersion {
|
||||
|
||||
/** The unpublished edit of a workflow. */
|
||||
export interface WorkflowDraft {
|
||||
workflow_id: string;
|
||||
/** The workflow's name. */
|
||||
name: string;
|
||||
body: string;
|
||||
/** The published version it began from, 0 for a workflow not yet published. */
|
||||
@@ -1165,6 +1188,8 @@ export interface WorkflowDraft {
|
||||
}
|
||||
|
||||
export interface WorkflowStats {
|
||||
workflow_id: string;
|
||||
/** The workflow's name. */
|
||||
workflow: string;
|
||||
total: number;
|
||||
succeeded: number;
|
||||
|
||||
@@ -148,7 +148,8 @@ const result = computed(() => {
|
||||
<MetadataList :rows="details">
|
||||
<template #value="{ row }">
|
||||
<span v-if="row.label === 'Workflow'" class="inline-flex flex-wrap items-center gap-2">
|
||||
<RouterLink class="underline" :to="`/workflows/${data.run.workflow}`">{{ row.value }}</RouterLink>
|
||||
<RouterLink v-if="data.run.workflow_id" class="underline" :to="`/workflows/${data.run.workflow_id}`">{{ row.value }}</RouterLink>
|
||||
<span v-else>{{ row.value }}</span>
|
||||
<Badge variant="outline">v{{ data.run.workflow_version }}</Badge>
|
||||
</span>
|
||||
<span v-else-if="row.label === 'Event' || row.label === 'Run'" class="inline-flex items-center gap-1">
|
||||
|
||||
@@ -48,7 +48,7 @@ const columns: DataTableColumn<Run>[] = [
|
||||
<template #cell-id="{ row }"><span class="font-mono text-caption text-fg-muted">{{ row.id.slice(0, 8) }}</span></template>
|
||||
<template #menu="{ row }">
|
||||
<ContextMenuItem @select="router.push(`/runs/${row.id}`)"><ExternalLink />Open run</ContextMenuItem>
|
||||
<ContextMenuItem @select="router.push(`/workflows/${row.workflow}`)"><Workflow />Open workflow</ContextMenuItem>
|
||||
<ContextMenuItem v-if="row.workflow_id" @select="router.push(`/workflows/${row.workflow_id}`)"><Workflow />Open workflow</ContextMenuItem>
|
||||
</template>
|
||||
<template #empty><slot name="empty" /></template>
|
||||
</DataTable>
|
||||
|
||||
@@ -2,11 +2,12 @@ import { defineStore } from "pinia";
|
||||
import { computed, reactive, ref } from "vue";
|
||||
|
||||
import { errors } from "../copy/errors/index.ts";
|
||||
import { api, ApiError, describeError } from "../lib/api.ts";
|
||||
import { api, ApiError, describeError, type WorkflowDraft, type WorkflowVersion } from "../lib/api.ts";
|
||||
import type { StepTypeInfo } from "../workflows/workflow-yaml.ts";
|
||||
|
||||
export interface WorkflowDefinitionEntry {
|
||||
id: string;
|
||||
name: string;
|
||||
yaml: string;
|
||||
/** The published version the yaml is. */
|
||||
version: number;
|
||||
@@ -19,6 +20,7 @@ export interface WorkflowDefinitionCollection {
|
||||
/** A workflow's unpublished edit. */
|
||||
export interface WorkflowDraftEntry {
|
||||
id: string;
|
||||
name: string;
|
||||
yaml: string;
|
||||
/** The draft's revision as last read; a save names it. */
|
||||
revision: number;
|
||||
@@ -42,7 +44,7 @@ export const useWorkflowsStore = defineStore("workflows", () => {
|
||||
async function load(): Promise<void> {
|
||||
try {
|
||||
const [published, held, types] = await Promise.all([api.workflowList(), api.workflowDrafts(), api.workflowStepTypes()]);
|
||||
definitions.value = published.map((w) => ({ id: w.name, yaml: w.body, version: w.version, enabled: w.enabled }));
|
||||
definitions.value = published.map(definitionEntry);
|
||||
drafts.value = held.map(draftEntry);
|
||||
stepTypes.value = types as StepTypeInfo[];
|
||||
loaded.value = true;
|
||||
@@ -103,8 +105,7 @@ export const useWorkflowsStore = defineStore("workflows", () => {
|
||||
error.value = "";
|
||||
try {
|
||||
const w = await api.putWorkflow(id, yaml, expected);
|
||||
const entry = { id: w.name, yaml: w.body, version: w.version, enabled: w.enabled };
|
||||
definitions.value = [...definitions.value.filter((d) => d.id !== id), entry].sort((a, b) => a.id.localeCompare(b.id));
|
||||
definitions.value = [...definitions.value.filter((d) => d.id !== id), definitionEntry(w)].sort((a, b) => a.name.localeCompare(b.name));
|
||||
drafts.value = drafts.value.filter((draft) => draft.id !== id);
|
||||
return true;
|
||||
} catch (cause) {
|
||||
@@ -115,7 +116,21 @@ export const useWorkflowsStore = defineStore("workflows", () => {
|
||||
}
|
||||
}
|
||||
|
||||
/** Deletes a published workflow with its draft; the server refuses while anything still names it. */
|
||||
/** Creates a workflow called name with yaml as its draft, and returns its id,
|
||||
* or undefined when it couldn't be created. */
|
||||
async function create(name: string, yaml: string): Promise<string | undefined> {
|
||||
draftState.error = "";
|
||||
try {
|
||||
const { id } = await api.createWorkflow(name);
|
||||
drafts.value = [...drafts.value, draftEntry(await api.putWorkflowDraft(id, yaml, 0))];
|
||||
return id;
|
||||
} catch (cause) {
|
||||
draftState.error = describeError(cause, errors.common.unknown);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Deletes a workflow with its draft; the server refuses while anything still refers to it. */
|
||||
async function remove(id: string): Promise<boolean> {
|
||||
saving.value = true;
|
||||
error.value = "";
|
||||
@@ -132,9 +147,13 @@ export const useWorkflowsStore = defineStore("workflows", () => {
|
||||
}
|
||||
}
|
||||
|
||||
return { state, drafts, draftState, putDraft, reloadDrafts, error, collection, stepTypes, load, publish, remove };
|
||||
return { state, drafts, draftState, putDraft, reloadDrafts, error, collection, stepTypes, load, publish, create, remove };
|
||||
});
|
||||
|
||||
function draftEntry(draft: { name: string; body: string; revision: number; base_version: number }): WorkflowDraftEntry {
|
||||
return { id: draft.name, yaml: draft.body, revision: draft.revision, baseVersion: draft.base_version };
|
||||
function definitionEntry(w: WorkflowVersion): WorkflowDefinitionEntry {
|
||||
return { id: w.id, name: w.name, yaml: w.body, version: w.version, enabled: w.enabled };
|
||||
}
|
||||
|
||||
function draftEntry(draft: WorkflowDraft): WorkflowDraftEntry {
|
||||
return { id: draft.workflow_id, name: draft.name, yaml: draft.body, revision: draft.revision, baseVersion: draft.base_version };
|
||||
}
|
||||
@@ -105,7 +105,7 @@ function setTarget(key: string, value: string): void {
|
||||
}
|
||||
write({ ...step.value, settings: next });
|
||||
}
|
||||
const callee = computed(() => props.workflows.find((entry) => entry.id === settings.value.workflow));
|
||||
const callee = computed(() => props.workflows.find((entry) => entry.name === settings.value.workflow));
|
||||
const callInputs = computed(() => declaredSpecs(callee.value?.yaml ?? "", "inputs"));
|
||||
const callOutputs = computed(() => declaredSpecs(callee.value?.yaml ?? "", "outputs"));
|
||||
const callerInputs = computed(() => declaredSpecs(props.yaml, "inputs"));
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import { CircleAlert, Copy, ExternalLink, RotateCcw, Square, Trash2 } from "@lucide/vue";
|
||||
import { CircleAlert, Copy, ExternalLink, Pencil, RotateCcw, Square, Trash2 } from "@lucide/vue";
|
||||
import { isSending, setTurnHooks } from "@/chat/state";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -39,7 +39,8 @@ import WorkflowHistory from "./WorkflowHistory.vue";
|
||||
import { revisionOfRun, useWorkflowHistory, type WorkflowRevision } from "./workflow-revisions";
|
||||
import { deleteStep, duplicateStep, insertStep, moveStep, normalizeStepIDs, replaceStep, revertWorkflowChange, stepAt, stepIDs, workflowChanges, type StepPath } from "./workflow-edit";
|
||||
import ChangeList from "@/components/ChangeList.vue";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { useWorkflowRuns } from "./workflow-runs";
|
||||
import WorkflowRuns from "./WorkflowRuns.vue";
|
||||
import type { WorkflowTrigger } from "./workflow-triggers";
|
||||
@@ -341,9 +342,28 @@ async function publish(): Promise<void> {
|
||||
const runOpen = defineModel<boolean>("runOpen", { default: false });
|
||||
const draftOpen = ref(false);
|
||||
const confirmDelete = ref(false);
|
||||
// A rename changes only the label: runs, triggers and callers refer to the id.
|
||||
const renaming = ref(false);
|
||||
const newName = ref("");
|
||||
const renameError = ref("");
|
||||
function startRename(): void {
|
||||
newName.value = name.value;
|
||||
renameError.value = "";
|
||||
renaming.value = true;
|
||||
}
|
||||
async function rename(): Promise<void> {
|
||||
try {
|
||||
await api.renameWorkflow(selected.value, newName.value.trim());
|
||||
await Promise.all([workflows.load(), workflows.reloadDrafts()]);
|
||||
renaming.value = false;
|
||||
} catch (cause) {
|
||||
renameError.value = describeError(cause, errors.common.unknown);
|
||||
}
|
||||
}
|
||||
|
||||
const confirmDiscard = ref(false);
|
||||
// A published workflow is deleted with its draft; one never published has only
|
||||
// the draft to discard. The server refuses a delete while anything names it.
|
||||
// Deleting a workflow discards its draft too. The server refuses a delete while
|
||||
// anything refers to the workflow.
|
||||
async function remove(): Promise<void> {
|
||||
if (!selected.value) return;
|
||||
clearTimeout(pending);
|
||||
@@ -351,7 +371,7 @@ async function remove(): Promise<void> {
|
||||
// The page unmounts the editor as the workflow disappears, and unmounting
|
||||
// would write the draft back.
|
||||
removed = true;
|
||||
const done = stored.value === undefined ? await workflows.putDraft(selected.value, undefined) : await workflows.remove(selected.value);
|
||||
const done = await workflows.remove(selected.value);
|
||||
if (!done) removed = false;
|
||||
else emit("deleted");
|
||||
}
|
||||
@@ -364,7 +384,14 @@ const vocabulary = computed(() => workflows.stepTypes);
|
||||
// The definitions loaded but carried no step types: cards can't open and YAML
|
||||
// can't be checked, which must not look like an empty, valid workflow.
|
||||
const stepTypesMissing = computed(() => !!workflows.state.resource && !vocabulary.value.length);
|
||||
const parsed = computed(() => parseWorkflowYaml(yaml.value, vocabulary.value, selected.value));
|
||||
// The path holds the workflow's id; people read its name.
|
||||
const name = computed(
|
||||
() =>
|
||||
collection.value.definitions.find((entry) => entry.id === selected.value)?.name ??
|
||||
workflows.drafts.find((draft) => draft.id === selected.value)?.name ??
|
||||
"",
|
||||
);
|
||||
const parsed = computed(() => parseWorkflowYaml(yaml.value, vocabulary.value, name.value));
|
||||
const stored = computed(() => collection.value.definitions.find((entry) => entry.id === selected.value)?.yaml);
|
||||
const dirty = computed(() => yaml.value !== (stored.value ?? ""));
|
||||
const changes = computed(() => (dirty.value ? workflowChanges(stored.value ?? "", yaml.value) : []));
|
||||
@@ -470,6 +497,7 @@ const runOptions = computed(() => [
|
||||
<DropdownMenuItem v-if="watchedRevision" @select="openRevision(watchedRevision.version)">Version {{ watchedRevision.version }}</DropdownMenuItem>
|
||||
<DropdownMenuItem v-if="changes.length" @select="draftOpen = true">Draft changes <span class="ml-auto font-mono text-caption text-fg-subtle">{{ changes.length }}</span></DropdownMenuItem>
|
||||
<DropdownMenuItem v-if="dirty" :disabled="archieWorking" @select="confirmDiscard = true"><RotateCcw />Discard changes</DropdownMenuItem>
|
||||
<DropdownMenuItem @select="startRename"><Pencil />Rename</DropdownMenuItem>
|
||||
<DropdownMenuItem v-if="stored !== undefined" @select="emit('duplicate', selected)"><Copy />Duplicate</DropdownMenuItem>
|
||||
<DropdownMenuItem variant="destructive" @select="confirmDelete = true"><Trash2 />{{ stored === undefined ? "Discard workflow" : "Delete workflow" }}</DropdownMenuItem>
|
||||
</MoreMenu>
|
||||
@@ -500,7 +528,7 @@ const runOptions = computed(() => [
|
||||
:readonly="!!pinnedYaml || archieWorking"
|
||||
:restartable="restartable"
|
||||
:problems="pinnedYaml ? undefined : nodeProblems"
|
||||
:title="selected"
|
||||
:title="name"
|
||||
@toggle="toggle"
|
||||
@restart="restartFrom"
|
||||
@insert="insertAt"
|
||||
@@ -572,7 +600,7 @@ const runOptions = computed(() => [
|
||||
<AlertDialog v-model:open="confirmDiscard">
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Discard the unpublished changes to {{ selected }}?</AlertDialogTitle>
|
||||
<AlertDialogTitle>Discard the unpublished changes to {{ name }}?</AlertDialogTitle>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
@@ -591,10 +619,20 @@ const runOptions = computed(() => [
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
<Dialog v-model:open="renaming">
|
||||
<DialogContent class="sm:max-w-md">
|
||||
<DialogHeader><DialogTitle>Rename {{ name }}</DialogTitle></DialogHeader>
|
||||
<form id="rename-workflow" class="flex flex-col gap-3" @submit.prevent="rename">
|
||||
<Input v-model="newName" aria-label="Name" placeholder="Name" pattern="[a-z0-9]+([.\-][a-z0-9]+)*" required />
|
||||
<p v-if="renameError" role="alert" class="text-caption text-danger">{{ renameError }}</p>
|
||||
</form>
|
||||
<DialogFooter><Button type="submit" form="rename-workflow" :disabled="!newName.trim() || newName.trim() === name">Rename</Button></DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<AlertDialog v-model:open="confirmDelete">
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{{ stored === undefined ? "Discard" : "Delete" }} the {{ selected }} workflow?</AlertDialogTitle>
|
||||
<AlertDialogTitle>{{ stored === undefined ? "Discard" : "Delete" }} the {{ name }} workflow?</AlertDialogTitle>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
|
||||
@@ -33,7 +33,7 @@ onMounted(() => {
|
||||
});
|
||||
usePoll(reload);
|
||||
|
||||
// The path names the workflow; deleting it returns to the list.
|
||||
// The path holds the workflow's id; deleting it returns to the list.
|
||||
const selected = computed({
|
||||
get: () => String(route.params.id ?? ""),
|
||||
set: (id: string) => void (id ? router.replace({ name: "workflow", params: { id }, query: route.query }) : router.replace({ name: "workflows" })),
|
||||
@@ -49,15 +49,15 @@ onMounted(() => {
|
||||
|
||||
const stored = computed(() => workflows.collection.definitions.find((d) => d.id === selected.value));
|
||||
const draft = computed(() => workflows.drafts.some((d) => d.id === selected.value));
|
||||
// A workflow just created has no draft until its first edit is saved.
|
||||
const known = computed(() => !!stored.value || draft.value || route.query.new !== undefined);
|
||||
const name = computed(() => stored.value?.name ?? workflows.drafts.find((d) => d.id === selected.value)?.name ?? "");
|
||||
const known = computed(() => !!stored.value || draft.value);
|
||||
const loaded = computed(() => !!workflows.state.resource);
|
||||
// A workflow that was open and is gone has been deleted: back to the list.
|
||||
watch(known, (now, was) => {
|
||||
if (was && !now) selected.value = "";
|
||||
});
|
||||
|
||||
const own = computed(() => (triggers.data.value ?? []).filter((t) => t.workflow === selected.value));
|
||||
const own = computed(() => (triggers.data.value ?? []).filter((t) => t.workflow_id === selected.value));
|
||||
const starts = computed(() => [...new Set(own.value.map(startedBy))]);
|
||||
const startsText = computed(() => starts.value[0] ?? (triggers.data.value ? "Manual" : ""));
|
||||
const startsMore = computed(() => starts.value.slice(1));
|
||||
@@ -76,10 +76,11 @@ async function setEnabled(enabled: boolean): Promise<void> {
|
||||
async function copy(id: string): Promise<void> {
|
||||
const source = workflows.drafts.find((d) => d.id === id)?.yaml ?? stored.value?.yaml;
|
||||
if (source === undefined) return;
|
||||
const taken = new Set([...workflows.collection.definitions.map((d) => d.id), ...workflows.drafts.map((d) => d.id)]);
|
||||
let next = `${id}-copy`;
|
||||
for (let n = 2; taken.has(next); n++) next = `${id}-copy-${n}`;
|
||||
if (await workflows.putDraft(next, source)) void router.push({ name: "workflow", params: { id: next } });
|
||||
const taken = new Set([...workflows.collection.definitions.map((d) => d.name), ...workflows.drafts.map((d) => d.name)]);
|
||||
let next = `${name.value}-copy`;
|
||||
for (let n = 2; taken.has(next); n++) next = `${name.value}-copy-${n}`;
|
||||
const created = await workflows.create(next, source);
|
||||
if (created) void router.push({ name: "workflow", params: { id: created } });
|
||||
else toast.error(workflows.draftState.error || errors.workflows.editor.draftNotSaved);
|
||||
}
|
||||
</script>
|
||||
@@ -99,8 +100,8 @@ async function copy(id: string): Promise<void> {
|
||||
<!-- No card around the editor: the canvas draws its own frame. -->
|
||||
<div v-else class="min-w-0 max-md:flex max-md:h-full max-md:min-h-0 max-md:flex-col" role="region" aria-label="Workflow">
|
||||
<header class="mb-2 flex shrink-0 flex-wrap items-center gap-x-3 gap-y-0.5 lg:hidden">
|
||||
<h1 class="min-w-0 truncate text-title font-medium">{{ selected }}</h1>
|
||||
<Switch v-if="stored" size="sm" :model-value="stored.enabled" :aria-label="`${selected} enabled`" @update:model-value="setEnabled" />
|
||||
<h1 class="min-w-0 truncate text-title font-medium">{{ name }}</h1>
|
||||
<Switch v-if="stored" size="sm" :model-value="stored.enabled" :aria-label="`${name} enabled`" @update:model-value="setEnabled" />
|
||||
<Badge v-if="draft" variant="outline" class="shrink-0">Draft</Badge>
|
||||
<p v-if="startsText" class="flex min-w-0 basis-full items-center gap-1.5 text-caption text-fg-muted">
|
||||
<span class="truncate">{{ startsText }}</span>
|
||||
@@ -111,14 +112,14 @@ async function copy(id: string): Promise<void> {
|
||||
v-model:selected="selected"
|
||||
v-model:view="view"
|
||||
v-model:run-open="runOpen"
|
||||
:stats="stats.data.value?.find((s) => s.workflow === selected)"
|
||||
:stats="stats.data.value?.find((s) => s.workflow_id === selected)"
|
||||
:triggers="canvasTriggers"
|
||||
@duplicate="copy"
|
||||
@deleted="selected = ''"
|
||||
>
|
||||
<template #title>
|
||||
<h1 class="min-w-0 truncate text-title font-medium">{{ selected }}</h1>
|
||||
<Switch v-if="stored" size="sm" :model-value="stored.enabled" :aria-label="`${selected} enabled`" @update:model-value="setEnabled" />
|
||||
<h1 class="min-w-0 truncate text-title font-medium">{{ name }}</h1>
|
||||
<Switch v-if="stored" size="sm" :model-value="stored.enabled" :aria-label="`${name} enabled`" @update:model-value="setEnabled" />
|
||||
<Badge v-if="draft" variant="outline" class="shrink-0">Draft</Badge>
|
||||
<p v-if="startsText" class="flex min-w-0 max-w-64 items-center gap-1.5 text-caption text-fg-muted">
|
||||
<span class="truncate">{{ startsText }}</span>
|
||||
|
||||
@@ -2,19 +2,19 @@
|
||||
import { SuggestInput } from "@/components/ui/suggest-input";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
|
||||
defineProps<{ value: string; workflows: { id: string }[]; label: string; class?: string; editable?: boolean }>();
|
||||
defineProps<{ value: string; workflows: { id: string; name: string }[]; label: string; class?: string; editable?: boolean }>();
|
||||
const emit = defineEmits<{ pick: [string] }>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<template v-if="editable">
|
||||
<SuggestInput :model-value="value" :options="workflows.map((entry) => entry.id)" :aria-label="label" :class="$props.class" placeholder="Workflow id or {{ reference }}" @update:model-value="emit('pick', $event)" />
|
||||
<SuggestInput :model-value="value" :options="workflows.map((entry) => entry.name)" :aria-label="label" :class="$props.class" placeholder="Workflow name or {{ reference }}" @update:model-value="emit('pick', $event)" />
|
||||
</template>
|
||||
<Select v-else :model-value="value || undefined" @update:model-value="emit('pick', String($event))">
|
||||
<SelectTrigger :aria-label="label" :class="$props.class"><SelectValue placeholder="Choose workflow" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-if="value && !workflows.some((entry) => entry.id === value)" :value="value" disabled>{{ value }} (unavailable)</SelectItem>
|
||||
<SelectItem v-for="entry in workflows" :key="entry.id" :value="entry.id">{{ entry.id }}</SelectItem>
|
||||
<SelectItem v-if="value && !workflows.some((entry) => entry.name === value)" :value="value" disabled>{{ value }} (unavailable)</SelectItem>
|
||||
<SelectItem v-for="entry in workflows" :key="entry.id" :value="entry.name">{{ entry.name }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</template>
|
||||
@@ -7,7 +7,7 @@ import { MoreMenu } from "@/components/ui/more-menu";
|
||||
import RunWorkflowButton from "./RunWorkflowButton.vue";
|
||||
|
||||
/** The run button and overflow menu for one workflow row. */
|
||||
const props = defineProps<{ id: string; yaml: string; published: boolean; enabled: boolean }>();
|
||||
const props = defineProps<{ id: string; name: string; yaml: string; published: boolean; enabled: boolean }>();
|
||||
const emit = defineEmits<{ runs: []; duplicate: []; delete: [] }>();
|
||||
const router = useRouter();
|
||||
</script>
|
||||
@@ -23,7 +23,7 @@ const router = useRouter();
|
||||
disabled-reason="Disabled"
|
||||
@started="(runId) => router.push(`/runs/${runId}`)"
|
||||
/>
|
||||
<MoreMenu :label="`${id} actions`">
|
||||
<MoreMenu :label="`${name} actions`">
|
||||
<DropdownMenuItem v-if="props.published" @select="emit('runs')"><ListChecks />Open runs</DropdownMenuItem>
|
||||
<DropdownMenuItem @select="emit('duplicate')"><Copy />Duplicate</DropdownMenuItem>
|
||||
<DropdownMenuItem variant="destructive" @select="emit('delete')"><Trash2 />{{ props.published ? "Delete" : "Discard" }}</DropdownMenuItem>
|
||||
|
||||
@@ -39,7 +39,7 @@ const shown = computed(() => {
|
||||
return needle ? rows.value.filter((row) => row.name.toLowerCase().includes(needle) || row.starts.some((s) => s.toLowerCase().includes(needle))) : rows.value;
|
||||
});
|
||||
|
||||
const open = (name: string, query?: Record<string, string>) => void router.push({ path: `/workflows/${name}`, query });
|
||||
const open = (id: string) => void router.push({ path: `/workflows/${id}` });
|
||||
const openRuns = (name: string) => void router.push({ path: "/runs", query: { workflow: name } });
|
||||
const startsText = (row: WorkflowRow) => row.starts[0] ?? "";
|
||||
const startsMore = (row: WorkflowRow) => row.starts.slice(1);
|
||||
@@ -53,9 +53,10 @@ async function copy(row: WorkflowRow): Promise<void> {
|
||||
let next = `${row.name}-copy`;
|
||||
for (let n = 2; taken.has(next); n++) next = `${row.name}-copy-${n}`;
|
||||
try {
|
||||
const draft = await api.workflowDraft(row.name);
|
||||
await api.putWorkflowDraft(next, draft?.body ?? row.body, 0);
|
||||
open(next);
|
||||
const draft = await api.workflowDraft(row.id);
|
||||
const { id } = await api.createWorkflow(next);
|
||||
await api.putWorkflowDraft(id, draft?.body ?? row.body, 0);
|
||||
open(id);
|
||||
} catch (cause) {
|
||||
toast.error(describeError(cause, errors.common.unknown));
|
||||
}
|
||||
@@ -63,19 +64,18 @@ async function copy(row: WorkflowRow): Promise<void> {
|
||||
|
||||
async function setEnabled(row: WorkflowRow, enabled: boolean): Promise<void> {
|
||||
try {
|
||||
await api.setWorkflowEnabled(row.name, enabled);
|
||||
await api.setWorkflowEnabled(row.id, enabled);
|
||||
} catch (cause) {
|
||||
toast.error(describeError(cause, errors.common.unknown));
|
||||
}
|
||||
await reload();
|
||||
}
|
||||
|
||||
// A published workflow is deleted; one with only a draft has the draft discarded.
|
||||
// Deleting a workflow discards its draft too.
|
||||
const deleting = ref<WorkflowRow | null>(null);
|
||||
async function remove(row: WorkflowRow): Promise<void> {
|
||||
try {
|
||||
if (row.version) await api.deleteWorkflow(row.name);
|
||||
else await api.discardWorkflowDraft(row.name);
|
||||
await api.deleteWorkflow(row.id);
|
||||
} catch (cause) {
|
||||
toast.error(describeError(cause, errors.common.unknown));
|
||||
}
|
||||
@@ -86,14 +86,20 @@ async function remove(row: WorkflowRow): Promise<void> {
|
||||
const creating = ref(false);
|
||||
const name = ref("");
|
||||
const createError = ref("");
|
||||
function create(): void {
|
||||
async function create(): Promise<void> {
|
||||
const next = name.value.trim();
|
||||
if (rows.value.some((row) => row.name === next)) {
|
||||
createError.value = `${next} already exists`;
|
||||
return;
|
||||
}
|
||||
creating.value = false;
|
||||
void router.push({ path: `/workflows/${next}`, query: { new: "" } });
|
||||
try {
|
||||
const { id } = await api.createWorkflow(next);
|
||||
await api.putWorkflowDraft(id, "steps: []\n", 0);
|
||||
creating.value = false;
|
||||
open(id);
|
||||
} catch (cause) {
|
||||
createError.value = describeError(cause, errors.common.unknown);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -135,12 +141,12 @@ function create(): void {
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<ContextMenu v-for="row in shown" :key="row.name">
|
||||
<ContextMenu v-for="row in shown" :key="row.id">
|
||||
<ContextMenuTrigger as-child>
|
||||
<TableRow class="cursor-pointer align-middle" @click="open(row.name)">
|
||||
<TableRow class="cursor-pointer align-middle" @click="open(row.id)">
|
||||
<TableCell class="whitespace-normal">
|
||||
<span class="flex min-w-0 items-center gap-2">
|
||||
<RouterLink :to="`/workflows/${row.name}`" class="min-w-0 truncate font-medium hover:underline focus-visible:outline-2 focus-visible:outline-ring" @click.stop>{{ row.name }}</RouterLink>
|
||||
<RouterLink :to="`/workflows/${row.id}`" class="min-w-0 truncate font-medium hover:underline focus-visible:outline-2 focus-visible:outline-ring" @click.stop>{{ row.name }}</RouterLink>
|
||||
<span class="shrink-0 text-caption text-fg-subtle">{{ versionLabel(row) }}</span>
|
||||
<Badge v-if="row.draft" variant="outline" class="shrink-0">Draft</Badge>
|
||||
</span>
|
||||
@@ -162,7 +168,7 @@ function create(): void {
|
||||
<span class="flex flex-col gap-0.5"><Timestamp :at="row.published" /><span v-if="row.by" class="truncate text-caption text-fg-muted">{{ row.by }}</span></span>
|
||||
</TableCell>
|
||||
<TableCell class="text-right">
|
||||
<WorkflowRowActions :id="row.name" :yaml="row.body" :published="!!row.version" :enabled="row.enabled" @runs="openRuns(row.name)" @duplicate="copy(row)" @delete="deleting = row" />
|
||||
<WorkflowRowActions :id="row.id" :name="row.name" :yaml="row.body" :published="!!row.version" :enabled="row.enabled" @runs="openRuns(row.name)" @duplicate="copy(row)" @delete="deleting = row" />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</ContextMenuTrigger>
|
||||
@@ -176,16 +182,16 @@ function create(): void {
|
||||
</Table>
|
||||
|
||||
<ul v-else-if="shown.length" class="flex flex-col gap-2" aria-label="Workflows">
|
||||
<li v-for="row in shown" :key="row.name">
|
||||
<li v-for="row in shown" :key="row.id">
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger as-child>
|
||||
<Card class="cursor-pointer gap-2.5 px-4 py-3 transition-colors hover:bg-secondary/60" @click="open(row.name)">
|
||||
<Card class="cursor-pointer gap-2.5 px-4 py-3 transition-colors hover:bg-secondary/60" @click="open(row.id)">
|
||||
<div class="flex items-center gap-2">
|
||||
<RouterLink :to="`/workflows/${row.name}`" class="min-w-0 truncate text-label font-medium focus-visible:outline-2 focus-visible:outline-ring" @click.stop>{{ row.name }}</RouterLink>
|
||||
<RouterLink :to="`/workflows/${row.id}`" class="min-w-0 truncate text-label font-medium focus-visible:outline-2 focus-visible:outline-ring" @click.stop>{{ row.name }}</RouterLink>
|
||||
<span class="shrink-0 text-caption text-fg-subtle">{{ versionLabel(row) }}</span>
|
||||
<Badge v-if="row.draft" variant="outline" class="shrink-0">Draft</Badge>
|
||||
<Switch v-if="row.version" size="sm" class="ml-auto" :model-value="row.enabled" :aria-label="`${row.name} enabled`" @click.stop @update:model-value="setEnabled(row, $event)" />
|
||||
<WorkflowRowActions :id="row.name" :yaml="row.body" :published="!!row.version" :enabled="row.enabled" :class="row.version ? '' : 'ml-auto'" @runs="openRuns(row.name)" @duplicate="copy(row)" @delete="deleting = row" />
|
||||
<WorkflowRowActions :id="row.id" :name="row.name" :yaml="row.body" :published="!!row.version" :enabled="row.enabled" :class="row.version ? '' : 'ml-auto'" @runs="openRuns(row.name)" @duplicate="copy(row)" @delete="deleting = row" />
|
||||
</div>
|
||||
<p class="flex min-w-0 items-center gap-1.5 text-caption text-fg-muted">
|
||||
<span class="truncate">{{ startsText(row) || (triggersKnown ? "Manual" : "") }}</span>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { usePoll, useRead } from "@/lib/use-read";
|
||||
import { useLiveResource } from "@/stores/session";
|
||||
|
||||
export interface WorkflowRow {
|
||||
id: string;
|
||||
name: string;
|
||||
/** The published version; 0 for a workflow with only a draft. */
|
||||
version: number;
|
||||
@@ -56,19 +57,20 @@ export function useWorkflowList() {
|
||||
usePoll(reload);
|
||||
|
||||
const rows = computed<WorkflowRow[]>(() => {
|
||||
const counted = new Map((stats.data.value ?? []).map((s) => [s.workflow, s]));
|
||||
const held = new Set((drafts.data.value ?? []).map((d) => d.name));
|
||||
const row = (name: string, own: Partial<WorkflowRow>): WorkflowRow => {
|
||||
const s = counted.get(name);
|
||||
const counted = new Map((stats.data.value ?? []).map((s) => [s.workflow_id, s]));
|
||||
const held = new Set((drafts.data.value ?? []).map((d) => d.workflow_id));
|
||||
const row = (id: string, name: string, own: Partial<WorkflowRow>): WorkflowRow => {
|
||||
const s = counted.get(id);
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
version: 0,
|
||||
body: "",
|
||||
steps: 0,
|
||||
published: "",
|
||||
enabled: true,
|
||||
draft: held.has(name),
|
||||
starts: [...new Set((triggers.data.value ?? []).filter((t) => t.workflow === name).map(startedBy))],
|
||||
draft: held.has(id),
|
||||
starts: [...new Set((triggers.data.value ?? []).filter((t) => t.workflow_id === id).map(startedBy))],
|
||||
runs: s?.total ?? 0,
|
||||
succeeded: s?.succeeded ?? 0,
|
||||
running: s?.active ?? 0,
|
||||
@@ -77,10 +79,12 @@ export function useWorkflowList() {
|
||||
};
|
||||
};
|
||||
const published = (workflows.data.value ?? []).map((w) =>
|
||||
row(w.name, { version: w.version, body: w.body, steps: w.steps?.length ?? 0, published: w.created_at, by: w.created_by, enabled: w.enabled }),
|
||||
row(w.id, w.name, { version: w.version, body: w.body, steps: w.steps?.length ?? 0, published: w.created_at, by: w.created_by, enabled: w.enabled }),
|
||||
);
|
||||
const known = new Set(published.map((r) => r.name));
|
||||
const drafted = (drafts.data.value ?? []).filter((d) => !known.has(d.name)).map((d) => row(d.name, { body: d.body, published: d.updated_at, by: d.updated_by }));
|
||||
const known = new Set(published.map((r) => r.id));
|
||||
const drafted = (drafts.data.value ?? [])
|
||||
.filter((d) => !known.has(d.workflow_id))
|
||||
.map((d) => row(d.workflow_id, d.name, { body: d.body, published: d.updated_at, by: d.updated_by }));
|
||||
return [...published, ...drafted].sort(byActivity);
|
||||
});
|
||||
/** Triggers, drafts or counts that failed to load: rows show without them, beside this. */
|
||||
|
||||
@@ -86,9 +86,9 @@ export function stepMarks(source: string, other: string, missing: "added" | "rem
|
||||
return marks;
|
||||
}
|
||||
|
||||
/** Every published version of workflow `name`, newest first, read again when
|
||||
* a new version is published. */
|
||||
export function useWorkflowHistory(name: Ref<string>, published: Ref<number>) {
|
||||
/** Every published version of the workflow with id `workflow`, newest first,
|
||||
* read again when a new version is published. */
|
||||
export function useWorkflowHistory(workflow: Ref<string>, published: Ref<number>) {
|
||||
const revisions = ref<WorkflowRevision[]>([]);
|
||||
const error = ref("");
|
||||
const loaded = ref(false);
|
||||
@@ -96,7 +96,7 @@ export function useWorkflowHistory(name: Ref<string>, published: Ref<number>) {
|
||||
let generation = 0;
|
||||
async function reload(): Promise<void> {
|
||||
const current = ++generation;
|
||||
const requested = name.value;
|
||||
const requested = workflow.value;
|
||||
try {
|
||||
const versions = await Promise.all(Array.from({ length: published.value }, (_, i) => api.workflow(requested, i + 1)));
|
||||
if (current !== generation) return;
|
||||
|
||||
@@ -8,9 +8,9 @@ export interface WorkflowTrigger {
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
/** The triggers that start a workflow. */
|
||||
/** The triggers that start the workflow with that id. */
|
||||
export function workflowTriggers(triggers: Trigger[], workflow: string): WorkflowTrigger[] {
|
||||
return triggers
|
||||
.filter((t) => t.workflow === workflow)
|
||||
.filter((t) => t.workflow_id === workflow)
|
||||
.map((t) => ({ kind: t.every ? "schedule" : "event", label: t.every ? startedBy(t) : t.name, detail: t.every ? undefined : startedBy(t) }));
|
||||
}
|
||||
Reference in new issue
Block a user