refactor(webui): extract the bindings resource module (#1778)

Pilot for one-module-per-resource: bindingsAPI owns the /api/bindings*
routes and their handlers, constructed only when the binding store is
configured; a 503 stub mounts the same routes otherwise, preserving the
old not-configured answers. Handlers move off *Server unchanged in
behavior; the shared dispatch-ledger handler stays on Server for the
captures/tasks routes. task check green.
This commit is contained in:
sam committed 2026-11-03 07:01:12 +11:00
1 parent 63229d1711
commit d55d8580cf
3 files changed
+399 -348

No files matched your search

+2 -337
View File
@@ -1,159 +1,14 @@
package webui
import (
"context"
"errors"
"net/http"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
)
// bindingRequest is the wire shape POST /api/bindings and
// PATCH /api/bindings/{id} both accept. ID/Version/Status/CreatedAt/UpdatedAt
// are server-assigned (or server-driven), never taken from the request body.
type bindingRequest struct {
Name string `json:"name"`
Matcher binding.Matcher `json:"matcher"`
MappingID string `json:"mapping_id"`
Filter string `json:"filter"`
Workflow string `json:"workflow"`
// Owner and Repo optionally pin the binding to one configured repo,
// for multi-repo deployments. Both empty is valid (falls back to the
// daemon's single-configured-repo behaviour); binding.Validate
// rejects setting only one.
Owner string `json:"owner"`
Repo string `json:"repo"`
// RepoParam takes the repository from a mapped parameter instead.
RepoParam string `json:"repo_param"`
Inputs map[string]binding.InputSource `json:"inputs"`
}
// bindingView is a listed binding with its source's signing state, so the
// list can flag a binding that dispatches unsigned events.
type bindingView struct {
binding.Binding
Unsigned bool `json:"unsigned"`
// WorkflowDisabled marks a binding whose org has disabled the workflow it
// targets; it does not dispatch until the workflow is enabled again.
WorkflowDisabled bool `json:"workflow_disabled"`
// LastOutcome is the binding's newest ledger row: the task it started or
// the reason it started none.
LastOutcome *storecontract.Dispatch `json:"last_outcome,omitempty"`
}
func (s *Server) handleBindingsList(w http.ResponseWriter, r *http.Request) {
if s.Bindings == nil {
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
return
}
bindings, err := s.Bindings.ListBindings(r.Context())
if err != nil {
s.Log.ErrorContext(r.Context(), "list bindings", "err", err)
http.Error(w, "list bindings failed", http.StatusInternalServerError)
return
}
unsigned, err := s.unsignedSources(r.Context())
if err != nil {
s.Log.ErrorContext(r.Context(), "list sources", "err", err)
http.Error(w, "list bindings failed", http.StatusInternalServerError)
return
}
enablement, _, err := s.workflowEnablement(r.Context())
if err != nil {
s.Log.ErrorContext(r.Context(), "workflow enablement", "err", err)
http.Error(w, "list bindings failed", http.StatusInternalServerError)
return
}
views := make([]bindingView, 0, len(bindings))
for _, b := range bindings {
if !listedIn(r, b.WorkspaceID) {
continue
}
views = append(views, bindingView{
Binding: b, Unsigned: unsigned[b.Matcher.Source], WorkflowDisabled: !enablement.Enabled(b.OrgID, b.Workflow),
LastOutcome: s.lastOutcome(r.Context(), b.ID),
})
}
writeJSON(w, map[string]any{"bindings": views})
}
// lastOutcome returns a binding's newest dispatch, or nil when it has none or
// the ledger is unreadable.
func (s *Server) lastOutcome(ctx context.Context, bindingID string) *storecontract.Dispatch {
if s.Dispatches == nil {
return nil
}
rows, err := s.Dispatches.ListDispatches(ctx, storecontract.DispatchFilter{BindingID: bindingID, Limit: 1})
if err != nil {
s.Log.WarnContext(ctx, "binding last outcome", "binding", bindingID, "err", err)
return nil
}
if len(rows) == 0 {
return nil
}
return &rows[0]
}
func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
if s.Bindings == nil {
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
return
}
req, ok := decodeBody[bindingRequest](w, r)
if !ok {
return
}
b, ok := s.checkedBinding(w, r, "", req)
if !ok {
return
}
id, err := s.Bindings.InsertBinding(r.Context(), b)
if err != nil {
s.Log.ErrorContext(r.Context(), "insert binding", "err", err)
http.Error(w, "create binding failed", http.StatusInternalServerError)
return
}
created, err := s.Bindings.GetBinding(r.Context(), id)
if err != nil || created == nil {
s.Log.ErrorContext(r.Context(), "get binding after insert", "err", err, "id", id)
http.Error(w, "create binding failed", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
writeJSON(w, created)
}
func (s *Server) handleBindingGet(w http.ResponseWriter, r *http.Request) {
if s.Bindings == nil {
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
return
}
id := r.PathValue("id")
if id == "" {
http.Error(w, "invalid binding id", http.StatusBadRequest)
return
}
b, err := s.Bindings.GetBinding(r.Context(), id)
if err != nil {
s.Log.ErrorContext(r.Context(), "get binding", "err", err, "id", id)
http.Error(w, "get binding failed", http.StatusInternalServerError)
return
}
if b == nil {
http.Error(w, "binding not found", http.StatusNotFound)
return
}
writeJSON(w, b)
}
// handleDispatches serves the newest dispatch ledger rows for the resource the
// path names, linking bindings, captures and tasks to each other.
// path names, linking bindings, captures and tasks to each other. Shared by
// the bindings module and the captures/tasks routes, so it stays on Server.
func (s *Server) handleDispatches(filterFor func(id string) (storecontract.DispatchFilter, bool)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if s.Dispatches == nil {
@@ -175,193 +30,3 @@ func (s *Server) handleDispatches(filterFor func(id string) (storecontract.Dispa
writeJSON(w, dispatches)
}
}
func (s *Server) handleBindingUpdate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
if s.Bindings == nil {
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
return
}
id := r.PathValue("id")
if id == "" {
http.Error(w, "invalid binding id", http.StatusBadRequest)
return
}
req, ok := decodeBody[bindingRequest](w, r)
if !ok {
return
}
b, ok := s.checkedBinding(w, r, id, req)
if !ok {
return
}
if err := s.Bindings.UpdateBinding(r.Context(), b); err != nil {
switch {
case errors.Is(err, storecontract.ErrBindingNotFound):
http.Error(w, "binding not found", http.StatusNotFound)
default:
s.Log.ErrorContext(r.Context(), "update binding", "err", err, "id", id)
http.Error(w, "update binding failed", http.StatusInternalServerError)
}
return
}
updated, err := s.Bindings.GetBinding(r.Context(), id)
if err != nil || updated == nil {
s.Log.ErrorContext(r.Context(), "get binding after update", "err", err, "id", id)
http.Error(w, "update binding failed", http.StatusInternalServerError)
return
}
writeJSON(w, updated)
}
func (s *Server) handleBindingDelete(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
if s.Bindings == nil {
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
return
}
id := r.PathValue("id")
if id == "" {
http.Error(w, "invalid binding id", http.StatusBadRequest)
return
}
if err := s.Bindings.DeleteBinding(r.Context(), id); err != nil {
if errors.Is(err, storecontract.ErrBindingNotFound) {
http.Error(w, "binding not found", http.StatusNotFound)
return
}
s.Log.ErrorContext(r.Context(), "delete binding", "err", err, "id", id)
http.Error(w, "delete binding failed", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
// handleBindingTransition serves one binding lifecycle command (approve,
// pause, resume) and answers the binding as it now stands.
func (s *Server) handleBindingTransition(verb string, apply func(storecontract.BindingStore, context.Context, string) error) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
if s.Bindings == nil {
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
return
}
id := r.PathValue("id")
if id == "" {
http.Error(w, "invalid binding id", http.StatusBadRequest)
return
}
if err := apply(s.Bindings, r.Context(), id); err != nil {
switch {
case errors.Is(err, storecontract.ErrBindingNotFound):
http.Error(w, "binding not found", http.StatusNotFound)
case errors.Is(err, storecontract.ErrBindingTransition):
http.Error(w, "binding cannot "+verb+" from its current state", http.StatusConflict)
default:
s.Log.ErrorContext(r.Context(), verb+" binding", "err", err, "id", id)
http.Error(w, verb+" binding failed", http.StatusInternalServerError)
}
return
}
updated, err := s.Bindings.GetBinding(r.Context(), id)
if err != nil || updated == nil {
s.Log.ErrorContext(r.Context(), "get binding after "+verb, "err", err, "id", id)
http.Error(w, verb+" binding failed", http.StatusInternalServerError)
return
}
writeJSON(w, updated)
}
}
// checkedBinding builds the binding a create or update request describes and
// refuses it, having written the error, unless it is well-formed, its mapping
// exists, its filter compiles against the mapping's parameters, and its inputs
// and repository satisfy the workflow it targets.
func (s *Server) checkedBinding(w http.ResponseWriter, r *http.Request, id string, req bindingRequest) (binding.Binding, bool) {
b := binding.Binding{
ID: id,
Name: req.Name,
Matcher: req.Matcher,
MappingID: req.MappingID,
Filter: req.Filter,
Workflow: req.Workflow,
Owner: req.Owner,
Repo: req.Repo,
RepoParam: req.RepoParam,
Inputs: req.Inputs,
Status: binding.StatusPendingApproval,
}
if err := b.Validate(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return binding.Binding{}, false
}
entry, found, err := s.workflowEntry(r.Context(), req.Workflow)
if err != nil {
http.Error(w, "workflow definitions unavailable", http.StatusServiceUnavailable)
return binding.Binding{}, false
}
if !found {
http.Error(w, "binding: workflow not found: "+req.Workflow, http.StatusBadRequest)
return binding.Binding{}, false
}
enabled, err := s.bindingWorkflowEnabled(r.Context(), id, req.Workflow)
if err != nil {
http.Error(w, "workflow enablement unavailable", http.StatusServiceUnavailable)
return binding.Binding{}, false
}
if !enabled {
http.Error(w, "binding: workflow is disabled: "+req.Workflow, http.StatusConflict)
return binding.Binding{}, false
}
iface, err := task.ParseWorkflowInterface(entry.YAML)
if err != nil {
http.Error(w, "binding: workflow "+req.Workflow+": "+err.Error(), http.StatusBadRequest)
return binding.Binding{}, false
}
if s.Mappings == nil {
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
return binding.Binding{}, false
}
m, err := s.Mappings.GetMapping(r.Context(), b.MappingID)
if err != nil {
s.Log.ErrorContext(r.Context(), "get mapping for binding", "err", err, "mapping", b.MappingID)
http.Error(w, "get mapping failed", http.StatusInternalServerError)
return binding.Binding{}, false
}
if m == nil {
http.Error(w, "binding: mapping not found: "+b.MappingID, http.StatusBadRequest)
return binding.Binding{}, false
}
if _, err := binding.CompileFilter(b.Filter, m.Fields); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return binding.Binding{}, false
}
if err := b.CheckWorkflow(iface, m.Fields); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return binding.Binding{}, false
}
return b, true
}
// bindingWorkflowEnabled reports whether the org owning binding id (the
// default org for a binding not yet created) has workflow enabled.
func (s *Server) bindingWorkflowEnabled(ctx context.Context, id, workflow string) (bool, error) {
owner := org.DefaultOrgID
if id != "" {
existing, err := s.Bindings.GetBinding(ctx, id)
if err != nil {
return false, err
}
if existing != nil {
owner = existing.OrgID
}
}
enablement, _, err := s.workflowEnablement(ctx)
return enablement.Enabled(owner, workflow), err
}
+388
View File
@@ -0,0 +1,388 @@
package webui
import (
"context"
"errors"
"log/slog"
"net/http"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
)
// bindingsAPI owns the /api/bindings routes and the binding dispatch
// sub-resource. The composition root constructs it only when the binding
// store is configured; otherwise Server mounts a 503 stub, so a.bindings is
// always non-nil here. dispatches and mappings stay optional: lastOutcome
// degrades to nil and checkedBinding answers 503, as before.
type bindingsAPI struct {
bindings storecontract.BindingStore
dispatches storecontract.DispatchLedger
mappings storecontract.MappingStore
log *slog.Logger
authorizeTaskMutation func(http.ResponseWriter, *http.Request) bool
workflowEntry func(context.Context, string) (task.WorkflowDefinitionEntry, bool, error)
workflowEnablement func(context.Context) (task.WorkflowEnablement, int64, error)
unsignedSources func(context.Context) (map[string]bool, error)
dispatchesFor func(func(string) (storecontract.DispatchFilter, bool)) http.HandlerFunc
}
func newBindingsAPI(s *Server) *bindingsAPI {
return &bindingsAPI{
bindings: s.Bindings,
dispatches: s.Dispatches,
mappings: s.Mappings,
log: s.Log,
authorizeTaskMutation: s.authorizeTaskMutation,
workflowEntry: s.workflowEntry,
workflowEnablement: s.workflowEnablement,
unsignedSources: s.unsignedSources,
dispatchesFor: s.handleDispatches,
}
}
// bindingsRoutes lists the method+path patterns the bindings module owns, so
// the 503 stub mounts exactly the same routes.
var bindingsRoutes = []string{
"GET /api/bindings",
"POST /api/bindings",
"GET /api/bindings/{id}",
"PATCH /api/bindings/{id}",
"DELETE /api/bindings/{id}",
"POST /api/bindings/{id}/approve",
"POST /api/bindings/{id}/pause",
"POST /api/bindings/{id}/resume",
"GET /api/bindings/{id}/dispatches",
}
// notConfigured answers every request with msg and 503, matching what the
// handlers did when their store field was nil.
func notConfigured(msg string) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, msg, http.StatusServiceUnavailable)
}
}
func (a *bindingsAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/bindings", a.handleBindingsList)
mux.HandleFunc("POST /api/bindings", a.handleBindingCreate)
mux.HandleFunc("GET /api/bindings/{id}", a.handleBindingGet)
mux.HandleFunc("PATCH /api/bindings/{id}", a.handleBindingUpdate)
mux.HandleFunc("DELETE /api/bindings/{id}", a.handleBindingDelete)
mux.HandleFunc("POST /api/bindings/{id}/approve", a.handleBindingTransition("approve", storecontract.BindingStore.ApproveBinding))
mux.HandleFunc("POST /api/bindings/{id}/pause", a.handleBindingTransition("pause", storecontract.BindingStore.PauseBinding))
mux.HandleFunc("POST /api/bindings/{id}/resume", a.handleBindingTransition("resume", storecontract.BindingStore.ResumeBinding))
mux.HandleFunc("GET /api/bindings/{id}/dispatches", a.dispatchesFor(func(id string) (storecontract.DispatchFilter, bool) {
return storecontract.DispatchFilter{BindingID: id}, id != ""
}))
}
// bindingRequest is the wire shape POST /api/bindings and
// PATCH /api/bindings/{id} both accept. ID/Version/Status/CreatedAt/UpdatedAt
// are server-assigned (or server-driven), never taken from the request body.
type bindingRequest struct {
Name string `json:"name"`
Matcher binding.Matcher `json:"matcher"`
MappingID string `json:"mapping_id"`
Filter string `json:"filter"`
Workflow string `json:"workflow"`
// Owner and Repo optionally pin the binding to one configured repo,
// for multi-repo deployments. Both empty is valid (falls back to the
// daemon's single-configured-repo behaviour); binding.Validate
// rejects setting only one.
Owner string `json:"owner"`
Repo string `json:"repo"`
// RepoParam takes the repository from a mapped parameter instead.
RepoParam string `json:"repo_param"`
Inputs map[string]binding.InputSource `json:"inputs"`
}
// bindingView is a listed binding with its source's signing state, so the
// list can flag a binding that dispatches unsigned events.
type bindingView struct {
binding.Binding
Unsigned bool `json:"unsigned"`
// WorkflowDisabled marks a binding whose org has disabled the workflow it
// targets; it does not dispatch until the workflow is enabled again.
WorkflowDisabled bool `json:"workflow_disabled"`
// LastOutcome is the binding's newest ledger row: the task it started or
// the reason it started none.
LastOutcome *storecontract.Dispatch `json:"last_outcome,omitempty"`
}
func (a *bindingsAPI) handleBindingsList(w http.ResponseWriter, r *http.Request) {
bindings, err := a.bindings.ListBindings(r.Context())
if err != nil {
a.log.ErrorContext(r.Context(), "list bindings", "err", err)
http.Error(w, "list bindings failed", http.StatusInternalServerError)
return
}
unsigned, err := a.unsignedSources(r.Context())
if err != nil {
a.log.ErrorContext(r.Context(), "list sources", "err", err)
http.Error(w, "list bindings failed", http.StatusInternalServerError)
return
}
enablement, _, err := a.workflowEnablement(r.Context())
if err != nil {
a.log.ErrorContext(r.Context(), "workflow enablement", "err", err)
http.Error(w, "list bindings failed", http.StatusInternalServerError)
return
}
views := make([]bindingView, 0, len(bindings))
for _, b := range bindings {
if !listedIn(r, b.WorkspaceID) {
continue
}
views = append(views, bindingView{
Binding: b, Unsigned: unsigned[b.Matcher.Source], WorkflowDisabled: !enablement.Enabled(b.OrgID, b.Workflow),
LastOutcome: a.lastOutcome(r.Context(), b.ID),
})
}
writeJSON(w, map[string]any{"bindings": views})
}
// lastOutcome returns a binding's newest dispatch, or nil when it has none or
// the ledger is unreadable.
func (a *bindingsAPI) lastOutcome(ctx context.Context, bindingID string) *storecontract.Dispatch {
if a.dispatches == nil {
return nil
}
rows, err := a.dispatches.ListDispatches(ctx, storecontract.DispatchFilter{BindingID: bindingID, Limit: 1})
if err != nil {
a.log.WarnContext(ctx, "binding last outcome", "binding", bindingID, "err", err)
return nil
}
if len(rows) == 0 {
return nil
}
return &rows[0]
}
func (a *bindingsAPI) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
if !a.authorizeTaskMutation(w, r) {
return
}
req, ok := decodeBody[bindingRequest](w, r)
if !ok {
return
}
b, ok := a.checkedBinding(w, r, "", req)
if !ok {
return
}
id, err := a.bindings.InsertBinding(r.Context(), b)
if err != nil {
a.log.ErrorContext(r.Context(), "insert binding", "err", err)
http.Error(w, "create binding failed", http.StatusInternalServerError)
return
}
created, err := a.bindings.GetBinding(r.Context(), id)
if err != nil || created == nil {
a.log.ErrorContext(r.Context(), "get binding after insert", "err", err, "id", id)
http.Error(w, "create binding failed", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
writeJSON(w, created)
}
func (a *bindingsAPI) handleBindingGet(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "" {
http.Error(w, "invalid binding id", http.StatusBadRequest)
return
}
b, err := a.bindings.GetBinding(r.Context(), id)
if err != nil {
a.log.ErrorContext(r.Context(), "get binding", "err", err, "id", id)
http.Error(w, "get binding failed", http.StatusInternalServerError)
return
}
if b == nil {
http.Error(w, "binding not found", http.StatusNotFound)
return
}
writeJSON(w, b)
}
func (a *bindingsAPI) handleBindingUpdate(w http.ResponseWriter, r *http.Request) {
if !a.authorizeTaskMutation(w, r) {
return
}
id := r.PathValue("id")
if id == "" {
http.Error(w, "invalid binding id", http.StatusBadRequest)
return
}
req, ok := decodeBody[bindingRequest](w, r)
if !ok {
return
}
b, ok := a.checkedBinding(w, r, id, req)
if !ok {
return
}
if err := a.bindings.UpdateBinding(r.Context(), b); err != nil {
switch {
case errors.Is(err, storecontract.ErrBindingNotFound):
http.Error(w, "binding not found", http.StatusNotFound)
default:
a.log.ErrorContext(r.Context(), "update binding", "err", err, "id", id)
http.Error(w, "update binding failed", http.StatusInternalServerError)
}
return
}
updated, err := a.bindings.GetBinding(r.Context(), id)
if err != nil || updated == nil {
a.log.ErrorContext(r.Context(), "get binding after update", "err", err, "id", id)
http.Error(w, "update binding failed", http.StatusInternalServerError)
return
}
writeJSON(w, updated)
}
func (a *bindingsAPI) handleBindingDelete(w http.ResponseWriter, r *http.Request) {
if !a.authorizeTaskMutation(w, r) {
return
}
id := r.PathValue("id")
if id == "" {
http.Error(w, "invalid binding id", http.StatusBadRequest)
return
}
if err := a.bindings.DeleteBinding(r.Context(), id); err != nil {
if errors.Is(err, storecontract.ErrBindingNotFound) {
http.Error(w, "binding not found", http.StatusNotFound)
return
}
a.log.ErrorContext(r.Context(), "delete binding", "err", err, "id", id)
http.Error(w, "delete binding failed", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
// handleBindingTransition serves one binding lifecycle command (approve,
// pause, resume) and answers the binding as it now stands.
func (a *bindingsAPI) handleBindingTransition(verb string, apply func(storecontract.BindingStore, context.Context, string) error) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !a.authorizeTaskMutation(w, r) {
return
}
id := r.PathValue("id")
if id == "" {
http.Error(w, "invalid binding id", http.StatusBadRequest)
return
}
if err := apply(a.bindings, r.Context(), id); err != nil {
switch {
case errors.Is(err, storecontract.ErrBindingNotFound):
http.Error(w, "binding not found", http.StatusNotFound)
case errors.Is(err, storecontract.ErrBindingTransition):
http.Error(w, "binding cannot "+verb+" from its current state", http.StatusConflict)
default:
a.log.ErrorContext(r.Context(), verb+" binding", "err", err, "id", id)
http.Error(w, verb+" binding failed", http.StatusInternalServerError)
}
return
}
updated, err := a.bindings.GetBinding(r.Context(), id)
if err != nil || updated == nil {
a.log.ErrorContext(r.Context(), "get binding after "+verb, "err", err, "id", id)
http.Error(w, verb+" binding failed", http.StatusInternalServerError)
return
}
writeJSON(w, updated)
}
}
// checkedBinding builds the binding a create or update request describes and
// refuses it, having written the error, unless it is well-formed, its mapping
// exists, its filter compiles against the mapping's parameters, and its inputs
// and repository satisfy the workflow it targets.
func (a *bindingsAPI) checkedBinding(w http.ResponseWriter, r *http.Request, id string, req bindingRequest) (binding.Binding, bool) {
b := binding.Binding{
ID: id,
Name: req.Name,
Matcher: req.Matcher,
MappingID: req.MappingID,
Filter: req.Filter,
Workflow: req.Workflow,
Owner: req.Owner,
Repo: req.Repo,
RepoParam: req.RepoParam,
Inputs: req.Inputs,
Status: binding.StatusPendingApproval,
}
if err := b.Validate(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return binding.Binding{}, false
}
entry, found, err := a.workflowEntry(r.Context(), req.Workflow)
if err != nil {
http.Error(w, "workflow definitions unavailable", http.StatusServiceUnavailable)
return binding.Binding{}, false
}
if !found {
http.Error(w, "binding: workflow not found: "+req.Workflow, http.StatusBadRequest)
return binding.Binding{}, false
}
enabled, err := a.bindingWorkflowEnabled(r.Context(), id, req.Workflow)
if err != nil {
http.Error(w, "workflow enablement unavailable", http.StatusServiceUnavailable)
return binding.Binding{}, false
}
if !enabled {
http.Error(w, "binding: workflow is disabled: "+req.Workflow, http.StatusConflict)
return binding.Binding{}, false
}
iface, err := task.ParseWorkflowInterface(entry.YAML)
if err != nil {
http.Error(w, "binding: workflow "+req.Workflow+": "+err.Error(), http.StatusBadRequest)
return binding.Binding{}, false
}
if a.mappings == nil {
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
return binding.Binding{}, false
}
m, err := a.mappings.GetMapping(r.Context(), b.MappingID)
if err != nil {
a.log.ErrorContext(r.Context(), "get mapping for binding", "err", err, "mapping", b.MappingID)
http.Error(w, "get mapping failed", http.StatusInternalServerError)
return binding.Binding{}, false
}
if m == nil {
http.Error(w, "binding: mapping not found: "+b.MappingID, http.StatusBadRequest)
return binding.Binding{}, false
}
if _, err := binding.CompileFilter(b.Filter, m.Fields); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return binding.Binding{}, false
}
if err := b.CheckWorkflow(iface, m.Fields); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return binding.Binding{}, false
}
return b, true
}
// bindingWorkflowEnabled reports whether the org owning binding id (the
// default org for a binding not yet created) has workflow enabled.
func (a *bindingsAPI) bindingWorkflowEnabled(ctx context.Context, id, workflow string) (bool, error) {
owner := org.DefaultOrgID
if id != "" {
existing, err := a.bindings.GetBinding(ctx, id)
if err != nil {
return false, err
}
if existing != nil {
owner = existing.OrgID
}
}
enablement, _, err := a.workflowEnablement(ctx)
return enablement.Enabled(owner, workflow), err
}
+9 -11
View File
@@ -336,17 +336,15 @@ func (s *Server) registerMappingAndBindingRoutes(mux *http.ServeMux) {
mux.HandleFunc("PATCH /api/mappings/{id}", s.handleMappingUpdate)
mux.HandleFunc("DELETE /api/mappings/{id}", s.handleMappingDelete)
mux.HandleFunc("POST /api/mappings/preview", s.handleMappingPreview)
mux.HandleFunc("GET /api/bindings", s.handleBindingsList)
mux.HandleFunc("POST /api/bindings", s.handleBindingCreate)
mux.HandleFunc("GET /api/bindings/{id}", s.handleBindingGet)
mux.HandleFunc("PATCH /api/bindings/{id}", s.handleBindingUpdate)
mux.HandleFunc("DELETE /api/bindings/{id}", s.handleBindingDelete)
mux.HandleFunc("POST /api/bindings/{id}/approve", s.handleBindingTransition("approve", storecontract.BindingStore.ApproveBinding))
mux.HandleFunc("POST /api/bindings/{id}/pause", s.handleBindingTransition("pause", storecontract.BindingStore.PauseBinding))
mux.HandleFunc("POST /api/bindings/{id}/resume", s.handleBindingTransition("resume", storecontract.BindingStore.ResumeBinding))
mux.HandleFunc("GET /api/bindings/{id}/dispatches", s.handleDispatches(func(id string) (storecontract.DispatchFilter, bool) {
return storecontract.DispatchFilter{BindingID: id}, id != ""
}))
// The bindings module owns its routes and registers itself when the store
// is configured; the stub keeps the 503 "not configured" answers otherwise.
if s.Bindings == nil {
for _, p := range bindingsRoutes {
mux.HandleFunc(p, notConfigured("bindings not configured"))
}
} else {
newBindingsAPI(s).register(mux)
}
mux.HandleFunc("GET /api/captures/{id}/dispatches", s.handleDispatches(func(id string) (storecontract.DispatchFilter, bool) {
return storecontract.DispatchFilter{CaptureID: id}, id != ""
}))