Files
sam cf049797b0
Quality / check (push) Canceled after 1m5s
deploy / gate (push) Successful in 4m33s
deploy / archied-image (push) Successful in 2m48s
deploy / agent-image (push) Successful in 12s
deploy / dist-zip (push) Skipped
refactor(webui): extract the schedules and alerts modules (#1778)
2026-11-03 08:37:15 +11:00

137 lines
4.6 KiB
Go

package webui
import (
"context"
"errors"
"log/slog"
"net/http"
"strconv"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/alert"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// AlertSource is the alert surface the dashboard reads and dismisses
// through. The caller's org is the only one it can reach.
type AlertSource interface {
ListAlerts(ctx context.Context, orgID org.OrgID, filter alert.Filter) ([]alert.Alert, error)
DismissAlert(ctx context.Context, orgID org.OrgID, id int64, by string) error
}
type alertView struct {
ID int64 `json:"id"`
Kind string `json:"kind"`
Subject string `json:"subject"`
Severity string `json:"severity"`
Title string `json:"title"`
Body string `json:"body"`
Link string `json:"link,omitempty"`
Condition bool `json:"condition"`
State string `json:"state"`
FirstRaised time.Time `json:"first_raised"`
LastSeen time.Time `json:"last_seen"`
Count int64 `json:"count"`
ClosedBy string `json:"closed_by,omitempty"`
ClosedAt *time.Time `json:"closed_at,omitempty"`
Deliveries []deliveryView `json:"deliveries"`
}
type deliveryView struct {
Event string `json:"event"`
State string `json:"state"`
Created time.Time `json:"created_at"`
Attempts []attemptView `json:"attempts"`
}
type attemptView struct {
N int64 `json:"n"`
At time.Time `json:"at"`
StatusCode int `json:"status_code,omitempty"`
Error string `json:"error,omitempty"`
}
func viewOfAlert(a alert.Alert) alertView {
view := alertView{
ID: a.ID, Kind: a.Kind, Subject: a.Subject, Severity: string(a.Severity), Title: a.Title,
Body: a.Body, Link: a.Link, Condition: a.Condition, State: string(a.State),
FirstRaised: a.FirstRaised, LastSeen: a.LastSeen, Count: a.Count, ClosedBy: a.ClosedBy,
Deliveries: make([]deliveryView, 0, len(a.Deliveries)),
}
if !a.ClosedAt.IsZero() {
view.ClosedAt = &a.ClosedAt
}
for _, d := range a.Deliveries {
dv := deliveryView{Event: d.Event, State: d.State, Created: d.CreatedAt, Attempts: make([]attemptView, 0, len(d.Attempts))}
for _, at := range d.Attempts {
dv.Attempts = append(dv.Attempts, attemptView{N: at.N, At: at.At, StatusCode: at.StatusCode, Error: at.Error})
}
view.Deliveries = append(view.Deliveries, dv)
}
return view
}
// alertsAPI owns the /api/alerts routes. A nil source answers 503.
type alertsAPI struct {
alerts AlertSource
log *slog.Logger
}
func newAlertsAPI(s *Server) *alertsAPI { return &alertsAPI{alerts: s.Alerts, log: s.Log} }
func (a *alertsAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/alerts", a.handleAlerts)
mux.HandleFunc("POST /api/alerts/{id}/dismiss", a.handleAlertDismiss)
}
// handleAlerts lists the caller's org's alerts: open ones unless ?state names
// others (comma separated), most severe first.
func (a *alertsAPI) handleAlerts(w http.ResponseWriter, r *http.Request) {
if a.alerts == nil {
http.Error(w, "alerts unavailable", http.StatusServiceUnavailable)
return
}
filter := alert.Filter{}
if states := r.URL.Query().Get("state"); states != "" {
for state := range strings.SplitSeq(states, ",") {
filter.States = append(filter.States, alert.State(strings.TrimSpace(state)))
}
}
alerts, err := a.alerts.ListAlerts(r.Context(), policyOrg(r), filter)
if err != nil {
a.log.ErrorContext(r.Context(), "list alerts", "err", err)
http.Error(w, "list alerts failed", http.StatusBadGateway)
return
}
views := make([]alertView, len(alerts))
for i, a := range alerts {
views[i] = viewOfAlert(a)
}
writeJSON(w, map[string]any{"alerts": views})
}
// handleAlertDismiss dismisses one open alert of the caller's org.
func (a *alertsAPI) handleAlertDismiss(w http.ResponseWriter, r *http.Request) {
if a.alerts == nil {
http.Error(w, "alerts unavailable", http.StatusServiceUnavailable)
return
}
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.Error(w, "invalid alert id", http.StatusBadRequest)
return
}
err = a.alerts.DismissAlert(r.Context(), policyOrg(r), id, access.ActorFromContext(r.Context()))
switch {
case errors.Is(err, alert.ErrNotFound):
http.Error(w, "alert not found", http.StatusNotFound)
case err != nil:
a.log.ErrorContext(r.Context(), "dismiss alert", "err", err)
http.Error(w, "dismiss alert failed", http.StatusBadGateway)
default:
w.WriteHeader(http.StatusNoContent)
}
}