Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ require (
github.com/hashicorp/hcl/v2 v2.25.0
github.com/jackc/pgx/v5 v5.10.0
github.com/michielvha/logger v0.0.5
github.com/michielvha/stackweaver/core v0.630.20
github.com/michielvha/stackweaver/core v0.631.0
github.com/redis/go-redis/v9 v9.23.0
github.com/robfig/cron/v3 v3.0.1
github.com/zclconf/go-cty v1.19.0
Expand Down
4 changes: 2 additions & 2 deletions backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,8 @@ github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/michielvha/logger v0.0.5 h1:zcepKGWRMgo32j6nU++RBWtzzz2Q5txVquGDbaSlCro=
github.com/michielvha/logger v0.0.5/go.mod h1:YJjpbm0AlPmmLBFO8tPyBAruWMJisu2sPo/DX9qxKJk=
github.com/michielvha/stackweaver/core v0.630.20 h1:b+kw8LSjJfYaxo2C2Equ5OVdKgxtaxqygTzCLhdGfk8=
github.com/michielvha/stackweaver/core v0.630.20/go.mod h1:Bt8/peil8riL5pzhiLbkoT5b9d30PH+GYKQVpfeqKKI=
github.com/michielvha/stackweaver/core v0.631.0 h1:FRVmsagWVTnWtfkknnjyKtvGlFssft3QFv6S1vIPoO4=
github.com/michielvha/stackweaver/core v0.631.0/go.mod h1:Bt8/peil8riL5pzhiLbkoT5b9d30PH+GYKQVpfeqKKI=
github.com/microsoft/go-mssqldb v1.7.2 h1:CHkFJiObW7ItKTJfHo1QX7QBBD1iV+mn1eOyRP3b/PA=
github.com/microsoft/go-mssqldb v1.7.2/go.mod h1:kOvZKUdrhhFQmxLZqbwUV0rHkNkZpthMITIb2Ko1IoA=
github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
Expand Down
73 changes: 64 additions & 9 deletions backend/internal/api/health/readiness.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
Expand Down
32 changes: 27 additions & 5 deletions backend/internal/api/health/readiness_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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)
}
}

Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading