Files
uptimesebi/internal/platform/health.go
T

51 lines
1.1 KiB
Go

package platform
import (
"context"
"net/http"
"sync/atomic"
"time"
"github.com/gin-gonic/gin"
)
type Probe func(context.Context) error
// Health separates liveness from readiness so a draining instance drops out
// of the load balancer before in-flight work is cancelled.
type Health struct {
probes map[string]Probe
draining atomic.Bool
}
func NewHealth(probes map[string]Probe) *Health {
return &Health{probes: probes}
}
func (h *Health) Drain() { h.draining.Store(true) }
func (h *Health) Register(r gin.IRoutes) {
r.GET("/healthz", func(c *gin.Context) { c.Status(http.StatusNoContent) })
r.GET("/readyz", h.ready)
}
func (h *Health) ready(c *gin.Context) {
if h.draining.Load() {
c.JSON(http.StatusServiceUnavailable, gin.H{"status": "draining"})
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second)
defer cancel()
failed := gin.H{}
for name, p := range h.probes {
if err := p(ctx); err != nil {
failed[name] = err.Error()
}
}
if len(failed) > 0 {
c.JSON(http.StatusServiceUnavailable, gin.H{"status": "unready", "failed": failed})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ready"})
}