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 <noreply@anthropic.com>
This commit is contained in:
M.ShakhmatovandClaude Opus 5.5 committed 2026-11-15 16:39:08 +03:00
1 parent 598ee0536d
commit c710afb127
2 files changed
+372

No files matched your search

+253
View File
@@ -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)
}