// Package health serves the probes. Liveness only proves the process // answers. Readiness means the process can serve the synchronous API: it is // switched off during shutdown, so an orchestrator stops routing new traffic // before the listener closes, and it fails while a critical dependency is // unreachable. package health import ( "context" "net/http" "sync/atomic" "time" "github.com/gin-gonic/gin" "messenger/internal/platform/apperr" "messenger/internal/platform/httpx" ) // checkTimeout is shared by all checks of one probe, so the probe answers // within it even when every dependency hangs; the Docker healthcheck allows // two seconds. const checkTimeout = time.Second // Check is a dependency the API cannot serve requests without. type Check struct { Name string Probe func(ctx context.Context) error } type Handler struct { ready atomic.Bool checks []Check } type status struct { Status string `json:"status"` } func New(checks ...Check) *Handler { h := &Handler{checks: checks} h.ready.Store(true) return h } func (h *Handler) SetReady(ready bool) { h.ready.Store(ready) } func (h *Handler) IsReady() bool { return h.ready.Load() } func (h *Handler) Register(r gin.IRouter) { r.GET("/health/live", h.live) r.GET("/health/ready", h.readyz) } func (h *Handler) live(c *gin.Context) { httpx.JSON(c, http.StatusOK, status{Status: "ok"}) } func (h *Handler) readyz(c *gin.Context) { if !h.ready.Load() { httpx.Error(c, apperr.Unavailable("service is shutting down")) return } ctx, cancel := context.WithTimeout(c.Request.Context(), checkTimeout) defer cancel() for _, check := range h.checks { if err := check.Probe(ctx); err != nil { httpx.Error(c, apperr.Wrap(apperr.KindUnavailable, check.Name+" is unavailable", err)) return } } httpx.JSON(c, http.StatusOK, status{Status: "ok"}) }