From bfda29193a4bf15246a0703a4f8638a1ca93d028 Mon Sep 17 00:00:00 2001 From: Rain Seven <128443127+RAiNY7Study@users.noreply.github.com> Date: Sun, 16 Aug 2026 21:28:01 +0800 Subject: [PATCH] feat: add operational health and metrics endpoints (#37) Co-authored-by: Meng Meng <227010654+MengMengCode@users.noreply.github.com> --- internal/server/health_endpoints.go | 52 ++++++++++++++++++ internal/server/health_endpoints_test.go | 67 ++++++++++++++++++++++++ internal/server/server.go | 3 ++ 3 files changed, 122 insertions(+) create mode 100644 internal/server/health_endpoints.go create mode 100644 internal/server/health_endpoints_test.go diff --git a/internal/server/health_endpoints.go b/internal/server/health_endpoints.go new file mode 100644 index 0000000..f357b53 --- /dev/null +++ b/internal/server/health_endpoints.go @@ -0,0 +1,52 @@ +package server + +import ( + "context" + "fmt" + "net/http" + "runtime" + "time" +) + +func (s *Server) handleLiveness(w http.ResponseWriter, r *http.Request) { + if !requireMethod(w, r, http.MethodGet) { + return + } + w.Header().Set("Cache-Control", "no-store") + writeJSON(w, http.StatusOK, map[string]any{"status": "ok"}) +} + +func (s *Server) handleReadiness(w http.ResponseWriter, r *http.Request) { + if !requireMethod(w, r, http.MethodGet) { + return + } + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) + defer cancel() + if err := s.store.Ready(ctx); err != nil { + writeJSON(w, http.StatusServiceUnavailable, map[string]any{"status": "not_ready"}) + return + } + w.Header().Set("Cache-Control", "no-store") + writeJSON(w, http.StatusOK, map[string]any{"status": "ready"}) +} + +// handleMetrics exposes only process-level, non-identifying Prometheus data. +// Device IDs, SIM identities, phone numbers and proxy information never enter +// this unauthenticated endpoint. +func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request) { + if !requireMethod(w, r, http.MethodGet) { + return + } + ready := 0 + ctx, cancel := context.WithTimeout(r.Context(), time.Second) + if s.store.Ready(ctx) == nil { + ready = 1 + } + cancel() + w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + fmt.Fprint(w, "# HELP vocat_up Whether the process is running.\n# TYPE vocat_up gauge\nvocat_up 1\n") + fmt.Fprintf(w, "# HELP vocat_ready Whether the database is ready.\n# TYPE vocat_ready gauge\nvocat_ready %d\n", ready) + fmt.Fprintf(w, "# HELP vocat_uptime_seconds Process uptime.\n# TYPE vocat_uptime_seconds counter\nvocat_uptime_seconds %.0f\n", time.Since(s.startedAt).Seconds()) + fmt.Fprintf(w, "# HELP vocat_go_goroutines Current Go goroutines.\n# TYPE vocat_go_goroutines gauge\nvocat_go_goroutines %d\n", runtime.NumGoroutine()) +} diff --git a/internal/server/health_endpoints_test.go b/internal/server/health_endpoints_test.go new file mode 100644 index 0000000..24fe1bd --- /dev/null +++ b/internal/server/health_endpoints_test.go @@ -0,0 +1,67 @@ +package server + +import ( + "io" + "net/http" + "strings" + "testing" +) + +func TestOperationalHealthEndpointsAreAnonymousAndNonIdentifying(t *testing.T) { + app := newTestApplication(t) + + tests := []struct { + path string + contentType string + contains string + }{ + {path: "/healthz", contentType: "application/json", contains: `"status":"ok"`}, + {path: "/readyz", contentType: "application/json", contains: `"status":"ready"`}, + {path: "/metrics", contentType: "text/plain", contains: "vocat_ready 1"}, + } + for _, test := range tests { + t.Run(test.path, func(t *testing.T) { + response, err := app.client.Get(app.server.URL + test.path) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + body, err := io.ReadAll(response.Body) + if err != nil { + t.Fatal(err) + } + if response.StatusCode != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.StatusCode, body) + } + if !strings.Contains(response.Header.Get("Content-Type"), test.contentType) { + t.Fatalf("Content-Type = %q", response.Header.Get("Content-Type")) + } + if !strings.Contains(string(body), test.contains) { + t.Fatalf("body = %q, want %q", body, test.contains) + } + for _, forbidden := range []string{"imsi", "iccid", "msisdn", "proxy", "device_id"} { + if strings.Contains(strings.ToLower(string(body)), forbidden) { + t.Fatalf("body exposes forbidden label %q: %s", forbidden, body) + } + } + }) + } +} + +func TestOperationalHealthEndpointsRejectPOST(t *testing.T) { + app := newTestApplication(t) + for _, path := range []string{"/healthz", "/readyz", "/metrics"} { + request, err := http.NewRequest(http.MethodPost, app.server.URL+path, nil) + if err != nil { + t.Fatal(err) + } + response, err := app.client.Do(request) + if err != nil { + t.Fatal(err) + } + response.Body.Close() + if response.StatusCode != http.StatusMethodNotAllowed { + t.Fatalf("%s status = %d, want %d", path, response.StatusCode, http.StatusMethodNotAllowed) + } + } +} diff --git a/internal/server/server.go b/internal/server/server.go index b4cbcf3..2156630 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -144,6 +144,9 @@ func New(options Options) (*Server, error) { server.loadUILanguage(context.Background()) mux := http.NewServeMux() + mux.HandleFunc("/healthz", server.handleLiveness) + mux.HandleFunc("/readyz", server.handleReadiness) + mux.HandleFunc("/metrics", server.handleMetrics) mux.HandleFunc("/api/health", server.handleHealth) mux.HandleFunc("/api/auth/login", server.handleLogin) mux.HandleFunc("/api/auth/session", server.handleSession)