fix(health): report readiness instead of static 200

The health endpoint returned 200 unconditionally from before dependencies were ready and never reflected MongoDB state. Handler now takes a readiness check; the endpoint returns 503 while starting or when MongoDB is unreachable and 200 only when ready.
This commit is contained in:
tiennm99 committed 2026-06-26 15:48:35 +07:00
1 parent c119386073
commit b3ab6317fe
3 files changed
+63 -8

No files matched your search

+20 -4
View File
@@ -13,19 +13,35 @@ const (
Path = "/healthz"
)
func Handler() http.Handler {
// Check reports whether the bot is ready to serve. It returns nil when healthy
// and an error describing why not otherwise. A nil Check is always healthy.
type Check func(ctx context.Context) error
// Handler serves the health endpoint. It returns 200 only when check passes,
// and 503 while the bot is still starting or a dependency is unreachable, so an
// orchestrator probe reflects real readiness instead of a static 200.
func Handler(check Check) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc(Path, func(w http.ResponseWriter, _ *http.Request) {
mux.HandleFunc(Path, func(w http.ResponseWriter, r *http.Request) {
if check != nil {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := check(ctx); err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
_, _ = w.Write([]byte("unavailable\n"))
return
}
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok\n"))
})
return mux
}
func Run(ctx context.Context, logger *slog.Logger) {
func Run(ctx context.Context, logger *slog.Logger, check Check) {
server := &http.Server{
Addr: Address,
Handler: Handler(),
Handler: Handler(check),
ReadHeaderTimeout: 3 * time.Second,
}
+26 -2
View File
@@ -1,16 +1,18 @@
package health
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
)
func TestHandlerReturnsOK(t *testing.T) {
func TestHandlerReturnsOKWhenCheckPasses(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, Path, nil)
res := httptest.NewRecorder()
Handler().ServeHTTP(res, req)
Handler(func(context.Context) error { return nil }).ServeHTTP(res, req)
if res.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", res.Code, http.StatusOK)
@@ -19,3 +21,25 @@ func TestHandlerReturnsOK(t *testing.T) {
t.Fatalf("body = %q, want ok", res.Body.String())
}
}
func TestHandlerNilCheckIsHealthy(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, Path, nil)
res := httptest.NewRecorder()
Handler(nil).ServeHTTP(res, req)
if res.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", res.Code, http.StatusOK)
}
}
func TestHandlerReturnsUnavailableWhenCheckFails(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, Path, nil)
res := httptest.NewRecorder()
Handler(func(context.Context) error { return errors.New("not ready") }).ServeHTTP(res, req)
if res.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want %d", res.Code, http.StatusServiceUnavailable)
}
}