Files
archie/modules/runs/internal/store/workflows.go
T

378 lines
14 KiB
Go

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 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")
// ErrDraftConflict means the stored draft is not the revision the writer
// last saw.
ErrDraftConflict = errors.New("the draft changed since it was read")
// ErrNoDraft means the workflow has no draft.
ErrNoDraft = errors.New("no such draft")
)
// 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"`
}
// 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"`
}
// 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
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
}
if err != nil {
return Workflow{}, fmt.Errorf("read workflow: %w", err)
}
return w, nil
}
// 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
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
}
// 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 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}
}
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 s.Workflow(ctx, orgID, id, version)
}
// 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, `
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)
}
if affected(res) == 0 {
return ErrNoWorkflow
}
return nil
}
// 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, `
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 workflow_id = $1`, id); err != nil {
return fmt.Errorf("delete workflow draft: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("delete workflow: %w", err)
}
return nil
}
// 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"`
Revision int `db:"revision"`
UpdatedBy string `db:"updated_by"`
UpdatedAt time.Time `db:"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 string, id uuid.UUID) (Draft, error) {
var d Draft
err := s.db.GetContext(ctx, &d, draftQuery+` AND d.workflow_id = $2`, orgID, id)
if errors.Is(err, sql.ErrNoRows) {
return Draft{}, ErrNoDraft
}
if err != nil {
return Draft{}, fmt.Errorf("read draft: %w", err)
}
return d, nil
}
// 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, draftQuery+` ORDER BY w.name`, orgID); err != nil {
return nil, fmt.Errorf("list drafts: %w", err)
}
return out, nil
}
// 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 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 {
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 {
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)
}
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 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)
}
return affected(res) > 0, nil
}
// Stats is what a workflow's runs add up to. Dry runs are not counted.
type Stats struct {
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.
Active int `db:"active"`
LastRunID string `db:"last_run_id"`
LastState string `db:"last_state"`
LastRunAt time.Time `db:"last_run_at"`
}
// Stats returns each workflow's run statistics over all of its runs.
func (s *Store) Stats(ctx context.Context, orgID string) ([]Stats, error) {
var out []Stats
if err := s.db.SelectContext(ctx, &out, `
SELECT r.workflow_id, w.name AS workflow,
count(*) AS total,
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 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_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"
}