Files
archie/modules/runs/catalogue.go
T

289 lines
9.6 KiB
Go

package runs
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 {
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 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 refers to a workflow.
type Referrers interface {
// 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
// workflow. It must be called before the API is served.
func (e *Engine) UseReferrers(r Referrers) {
e.mu.Lock()
defer e.mu.Unlock()
e.referrers = r
}
var (
// ErrVersionConflict is returned by Publish when the workflow's latest
// version is not the one the caller expected.
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 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
// it can't run yet. It is the caller's to fix, unlike a failure to reach storage.
type refusal struct{ error }
func (r refusal) Unwrap() error { return r.error }
// IsRefusal reports whether err says a run can't start as asked.
func IsRefusal(err error) bool {
_, ok := errors.AsType[refusal](err)
return ok
}
// ReferencedError says what keeps a workflow from being deleted.
type ReferencedError struct {
Workflow string
// By names each trigger, workflow or run that still depends on it.
By []string
}
func (e *ReferencedError) Error() string {
return fmt.Sprintf("workflow %q is still used by %s", e.Workflow, strings.Join(e.By, ", "))
}
// 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)
}
// 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
}
if expected != nil && latest.Version != *expected {
return 0, ErrVersionConflict
}
version := latest.Version
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, 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 string, id uuid.UUID, enabled bool) error {
return e.defs.SetEnabled(ctx, orgID, id, enabled)
}
// 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
}
if w.Deleted {
return ErrNoWorkflow
}
by, err := e.referencesTo(ctx, orgID, id)
if err != nil {
return err
}
if len(by) > 0 {
return &ReferencedError{Workflow: w.Name, By: by}
}
return e.defs.DeleteWorkflow(ctx, orgID, id)
}
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, id)
if err != nil {
return nil, fmt.Errorf("find triggers of workflow %s: %w", id, err)
}
for _, t := range triggers {
by = append(by, "trigger "+t)
}
}
all, err := e.defs.Workflows(ctx, orgID)
if err != nil {
return nil, err
}
for _, w := range all {
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, id)
if err != nil {
return nil, err
}
if active > 0 {
by = append(by, fmt.Sprintf("%d runs in progress", active))
}
return by, nil
}
// 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 || s.Type == typeApprove {
var named struct {
Workflow string `yaml:"workflow"`
Then string `yaml:"then"`
}
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 {
out = append(out, workflowsNamedIn(branch)...)
}
if s.Switch != nil {
for _, branch := range s.Switch.Cases {
out = append(out, workflowsNamedIn(branch)...)
}
}
}
return out
}