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) }