package webui import ( "context" "errors" "log/slog" "net/http" "slices" "github.com/samcharles93/archie-core/internal/domain/mapping" "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. type mappingRequest struct { Name string `json:"name"` SourceHint string `json:"source_hint"` EventTypeID string `json:"event_type_id"` Fields []mapping.Field `json:"fields"` } // 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 (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 a.eventTypes == nil { http.Error(w, "event types not configured", http.StatusServiceUnavailable) return false } types, err := a.eventTypes.ListEventTypes(r.Context()) if err != nil { a.log.ErrorContext(r.Context(), "list event types", "err", err) http.Error(w, "list event types failed", http.StatusInternalServerError) return false } for _, t := range types { if t.ID == m.EventTypeID { if err := mapping.CheckSchema(m.Fields, t.Schema); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return false } return true } } http.Error(w, "mapping: event type not found: "+m.EventTypeID, http.StatusBadRequest) return false } 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 := a.mappings.ListMappings(r.Context()) if err != nil { a.log.ErrorContext(r.Context(), "list mappings", "err", err) http.Error(w, "list mappings failed", http.StatusInternalServerError) return } mappings = slices.DeleteFunc(mappings, func(m mapping.Mapping) bool { return !listedIn(r, m.WorkspaceID) }) writeJSON(w, map[string]any{"mappings": mappings}) } func (a *mappingsAPI) handleMappingCreate(w http.ResponseWriter, r *http.Request) { if !a.authorize(w, r) { return } if a.mappings == nil { http.Error(w, "mappings not configured", http.StatusServiceUnavailable) return } req, ok := decodeBody[mappingRequest](w, r) if !ok { return } m := mapping.Mapping{Name: req.Name, SourceHint: req.SourceHint, EventTypeID: req.EventTypeID, Fields: req.Fields} if !a.validateMapping(w, r, m) { return } id, err := a.mappings.InsertMapping(r.Context(), m) if err != nil { a.log.ErrorContext(r.Context(), "insert mapping", "err", err) http.Error(w, "create mapping failed", http.StatusInternalServerError) return } created, err := a.mappings.GetMapping(r.Context(), id) if err != nil || created == nil { a.log.ErrorContext(r.Context(), "get mapping after insert", "err", err, "id", id) http.Error(w, "create mapping failed", http.StatusInternalServerError) return } w.WriteHeader(http.StatusCreated) writeJSON(w, created) } func (a *mappingsAPI) handleMappingGet(w http.ResponseWriter, r *http.Request) { if a.mappings == nil { http.Error(w, "mappings not configured", http.StatusServiceUnavailable) return } id := r.PathValue("id") if id == "" { http.Error(w, "invalid mapping id", http.StatusBadRequest) return } m, err := a.mappings.GetMapping(r.Context(), id) if err != nil { a.log.ErrorContext(r.Context(), "get mapping", "err", err, "id", id) http.Error(w, "get mapping failed", http.StatusInternalServerError) return } if m == nil { http.Error(w, "mapping not found", http.StatusNotFound) return } writeJSON(w, m) } func (a *mappingsAPI) handleMappingUpdate(w http.ResponseWriter, r *http.Request) { if !a.authorize(w, r) { return } if a.mappings == nil { http.Error(w, "mappings not configured", http.StatusServiceUnavailable) return } id := r.PathValue("id") if id == "" { http.Error(w, "invalid mapping id", http.StatusBadRequest) return } req, ok := decodeBody[mappingRequest](w, r) if !ok { return } m := mapping.Mapping{ID: id, Name: req.Name, SourceHint: req.SourceHint, EventTypeID: req.EventTypeID, Fields: req.Fields} if !a.validateMapping(w, r, m) { return } 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 } a.log.ErrorContext(r.Context(), "update mapping", "err", err, "id", id) http.Error(w, "update mapping failed", http.StatusInternalServerError) return } updated, err := a.mappings.GetMapping(r.Context(), id) if err != nil || updated == nil { 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 (a *mappingsAPI) handleMappingDelete(w http.ResponseWriter, r *http.Request) { if !a.authorize(w, r) { return } if a.mappings == nil { http.Error(w, "mappings not configured", http.StatusServiceUnavailable) return } id := r.PathValue("id") if id == "" { http.Error(w, "invalid mapping id", http.StatusBadRequest) return } 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 } a.log.ErrorContext(r.Context(), "delete mapping", "err", err, "id", id) http.Error(w, "delete mapping failed", http.StatusInternalServerError) return } w.WriteHeader(http.StatusNoContent) } // mappingPreviewRequest lets an operator resolve a candidate set of fields // against a real captured event before saving anything -- Fields is loose // input, not a saved mapping ID type mappingPreviewRequest struct { CaptureID string `json:"capture_id"` Fields []mapping.Field `json:"fields"` } func (a *mappingsAPI) handleMappingPreview(w http.ResponseWriter, r *http.Request) { if a.mappings == nil { http.Error(w, "mappings not configured", http.StatusServiceUnavailable) return } if a.captures == nil { http.Error(w, "captures not configured", http.StatusServiceUnavailable) return } req, ok := decodeBody[mappingPreviewRequest](w, r) if !ok { return } capture, err := a.captureByID(r.Context(), req.CaptureID) if err != nil { a.log.ErrorContext(r.Context(), "get capture for preview", "err", err, "capture_id", req.CaptureID) http.Error(w, "preview failed", http.StatusInternalServerError) return } if capture == nil { http.Error(w, "capture not found", http.StatusNotFound) return } values, failures := mapping.Resolve(req.Fields, []byte(capture.Body)) if failures == nil { failures = []mapping.Failure{} } writeJSON(w, map[string]any{"values": values, "failures": failures}) } // 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 (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 } for i := range captures { if captures[i].ID == id { return &captures[i], nil } } return nil, nil } // captureScanWindowDefault bounds captureByID's scan when CaptureMaxEvents is // unset. const captureScanWindowDefault = 5000 // mappingCaptureScanWindow returns the configured capture retention, or the // default. func mappingCaptureScanWindow(configuredMaxEvents int) int { if configuredMaxEvents <= 0 { return captureScanWindowDefault } return configuredMaxEvents }