refactor(webui): extract event-types, mappings and sources modules (#1778)
Quality / check (push) Successful in 3m52s
deploy / gate (push) Successful in 4m29s
deploy / archied-image (push) Successful in 2m48s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped

Same pattern as the bindings pilot: eventTypesAPI (registers unconditionally,
list answers enabled:false without a store), mappingsAPI and sourcesAPI
(constructed only when their store is configured, 503 stub otherwise).
Shared helpers unsignedSources/recentRefusals/listedIn stay on Server; the
dispatch-ledger handler stays shared for captures/tasks. task check green.
This commit is contained in:
sam committed 2026-11-03 07:42:50 +11:00
1 parent d55d8580cf
commit 864b87faa6
5 files changed
+444 -318

No files matched your search

+3 -236
View File
@@ -2,254 +2,21 @@ package webui
import (
"context"
"encoding/json"
"errors"
"net/http"
"slices"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// Shared source helpers: unsignedSources feeds the bindings list, recentRefusals
// the sources list, listedIn every workspace-scoped list.
// Capture sources and their signing setting. A secret is returned only by the
// two writes that generate it, so the operator can copy it into the sender;
// every other read withholds it. Turning signing off is a request plus an
// approval, both behind the same mutation gate that arms a binding.
func (s *Server) handleSourcesList(w http.ResponseWriter, r *http.Request) {
if s.Sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return
}
list, err := s.Sources.ListSources(r.Context())
if err != nil {
s.Log.ErrorContext(r.Context(), "list sources", "err", err)
http.Error(w, "list sources failed", http.StatusInternalServerError)
return
}
list = slices.DeleteFunc(list, func(src source.Source) bool { return !listedIn(r, src.WorkspaceID) })
for i := range list {
list[i].Secret = ""
}
writeJSON(w, map[string]any{"sources": list, "refusals": s.recentRefusals(r)})
}
func (s *Server) handleSourceCreate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
if s.Sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return
}
var req struct {
Path string `json:"path"`
// Workspace is the caller's org workspace to create it in; empty is
// the default one.
Workspace org.WorkspaceID `json:"workspace"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
return
}
if !s.authorizeCreateIn(w, r, access.KindSource, req.Workspace) {
return
}
src, err := source.New(req.Path)
if errors.Is(err, source.ErrInvalidPath) || errors.Is(err, source.ErrReservedPath) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err == nil {
src.WorkspaceID = req.Workspace
err = s.Sources.InsertSource(r.Context(), src)
}
if err != nil {
s.sourceError(w, "create source", err)
return
}
w.WriteHeader(http.StatusCreated)
writeJSON(w, src)
}
// handleSourceSigning turns signing on at once, or requests turning it off.
func (s *Server) handleSourceSigning(w http.ResponseWriter, r *http.Request) {
var req struct {
Signed bool `json:"signed"`
}
if !s.authorizeTaskMutation(w, r) {
return
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
return
}
transition := (*source.Source).RequestUnsigned
if req.Signed {
transition = (*source.Source).RequireSigning
}
s.transitionSource(w, r, transition)
}
func (s *Server) handleSourceApproveUnsigned(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
s.transitionSource(w, r, (*source.Source).ApproveUnsigned)
}
// transitionSource applies one domain signing transition and writes it with
// the state it was decided from, so a concurrent change is refused.
func (s *Server) transitionSource(w http.ResponseWriter, r *http.Request, transition func(*source.Source) error) {
src, ok := s.loadSource(w, r)
if !ok {
return
}
from := src.Signing
if err := transition(src); err != nil {
http.Error(w, err.Error(), http.StatusConflict)
return
}
if err := s.Sources.SetSourceSigning(r.Context(), src.Path, from, src.Signing); err != nil {
s.sourceError(w, "set source signing", err)
return
}
src.Secret = ""
writeJSON(w, src)
}
// handleSourceSecret generates a new secret and returns it once.
func (s *Server) handleSourceSecret(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
src, ok := s.loadSource(w, r)
if !ok {
return
}
secret, err := source.NewSecret()
if err == nil {
err = s.Sources.SetSourceSecret(r.Context(), src.Path, secret)
}
if err != nil {
s.sourceError(w, "set source secret", err)
return
}
src.Secret = secret
writeJSON(w, src)
}
// handleSourceName relabels a source; its path does not change.
func (s *Server) handleSourceName(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
src, ok := s.loadSource(w, r)
if !ok {
return
}
var request struct {
Name string `json:"name"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&request); err != nil {
http.Error(w, "invalid source name", http.StatusBadRequest)
return
}
src.Name = strings.TrimSpace(request.Name)
if err := s.Sources.SetSourceName(r.Context(), src.Path, src.Name); err != nil {
s.sourceError(w, "set source name", err)
return
}
src.Secret = ""
writeJSON(w, src)
}
// handleSourceDeliveryHeader sets the header that names a source's
// deliveries, so a sender's retry dispatches no second run.
func (s *Server) handleSourceDeliveryHeader(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
src, ok := s.loadSource(w, r)
if !ok {
return
}
var request struct {
Header string `json:"header"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&request); err != nil {
http.Error(w, "invalid delivery header", http.StatusBadRequest)
return
}
header, err := source.DeliveryHeader(request.Header)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
src.DeliveryHeader = header
if err := s.Sources.SetSourceDeliveryHeader(r.Context(), src.Path, header); err != nil {
s.sourceError(w, "set source delivery header", err)
return
}
src.Secret = ""
writeJSON(w, src)
}
// handleSourceDelete deletes a source no armed binding fires on.
func (s *Server) handleSourceDelete(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
if s.Sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return
}
if err := s.Sources.DeleteSource(r.Context(), r.PathValue("path")); err != nil {
s.sourceError(w, "delete source", err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) loadSource(w http.ResponseWriter, r *http.Request) (*source.Source, bool) {
if s.Sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return nil, false
}
src, err := s.Sources.GetSource(r.Context(), r.PathValue("path"))
if err != nil {
s.sourceError(w, "get source", err)
return nil, false
}
if src == nil {
http.Error(w, "source not found", http.StatusNotFound)
return nil, false
}
return src, true
}
func (s *Server) sourceError(w http.ResponseWriter, what string, err error) {
switch {
case errors.Is(err, storecontract.ErrSourcePathTaken):
http.Error(w, "source path already taken", http.StatusConflict)
case errors.Is(err, storecontract.ErrSourceSigningStale):
http.Error(w, "source signing changed; reload and retry", http.StatusConflict)
case errors.Is(err, storecontract.ErrSourceNotFound):
http.Error(w, "source not found", http.StatusNotFound)
case errors.Is(err, org.ErrInvalidWorkspace):
http.Error(w, "that workspace is not one of this org's", http.StatusBadRequest)
case errors.Is(err, storecontract.ErrSourceInUse):
http.Error(w, "an armed binding fires on this source; pause or delete it first", http.StatusConflict)
default:
s.Log.Error(what, "err", err)
http.Error(w, what+" failed", http.StatusInternalServerError)
}
}
// unsignedSources is the set of source paths approved to take unsigned
// events. With no source store nothing is unsigned.
func (s *Server) unsignedSources(ctx context.Context) (map[string]bool, error) {
@@ -2,12 +2,39 @@ package webui
import (
"errors"
"log/slog"
"net/http"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// eventTypesAPI owns the /api/event-types routes. eventTypes and captures stay
// optional: the list answers {"enabled": false} with no store, and proposals
// are empty without captures, as before.
type eventTypesAPI struct {
eventTypes storecontract.EventTypeStore
captures storecontract.CaptureStore
log *slog.Logger
authorize func(http.ResponseWriter, *http.Request) bool
}
func newEventTypesAPI(s *Server) *eventTypesAPI {
return &eventTypesAPI{
eventTypes: s.EventTypes,
captures: s.Captures,
log: s.Log,
authorize: s.authorizeTaskMutation,
}
}
func (a *eventTypesAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/event-types", a.handleEventTypes)
mux.HandleFunc("POST /api/event-types", a.handleEventTypeCreate)
mux.HandleFunc("PUT /api/event-types/{id}", a.handleEventTypeUpdate)
mux.HandleFunc("DELETE /api/event-types/{id}", a.handleEventTypeDelete)
}
// proposalScanLimit bounds how many recent captures are grouped into
// proposals on one read.
const proposalScanLimit = 500
@@ -37,22 +64,22 @@ type eventTypeUpdate struct {
// handleEventTypes lists the named event types and the proposals grouped from
// recent captures that were unidentified on arrival and still match no type.
func (s *Server) handleEventTypes(w http.ResponseWriter, r *http.Request) {
if s.EventTypes == nil {
func (a *eventTypesAPI) handleEventTypes(w http.ResponseWriter, r *http.Request) {
if a.eventTypes == nil {
writeJSON(w, map[string]any{"enabled": false, "event_types": []any{}, "proposals": []any{}})
return
}
types, err := s.EventTypes.ListEventTypes(r.Context())
types, err := a.eventTypes.ListEventTypes(r.Context())
if err != nil {
s.Log.ErrorContext(r.Context(), "list event types", "err", err)
a.log.ErrorContext(r.Context(), "list event types", "err", err)
http.Error(w, "list event types failed", http.StatusInternalServerError)
return
}
proposals := []eventtype.Proposal{}
if s.Captures != nil {
captures, err := s.Captures.ListCaptures(r.Context(), proposalScanLimit)
if a.captures != nil {
captures, err := a.captures.ListCaptures(r.Context(), proposalScanLimit)
if err != nil {
s.Log.ErrorContext(r.Context(), "list captures for proposals", "err", err)
a.log.ErrorContext(r.Context(), "list captures for proposals", "err", err)
http.Error(w, "list captures failed", http.StatusInternalServerError)
return
}
@@ -86,11 +113,11 @@ func unmatchedCaptures(types []eventtype.EventType, captures []storecontract.Cap
return out
}
func (s *Server) handleEventTypeCreate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
func (a *eventTypesAPI) handleEventTypeCreate(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if s.EventTypes == nil {
if a.eventTypes == nil {
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
return
}
@@ -105,9 +132,9 @@ func (s *Server) handleEventTypeCreate(w http.ResponseWriter, r *http.Request) {
if req.Rule != nil {
t.Rule = *req.Rule
}
id, err := s.EventTypes.InsertEventType(r.Context(), t)
id, err := a.eventTypes.InsertEventType(r.Context(), t)
if err != nil {
s.writeEventTypeError(w, "create", err)
a.writeEventTypeError(w, "create", err)
return
}
t.ID = id
@@ -115,11 +142,11 @@ func (s *Server) handleEventTypeCreate(w http.ResponseWriter, r *http.Request) {
writeJSON(w, t)
}
func (s *Server) handleEventTypeUpdate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
func (a *eventTypesAPI) handleEventTypeUpdate(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if s.EventTypes == nil {
if a.eventTypes == nil {
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
return
}
@@ -129,29 +156,29 @@ func (s *Server) handleEventTypeUpdate(w http.ResponseWriter, r *http.Request) {
}
// Source is not editable: the store validates against the stored one.
t := eventtype.EventType{ID: r.PathValue("id"), Name: req.Name, Rule: req.Rule}
if err := s.EventTypes.UpdateEventType(r.Context(), t); err != nil {
s.writeEventTypeError(w, "update", err)
if err := a.eventTypes.UpdateEventType(r.Context(), t); err != nil {
a.writeEventTypeError(w, "update", err)
return
}
writeJSON(w, map[string]string{"id": t.ID})
}
func (s *Server) handleEventTypeDelete(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
func (a *eventTypesAPI) handleEventTypeDelete(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if s.EventTypes == nil {
if a.eventTypes == nil {
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
return
}
if err := s.EventTypes.DeleteEventType(r.Context(), r.PathValue("id")); err != nil {
s.writeEventTypeError(w, "delete", err)
if err := a.eventTypes.DeleteEventType(r.Context(), r.PathValue("id")); err != nil {
a.writeEventTypeError(w, "delete", err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) writeEventTypeError(w http.ResponseWriter, action string, err error) {
func (a *eventTypesAPI) writeEventTypeError(w http.ResponseWriter, action string, err error) {
switch {
case errors.Is(err, eventtype.ErrOverlap):
http.Error(w, "this rule can match events another type on the source already matches", http.StatusConflict)
@@ -160,7 +187,7 @@ func (s *Server) writeEventTypeError(w http.ResponseWriter, action string, err e
case errors.Is(err, storecontract.ErrEventTypeNotFound):
http.Error(w, "event type not found", http.StatusNotFound)
default:
s.Log.Error(action+" event type", "err", err)
a.log.Error(action+" event type", "err", err)
http.Error(w, action+" event type failed", http.StatusInternalServerError)
}
}
@@ -3,6 +3,7 @@ package webui
import (
"context"
"errors"
"log/slog"
"net/http"
"slices"
@@ -10,6 +11,49 @@ import (
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// mappingsAPI owns the /api/mappings routes. Constructed only when the
// mapping store is configured; Server mounts a 503 stub otherwise. eventTypes
// and captures stay optional inside (validateMapping and preview answer 503).
type mappingsAPI struct {
mappings storecontract.MappingStore
eventTypes storecontract.EventTypeStore
captures storecontract.CaptureStore
captureMaxEvents int
log *slog.Logger
authorize func(http.ResponseWriter, *http.Request) bool
}
func newMappingsAPI(s *Server) *mappingsAPI {
return &mappingsAPI{
mappings: s.Mappings,
eventTypes: s.EventTypes,
captures: s.Captures,
captureMaxEvents: s.CaptureMaxEvents,
log: s.Log,
authorize: s.authorizeTaskMutation,
}
}
// mappingsRoutes lists the method+path patterns the mappings module owns, so
// the 503 stub mounts exactly the same routes.
var mappingsRoutes = []string{
"GET /api/mappings",
"POST /api/mappings",
"GET /api/mappings/{id}",
"PATCH /api/mappings/{id}",
"DELETE /api/mappings/{id}",
"POST /api/mappings/preview",
}
func (a *mappingsAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/mappings", a.handleMappingsList)
mux.HandleFunc("POST /api/mappings", a.handleMappingCreate)
mux.HandleFunc("GET /api/mappings/{id}", a.handleMappingGet)
mux.HandleFunc("PATCH /api/mappings/{id}", a.handleMappingUpdate)
mux.HandleFunc("DELETE /api/mappings/{id}", a.handleMappingDelete)
mux.HandleFunc("POST /api/mappings/preview", a.handleMappingPreview)
}
// mappingRequest is the wire shape POST /api/mappings and
// PATCH /api/mappings/{id} both accept. ID/CreatedAt/UpdatedAt are
// server-assigned, never taken from the request body.
@@ -22,18 +66,18 @@ type mappingRequest struct {
// validateMapping checks m is well-formed and fits its event type's schema.
// It writes the refusal and returns false when it does not.
func (s *Server) validateMapping(w http.ResponseWriter, r *http.Request, m mapping.Mapping) bool {
func (a *mappingsAPI) validateMapping(w http.ResponseWriter, r *http.Request, m mapping.Mapping) bool {
if err := m.Validate(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return false
}
if s.EventTypes == nil {
if a.eventTypes == nil {
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
return false
}
types, err := s.EventTypes.ListEventTypes(r.Context())
types, err := a.eventTypes.ListEventTypes(r.Context())
if err != nil {
s.Log.ErrorContext(r.Context(), "list event types", "err", err)
a.log.ErrorContext(r.Context(), "list event types", "err", err)
http.Error(w, "list event types failed", http.StatusInternalServerError)
return false
}
@@ -50,14 +94,14 @@ func (s *Server) validateMapping(w http.ResponseWriter, r *http.Request, m mappi
return false
}
func (s *Server) handleMappingsList(w http.ResponseWriter, r *http.Request) {
if s.Mappings == nil {
func (a *mappingsAPI) handleMappingsList(w http.ResponseWriter, r *http.Request) {
if a.mappings == nil {
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
return
}
mappings, err := s.Mappings.ListMappings(r.Context())
mappings, err := a.mappings.ListMappings(r.Context())
if err != nil {
s.Log.ErrorContext(r.Context(), "list mappings", "err", err)
a.log.ErrorContext(r.Context(), "list mappings", "err", err)
http.Error(w, "list mappings failed", http.StatusInternalServerError)
return
}
@@ -65,11 +109,11 @@ func (s *Server) handleMappingsList(w http.ResponseWriter, r *http.Request) {
writeJSON(w, map[string]any{"mappings": mappings})
}
func (s *Server) handleMappingCreate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
func (a *mappingsAPI) handleMappingCreate(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if s.Mappings == nil {
if a.mappings == nil {
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
return
}
@@ -78,18 +122,18 @@ func (s *Server) handleMappingCreate(w http.ResponseWriter, r *http.Request) {
return
}
m := mapping.Mapping{Name: req.Name, SourceHint: req.SourceHint, EventTypeID: req.EventTypeID, Fields: req.Fields}
if !s.validateMapping(w, r, m) {
if !a.validateMapping(w, r, m) {
return
}
id, err := s.Mappings.InsertMapping(r.Context(), m)
id, err := a.mappings.InsertMapping(r.Context(), m)
if err != nil {
s.Log.ErrorContext(r.Context(), "insert mapping", "err", err)
a.log.ErrorContext(r.Context(), "insert mapping", "err", err)
http.Error(w, "create mapping failed", http.StatusInternalServerError)
return
}
created, err := s.Mappings.GetMapping(r.Context(), id)
created, err := a.mappings.GetMapping(r.Context(), id)
if err != nil || created == nil {
s.Log.ErrorContext(r.Context(), "get mapping after insert", "err", err, "id", id)
a.log.ErrorContext(r.Context(), "get mapping after insert", "err", err, "id", id)
http.Error(w, "create mapping failed", http.StatusInternalServerError)
return
}
@@ -97,8 +141,8 @@ func (s *Server) handleMappingCreate(w http.ResponseWriter, r *http.Request) {
writeJSON(w, created)
}
func (s *Server) handleMappingGet(w http.ResponseWriter, r *http.Request) {
if s.Mappings == nil {
func (a *mappingsAPI) handleMappingGet(w http.ResponseWriter, r *http.Request) {
if a.mappings == nil {
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
return
}
@@ -107,9 +151,9 @@ func (s *Server) handleMappingGet(w http.ResponseWriter, r *http.Request) {
http.Error(w, "invalid mapping id", http.StatusBadRequest)
return
}
m, err := s.Mappings.GetMapping(r.Context(), id)
m, err := a.mappings.GetMapping(r.Context(), id)
if err != nil {
s.Log.ErrorContext(r.Context(), "get mapping", "err", err, "id", id)
a.log.ErrorContext(r.Context(), "get mapping", "err", err, "id", id)
http.Error(w, "get mapping failed", http.StatusInternalServerError)
return
}
@@ -120,11 +164,11 @@ func (s *Server) handleMappingGet(w http.ResponseWriter, r *http.Request) {
writeJSON(w, m)
}
func (s *Server) handleMappingUpdate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
func (a *mappingsAPI) handleMappingUpdate(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if s.Mappings == nil {
if a.mappings == nil {
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
return
}
@@ -138,32 +182,32 @@ func (s *Server) handleMappingUpdate(w http.ResponseWriter, r *http.Request) {
return
}
m := mapping.Mapping{ID: id, Name: req.Name, SourceHint: req.SourceHint, EventTypeID: req.EventTypeID, Fields: req.Fields}
if !s.validateMapping(w, r, m) {
if !a.validateMapping(w, r, m) {
return
}
if err := s.Mappings.UpdateMapping(r.Context(), m); err != nil {
if err := a.mappings.UpdateMapping(r.Context(), m); err != nil {
if errors.Is(err, storecontract.ErrMappingNotFound) {
http.Error(w, "mapping not found", http.StatusNotFound)
return
}
s.Log.ErrorContext(r.Context(), "update mapping", "err", err, "id", id)
a.log.ErrorContext(r.Context(), "update mapping", "err", err, "id", id)
http.Error(w, "update mapping failed", http.StatusInternalServerError)
return
}
updated, err := s.Mappings.GetMapping(r.Context(), id)
updated, err := a.mappings.GetMapping(r.Context(), id)
if err != nil || updated == nil {
s.Log.ErrorContext(r.Context(), "get mapping after update", "err", err, "id", id)
a.log.ErrorContext(r.Context(), "get mapping after update", "err", err, "id", id)
http.Error(w, "update mapping failed", http.StatusInternalServerError)
return
}
writeJSON(w, updated)
}
func (s *Server) handleMappingDelete(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
func (a *mappingsAPI) handleMappingDelete(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if s.Mappings == nil {
if a.mappings == nil {
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
return
}
@@ -172,12 +216,12 @@ func (s *Server) handleMappingDelete(w http.ResponseWriter, r *http.Request) {
http.Error(w, "invalid mapping id", http.StatusBadRequest)
return
}
if err := s.Mappings.DeleteMapping(r.Context(), id); err != nil {
if err := a.mappings.DeleteMapping(r.Context(), id); err != nil {
if errors.Is(err, storecontract.ErrMappingNotFound) {
http.Error(w, "mapping not found", http.StatusNotFound)
return
}
s.Log.ErrorContext(r.Context(), "delete mapping", "err", err, "id", id)
a.log.ErrorContext(r.Context(), "delete mapping", "err", err, "id", id)
http.Error(w, "delete mapping failed", http.StatusInternalServerError)
return
}
@@ -192,12 +236,12 @@ type mappingPreviewRequest struct {
Fields []mapping.Field `json:"fields"`
}
func (s *Server) handleMappingPreview(w http.ResponseWriter, r *http.Request) {
if s.Mappings == nil {
func (a *mappingsAPI) handleMappingPreview(w http.ResponseWriter, r *http.Request) {
if a.mappings == nil {
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
return
}
if s.Captures == nil {
if a.captures == nil {
http.Error(w, "captures not configured", http.StatusServiceUnavailable)
return
}
@@ -205,9 +249,9 @@ func (s *Server) handleMappingPreview(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
capture, err := s.captureByID(r.Context(), req.CaptureID)
capture, err := a.captureByID(r.Context(), req.CaptureID)
if err != nil {
s.Log.ErrorContext(r.Context(), "get capture for preview", "err", err, "capture_id", req.CaptureID)
a.log.ErrorContext(r.Context(), "get capture for preview", "err", err, "capture_id", req.CaptureID)
http.Error(w, "preview failed", http.StatusInternalServerError)
return
}
@@ -225,8 +269,8 @@ func (s *Server) handleMappingPreview(w http.ResponseWriter, r *http.Request) {
// captureByID finds one captured event by ID. CaptureStore exposes only
// ListCaptures, so this scans the newest window rather than adding a new store
// method for a single low-volume caller.
func (s *Server) captureByID(ctx context.Context, id string) (*storecontract.CapturedEvent, error) {
captures, err := s.Captures.ListCaptures(ctx, mappingCaptureScanWindow(s.CaptureMaxEvents))
func (a *mappingsAPI) captureByID(ctx context.Context, id string) (*storecontract.CapturedEvent, error) {
captures, err := a.captures.ListCaptures(ctx, mappingCaptureScanWindow(a.captureMaxEvents))
if err != nil {
return nil, err
}
+17 -18
View File
@@ -326,16 +326,16 @@ func (s *Server) registerTaskRoutes(mux *http.ServeMux) {
}
func (s *Server) registerMappingAndBindingRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/event-types", s.handleEventTypes)
mux.HandleFunc("POST /api/event-types", s.handleEventTypeCreate)
mux.HandleFunc("PUT /api/event-types/{id}", s.handleEventTypeUpdate)
mux.HandleFunc("DELETE /api/event-types/{id}", s.handleEventTypeDelete)
mux.HandleFunc("GET /api/mappings", s.handleMappingsList)
mux.HandleFunc("POST /api/mappings", s.handleMappingCreate)
mux.HandleFunc("GET /api/mappings/{id}", s.handleMappingGet)
mux.HandleFunc("PATCH /api/mappings/{id}", s.handleMappingUpdate)
mux.HandleFunc("DELETE /api/mappings/{id}", s.handleMappingDelete)
mux.HandleFunc("POST /api/mappings/preview", s.handleMappingPreview)
// Event types register unconditionally: the list answers {"enabled": false}
// when the store is nil. Mappings and sources mount a 503 stub otherwise.
newEventTypesAPI(s).register(mux)
if s.Mappings == nil {
for _, p := range mappingsRoutes {
mux.HandleFunc(p, notConfigured("mappings not configured"))
}
} else {
newMappingsAPI(s).register(mux)
}
// 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 {
@@ -352,14 +352,13 @@ func (s *Server) registerMappingAndBindingRoutes(mux *http.ServeMux) {
taskID, err := strconv.ParseInt(id, 10, 64)
return storecontract.DispatchFilter{TaskID: taskID}, err == nil && taskID > 0
}))
mux.HandleFunc("GET /api/sources", s.handleSourcesList)
mux.HandleFunc("POST /api/sources", s.handleSourceCreate)
mux.HandleFunc("POST /api/sources/{path}/signing", s.handleSourceSigning)
mux.HandleFunc("POST /api/sources/{path}/approve-unsigned", s.handleSourceApproveUnsigned)
mux.HandleFunc("POST /api/sources/{path}/secret", s.handleSourceSecret)
mux.HandleFunc("PUT /api/sources/{path}/name", s.handleSourceName)
mux.HandleFunc("PUT /api/sources/{path}/delivery-header", s.handleSourceDeliveryHeader)
mux.HandleFunc("DELETE /api/sources/{path}", s.handleSourceDelete)
if s.Sources == nil {
for _, p := range sourcesRoutes {
mux.HandleFunc(p, notConfigured("sources not configured"))
}
} else {
newSourcesAPI(s).register(mux)
}
}
func (s *Server) registerHarnessRoutes(mux *http.ServeMux) {
+289
View File
@@ -0,0 +1,289 @@
package webui
import (
"encoding/json"
"errors"
"log/slog"
"net/http"
"slices"
"strings"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// sourcesAPI owns the /api/sources routes. Constructed only when the source
// store is configured; Server mounts a 503 stub otherwise.
type sourcesAPI struct {
sources storecontract.SourceStore
log *slog.Logger
authorize func(http.ResponseWriter, *http.Request) bool
authorizeCreateIn func(http.ResponseWriter, *http.Request, access.ResourceKind, org.WorkspaceID) bool
recentRefusals func(*http.Request) map[string]storecontract.CaptureRefusals
}
func newSourcesAPI(s *Server) *sourcesAPI {
return &sourcesAPI{
sources: s.Sources,
log: s.Log,
authorize: s.authorizeTaskMutation,
authorizeCreateIn: s.authorizeCreateIn,
recentRefusals: s.recentRefusals,
}
}
// sourcesRoutes lists the method+path patterns the sources module owns, so
// the 503 stub mounts exactly the same routes.
var sourcesRoutes = []string{
"GET /api/sources",
"POST /api/sources",
"POST /api/sources/{path}/signing",
"POST /api/sources/{path}/approve-unsigned",
"POST /api/sources/{path}/secret",
"PUT /api/sources/{path}/name",
"PUT /api/sources/{path}/delivery-header",
"DELETE /api/sources/{path}",
}
func (a *sourcesAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/sources", a.handleSourcesList)
mux.HandleFunc("POST /api/sources", a.handleSourceCreate)
mux.HandleFunc("POST /api/sources/{path}/signing", a.handleSourceSigning)
mux.HandleFunc("POST /api/sources/{path}/approve-unsigned", a.handleSourceApproveUnsigned)
mux.HandleFunc("POST /api/sources/{path}/secret", a.handleSourceSecret)
mux.HandleFunc("PUT /api/sources/{path}/name", a.handleSourceName)
mux.HandleFunc("PUT /api/sources/{path}/delivery-header", a.handleSourceDeliveryHeader)
mux.HandleFunc("DELETE /api/sources/{path}", a.handleSourceDelete)
}
func (a *sourcesAPI) handleSourcesList(w http.ResponseWriter, r *http.Request) {
if a.sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return
}
list, err := a.sources.ListSources(r.Context())
if err != nil {
a.log.ErrorContext(r.Context(), "list sources", "err", err)
http.Error(w, "list sources failed", http.StatusInternalServerError)
return
}
list = slices.DeleteFunc(list, func(src source.Source) bool { return !listedIn(r, src.WorkspaceID) })
for i := range list {
list[i].Secret = ""
}
writeJSON(w, map[string]any{"sources": list, "refusals": a.recentRefusals(r)})
}
func (a *sourcesAPI) handleSourceCreate(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if a.sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return
}
var req struct {
Path string `json:"path"`
// Workspace is the caller's org workspace to create it in; empty is
// the default one.
Workspace org.WorkspaceID `json:"workspace"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
return
}
if !a.authorizeCreateIn(w, r, access.KindSource, req.Workspace) {
return
}
src, err := source.New(req.Path)
if errors.Is(err, source.ErrInvalidPath) || errors.Is(err, source.ErrReservedPath) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err == nil {
src.WorkspaceID = req.Workspace
err = a.sources.InsertSource(r.Context(), src)
}
if err != nil {
a.sourceError(w, "create source", err)
return
}
w.WriteHeader(http.StatusCreated)
writeJSON(w, src)
}
// handleSourceSigning turns signing on at once, or requests turning it off.
func (a *sourcesAPI) handleSourceSigning(w http.ResponseWriter, r *http.Request) {
var req struct {
Signed bool `json:"signed"`
}
if !a.authorize(w, r) {
return
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
return
}
transition := (*source.Source).RequestUnsigned
if req.Signed {
transition = (*source.Source).RequireSigning
}
a.transitionSource(w, r, transition)
}
func (a *sourcesAPI) handleSourceApproveUnsigned(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
a.transitionSource(w, r, (*source.Source).ApproveUnsigned)
}
// transitionSource applies one domain signing transition and writes it with
// the state it was decided from, so a concurrent change is refused.
func (a *sourcesAPI) transitionSource(w http.ResponseWriter, r *http.Request, transition func(*source.Source) error) {
src, ok := a.loadSource(w, r)
if !ok {
return
}
from := src.Signing
if err := transition(src); err != nil {
http.Error(w, err.Error(), http.StatusConflict)
return
}
if err := a.sources.SetSourceSigning(r.Context(), src.Path, from, src.Signing); err != nil {
a.sourceError(w, "set source signing", err)
return
}
src.Secret = ""
writeJSON(w, src)
}
// handleSourceSecret generates a new secret and returns it once.
func (a *sourcesAPI) handleSourceSecret(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
src, ok := a.loadSource(w, r)
if !ok {
return
}
secret, err := source.NewSecret()
if err == nil {
err = a.sources.SetSourceSecret(r.Context(), src.Path, secret)
}
if err != nil {
a.sourceError(w, "set source secret", err)
return
}
src.Secret = secret
writeJSON(w, src)
}
// handleSourceName relabels a source; its path does not change.
func (a *sourcesAPI) handleSourceName(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
src, ok := a.loadSource(w, r)
if !ok {
return
}
var request struct {
Name string `json:"name"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&request); err != nil {
http.Error(w, "invalid source name", http.StatusBadRequest)
return
}
src.Name = strings.TrimSpace(request.Name)
if err := a.sources.SetSourceName(r.Context(), src.Path, src.Name); err != nil {
a.sourceError(w, "set source name", err)
return
}
src.Secret = ""
writeJSON(w, src)
}
// handleSourceDeliveryHeader sets the header that names a source's
// deliveries, so a sender's retry dispatches no second run.
func (a *sourcesAPI) handleSourceDeliveryHeader(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
src, ok := a.loadSource(w, r)
if !ok {
return
}
var request struct {
Header string `json:"header"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&request); err != nil {
http.Error(w, "invalid delivery header", http.StatusBadRequest)
return
}
header, err := source.DeliveryHeader(request.Header)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
src.DeliveryHeader = header
if err := a.sources.SetSourceDeliveryHeader(r.Context(), src.Path, header); err != nil {
a.sourceError(w, "set source delivery header", err)
return
}
src.Secret = ""
writeJSON(w, src)
}
// handleSourceDelete deletes a source no armed binding fires on.
func (a *sourcesAPI) handleSourceDelete(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if a.sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return
}
if err := a.sources.DeleteSource(r.Context(), r.PathValue("path")); err != nil {
a.sourceError(w, "delete source", err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (a *sourcesAPI) loadSource(w http.ResponseWriter, r *http.Request) (*source.Source, bool) {
if a.sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return nil, false
}
src, err := a.sources.GetSource(r.Context(), r.PathValue("path"))
if err != nil {
a.sourceError(w, "get source", err)
return nil, false
}
if src == nil {
http.Error(w, "source not found", http.StatusNotFound)
return nil, false
}
return src, true
}
func (a *sourcesAPI) sourceError(w http.ResponseWriter, what string, err error) {
switch {
case errors.Is(err, storecontract.ErrSourcePathTaken):
http.Error(w, "source path already taken", http.StatusConflict)
case errors.Is(err, storecontract.ErrSourceSigningStale):
http.Error(w, "source signing changed; reload and retry", http.StatusConflict)
case errors.Is(err, storecontract.ErrSourceNotFound):
http.Error(w, "source not found", http.StatusNotFound)
case errors.Is(err, org.ErrInvalidWorkspace):
http.Error(w, "that workspace is not one of this org's", http.StatusBadRequest)
case errors.Is(err, storecontract.ErrSourceInUse):
http.Error(w, "an armed binding fires on this source; pause or delete it first", http.StatusConflict)
default:
a.log.Error(what, "err", err)
http.Error(w, what+" failed", http.StatusInternalServerError)
}
}