From c710afb127924865d635328346d6051797a14fbd Mon Sep 17 00:00:00 2001 From: "M.Shakhmatov" Date: Fri, 30 Oct 2026 00:18:43 +0300 Subject: [PATCH] Add liveness and readiness health checks Concurrent checks with per-check timeouts and panic recovery, HTTP handlers, grpc.health.v1 server, SetReady for graceful shutdown and the health_check_status metric. Co-Authored-By: Claude Opus 5.5 --- health.go | 253 +++++++++++++++++++++++++++++++++++++++++++++++++ health_test.go | 119 +++++++++++++++++++++++ 2 files changed, 372 insertions(+) create mode 100644 health.go create mode 100644 health_test.go diff --git a/health.go b/health.go new file mode 100644 index 0000000..df92b29 --- /dev/null +++ b/health.go @@ -0,0 +1,253 @@ +package obsx + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "sync" + "sync/atomic" + "time" + + "github.com/prometheus/client_golang/prometheus" + "google.golang.org/grpc/codes" + healthpb "google.golang.org/grpc/health/grpc_health_v1" + "google.golang.org/grpc/status" +) + +// Health check statuses reported in JSON responses. +const ( + StatusOK = "ok" + StatusFail = "fail" +) + +// CheckFunc checks a dependency and returns a non-nil error when it is unhealthy. +// It must respect ctx cancellation. +type CheckFunc func(ctx context.Context) error + +// HealthConfig configures health checks. +type HealthConfig struct { + Timeout time.Duration // per-check timeout, default: 5s + Metrics *Metrics // optional: exports health_check_status{check,kind} +} + +func (c *HealthConfig) defaults() { + if c.Timeout <= 0 { + c.Timeout = 5 * time.Second + } +} + +type namedCheck struct { + name string + fn CheckFunc +} + +// Health runs liveness and readiness checks and serves them over HTTP +// (Kubernetes probes) and gRPC (grpc.health.v1). +// +// Liveness answers "should the process be restarted?" and should only include +// checks of the process itself. Readiness answers "can it serve traffic?" and +// typically includes dependencies (database, cache, downstream services). +type Health struct { + timeout time.Duration + status *prometheus.GaugeVec + + mu sync.RWMutex + liveness []namedCheck + ready []namedCheck + + notReady atomic.Bool +} + +// NewHealth creates a Health with no checks; it reports healthy and ready. +func NewHealth(cfg HealthConfig) *Health { + cfg.defaults() + h := &Health{timeout: cfg.Timeout} + if cfg.Metrics != nil { + h.status = cfg.Metrics.base().Gauge("health_check_status", + "Result of the last health check run: 1 healthy, 0 failing.", "check", "kind") + } + return h +} + +// AddLivenessCheck registers a check that affects the liveness probe. +func (h *Health) AddLivenessCheck(name string, fn CheckFunc) { + h.mu.Lock() + defer h.mu.Unlock() + h.liveness = append(h.liveness, namedCheck{name: name, fn: fn}) +} + +// AddReadinessCheck registers a check that affects the readiness probe. +func (h *Health) AddReadinessCheck(name string, fn CheckFunc) { + h.mu.Lock() + defer h.mu.Unlock() + h.ready = append(h.ready, namedCheck{name: name, fn: fn}) +} + +// SetReady overrides readiness. Call SetReady(false) during startup warm-up or +// at the beginning of graceful shutdown so that load balancers stop sending +// traffic; readiness checks are not run while the service is marked not ready. +func (h *Health) SetReady(ready bool) { + h.notReady.Store(!ready) +} + +// Report is the result of running a set of checks. +type Report struct { + Status string `json:"status"` + Error string `json:"error,omitempty"` + Checks map[string]CheckResult `json:"checks,omitempty"` +} + +// CheckResult is the outcome of a single check. +type CheckResult struct { + Status string `json:"status"` + Error string `json:"error,omitempty"` + Duration string `json:"duration"` +} + +// Healthy reports whether all checks passed. +func (r Report) Healthy() bool { return r.Status == StatusOK } + +// CheckLiveness runs all liveness checks concurrently. +func (h *Health) CheckLiveness(ctx context.Context) Report { + h.mu.RLock() + checks := h.liveness + h.mu.RUnlock() + return h.run(ctx, "liveness", checks) +} + +// CheckReadiness runs all readiness checks concurrently. It fails immediately +// when the service was marked not ready with SetReady(false). +func (h *Health) CheckReadiness(ctx context.Context) Report { + if h.notReady.Load() { + return Report{Status: StatusFail, Error: "service is not ready"} + } + h.mu.RLock() + checks := h.ready + h.mu.RUnlock() + return h.run(ctx, "readiness", checks) +} + +func (h *Health) run(ctx context.Context, kind string, checks []namedCheck) Report { + report := Report{Status: StatusOK} + if len(checks) == 0 { + return report + } + + results := make([]CheckResult, len(checks)) + var wg sync.WaitGroup + for i, c := range checks { + wg.Add(1) + go func() { + defer wg.Done() + results[i] = h.runOne(ctx, c.fn) + }() + } + wg.Wait() + + report.Checks = make(map[string]CheckResult, len(checks)) + for i, c := range checks { + res := results[i] + report.Checks[c.name] = res + healthy := 1.0 + if res.Status != StatusOK { + report.Status = StatusFail + healthy = 0 + } + if h.status != nil { + h.status.WithLabelValues(c.name, kind).Set(healthy) + } + } + return report +} + +func (h *Health) runOne(ctx context.Context, fn CheckFunc) CheckResult { + ctx, cancel := context.WithTimeout(ctx, h.timeout) + defer cancel() + + start := time.Now() + done := make(chan error, 1) + go func() { + defer func() { + if rec := recover(); rec != nil { + done <- fmt.Errorf("panic: %v", rec) + } + }() + done <- fn(ctx) + }() + + var err error + select { + case err = <-done: + case <-ctx.Done(): + err = ctx.Err() + if errors.Is(err, context.DeadlineExceeded) { + err = fmt.Errorf("timed out after %s", h.timeout) + } + } + + res := CheckResult{Status: StatusOK, Duration: time.Since(start).String()} + if err != nil { + res.Status = StatusFail + res.Error = err.Error() + } + return res +} + +// LivenessHandler serves liveness checks: 200 when healthy, 503 otherwise. +func (h *Health) LivenessHandler() http.Handler { + return reportHandler(h.CheckLiveness) +} + +// ReadinessHandler serves readiness checks: 200 when ready, 503 otherwise. +func (h *Health) ReadinessHandler() http.Handler { + return reportHandler(h.CheckReadiness) +} + +func reportHandler(check func(context.Context) Report) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + report := check(r.Context()) + code := http.StatusOK + if !report.Healthy() { + code = http.StatusServiceUnavailable + } + writeJSON(w, code, report) + }) +} + +// GRPCServer returns a grpc.health.v1 implementation backed by readiness +// checks. Register it with healthpb.RegisterHealthServer(srv, h.GRPCServer()). +// Watch is not supported. +func (h *Health) GRPCServer() healthpb.HealthServer { + return &grpcHealthServer{h: h} +} + +type grpcHealthServer struct { + healthpb.UnimplementedHealthServer + h *Health +} + +func (s *grpcHealthServer) Check(ctx context.Context, _ *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) { + if err := ctx.Err(); err != nil { + return nil, status.FromContextError(err).Err() + } + st := healthpb.HealthCheckResponse_SERVING + if !s.h.CheckReadiness(ctx).Healthy() { + st = healthpb.HealthCheckResponse_NOT_SERVING + } + return &healthpb.HealthCheckResponse{Status: st}, nil +} + +func (s *grpcHealthServer) Watch(*healthpb.HealthCheckRequest, healthpb.Health_WatchServer) error { + return status.Error(codes.Unimplemented, "watch is not supported") +} + +func writeJSON(w http.ResponseWriter, code int, v any) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(code) + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + _ = enc.Encode(v) +} diff --git a/health_test.go b/health_test.go new file mode 100644 index 0000000..fba8681 --- /dev/null +++ b/health_test.go @@ -0,0 +1,119 @@ +package obsx + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestHealth_NoChecks(t *testing.T) { + h := NewHealth(HealthConfig{}) + if r := h.CheckLiveness(context.Background()); !r.Healthy() { + t.Errorf("liveness = %+v, want ok", r) + } + if r := h.CheckReadiness(context.Background()); !r.Healthy() { + t.Errorf("readiness = %+v, want ok", r) + } +} + +func TestHealth_ReadinessChecks(t *testing.T) { + m := NewMetrics(MetricsConfig{}) + h := NewHealth(HealthConfig{Timeout: 50 * time.Millisecond, Metrics: m}) + h.AddReadinessCheck("db", func(ctx context.Context) error { return nil }) + h.AddReadinessCheck("cache", func(ctx context.Context) error { return errors.New("connection refused") }) + h.AddReadinessCheck("slow", func(ctx context.Context) error { + <-ctx.Done() + return ctx.Err() + }) + h.AddReadinessCheck("stuck", func(ctx context.Context) error { + time.Sleep(time.Second) // ignores ctx; must not block the probe + return nil + }) + h.AddReadinessCheck("panics", func(ctx context.Context) error { panic("oops") }) + + start := time.Now() + r := h.CheckReadiness(context.Background()) + if elapsed := time.Since(start); elapsed > 500*time.Millisecond { + t.Errorf("readiness took %s, checks must time out", elapsed) + } + + if r.Healthy() { + t.Fatal("readiness must fail") + } + if r.Checks["db"].Status != StatusOK { + t.Errorf("db = %+v", r.Checks["db"]) + } + if c := r.Checks["cache"]; c.Status != StatusFail || c.Error != "connection refused" { + t.Errorf("cache = %+v", c) + } + if c := r.Checks["stuck"]; c.Status != StatusFail || !strings.Contains(c.Error, "timed out") { + t.Errorf("stuck = %+v", c) + } + if c := r.Checks["panics"]; c.Status != StatusFail || !strings.Contains(c.Error, "panic: oops") { + t.Errorf("panics = %+v", c) + } + + // Liveness is independent of readiness checks. + if !h.CheckLiveness(context.Background()).Healthy() { + t.Error("liveness must not include readiness checks") + } + + body := scrape(t, m) + for _, want := range []string{ + `health_check_status{check="db",kind="readiness"} 1`, + `health_check_status{check="cache",kind="readiness"} 0`, + } { + if !strings.Contains(body, want) { + t.Errorf("metrics missing %q", want) + } + } +} + +func TestHealth_SetReady(t *testing.T) { + h := NewHealth(HealthConfig{}) + called := false + h.AddReadinessCheck("db", func(ctx context.Context) error { called = true; return nil }) + + h.SetReady(false) + r := h.CheckReadiness(context.Background()) + if r.Healthy() || called { + t.Errorf("not-ready service must fail without running checks: %+v called=%v", r, called) + } + + h.SetReady(true) + if !h.CheckReadiness(context.Background()).Healthy() || !called { + t.Error("ready service must run checks and pass") + } +} + +func TestHealth_Handlers(t *testing.T) { + h := NewHealth(HealthConfig{}) + h.AddLivenessCheck("deadlock", func(ctx context.Context) error { return errors.New("stuck") }) + + w := httptest.NewRecorder() + h.LivenessHandler().ServeHTTP(w, httptest.NewRequest("GET", "/healthz", nil)) + if w.Code != http.StatusServiceUnavailable { + t.Errorf("liveness code = %d, want 503", w.Code) + } + var r Report + if err := json.Unmarshal(w.Body.Bytes(), &r); err != nil { + t.Fatal(err) + } + if r.Status != StatusFail || r.Checks["deadlock"].Error != "stuck" { + t.Errorf("unexpected report: %+v", r) + } + if ct := w.Header().Get("Content-Type"); ct != "application/json" { + t.Errorf("Content-Type = %q", ct) + } + + w = httptest.NewRecorder() + h.ReadinessHandler().ServeHTTP(w, httptest.NewRequest("GET", "/readyz", nil)) + if w.Code != http.StatusOK { + t.Errorf("readiness code = %d, want 200", w.Code) + } +}