Files
M.ShakhmatovandClaude Fable 5.2 c92fd9826b
CI / test (push) Failing after 43s
Harden instrumentation, health checks and the admin server
- Admin pprof is opt-in (AdminConfig.EnablePprof)
- Client spans drop the URL query string; HostFunc bounds the host label
- Config.HTTP/HTTPClient/GRPC configure the Observer's instrumentation
- A panic after a partial HTTP response counts as 500
- GaugeFunc, CounterFunc and RegisterDBStats panic on duplicates
- Abandoned client gRPC streams are recorded as Canceled
- OTEL_EXPORTER_OTLP_PROTOCOL selects the protocol when unset
- Health reports are cached for 1s; hung checks are not restarted
- Environment is exported as deployment.environment.name

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-15 16:56:39 +03:00

290 lines
7.9 KiB
Go

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
busy *atomic.Bool // a run that outlived its timeout is still in progress
}
// healthCacheTTL bounds how often checks hit their dependencies, however
// often the probes (which may be reachable by clients) are called.
const healthCacheTTL = time.Second
type reportCache struct {
mu sync.Mutex // also serializes runs
at time.Time
report Report
}
func (c *reportCache) reset() {
c.mu.Lock()
c.at = time.Time{}
c.mu.Unlock()
}
// 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
livenessCache, readyCache reportCache
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()
h.liveness = append(h.liveness, namedCheck{name: name, fn: fn, busy: new(atomic.Bool)})
h.mu.Unlock()
h.livenessCache.reset()
}
// AddReadinessCheck registers a check that affects the readiness probe.
func (h *Health) AddReadinessCheck(name string, fn CheckFunc) {
h.mu.Lock()
h.ready = append(h.ready, namedCheck{name: name, fn: fn, busy: new(atomic.Bool)})
h.mu.Unlock()
h.readyCache.reset()
}
// 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. Results are reused for
// up to a second, so frequent probes do not hammer the checked dependencies.
func (h *Health) CheckLiveness(ctx context.Context) Report {
h.mu.RLock()
checks := h.liveness
h.mu.RUnlock()
return h.run(ctx, "liveness", checks, &h.livenessCache)
}
// 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, &h.readyCache)
}
func (h *Health) run(ctx context.Context, kind string, checks []namedCheck, cache *reportCache) Report {
report := Report{Status: StatusOK}
if len(checks) == 0 {
return report
}
cache.mu.Lock()
defer cache.mu.Unlock()
if !cache.at.IsZero() && time.Since(cache.at) < healthCacheTTL {
return cache.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)
}()
}
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)
}
}
if ctx.Err() == nil { // a cancelled caller must not fail the probe for everyone
cache.at, cache.report = time.Now(), report
}
return report
}
func (h *Health) runOne(ctx context.Context, c namedCheck) CheckResult {
// A check that ignores ctx must not pile up one goroutine per probe.
if !c.busy.CompareAndSwap(false, true) {
return CheckResult{Status: StatusFail, Error: "previous run is still in progress", Duration: "0s"}
}
ctx, cancel := context.WithTimeout(ctx, h.timeout)
defer cancel()
start := time.Now()
done := make(chan error, 1)
go func() {
defer c.busy.Store(false)
defer func() {
if rec := recover(); rec != nil {
done <- fmt.Errorf("panic: %v", rec)
}
}()
done <- c.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)
}