package runs import ( "context" "errors" "log/slog" "maps" "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, // keyed by name. A workflow's id is wid of its name. type shelf struct { versions map[string][]string drafts map[string]bool active map[string]int deleted []string } 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 } 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, wid(name), 0) out = append(out, w) } return out, nil } // 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, _ 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{ID: id, Name: name, Version: len(s.versions[name]), Body: body}, nil } func (s *shelf) SetEnabled(context.Context, string, uuid.UUID, bool) error { return nil } 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, _ 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, _ 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 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" // TestPublishRefusesAStaleVersion guards that an editor can't publish over a // version it never saw: a publish that names a version other than the latest // stores nothing and leaves the draft, while a publish of the version it was // edited from is stored and consumes the draft. Without it two editors silently // overwrite each other's published work. func TestPublishRefusesAStaleVersion(t *testing.T) { two, zero := 2, 0 tests := []struct { name string stored []string expected *int body string wantVersions int wantDraft bool wantErr error }{ {name: "an unconditional publish", stored: []string{"a", "b"}, body: "c", wantVersions: 3}, {name: "the version it was edited from", stored: []string{"a", "b"}, expected: &two, body: "c", wantVersions: 3}, {name: "a stale version", stored: []string{"a", "b", "c"}, expected: &two, body: "d", wantVersions: 3, wantDraft: true, wantErr: ErrVersionConflict}, {name: "a new workflow that now exists", stored: []string{"a"}, expected: &zero, body: "b", wantVersions: 1, wantDraft: true, wantErr: ErrVersionConflict}, {name: "a new workflow", expected: &zero, body: "a", wantVersions: 1}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { 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", wid("triage"), tt.body, nil, "admin", tt.expected) if !errors.Is(err, tt.wantErr) { t.Fatalf("error = %v, want %v", err, tt.wantErr) } if got := len(s.versions["triage"]); got != tt.wantVersions { t.Fatalf("versions stored = %d, want %d", got, tt.wantVersions) } if s.drafts["triage"] != tt.wantDraft { t.Fatalf("draft kept = %v, want %v", s.drafts["triage"], tt.wantDraft) } }) } } // TestDisabledWorkflowIsNeverStarted guards that a disabled workflow starts // from no door: a trigger and a person both start through Start, and a call // from another workflow resolves through newRun. Without it disabling a // workflow would only hide it. func TestDisabledWorkflowIsNeverStarted(t *testing.T) { tests := []struct { name string disabled bool viaCall bool wantErr error want int }{ {name: "an enabled workflow starts", want: 1}, {name: "a trigger or a person can't start a disabled one", disabled: true, wantErr: ErrDisabled}, {name: "a call can't start a disabled one", disabled: true, viaCall: true, wantErr: ErrDisabled}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { work := &queueingStore{} work.disabled = map[string]bool{"triage": tt.disabled} engine := newEngine(nil, work, slog.New(slog.DiscardHandler), Options{}) engine.queue = work engine.Use(Deps{Access: &recordingAccess{decision: governance.Allowed()}}) req := StartRequest{OrgID: "org", WorkflowID: wid("triage"), Key: "event:trigger"} var err error if tt.viaCall { _, err = newRun(t.Context(), work, req) } else { ctx := governance.WithPrincipal(t.Context(), governance.WorkloadPrincipal(governance.DefaultOrgID)) _, err = engine.Start(ctx, req) } if !errors.Is(err, tt.wantErr) { t.Fatalf("error = %v, want %v", err, tt.wantErr) } if len(work.queued) != tt.want { t.Fatalf("runs queued = %d, want %d", len(work.queued), tt.want) } }) } } // TestDeleteIsRefusedWhileReferenced guards that a workflow nothing depends on // is deleted, and one a trigger, another workflow (at any depth) or a run in // progress depends on is refused with each dependant named. Without it a // delete leaves triggers and calls that fail on their next use. func TestDeleteIsRefusedWhileReferenced(t *testing.T) { calls := "steps:\n - type: workflow.call\n settings: {workflow: triage}\n" tests := []struct { name string others map[string][]string triggers triggerNames active int wantBy []string }{ {name: "nothing depends on it"}, {name: "a trigger", triggers: triggerNames{"triage": {"alerts"}}, wantBy: []string{"trigger alerts"}}, {name: "another workflow's call", others: map[string][]string{"parent": {calls}}, wantBy: []string{"workflow parent"}}, {name: "a run in progress", active: 2, wantBy: []string{"2 runs in progress"}}, { name: "a trigger and a workflow", triggers: triggerNames{"triage": {"alerts"}}, others: map[string][]string{"parent": {calls}}, wantBy: []string{"trigger alerts", "workflow parent"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { s := &shelf{versions: map[string][]string{"triage": {notifyDoc}}, drafts: map[string]bool{}, active: map[string]int{"triage": tt.active}} maps.Copy(s.versions, tt.others) e := &Engine{defs: s, log: slog.New(slog.DiscardHandler), referrers: tt.triggers} 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"}) { t.Fatalf("delete = %v, deleted %v, want it deleted", err, s.deleted) } return } if !errors.As(err, &refs) || !slices.Equal(refs.By, tt.wantBy) { t.Fatalf("error = %v, want a refusal naming %v", err, tt.wantBy) } if len(s.deleted) != 0 { t.Fatalf("deleted %v despite the refusal", s.deleted) } }) } }