package platform import ( "context" "net/http" "sync" "sync/atomic" "time" "github.com/gin-gonic/gin" ) // Probe reports whether a dependency is usable. 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 drained chan struct{} once sync.Once } // NewHealth returns a Health that is ready while all probes pass. func NewHealth(probes map[string]Probe) *Health { return &Health{probes: probes, drained: make(chan struct{})} } // Drain makes /readyz fail permanently. Call it before shutdown. func (h *Health) Drain() { h.draining.Store(true) h.once.Do(func() { close(h.drained) }) } // Draining is closed once Drain is called, so long-running requests can // end early instead of holding up the shutdown. func (h *Health) Draining() <-chan struct{} { return h.drained } // Register mounts /healthz (liveness) and /readyz (readiness). 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"}) }