package runs import ( "context" "encoding/json/jsontext" json "encoding/json/v2" "errors" "net/http" "time" "github.com/danielgtaylor/huma/v2" "github.com/google/uuid" "github.com/samcharles93/archie-core/internal/platform/httpapi" "github.com/samcharles93/archie-core/internal/platform/stableid" "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/runs/internal/store" ) // 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"` CreatedBy string `json:"created_by"` CreatedAt time.Time `json:"created_at"` // Steps say in plain language what each step does. Steps []string `json:"steps"` // Enabled is false for a workflow nothing may start. Enabled bool `json:"enabled"` } func workflowView(w store.Workflow) WorkflowView { 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() } return v } // 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 // workflow not yet published. BaseVersion int `json:"base_version"` // Revision counts the draft's writes; a write names the one it last saw. Revision int `json:"revision"` UpdatedBy string `json:"updated_by"` UpdatedAt time.Time `json:"updated_at"` } func draftView(d store.Draft) DraftView { 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"` // Failed counts runs that failed, parked or were declined. Failed int `json:"failed"` // Active counts runs that haven't ended. Active int `json:"active"` // SuccessRate is the share of ended runs that succeeded; absent until one // has ended. SuccessRate *float64 `json:"success_rate,omitzero"` LastRun LastRun `json:"last_run"` } // LastRun is a workflow's most recent run. type LastRun struct { ID string `json:"id"` State string `json:"state"` At time.Time `json:"at"` } func workflowStats(s store.Stats) WorkflowStats { out := WorkflowStats{ 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 { rate := float64(s.Succeeded) / float64(ended) out.SuccessRate = &rate } return out } type workflowAPI struct { e *Engine orgID string } func (e *Engine) registerWorkflows(api huma.API, orgID string) { a := &workflowAPI{e: e, orgID: orgID} tags := []string{"Workflows"} httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindWorkflow), huma.Operation{ 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/{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/{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/{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/{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/{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{ OperationID: "list-workflow-drafts", Method: http.MethodGet, Path: "/api/workflow-drafts", 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/{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/{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/{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/{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{ OperationID: "list-workflow-stats", Method: http.MethodGet, Path: "/api/workflow-stats", Summary: "Count each workflow's runs, with its last run and success rate", Tags: tags, }, a.stats) httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindWorkflow), huma.Operation{ OperationID: "list-workflow-step-types", Method: http.MethodGet, Path: "/api/workflow-step-types", Summary: "List the step types a workflow document may name, with their titles and settings schemas", Tags: tags, }, a.stepTypes) } type emptyInput struct{} func (a *workflowAPI) fail(ctx context.Context, what string, err error) error { a.e.log.ErrorContext(ctx, what, "error", err) return huma.Error500InternalServerError("couldn't " + what) } func (a *workflowAPI) list(ctx context.Context, _ *emptyInput) (*httpapi.Reply[[]WorkflowView], error) { stored, err := a.e.db.Workflows(ctx, a.orgID) if err != nil { return nil, a.fail(ctx, "list the workflows", err) } out := make([]WorkflowView, 0, len(stored)) for _, w := range stored { out = append(out, workflowView(w)) } 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 { 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) { 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), err == nil && w.Deleted: return nil, huma.Error404NotFound("no such workflow") case err != nil: return nil, a.fail(ctx, "read the workflow", err) } 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 { 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 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) { id, err := workflowID(in.ID) if err != nil { return nil, err } version, err := a.e.Publish(ctx, a.orgID, id, in.Body.Body, governance.CallerID(ctx), in.Body.ExpectedVersion) if err != nil { return nil, a.publishError(ctx, err) } return a.view(ctx, id, version) } // 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 *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: if refs, ok := errors.AsType[*ReferencedError](err); ok { return nil, huma.Error409Conflict(refs.Error()) } return nil, a.fail(ctx, "delete the workflow", err) } return &struct{}{}, nil } type setEnabledInput struct { 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) { 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.view(ctx, id, 0) } type runWorkflowInput struct { 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") } 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, run) } func (a *workflowAPI) started(ctx context.Context, id uuid.UUID) (*httpapi.Reply[RunView], error) { v, ok, err := a.e.Run(ctx, a.orgID, id) if err != nil || !ok { return nil, a.fail(ctx, "read the run", errors.Join(err, errors.New("the started run is missing"))) } return httpapi.OK(v), nil } // startError turns why a run didn't start into the response that says what to // do about it. func (a *workflowAPI) startError(ctx context.Context, err error) error { if invalid, ok := errors.AsType[*InvalidError](err); ok { return Problems(invalid) } switch { case errors.Is(err, governance.ErrDenied): return huma.Error403Forbidden(err.Error()) case errors.Is(err, governance.ErrChainUnavailable): return huma.Error503ServiceUnavailable("the access policies can't decide right now; try again") case errors.Is(err, ErrNoWorkflow): return huma.Error404NotFound("no such workflow") case errors.Is(err, ErrDisabled): return huma.Error409Conflict(err.Error()) case IsRefusal(err): return huma.Error400BadRequest(err.Error()) } return a.fail(ctx, "start the run", err) } func (a *workflowAPI) drafts(ctx context.Context, _ *emptyInput) (*httpapi.Reply[[]DraftView], error) { stored, err := a.e.db.Drafts(ctx, a.orgID) if err != nil { return nil, a.fail(ctx, "list the drafts", err) } out := make([]DraftView, 0, len(stored)) for _, d := range stored { out = append(out, draftView(d)) } return httpapi.OK(out), nil } 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") case err != nil: return nil, a.fail(ctx, "read the draft", err) } return httpapi.OK(draftView(d)), nil } type putDraftInput struct { 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 // replace an edit it never saw. Revision int `json:"revision" minimum:"0" doc:"The revision of the draft as last read, 0 when there is none; the write is refused with 409 when the stored draft is at another"` } } func (a *workflowAPI) putDraft(ctx context.Context, in *putDraftInput) (*httpapi.Reply[DraftView], error) { id, err := workflowID(in.ID) if err != nil { return nil, err } 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: return nil, a.fail(ctx, "save the draft", err) } return httpapi.OK(draftView(d)), nil } 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) case !had: return nil, huma.Error404NotFound("the workflow has no draft") } return &struct{}{}, nil } func (a *workflowAPI) testDraft(ctx context.Context, in *runWorkflowInput) (*httpapi.Reply[RunView], 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 to test") case err != nil: return nil, a.fail(ctx, "read the draft", err) } input, err := inputOf(in.Body.Input) if err != nil { return nil, huma.Error400BadRequest("the input isn't valid JSON") } 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, run) } func (a *workflowAPI) stats(ctx context.Context, _ *emptyInput) (*httpapi.Reply[[]WorkflowStats], error) { counted, err := a.e.db.Stats(ctx, a.orgID) if err != nil { return nil, a.fail(ctx, "count the workflows' runs", err) } out := make([]WorkflowStats, 0, len(counted)) for _, s := range counted { out = append(out, workflowStats(s)) } return httpapi.OK(out), nil } func (a *workflowAPI) stepTypes(context.Context, *emptyInput) (*httpapi.Reply[[]StepType], error) { return httpapi.OK(StepTypes()), nil } // Problems is a document's problems as a 400 response, one detail per problem // at its path. func Problems(invalid *InvalidError) error { details := make([]error, 0, len(invalid.Problems)) for _, p := range invalid.Problems { details = append(details, &huma.ErrorDetail{Location: p.Path, Message: p.Message}) } return huma.Error400BadRequest(invalid.Error(), details...) } // inputOf encodes a run's input, which is null when there is none. func inputOf(input map[string]any) (jsontext.Value, error) { if input == nil { return nil, nil } return json.Marshal(input) }