Files

194 lines
6.2 KiB
Go

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
// eventTypeExample is a pasted (or sampled) event: headers by name and the
// raw body. The type's schema is inferred from it.
type eventTypeExample struct {
Headers map[string]string `json:"headers"`
Body string `json:"body"`
}
// eventTypeRequest is POST /api/event-types. Rule, when absent, is the one
// inferred from the example.
type eventTypeRequest struct {
Source string `json:"source"`
Name string `json:"name"`
Rule *eventtype.Rule `json:"rule"`
Example eventTypeExample `json:"example"`
}
// eventTypeUpdate is PUT /api/event-types/{id}: the name and rule are the
// editable parts of a type.
type eventTypeUpdate struct {
Name string `json:"name"`
Rule eventtype.Rule `json:"rule"`
}
// handleEventTypes lists the named event types and the proposals grouped from
// recent captures that were unidentified on arrival and still match no type.
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 := 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
}
proposals := []eventtype.Proposal{}
if a.captures != nil {
captures, err := a.captures.ListCaptures(r.Context(), "", proposalScanLimit)
if err != nil {
a.log.ErrorContext(r.Context(), "list captures for proposals", "err", err)
http.Error(w, "list captures failed", http.StatusInternalServerError)
return
}
proposals = append(proposals, eventtype.Propose(unmatchedCaptures(types, captures))...)
}
listed := []eventtype.EventType{}
for _, t := range types {
if listedIn(r, t.WorkspaceID) {
listed = append(listed, t)
}
}
writeJSON(w, map[string]any{"enabled": true, "event_types": listed, "proposals": proposals})
}
// unmatchedCaptures keeps the captures that were unidentified on arrival and
// that no current type would identify either. A capture a newer type now
// matches stays unidentified (it was never dispatched) but is no longer
// proposed.
func unmatchedCaptures(types []eventtype.EventType, captures []storecontract.CapturedEvent) []eventtype.Capture {
var out []eventtype.Capture
for _, c := range captures {
if c.EventType != "" {
continue
}
sample := eventtype.Sample{Headers: eventtype.ParseHeaders(c.Headers), Body: []byte(c.Body)}
if _, ok := eventtype.Identify(types, c.Source, sample); ok {
continue
}
out = append(out, eventtype.Capture{ID: c.ID, Source: c.Source, ReceivedAt: c.ReceivedAt, Sample: sample})
}
return out
}
func (a *eventTypesAPI) handleEventTypeCreate(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if a.eventTypes == nil {
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
return
}
req, ok := decodeBody[eventTypeRequest](w, r)
if !ok {
return
}
t := eventtype.FromExample(req.Source, req.Name, eventtype.Sample{
Headers: req.Example.Headers,
Body: []byte(req.Example.Body),
})
if req.Rule != nil {
t.Rule = *req.Rule
}
id, err := a.eventTypes.InsertEventType(r.Context(), t)
if err != nil {
a.writeEventTypeError(w, "create", err)
return
}
t.ID = id
w.WriteHeader(http.StatusCreated)
writeJSON(w, t)
}
func (a *eventTypesAPI) handleEventTypeUpdate(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if a.eventTypes == nil {
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
return
}
req, ok := decodeBody[eventTypeUpdate](w, r)
if !ok {
return
}
// 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 := a.eventTypes.UpdateEventType(r.Context(), t); err != nil {
a.writeEventTypeError(w, "update", err)
return
}
writeJSON(w, map[string]string{"id": t.ID})
}
func (a *eventTypesAPI) handleEventTypeDelete(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if a.eventTypes == nil {
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
return
}
if err := a.eventTypes.DeleteEventType(r.Context(), r.PathValue("id")); err != nil {
a.writeEventTypeError(w, "delete", err)
return
}
w.WriteHeader(http.StatusNoContent)
}
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)
case errors.Is(err, eventtype.ErrInvalid):
http.Error(w, err.Error(), http.StatusBadRequest)
case errors.Is(err, storecontract.ErrEventTypeNotFound):
http.Error(w, "event type not found", http.StatusNotFound)
default:
a.log.Error(action+" event type", "err", err)
http.Error(w, action+" event type failed", http.StatusInternalServerError)
}
}