This commit is contained in:
@@ -0,0 +1,252 @@
|
||||
package serviceapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/itworx/pulse/internal/auth"
|
||||
"github.com/itworx/pulse/internal/probe"
|
||||
"github.com/itworx/pulse/internal/problem"
|
||||
"github.com/itworx/pulse/internal/reverseproxy"
|
||||
"github.com/itworx/pulse/internal/service"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
Provider service.Provider
|
||||
Dependencies interface {
|
||||
List(context.Context, string, int) ([]service.Dependency, error)
|
||||
}
|
||||
MaxPageSize int
|
||||
MaxHistory int
|
||||
ReverseProxy reverseproxy.Provider
|
||||
}
|
||||
|
||||
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet || (r.URL.Path != "/api/v1/services" && !strings.HasPrefix(r.URL.Path, "/api/v1/services/") && r.URL.Path != "/api/v1/topology") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if _, ok := auth.PrincipalFromContext(r.Context()); !ok {
|
||||
problem.Write(w, r, http.StatusUnauthorized, "UNAUTHORIZED", "Authentication required", "Authentication is required to read services.", nil)
|
||||
return
|
||||
}
|
||||
if err := r.Context().Err(); err != nil {
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/topology" {
|
||||
h.serveTopology(w, r)
|
||||
return
|
||||
}
|
||||
if strings.HasSuffix(r.URL.Path, "/dependencies") {
|
||||
h.serveDependencies(w, r)
|
||||
return
|
||||
}
|
||||
snapshot, err := h.snapshot(r)
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return
|
||||
}
|
||||
problem.Write(w, r, http.StatusServiceUnavailable, "SERVICES_UNAVAILABLE", "Servicegegevens niet beschikbaar", "De servicegegevens konden niet worden gelezen.", nil)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/services" {
|
||||
limit, parseErr := h.limit(r.URL.Query().Get("limit"), h.pageLimit())
|
||||
if parseErr != nil {
|
||||
problem.Write(w, r, http.StatusBadRequest, "SERVICE_QUERY_INVALID", "Invalid service query", "De servicelimiet is ongeldig.", nil)
|
||||
return
|
||||
}
|
||||
response := boundedSnapshot(snapshot, limit, h.historyLimit())
|
||||
writeJSON(w, response)
|
||||
return
|
||||
}
|
||||
path := strings.TrimPrefix(r.URL.Path, "/api/v1/services/")
|
||||
historyRequest := strings.HasSuffix(path, "/history")
|
||||
if strings.Contains(path, "/") && !historyRequest {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
id := strings.TrimSuffix(path, "/history")
|
||||
id = strings.TrimSuffix(id, "/")
|
||||
if id == "" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
for _, item := range snapshot.Services {
|
||||
if item.ID != id {
|
||||
continue
|
||||
}
|
||||
item = boundedStatus(item, h.historyLimit())
|
||||
if historyRequest {
|
||||
limit, parseErr := h.limit(r.URL.Query().Get("limit"), h.historyLimit())
|
||||
if parseErr != nil {
|
||||
problem.Write(w, r, http.StatusBadRequest, "SERVICE_HISTORY_QUERY_INVALID", "Invalid service history query", "De historielimiet is ongeldig.", nil)
|
||||
return
|
||||
}
|
||||
if len(item.History) > limit {
|
||||
item.History = item.History[:limit]
|
||||
}
|
||||
writeJSON(w, struct {
|
||||
ServiceID string `json:"serviceId"`
|
||||
History []probe.Result `json:"history"`
|
||||
}{ServiceID: item.ID, History: item.History})
|
||||
return
|
||||
}
|
||||
writeJSON(w, struct {
|
||||
Service service.ServiceStatus `json:"service"`
|
||||
}{Service: item})
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
|
||||
func (h Handler) serveTopology(w http.ResponseWriter, r *http.Request) {
|
||||
if h.Dependencies == nil {
|
||||
problem.Write(w, r, http.StatusServiceUnavailable, "TOPOLOGY_UNAVAILABLE", "Topology not available", "De topologygegevens zijn niet beschikbaar.", nil)
|
||||
return
|
||||
}
|
||||
limit, err := h.limit(r.URL.Query().Get("limit"), 100)
|
||||
if err != nil {
|
||||
problem.Write(w, r, http.StatusBadRequest, "TOPOLOGY_QUERY_INVALID", "Invalid topology query", "De topologylimiet is ongeldig.", nil)
|
||||
return
|
||||
}
|
||||
snapshot, err := h.snapshot(r)
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return
|
||||
}
|
||||
problem.Write(w, r, http.StatusServiceUnavailable, "TOPOLOGY_UNAVAILABLE", "Topology not available", "De topologygegevens konden niet worden gelezen.", nil)
|
||||
return
|
||||
}
|
||||
dependencies, err := h.Dependencies.List(r.Context(), "", minTopologyEdges(limit))
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return
|
||||
}
|
||||
problem.Write(w, r, http.StatusServiceUnavailable, "TOPOLOGY_UNAVAILABLE", "Topology not available", "De afhankelijkheden konden niet worden gelezen.", nil)
|
||||
return
|
||||
}
|
||||
var routes []reverseproxy.Route
|
||||
if h.ReverseProxy != nil {
|
||||
proxySnapshot, proxyErr := h.ReverseProxy.Snapshot(r.Context())
|
||||
if proxyErr != nil {
|
||||
if errors.Is(proxyErr, context.Canceled) || errors.Is(proxyErr, context.DeadlineExceeded) {
|
||||
return
|
||||
}
|
||||
} else if proxySnapshot.Source.State == reverseproxy.StateEnabled {
|
||||
routes = proxySnapshot.Routes
|
||||
}
|
||||
}
|
||||
sourceTruncated := len(snapshot.Services) > limit
|
||||
topology, err := service.BuildTopologyWithRoutes(boundedSnapshot(snapshot, limit, h.historyLimit()), dependencies, routes, limit, minTopologyEdges(limit))
|
||||
if err != nil {
|
||||
problem.Write(w, r, http.StatusServiceUnavailable, "TOPOLOGY_UNAVAILABLE", "Topology not available", "De topology kon niet veilig worden samengesteld.", nil)
|
||||
return
|
||||
}
|
||||
topology.Truncated = topology.Truncated || sourceTruncated
|
||||
writeJSON(w, topology)
|
||||
}
|
||||
|
||||
func minTopologyEdges(limit int) int {
|
||||
if limit > 250 {
|
||||
return 500
|
||||
}
|
||||
return limit * 2
|
||||
}
|
||||
func (h Handler) serveDependencies(w http.ResponseWriter, r *http.Request) {
|
||||
if h.Dependencies == nil {
|
||||
problem.Write(w, r, http.StatusServiceUnavailable, "DEPENDENCIES_UNAVAILABLE", "Dependencies not available", "Afhankelijkheden zijn niet beschikbaar.", nil)
|
||||
return
|
||||
}
|
||||
id := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/api/v1/services/"), "/dependencies")
|
||||
if id == "" || strings.Contains(id, "/") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
limit, err := h.limit(r.URL.Query().Get("limit"), 100)
|
||||
if err != nil {
|
||||
problem.Write(w, r, http.StatusBadRequest, "DEPENDENCY_QUERY_INVALID", "Invalid dependency query", "De afhankelijkheidslimiet is ongeldig.", nil)
|
||||
return
|
||||
}
|
||||
items, err := h.Dependencies.List(r.Context(), id, limit)
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return
|
||||
}
|
||||
problem.Write(w, r, http.StatusServiceUnavailable, "DEPENDENCIES_UNAVAILABLE", "Dependencies not available", "Afhankelijkheden konden niet worden gelezen.", nil)
|
||||
return
|
||||
}
|
||||
service.SortDependencies(items)
|
||||
writeJSON(w, struct {
|
||||
ServiceID string `json:"serviceId"`
|
||||
Dependencies []service.Dependency `json:"dependencies"`
|
||||
}{ServiceID: id, Dependencies: items})
|
||||
}
|
||||
func (h Handler) snapshot(r *http.Request) (service.Snapshot, error) {
|
||||
if h.Provider == nil {
|
||||
return service.UnknownSnapshot(time.Now().UTC(), "source_unavailable"), nil
|
||||
}
|
||||
return h.Provider.Snapshot(r.Context())
|
||||
}
|
||||
|
||||
func (h Handler) pageLimit() int {
|
||||
if h.MaxPageSize == 0 {
|
||||
return 100
|
||||
}
|
||||
return h.MaxPageSize
|
||||
}
|
||||
|
||||
func (h Handler) historyLimit() int {
|
||||
if h.MaxHistory == 0 {
|
||||
return 100
|
||||
}
|
||||
return h.MaxHistory
|
||||
}
|
||||
|
||||
func (h Handler) limit(raw string, fallback int) (int, error) {
|
||||
if raw == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
value, err := strconv.Atoi(raw)
|
||||
if err != nil || value < 1 || value > fallback {
|
||||
return 0, errors.New("limit outside bounds")
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func boundedSnapshot(snapshot service.Snapshot, maxServices, maxHistory int) service.Snapshot {
|
||||
snapshot.Services = append([]service.ServiceStatus(nil), snapshot.Services...)
|
||||
sort.Slice(snapshot.Services, func(i, j int) bool { return snapshot.Services[i].ID < snapshot.Services[j].ID })
|
||||
if len(snapshot.Services) > maxServices {
|
||||
snapshot.Services = snapshot.Services[:maxServices]
|
||||
}
|
||||
for index := range snapshot.Services {
|
||||
snapshot.Services[index] = boundedStatus(snapshot.Services[index], maxHistory)
|
||||
}
|
||||
if len(snapshot.Events) > 100 {
|
||||
snapshot.Events = snapshot.Events[:100]
|
||||
}
|
||||
return snapshot
|
||||
}
|
||||
|
||||
func boundedStatus(status service.ServiceStatus, maxHistory int) service.ServiceStatus {
|
||||
status.History = append([]probe.Result(nil), status.History...)
|
||||
if len(status.History) > maxHistory {
|
||||
status.History = status.History[:maxHistory]
|
||||
}
|
||||
if len(status.Probes) > 100 {
|
||||
status.Probes = status.Probes[:100]
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, value any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "private, max-age=5")
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package serviceapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/itworx/pulse/internal/auth"
|
||||
"github.com/itworx/pulse/internal/probe"
|
||||
"github.com/itworx/pulse/internal/service"
|
||||
)
|
||||
|
||||
type staticProvider struct {
|
||||
snapshot service.Snapshot
|
||||
err error
|
||||
}
|
||||
|
||||
func (p staticProvider) Snapshot(context.Context) (service.Snapshot, error) { return p.snapshot, p.err }
|
||||
|
||||
func authenticatedRequest(method, path string) *http.Request {
|
||||
request := httptest.NewRequest(method, path, nil)
|
||||
return request.WithContext(auth.WithPrincipal(request.Context(), auth.Principal{Subject: "viewer", Role: auth.RoleViewer}))
|
||||
}
|
||||
|
||||
func apiSnapshot() service.Snapshot {
|
||||
now := time.Date(2026, 8, 2, 12, 0, 0, 0, time.UTC)
|
||||
latency := 12
|
||||
return service.Snapshot{ContractVersion: service.ContractVersion, ObservedAt: now, Services: []service.ServiceStatus{
|
||||
{ID: "service-2", Name: "Second", State: service.StateUp, History: []probe.Result{{ProbeID: "probe-2", ObservedAt: now, State: service.StateUp, ResponseTimeMS: &latency}}},
|
||||
{ID: "service-1", Name: "First", State: service.StateDown, History: []probe.Result{{ProbeID: "probe-1", ObservedAt: now, State: service.StateDown}}},
|
||||
}, Total: 2}
|
||||
}
|
||||
|
||||
func TestServiceHandlerRequiresViewerAndBoundsListAndHistory(t *testing.T) {
|
||||
handler := Handler{Provider: staticProvider{snapshot: apiSnapshot()}, MaxPageSize: 1, MaxHistory: 1}
|
||||
unauthorized := httptest.NewRecorder()
|
||||
handler.ServeHTTP(unauthorized, httptest.NewRequest(http.MethodGet, "/api/v1/services", nil))
|
||||
if unauthorized.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("unauthorized status=%d", unauthorized.Code)
|
||||
}
|
||||
|
||||
listResponse := httptest.NewRecorder()
|
||||
handler.ServeHTTP(listResponse, authenticatedRequest(http.MethodGet, "/api/v1/services?limit=1"))
|
||||
if listResponse.Code != http.StatusOK {
|
||||
t.Fatalf("list status=%d body=%s", listResponse.Code, listResponse.Body.String())
|
||||
}
|
||||
var snapshot service.Snapshot
|
||||
if err := json.Unmarshal(listResponse.Body.Bytes(), &snapshot); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(snapshot.Services) != 1 || snapshot.Services[0].ID != "service-1" || snapshot.Total != 2 || len(snapshot.Services[0].History) != 1 {
|
||||
t.Fatalf("bounded/deterministic list=%+v", snapshot)
|
||||
}
|
||||
|
||||
historyResponse := httptest.NewRecorder()
|
||||
handler.ServeHTTP(historyResponse, authenticatedRequest(http.MethodGet, "/api/v1/services/service-2/history?limit=1"))
|
||||
if historyResponse.Code != http.StatusOK || !strings.Contains(historyResponse.Body.String(), `"serviceId":"service-2"`) {
|
||||
t.Fatalf("history response status=%d body=%s", historyResponse.Code, historyResponse.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceHandlerDetailErrorsAndCancellation(t *testing.T) {
|
||||
handler := Handler{Provider: staticProvider{snapshot: apiSnapshot()}, MaxPageSize: 2, MaxHistory: 2}
|
||||
detail := httptest.NewRecorder()
|
||||
handler.ServeHTTP(detail, authenticatedRequest(http.MethodGet, "/api/v1/services/service-1"))
|
||||
if detail.Code != http.StatusOK || !strings.Contains(detail.Body.String(), `"state":"down"`) {
|
||||
t.Fatalf("detail status=%d body=%s", detail.Code, detail.Body.String())
|
||||
}
|
||||
invalidLimit := httptest.NewRecorder()
|
||||
handler.ServeHTTP(invalidLimit, authenticatedRequest(http.MethodGet, "/api/v1/services?limit=3"))
|
||||
if invalidLimit.Code != http.StatusBadRequest {
|
||||
t.Fatalf("invalid limit status=%d", invalidLimit.Code)
|
||||
}
|
||||
missing := httptest.NewRecorder()
|
||||
handler.ServeHTTP(missing, authenticatedRequest(http.MethodGet, "/api/v1/services/missing"))
|
||||
if missing.Code != http.StatusNotFound {
|
||||
t.Fatalf("missing status=%d", missing.Code)
|
||||
}
|
||||
failed := Handler{Provider: staticProvider{err: errors.New("backend unavailable")}}
|
||||
failedResponse := httptest.NewRecorder()
|
||||
failed.ServeHTTP(failedResponse, authenticatedRequest(http.MethodGet, "/api/v1/services"))
|
||||
if failedResponse.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("provider failure status=%d", failedResponse.Code)
|
||||
}
|
||||
}
|
||||
|
||||
type staticDependencyProvider struct {
|
||||
items []service.Dependency
|
||||
err error
|
||||
}
|
||||
|
||||
func (p staticDependencyProvider) List(context.Context, string, int) ([]service.Dependency, error) {
|
||||
return p.items, p.err
|
||||
}
|
||||
|
||||
func TestServiceHandlerDependenciesAuthBoundsAndDeterminism(t *testing.T) {
|
||||
provider := staticDependencyProvider{items: []service.Dependency{{ID: "dep-2", ServiceID: "service-1", DependsOnServiceID: "service-3", RelationType: service.RelationDependsOn, Confidence: .8}, {ID: "dep-1", ServiceID: "service-1", DependsOnServiceID: "service-2", RelationType: service.RelationDependsOn, Confidence: .9}}}
|
||||
handler := Handler{Provider: staticProvider{snapshot: apiSnapshot()}, Dependencies: provider}
|
||||
unauthorized := httptest.NewRecorder()
|
||||
handler.ServeHTTP(unauthorized, httptest.NewRequest(http.MethodGet, "/api/v1/services/service-1/dependencies", nil))
|
||||
if unauthorized.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("unauthorized dependency status=%d", unauthorized.Code)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, authenticatedRequest(http.MethodGet, "/api/v1/services/service-1/dependencies?limit=1"))
|
||||
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"serviceId":"service-1"`) {
|
||||
t.Fatalf("dependency status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
if strings.Index(response.Body.String(), "service-2") > strings.Index(response.Body.String(), "service-3") {
|
||||
t.Fatalf("dependencies were not deterministic: %s", response.Body.String())
|
||||
}
|
||||
invalid := httptest.NewRecorder()
|
||||
handler.ServeHTTP(invalid, authenticatedRequest(http.MethodGet, "/api/v1/services/service-1/dependencies?limit=101"))
|
||||
if invalid.Code != http.StatusBadRequest {
|
||||
t.Fatalf("invalid dependency limit status=%d", invalid.Code)
|
||||
}
|
||||
failed := Handler{Dependencies: staticDependencyProvider{err: errors.New("dependency backend unavailable")}}
|
||||
failure := httptest.NewRecorder()
|
||||
failed.ServeHTTP(failure, authenticatedRequest(http.MethodGet, "/api/v1/services/service-1/dependencies"))
|
||||
if failure.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("dependency failure status=%d", failure.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceHandlerTopologyIsAuthenticatedBoundedAndExplicit(t *testing.T) {
|
||||
provider := staticDependencyProvider{items: []service.Dependency{{ID: "edge-2", ServiceID: "service-2", DependsOnServiceID: "service-1", RelationType: service.RelationDependsOn, Confidence: .7}, {ID: "edge-1", ServiceID: "service-1", DependsOnServiceID: "missing", RelationType: service.RelationBacks, Confidence: .4}}}
|
||||
handler := Handler{Provider: staticProvider{snapshot: apiSnapshot()}, Dependencies: provider}
|
||||
unauthorized := httptest.NewRecorder()
|
||||
handler.ServeHTTP(unauthorized, httptest.NewRequest(http.MethodGet, "/api/v1/topology", nil))
|
||||
if unauthorized.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("unauthorized topology status=%d", unauthorized.Code)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, authenticatedRequest(http.MethodGet, "/api/v1/topology?limit=2"))
|
||||
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"truncated"`) || !strings.Contains(response.Body.String(), `"inferred":true`) {
|
||||
t.Fatalf("topology status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
invalid := httptest.NewRecorder()
|
||||
handler.ServeHTTP(invalid, authenticatedRequest(http.MethodGet, "/api/v1/topology?limit=101"))
|
||||
if invalid.Code != http.StatusBadRequest {
|
||||
t.Fatalf("invalid topology limit status=%d", invalid.Code)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user