diff --git a/backend/internal/api/health/readiness.go b/backend/internal/api/health/readiness.go index 7650644..6f899b3 100644 --- a/backend/internal/api/health/readiness.go +++ b/backend/internal/api/health/readiness.go @@ -3,18 +3,24 @@ // Package health serves the API's probe endpoints and the healthcheck command that probes them. // // /livez reports that the process answers. /readyz reports whether the API's own database pool can -// ping Postgres within ReadinessTimeout. Neither handler logs, and no error text reaches a response. +// ping Postgres within ReadinessTimeout. Concurrent /readyz requests share one ping, and a finished +// ping answers for ReadinessResultLifetime, so readiness holds at most one pool connection however +// many callers probe it. Neither handler logs, and no error text reaches a response. package health import ( "context" "net/http" + "sync" "time" ) -// ReadinessTimeout bounds the database ping of one /readyz request, counted from the request's arrival. +// ReadinessTimeout bounds a /readyz ping, counted from the arrival of the request that started it. const ReadinessTimeout = 2 * time.Second +// ReadinessResultLifetime is how long a finished ping answers later /readyz requests without a new one. +const ReadinessResultLifetime = time.Second + // Pinger is the one method readiness needs from the API's main pool; *sql.DB satisfies it. type Pinger interface { PingContext(ctx context.Context) error @@ -25,22 +31,71 @@ var ( unavailableBody = []byte(`{"status":"unavailable","failing":["postgres"]}`) ) -// Readiness answers /readyz with one PingContext call on the pool it holds. +// Readiness answers /readyz from one PingContext call on the pool it holds, shared by every request +// that arrives while it runs and reused for ReadinessResultLifetime after it ends. type Readiness struct { pool Pinger + now func() time.Time + + mu sync.Mutex + flight *check // the ping in progress, or nil + last error // the outcome of the last finished ping + lastAt time.Time // when it finished; zero before the first +} + +// check is one ping. It runs to its own deadline whatever its callers do, so callers that leave early +// cannot make readiness start pings faster than they finish. +type check struct { + done chan struct{} // closed when err is set + err error } // NewReadiness returns the /readyz handler for the API's main pool. It opens no pool of its own. func NewReadiness(pool Pinger) *Readiness { - return &Readiness{pool: pool} + return &Readiness{pool: pool, now: time.Now} } -// ServeHTTP pings the pool under a context that ends ReadinessTimeout after the request arrived, or -// when the request is cancelled, and answers 200 on success and 503 on any error. +// ServeHTTP answers 200 when the ping succeeded and 503 when it failed. A request that leaves before +// the ping ends stops waiting; the ping goes on for the requests that arrive after it. func (r *Readiness) ServeHTTP(w http.ResponseWriter, req *http.Request) { - ctx, cancel := context.WithTimeout(req.Context(), ReadinessTimeout) - defer cancel() - if err := r.pool.PingContext(ctx); err != nil { + r.mu.Lock() + if !r.lastAt.IsZero() && r.now().Sub(r.lastAt) < ReadinessResultLifetime { + err := r.last + r.mu.Unlock() + respond(w, req, err) + return + } + c := r.flight + if c == nil { + c = &check{done: make(chan struct{})} + r.flight = c + go r.ping(context.WithoutCancel(req.Context()), c) + } + r.mu.Unlock() + + select { + case <-c.done: + respond(w, req, c.err) + case <-req.Context().Done(): + respond(w, req, req.Context().Err()) + } +} + +// ping runs one check under ReadinessTimeout and records its outcome for later requests. +func (r *Readiness) ping(parent context.Context, c *check) { + ctx, cancel := context.WithTimeout(parent, ReadinessTimeout) + err := r.pool.PingContext(ctx) + cancel() + r.mu.Lock() + c.err = err + r.flight = nil + r.last, r.lastAt = err, r.now() + r.mu.Unlock() + close(c.done) +} + +func respond(w http.ResponseWriter, req *http.Request, err error) { + if err != nil { write(w, req, http.StatusServiceUnavailable, unavailableBody) return } diff --git a/backend/internal/api/health/readiness_integration_test.go b/backend/internal/api/health/readiness_integration_test.go index 5a5b473..1f41c7d 100644 --- a/backend/internal/api/health/readiness_integration_test.go +++ b/backend/internal/api/health/readiness_integration_test.go @@ -46,6 +46,10 @@ func withApplicationName(t *testing.T, dsn, name string) string { return u.String() } +// outliveResult waits until /readyz no longer reuses the outcome of its last ping, so the next request +// sees the state the test has just set up. +func outliveResult() { time.Sleep(ReadinessResultLifetime + 50*time.Millisecond) } + func readyzStatus(t *testing.T, srvURL string) (int, time.Duration) { t.Helper() start := time.Now() @@ -126,6 +130,7 @@ func TestReadinessOnTheMainPool(t *testing.T) { t.Errorf("pg_stat_activity shows %d sessions under the pool's name, want exactly 5", sessions) } + outliveResult() code, elapsed := readyzStatus(t, srv.URL) if code != http.StatusServiceUnavailable { t.Errorf("/readyz with every connection held answered %d, want 503", code) @@ -139,20 +144,33 @@ func TestReadinessOnTheMainPool(t *testing.T) { t.Fatal(err) } held = held[1:] + outliveResult() if code, _ := readyzStatus(t, srv.URL); code != http.StatusOK { t.Errorf("/readyz after releasing one connection answered %d, want 200", code) } } -// countingPinger counts PingContext calls. -type countingPinger struct{ calls atomic.Int64 } +// countingPinger counts PingContext calls and the most that ran at once. Each call takes long enough +// for concurrent requests to overlap it. +type countingPinger struct { + calls, running, most atomic.Int64 +} func (c *countingPinger) PingContext(context.Context) error { c.calls.Add(1) + n := c.running.Add(1) + for { + m := c.most.Load() + if n <= m || c.most.CompareAndSwap(m, n) { + break + } + } + time.Sleep(20 * time.Millisecond) + c.running.Add(-1) return nil } -func TestReadinessPingsOncePerRequest(t *testing.T) { +func TestReadinessRunsOnePingAtATime(t *testing.T) { p := &countingPinger{} srv := newServer(t, p) const requests = 100 @@ -165,8 +183,11 @@ func TestReadinessPingsOncePerRequest(t *testing.T) { }) } wg.Wait() - if got := p.calls.Load(); got != requests { - t.Errorf("%d requests made %d PingContext calls, want one each", requests, got) + if got := p.most.Load(); got != 1 { + t.Errorf("%d PingContext calls ran at once for %d concurrent requests, want 1", got, requests) + } + if got := p.calls.Load(); got < 1 || got >= requests { + t.Errorf("%d concurrent requests made %d PingContext calls, want at least 1 and fewer than one each", requests, got) } } @@ -283,6 +304,7 @@ func TestReadinessOnAOneConnectionPool(t *testing.T) { t.Errorf("/readyz under refuse-new with one idle healthy connection answered %d, want 200", code) } setMode("refuse") + outliveResult() code, elapsed := readyzStatus(t, srv.URL) if code != http.StatusServiceUnavailable { t.Errorf("/readyz under refuse answered %d, want 503", code) diff --git a/backend/internal/api/health/readiness_test.go b/backend/internal/api/health/readiness_test.go index d4c65b5..d99ffd4 100644 --- a/backend/internal/api/health/readiness_test.go +++ b/backend/internal/api/health/readiness_test.go @@ -17,7 +17,8 @@ import ( type fakePinger struct { mu sync.Mutex err error - block bool // wait until the context ends, then return its error + block bool // wait until the context ends, then return its error + gate chan struct{} // when set, wait until it is closed or the context ends gotCtx context.Context received time.Time calls int @@ -28,8 +29,15 @@ func (f *fakePinger) PingContext(ctx context.Context) error { f.gotCtx = ctx f.received = time.Now() f.calls++ - block, err := f.block, f.err + block, err, gate := f.block, f.err, f.gate f.mu.Unlock() + if gate != nil { + select { + case <-gate: + case <-ctx.Done(): + return ctx.Err() + } + } if block { <-ctx.Done() return ctx.Err() @@ -43,10 +51,20 @@ func (f *fakePinger) context() context.Context { return f.gotCtx } +func (f *fakePinger) callCount() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.calls +} + func newServer(t *testing.T, p Pinger) *httptest.Server { + t.Helper() + return newServerFor(t, NewReadiness(p)) +} + +func newServerFor(t *testing.T, r *Readiness) *httptest.Server { t.Helper() mux := http.NewServeMux() - r := NewReadiness(p) mux.Handle("/readyz", r) mux.Handle("/livez", Livez()) srv := httptest.NewServer(mux) @@ -150,36 +168,41 @@ func TestReadyzTimesOutAtTwoSeconds(t *testing.T) { } } -func TestReadyzCancelledRequestCancelsPing(t *testing.T) { - p := &fakePinger{block: true} +func TestReadyzLeavingDoesNotCancelTheCheck(t *testing.T) { + p := &fakePinger{gate: make(chan struct{})} srv := newServer(t, p) - ctx, cancel := context.WithCancel(context.Background()) - done := make(chan struct{}) - go func() { - defer close(done) - req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/readyz", http.NoBody) - resp, err := http.DefaultClient.Do(req) - if err == nil { - _ = resp.Body.Close() - } - }() - deadline := time.Now().Add(time.Second) - for p.context() == nil && time.Now().Before(deadline) { - time.Sleep(5 * time.Millisecond) + // Callers that arrive and leave at once, one after another. + for range 5 { + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/readyz", http.NoBody) + if resp, err := http.DefaultClient.Do(req); err == nil { + _ = resp.Body.Close() + } + }() + waitFor(t, "the check", func() bool { return p.context() != nil }) + time.Sleep(20 * time.Millisecond) + cancel() + <-done } - if p.context() == nil { - t.Fatal("the ping never started") + if err := p.context().Err(); err != nil { + t.Fatalf("the check ended with %v after its callers left", err) } - cancel() - select { - case <-p.context().Done(): - if !errors.Is(p.context().Err(), context.Canceled) { - t.Errorf("ping context ended with %v, want context.Canceled", p.context().Err()) - } - case <-time.After(1500 * time.Millisecond): - t.Error("cancelling the request did not cancel the ping") + if got := p.callCount(); got != 1 { + t.Fatalf("callers that left started %d checks, want 1", got) + } + staying := make(chan answer, 1) + go func() { staying <- do(t, context.Background(), http.MethodGet, srv.URL+"/readyz") }() + time.Sleep(50 * time.Millisecond) + close(p.gate) + if resp := <-staying; resp.code != http.StatusOK { + t.Errorf("a caller joining the running check got %d, want 200", resp.code) + } + if got := p.callCount(); got != 1 { + t.Errorf("%d checks, want 1", got) } - <-done } func TestLivez(t *testing.T) { @@ -195,3 +218,108 @@ func TestLivez(t *testing.T) { } assertHeaders(t, resp) } + +// waitFor polls cond until it holds or a second has passed. +func waitFor(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + time.Sleep(5 * time.Millisecond) + } +} + +func TestReadyzConcurrentRequestsShareOneCheck(t *testing.T) { + p := &fakePinger{gate: make(chan struct{})} + srv := newServer(t, p) + const callers = 20 + codes := make(chan int, callers) + var wg sync.WaitGroup + for range callers { + wg.Add(1) + go func() { + defer wg.Done() + codes <- do(t, context.Background(), http.MethodGet, srv.URL+"/readyz").code + }() + } + waitFor(t, "the first check", func() bool { return p.callCount() >= 1 }) + time.Sleep(100 * time.Millisecond) // give the other requests time to arrive + if got := p.callCount(); got != 1 { + t.Fatalf("%d checks in flight for %d concurrent requests, want 1", got, callers) + } + close(p.gate) + wg.Wait() + close(codes) + for code := range codes { + if code != http.StatusOK { + t.Errorf("a request sharing the check answered %d, want 200", code) + } + } + if got := p.callCount(); got != 1 { + t.Errorf("%d checks for one burst of requests, want 1", got) + } +} + +func TestReadyzReusesAResultForItsLifetime(t *testing.T) { + p := &fakePinger{} + r := NewReadiness(p) + var mu sync.Mutex + now := time.Unix(1_700_000_000, 0) + r.now = func() time.Time { mu.Lock(); defer mu.Unlock(); return now } + advance := func(d time.Duration) { mu.Lock(); now = now.Add(d); mu.Unlock() } + srv := newServerFor(t, r) + get := func() answer { return do(t, context.Background(), http.MethodGet, srv.URL+"/readyz") } + + if resp := get(); resp.code != http.StatusOK || p.callCount() != 1 { + t.Fatalf("first request: %d after %d checks, want 200 after 1", resp.code, p.callCount()) + } + p.mu.Lock() + p.err = errors.New("connection refused") + p.mu.Unlock() + advance(ReadinessResultLifetime - time.Millisecond) + if resp := get(); resp.code != http.StatusOK || resp.body != wantOK || p.callCount() != 1 { + t.Errorf("within the lifetime: %d %q after %d checks, want the reused 200 after 1", resp.code, resp.body, p.callCount()) + } + advance(time.Millisecond) + resp := get() + if resp.code != http.StatusServiceUnavailable || resp.body != wantUnavailable || p.callCount() != 2 { + t.Errorf("after the lifetime: %d %q after %d checks, want 503 after 2", resp.code, resp.body, p.callCount()) + } + assertHeaders(t, resp) + if head := do(t, context.Background(), http.MethodHead, srv.URL+"/readyz"); head.code != http.StatusServiceUnavailable || head.body != "" || p.callCount() != 2 { + t.Errorf("HEAD on the reused failure: %d %q after %d checks, want 503, no body, 2 checks", head.code, head.body, p.callCount()) + } +} + +func TestReadyzOneCallerLeavingKeepsTheSharedCheck(t *testing.T) { + p := &fakePinger{gate: make(chan struct{})} + srv := newServer(t, p) + leaving, leave := context.WithCancel(context.Background()) + left := make(chan struct{}) + go func() { + defer close(left) + req, _ := http.NewRequestWithContext(leaving, http.MethodGet, srv.URL+"/readyz", http.NoBody) + if resp, err := http.DefaultClient.Do(req); err == nil { + _ = resp.Body.Close() + } + }() + waitFor(t, "the shared check", func() bool { return p.context() != nil }) + staying := make(chan answer, 1) + go func() { staying <- do(t, context.Background(), http.MethodGet, srv.URL+"/readyz") }() + time.Sleep(100 * time.Millisecond) // let the second request join + leave() + <-left + time.Sleep(50 * time.Millisecond) + if err := p.context().Err(); err != nil { + t.Fatalf("the shared check ended with %v when one of two callers left", err) + } + close(p.gate) + if resp := <-staying; resp.code != http.StatusOK { + t.Errorf("the remaining caller got %d, want 200", resp.code) + } + if got := p.callCount(); got != 1 { + t.Errorf("%d checks, want 1", got) + } +}