From 2fb8c09a0078064b16ca817882d813ddb4275506 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Tue, 3 Nov 2026 08:39:40 +1100 Subject: [PATCH] refactor(webui): extract the workflows module (#1778) --- internal/webui/audit.go | 2 +- internal/webui/bindings.go | 4 +- internal/webui/server.go | 5 +- ...w_enablement.go => workflow_enablement.go} | 18 ++-- .../webui/{api_workflows.go => workflows.go} | 102 +++++++++++------- ...pi_workflows_test.go => workflows_test.go} | 4 +- 6 files changed, 79 insertions(+), 56 deletions(-) rename internal/webui/{api_workflow_enablement.go => workflow_enablement.go} (81%) rename internal/webui/{api_workflows.go => workflows.go} (72%) rename internal/webui/{api_workflows_test.go => workflows_test.go} (95%) diff --git a/internal/webui/audit.go b/internal/webui/audit.go index c609c077a..b54b04a5d 100644 --- a/internal/webui/audit.go +++ b/internal/webui/audit.go @@ -141,7 +141,7 @@ func newAuditAPI(s *Server) *auditAPI { controlPlane: s.ControlPlane, log: s.Log, actorNames: s.actorNames, - workflowDefinitions: s.workflowDefinitions, + workflowDefinitions: newWorkflowsAPI(s).workflowDefinitions, exportRate: ratelimit.New(auditExportWindow, auditExportPerHour), exporting: map[string]bool{}, } diff --git a/internal/webui/bindings.go b/internal/webui/bindings.go index ab4902e57..9ce4c39fb 100644 --- a/internal/webui/bindings.go +++ b/internal/webui/bindings.go @@ -37,8 +37,8 @@ func newBindingsAPI(s *Server) *bindingsAPI { mappings: s.Mappings, log: s.Log, authorizeTaskMutation: s.authorizeTaskMutation, - workflowEntry: s.workflowEntry, - workflowEnablement: s.workflowEnablement, + workflowEntry: newWorkflowsAPI(s).workflowEntry, + workflowEnablement: newWorkflowsAPI(s).workflowEnablement, unsignedSources: s.unsignedSources, dispatchesFor: s.handleDispatches, } diff --git a/internal/webui/server.go b/internal/webui/server.go index ebaae0d0b..5bc66a294 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -273,10 +273,7 @@ func (s *Server) Broadcast(e events.Event) { func (s *Server) registerCoreRoutes(mux *http.ServeMux) { mux.HandleFunc("GET /api/summary", s.handleSummary) mux.HandleFunc("GET /api/setup", s.handleSetup) - mux.HandleFunc("GET /api/workflows", s.handleWorkflows) - mux.HandleFunc("PUT /api/workflows/{id}/enabled", s.handleWorkflowEnabled) - mux.HandleFunc("POST /api/work-requests", s.handleWorkRequest) - mux.HandleFunc("GET /api/repositories", s.handleRepositories) + newWorkflowsAPI(s).register(mux) mux.HandleFunc("POST /api/control-plane/resources/repository-policies/check", s.handleRepositoryCheck) mux.HandleFunc("GET /api/skills", instanceOnly(s.handleSkills)) mux.HandleFunc("GET /api/curators", instanceOnly(s.handleCurators)) diff --git a/internal/webui/api_workflow_enablement.go b/internal/webui/workflow_enablement.go similarity index 81% rename from internal/webui/api_workflow_enablement.go rename to internal/webui/workflow_enablement.go index 9e08845e1..cd6766621 100644 --- a/internal/webui/api_workflow_enablement.go +++ b/internal/webui/workflow_enablement.go @@ -15,11 +15,11 @@ const workflowEnablementKind = "workflow-enablement" // workflowEnablement returns which workflows each org has disabled, and the // resource version a replacement must name. -func (s *Server) workflowEnablement(ctx context.Context) (task.WorkflowEnablement, int64, error) { - if s.ControlPlane == nil { +func (a *workflowsAPI) workflowEnablement(ctx context.Context) (task.WorkflowEnablement, int64, error) { + if a.controlPlane == nil { return task.WorkflowEnablement{}, 0, nil } - response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: workflowEnablementKind}) + response, err := a.controlPlane.Query(ctx, &controlpb.QueryRequest{Kind: workflowEnablementKind}) if err != nil { return task.WorkflowEnablement{}, 0, err } @@ -39,11 +39,11 @@ type workflowEnabledRequest struct { // handleWorkflowEnabled enables or disables a workflow for the caller's org // (org.OrgFromContext). -func (s *Server) handleWorkflowEnabled(w http.ResponseWriter, r *http.Request) { - if !s.authorizeTaskMutation(w, r) { +func (a *workflowsAPI) handleWorkflowEnabled(w http.ResponseWriter, r *http.Request) { + if !a.authorize(w, r) { return } - if s.ControlPlane == nil { + if a.controlPlane == nil { http.Error(w, "control plane unavailable", http.StatusServiceUnavailable) return } @@ -52,7 +52,7 @@ func (s *Server) handleWorkflowEnabled(w http.ResponseWriter, r *http.Request) { return } id := r.PathValue("id") - found, err := s.hasWorkflowDefinition(r.Context(), id) + found, err := a.hasWorkflowDefinition(r.Context(), id) if err != nil { http.Error(w, "workflow definitions unavailable", http.StatusServiceUnavailable) return @@ -61,7 +61,7 @@ func (s *Server) handleWorkflowEnabled(w http.ResponseWriter, r *http.Request) { http.Error(w, "workflow not found", http.StatusNotFound) return } - enablement, version, err := s.workflowEnablement(r.Context()) + enablement, version, err := a.workflowEnablement(r.Context()) if err != nil { http.Error(w, "workflow enablement unavailable", http.StatusServiceUnavailable) return @@ -76,7 +76,7 @@ func (s *Server) handleWorkflowEnabled(w http.ResponseWriter, r *http.Request) { http.Error(w, "cannot create request ID", http.StatusInternalServerError) return } - if _, err := s.ControlPlane.Command(r.Context(), &controlpb.CommandRequest{ + if _, err := a.controlPlane.Command(r.Context(), &controlpb.CommandRequest{ Kind: workflowEnablementKind, Command: "replace", ValueJson: value, ExpectedVersion: version, Actor: string(audit.ActorID), Source: audit.Source, RequestId: audit.RequestID, diff --git a/internal/webui/api_workflows.go b/internal/webui/workflows.go similarity index 72% rename from internal/webui/api_workflows.go rename to internal/webui/workflows.go index 62be5a275..642b53add 100644 --- a/internal/webui/api_workflows.go +++ b/internal/webui/workflows.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "io" + "log/slog" "net/http" "strings" "unicode/utf8" @@ -17,6 +18,7 @@ import ( controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" "github.com/samcharles93/archie-core/internal/domain/access" "github.com/samcharles93/archie-core/internal/domain/org" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" @@ -24,22 +26,46 @@ import ( const workflowDefinitionsKind = "workflow-definitions" +// workflowsAPI owns the workflow catalogue, per-org enablement, the +// repository list and manual work requests. Its definition readers also back +// the bindings and audit modules. +type workflowsAPI struct { + controlPlane controlpb.ControlPlaneServiceClient + store storecontract.TaskStore + log *slog.Logger + emit func(context.Context, events.Event) + authorize func(http.ResponseWriter, *http.Request) bool +} + +func newWorkflowsAPI(s *Server) *workflowsAPI { + return &workflowsAPI{controlPlane: s.ControlPlane, store: s.Store, log: s.Log, emit: s.emit, authorize: s.authorizeTaskMutation} +} + +func (a *workflowsAPI) logf(msg string, args ...any) { warnf(a.log, msg, args...) } + +func (a *workflowsAPI) register(mux *http.ServeMux) { + mux.HandleFunc("GET /api/workflows", a.handleWorkflows) + mux.HandleFunc("PUT /api/workflows/{id}/enabled", a.handleWorkflowEnabled) + mux.HandleFunc("POST /api/work-requests", a.handleWorkRequest) + mux.HandleFunc("GET /api/repositories", a.handleRepositories) +} + // handleWorkflows returns per-workflow and per-stage statistics: run counts, // outcome breakdowns and spend per workflow, plus duration and failure counts // per stage -- "where does it get stuck" for the workflows page. -func (s *Server) handleWorkflows(w http.ResponseWriter, r *http.Request) { +func (a *workflowsAPI) handleWorkflows(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - workflows, err := s.Store.WorkflowStats(ctx) + workflows, err := a.store.WorkflowStats(ctx) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } - stages, err := s.Store.StageStats(ctx) + stages, err := a.store.StageStats(ctx) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } - definitions, err := s.workflowDefinitions(ctx) + definitions, err := a.workflowDefinitions(ctx) if err != nil { http.Error(w, "workflow definitions unavailable", http.StatusServiceUnavailable) return @@ -67,8 +93,8 @@ type workRequest struct { Draft string `json:"draft"` } -func (s *Server) handleWorkRequest(w http.ResponseWriter, r *http.Request) { - if !s.authorizeTaskMutation(w, r) { +func (a *workflowsAPI) handleWorkRequest(w http.ResponseWriter, r *http.Request) { + if !a.authorize(w, r) { return } principal, ok := access.PrincipalFromContext(r.Context()) @@ -104,7 +130,7 @@ func (s *Server) handleWorkRequest(w http.ResponseWriter, r *http.Request) { http.Error(w, "title must be 80 characters or fewer; put details in instructions", http.StatusBadRequest) return } - iface, code, err := s.workRequestInterface(r.Context(), request) + iface, code, err := a.workRequestInterface(r.Context(), request) if err != nil { http.Error(w, err.Error(), code) return @@ -113,18 +139,18 @@ func (s *Server) handleWorkRequest(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusBadRequest) return } - owner, repo, status, err := s.workRequestRepository(r.Context(), iface.RepositoryMode(), request.Repository) + owner, repo, status, err := a.workRequestRepository(r.Context(), iface.RepositoryMode(), request.Repository) if err != nil { http.Error(w, err.Error(), status) return } - created, err := s.Store.EnqueueChatTask(r.Context(), owner, repo, request.Title, request.Instructions, request.Workflow, string(principal.IdentityID), "", request.Draft, request.Inputs) + created, err := a.store.EnqueueChatTask(r.Context(), owner, repo, request.Title, request.Instructions, request.Workflow, string(principal.IdentityID), "", request.Draft, request.Inputs) if err != nil { - s.logf("work request enqueue failed", "err", err) + a.logf("work request enqueue failed", "err", err) http.Error(w, "work request rejected", http.StatusBadRequest) return } - s.emit(r.Context(), events.Event{Kind: events.KindWorkRequestSubmitted, TaskID: created.ID, Repo: request.Repository, Workflow: request.Workflow, Detail: request.Title}) + a.emit(r.Context(), events.Event{Kind: events.KindWorkRequestSubmitted, TaskID: created.ID, Repo: request.Repository, Workflow: request.Workflow, Detail: request.Title}) w.WriteHeader(http.StatusCreated) writeJSON(w, map[string]any{"ok": true, "task_id": created.ID}) } @@ -132,26 +158,26 @@ func (s *Server) handleWorkRequest(w http.ResponseWriter, r *http.Request) { // workRequestInterface returns the interface a request runs against: the // draft's when it carries one, else the stored definition's. The workflow must // be defined and enabled either way. -func (s *Server) workRequestInterface(ctx context.Context, request workRequest) (task.WorkflowInterface, int, error) { - iface, enabled, err := s.enabledWorkflowInterface(ctx, request.Workflow) +func (a *workflowsAPI) workRequestInterface(ctx context.Context, request workRequest) (task.WorkflowInterface, int, error) { + iface, enabled, err := a.enabledWorkflowInterface(ctx, request.Workflow) switch { case err != nil: return iface, http.StatusServiceUnavailable, errors.New("workflow definitions unavailable") case !enabled: return iface, http.StatusConflict, errors.New("workflow is not enabled") case request.Draft != "": - return s.checkDraft(ctx, request.Workflow, request.Draft) + return a.checkDraft(ctx, request.Workflow, request.Draft) } return iface, 0, nil } // checkDraft refuses a draft a save of the same document would refuse, and // returns the interface the draft declares. -func (s *Server) checkDraft(ctx context.Context, id, draft string) (task.WorkflowInterface, int, error) { +func (a *workflowsAPI) checkDraft(ctx context.Context, id, draft string) (task.WorkflowInterface, int, error) { if declared, err := workflow.DefinitionID(draft); err != nil || declared != id { return task.WorkflowInterface{}, http.StatusBadRequest, errors.New("the draft must be a definition of the workflow being run") } - collection, err := s.workflowCollection(ctx) + collection, err := a.workflowCollection(ctx) if err != nil { return task.WorkflowInterface{}, http.StatusServiceUnavailable, errors.New("workflow definitions unavailable") } @@ -166,7 +192,7 @@ func (s *Server) checkDraft(ctx context.Context, id, draft string) (task.Workflo if err != nil { return task.WorkflowInterface{}, http.StatusInternalServerError, err } - if _, err := s.ControlPlane.Command(ctx, &controlpb.CommandRequest{Kind: workflowDefinitionsKind, Command: "validate", ValueJson: value}); err != nil { + if _, err := a.controlPlane.Command(ctx, &controlpb.CommandRequest{Kind: workflowDefinitionsKind, Command: "validate", ValueJson: value}); err != nil { if status.Code(err) == codes.InvalidArgument { return task.WorkflowInterface{}, http.StatusBadRequest, errors.New(status.Convert(err).Message()) } @@ -183,7 +209,7 @@ func (s *Server) checkDraft(ctx context.Context, id, draft string) (task.Workflo // workflow's repository mode and the configured repositories, and returns it // split. A workflow that takes none refuses one; one that requires it refuses // its absence. -func (s *Server) workRequestRepository(ctx context.Context, mode task.RepositoryMode, requested string) (owner, repo string, status int, err error) { +func (a *workflowsAPI) workRequestRepository(ctx context.Context, mode task.RepositoryMode, requested string) (owner, repo string, status int, err error) { switch { case requested == "" && mode == task.RepositoryRequired: return "", "", http.StatusBadRequest, errors.New("this workflow needs a repository") @@ -196,7 +222,7 @@ func (s *Server) workRequestRepository(ctx context.Context, mode task.Repository if !ok || owner == "" || repo == "" || strings.Contains(repo, "/") { return "", "", http.StatusBadRequest, errors.New("repository must be owner/name") } - repos, err := s.configuredRepositories(ctx) + repos, err := a.configuredRepositories(ctx) if err != nil { return "", "", http.StatusServiceUnavailable, err } @@ -215,8 +241,8 @@ func (s *Server) workRequestRepository(ctx context.Context, mode task.Repository // handleRepositories lists configured names without requiring permission to // read or edit the organisation's full settings document. -func (s *Server) handleRepositories(w http.ResponseWriter, r *http.Request) { - repos, err := s.configuredRepositories(r.Context()) +func (a *workflowsAPI) handleRepositories(w http.ResponseWriter, r *http.Request) { + repos, err := a.configuredRepositories(r.Context()) if err != nil { http.Error(w, "Configured repositories are unavailable.", http.StatusServiceUnavailable) return @@ -232,11 +258,11 @@ func (s *Server) handleRepositories(w http.ResponseWriter, r *http.Request) { writeJSON(w, names) } -func (s *Server) configuredRepositories(ctx context.Context) ([]config.Repo, error) { - if s.ControlPlane == nil { +func (a *workflowsAPI) configuredRepositories(ctx context.Context) ([]config.Repo, error) { + if a.controlPlane == nil { return nil, errors.New("configured repositories unavailable") } - response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: "repository-policies"}) + response, err := a.controlPlane.Query(ctx, &controlpb.QueryRequest{Kind: "repository-policies"}) if err != nil || response.Resource == nil { return nil, errors.New("configured repositories unavailable") } @@ -249,12 +275,12 @@ func (s *Server) configuredRepositories(ctx context.Context) ([]config.Repo, err // enabledWorkflowInterface returns a workflow's declared interface and whether // it is defined and enabled for the caller's org. -func (s *Server) enabledWorkflowInterface(ctx context.Context, id string) (task.WorkflowInterface, bool, error) { - entry, found, err := s.workflowEntry(ctx, id) +func (a *workflowsAPI) enabledWorkflowInterface(ctx context.Context, id string) (task.WorkflowInterface, bool, error) { + entry, found, err := a.workflowEntry(ctx, id) if err != nil || !found { return task.WorkflowInterface{}, false, err } - enablement, _, err := s.workflowEnablement(ctx) + enablement, _, err := a.workflowEnablement(ctx) if err != nil || !enablement.Enabled(org.OrgFromContext(ctx), id) { return task.WorkflowInterface{}, false, err } @@ -265,14 +291,14 @@ func (s *Server) enabledWorkflowInterface(ctx context.Context, id string) (task. return iface, true, nil } -func (s *Server) hasWorkflowDefinition(ctx context.Context, id string) (bool, error) { - _, found, err := s.workflowEntry(ctx, id) +func (a *workflowsAPI) hasWorkflowDefinition(ctx context.Context, id string) (bool, error) { + _, found, err := a.workflowEntry(ctx, id) return found, err } // workflowEntry returns the stored definition of workflow id. -func (s *Server) workflowEntry(ctx context.Context, id string) (task.WorkflowDefinitionEntry, bool, error) { - collection, err := s.workflowCollection(ctx) +func (a *workflowsAPI) workflowEntry(ctx context.Context, id string) (task.WorkflowDefinitionEntry, bool, error) { + collection, err := a.workflowCollection(ctx) if err != nil { return task.WorkflowDefinitionEntry{}, false, err } @@ -280,11 +306,11 @@ func (s *Server) workflowEntry(ctx context.Context, id string) (task.WorkflowDef return entry, found, nil } -func (s *Server) workflowCollection(ctx context.Context) (task.WorkflowDefinitionCollection, error) { - if s.ControlPlane == nil { +func (a *workflowsAPI) workflowCollection(ctx context.Context) (task.WorkflowDefinitionCollection, error) { + if a.controlPlane == nil { return task.WorkflowDefinitionCollection{}, nil } - response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: workflowDefinitionsKind}) + response, err := a.controlPlane.Query(ctx, &controlpb.QueryRequest{Kind: workflowDefinitionsKind}) if err != nil { return task.WorkflowDefinitionCollection{}, err } @@ -298,15 +324,15 @@ func (s *Server) workflowCollection(ctx context.Context) (task.WorkflowDefinitio return collection, nil } -func (s *Server) workflowDefinitions(ctx context.Context) ([]task.Definition, error) { - if s.ControlPlane == nil { +func (a *workflowsAPI) workflowDefinitions(ctx context.Context) ([]task.Definition, error) { + if a.controlPlane == nil { return nil, nil } - collection, err := s.workflowCollection(ctx) + collection, err := a.workflowCollection(ctx) if err != nil { return nil, err } - enablement, _, err := s.workflowEnablement(ctx) + enablement, _, err := a.workflowEnablement(ctx) if err != nil { return nil, err } diff --git a/internal/webui/api_workflows_test.go b/internal/webui/workflows_test.go similarity index 95% rename from internal/webui/api_workflows_test.go rename to internal/webui/workflows_test.go index 83376d88e..a8c2509db 100644 --- a/internal/webui/api_workflows_test.go +++ b/internal/webui/workflows_test.go @@ -28,7 +28,7 @@ func TestWorkRequestRejectsLongTitle(t *testing.T) { request.Header.Set("Content-Type", "application/json") request.Header.Set("X-Archie-CSRF", "1") response := httptest.NewRecorder() - (&Server{}).handleWorkRequest(response, request) + newWorkflowsAPI(&Server{}).handleWorkRequest(response, request) if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "title must be 80 characters or fewer") { t.Fatalf("response = %d %s", response.Code, response.Body.String()) } @@ -81,7 +81,7 @@ func TestWorkRequestRequester(t *testing.T) { req.Header.Set("X-Archie-CSRF", "1") tasks := &workRequestTasks{} response := httptest.NewRecorder() - (&Server{Store: tasks, ControlPlane: workRequestControl{}}).handleWorkRequest(response, req) + newWorkflowsAPI(&Server{Store: tasks, ControlPlane: workRequestControl{}}).handleWorkRequest(response, req) if response.Code != tt.status || tasks.requester != tt.requester { t.Fatalf("response = %d %s, requester = %q; want %d, %q", response.Code, response.Body.String(), tasks.requester, tt.status, tt.requester) }