Ограничить ожидание зависимостей и отвечать 503 при их недоступности
This commit is contained in:
@@ -1,11 +1,15 @@
|
||||
// Package health serves the probes. Liveness only proves the process
|
||||
// answers; readiness is switched off during shutdown so an orchestrator stops
|
||||
// routing new traffic before the listener closes.
|
||||
// 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"
|
||||
|
||||
@@ -13,16 +17,28 @@ import (
|
||||
"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
|
||||
ready atomic.Bool
|
||||
checks []Check
|
||||
}
|
||||
|
||||
type status struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
func New() *Handler {
|
||||
h := &Handler{}
|
||||
func New(checks ...Check) *Handler {
|
||||
h := &Handler{checks: checks}
|
||||
h.ready.Store(true)
|
||||
return h
|
||||
}
|
||||
@@ -49,5 +65,13 @@ func (h *Handler) readyz(c *gin.Context) {
|
||||
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"})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user