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
@@ -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) {
|
||||
|
||||
Reference in new issue
Block a user