From 84d46e60711e291dbb626610e766ec55d862d215 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Tue, 15 Sep 2026 19:13:12 -0700 Subject: [PATCH 1/5] kms: re-admit a suspended host only once it responds again A host whose request fails is suspended and skipped for subsequent requests. Until now it was re-admitted once `LoadBalancer.Timeout` elapsed, without checking whether it can serve requests again. For a host that is merely not listening this is harmless: the next request to it fails immediately and suspends it again. For a host that is unreachable it is not. Nothing answers, so the request sits in `net.Dialer.Timeout` - 30 seconds by default - before the load balancer gives up and retries the next host. Since the timer re-admits the host every 30 seconds regardless, a client keeps paying that stall for as long as the host stays unreachable. Powering off the machine a KMS server runs on is enough to trigger this, and the stall is visible to whoever waits on the KMS operation. This commit adds `LoadBalancer.Probe`. When set, a suspended host is only re-admitted once a probe of that host succeeds, so an unreachable host stays out of host selection instead of being handed back out on a timer. Probing starts when the first host is suspended, runs once per `LoadBalancer.ProbeInterval`, and stops once no host is suspended anymore, so it costs nothing while all hosts are healthy. `NewClient` probes with the liveness API, which reports whether a server is listening and responding at all, and which does not send its request through the load balancer. `LoadBalancer.Timeout` keeps its previous meaning when no probe is set. `Host` still returns a host when every host is suspended, so a client keeps making progress during a full outage. Signed-off-by: Harshavardhana --- kms/client.go | 11 +- kms/client_test.go | 47 +++++++ kms/internal/https/retry.go | 154 +++++++++++++++++++---- kms/internal/https/retry_test.go | 202 +++++++++++++++++++++++++++++++ 4 files changed, 391 insertions(+), 23 deletions(-) create mode 100644 kms/client_test.go create mode 100644 kms/internal/https/retry_test.go diff --git a/kms/client.go b/kms/client.go index 6c334fd..8c1edc8 100644 --- a/kms/client.go +++ b/kms/client.go @@ -132,11 +132,18 @@ func NewClient(conf *Config) (*Client, error) { Hosts: hosts, RoundTripper: transport, } - return &Client{ + client := &Client{ direct: http.Client{Transport: lb.RoundTripper}, client: http.Client{Transport: lb}, lb: lb, - }, nil + } + + // Live does not send its request through the load balancer, which + // would never select a suspended host. + lb.Probe = func(ctx context.Context, host string) error { + return client.Live(ctx, &LivenessRequest{Hosts: []string{host}}) + } + return client, nil } // Client is a KMS client. It performs client-side load balancing diff --git a/kms/client_test.go b/kms/client_test.go new file mode 100644 index 0000000..0139ff2 --- /dev/null +++ b/kms/client_test.go @@ -0,0 +1,47 @@ +// Copyright 2025 - MinIO, Inc. All rights reserved. +// Use of this source code is governed by the AGPLv3 +// license that can be found in the LICENSE file. + +package kms + +import ( + "context" + "net/http" + "testing" + + "github.com/minio/kms-go/kms/internal/api" +) + +type recordingRoundTripper struct { + paths chan string +} + +func (r *recordingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + r.paths <- req.URL.Path + return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil +} + +// A client must probe a suspended host for liveness. Without a probe, +// the load balancer re-admits a host on a timer, even one that is +// still unreachable. +func TestNewClientProbesForLiveness(t *testing.T) { + transport := &recordingRoundTripper{paths: make(chan string, 1)} + + client, err := NewClient(&Config{ + Endpoints: []string{"kms-0.local:7373"}, + Transport: transport, + }) + if err != nil { + t.Fatalf("NewClient: %v", err) + } + if client.lb.Probe == nil { + t.Fatal("NewClient did not configure a probe") + } + + if err := client.lb.Probe(context.Background(), "kms-1.local:7373"); err != nil { + t.Fatalf("Probe: %v", err) + } + if path := <-transport.paths; path != api.PathHealthLive { + t.Fatalf("Probe requested %q, want %q", path, api.PathHealthLive) + } +} diff --git a/kms/internal/https/retry.go b/kms/internal/https/retry.go index 9d1de9c..1ad8eb5 100644 --- a/kms/internal/https/retry.go +++ b/kms/internal/https/retry.go @@ -27,8 +27,11 @@ import ( // If a request to one of these hosts fails, the LoadBalancer retries // the request with different hosts until either the request succeeds // or there are no hosts remaining resp. the retry limit is reached. -// Hosts for which requests fail are temporarily excluded and no longer -// selected for subsequent requests. +// Hosts for which requests fail are suspended and no longer selected +// for subsequent requests. +// +// A suspended host is re-admitted once a Probe of that host succeeds. +// Without a Probe, it is re-admitted after Timeout elapsed. type LoadBalancer struct { // Underlying RoundTripper used to send requests. http.RoundTripper @@ -40,17 +43,41 @@ type LoadBalancer struct { // request. Hosts []string - // Timeout controls how long a host is excluded if a + // Timeout controls how long a host is suspended if a // request to this host fails. If 0, defaults to 30 // seconds. + // + // It is only used if Probe is nil. Timeout time.Duration + // Probe reports whether a host is able to serve requests. + // It should return a nil error if, and only if, the host + // responded. + // + // If Probe is not nil, a suspended host is only re-admitted + // once a Probe of that host succeeds. An unreachable host + // therefore stays suspended instead of being re-admitted on + // a timer while it is still unreachable. + // + // Probe must not send its requests through the LoadBalancer + // itself since the LoadBalancer does not select suspended + // hosts. + Probe func(ctx context.Context, host string) error + + // ProbeInterval is the delay between two rounds of probing + // the suspended hosts. If 0, defaults to 5 seconds. A probe + // is canceled once ProbeInterval elapsed. + // + // It is only used if Probe is not nil. + ProbeInterval time.Duration + // Retry specifies how often the LoadBalancer retries // a request with different hosts bef Retry int mu sync.RWMutex timeout map[string]time.Time + probing bool } // URL returns an URL string with the next host and the provided @@ -85,14 +112,14 @@ func (lb *LoadBalancer) Host() (string, error) { case 1: return lb.Hosts[0], nil default: - t, r := timeout(lb.Timeout), rand.Intn(len(lb.Hosts)) + r := rand.Intn(len(lb.Hosts)) lb.mu.RLock() defer lb.mu.RUnlock() now := time.Now() for i := 0; i < len(lb.Hosts); i++ { - if timeout, ok := lb.timeout[lb.Hosts[r]]; !ok || now.Sub(timeout) > t { + if !lb.isSuspended(lb.Hosts[r], now) { return lb.Hosts[r], nil } r = (r + 1) % len(lb.Hosts) @@ -109,8 +136,8 @@ func (lb *LoadBalancer) Host() (string, error) { // succeeded before. It stops retrying once the request succeeds, // there are no more non-suspended hosts remaining or the retry limit // is reached. -// Hosts, for which requests fail, are temporarily excluded and no longer -// selected for subsequent requests or retries. +// Hosts, for which requests fail, are suspended and no longer selected +// for subsequent requests or retries. func (lb *LoadBalancer) RoundTrip(req *http.Request) (*http.Response, error) { resp, err := lb.RoundTripper.RoundTrip(req) if err != nil && isRetryable(err) { @@ -118,24 +145,17 @@ func (lb *LoadBalancer) RoundTrip(req *http.Request) (*http.Response, error) { if r < 0 { return resp, err } + lb.suspend(req.URL.Host) now := time.Now() - lb.mu.Lock() - if lb.timeout == nil { - lb.timeout = map[string]time.Time{} - } - lb.timeout[req.URL.Host] = now - lb.mu.Unlock() - - t := timeout(lb.Timeout) for i := 1; i < len(lb.Hosts); i++ { r = (r + 1) % len(lb.Hosts) lb.mu.RLock() - timeout, ok := lb.timeout[lb.Hosts[r]] + suspended := lb.isSuspended(lb.Hosts[r], now) lb.mu.RUnlock() - if ok && now.Sub(timeout) < t { + if suspended { continue } closeResponseBody(resp) @@ -145,15 +165,100 @@ func (lb *LoadBalancer) RoundTrip(req *http.Request) (*http.Response, error) { if err == nil || !isRetryable(err) { return resp, err } - - lb.mu.Lock() - lb.timeout[req.URL.Host] = time.Now() - lb.mu.Unlock() + lb.suspend(req.URL.Host) } } return resp, err } +// suspend excludes host from host selection. It starts probing the +// suspended hosts if lb re-admits hosts based on Probe and no probing +// is in progress. +func (lb *LoadBalancer) suspend(host string) { + lb.mu.Lock() + defer lb.mu.Unlock() + + if lb.timeout == nil { + lb.timeout = map[string]time.Time{} + } + lb.timeout[host] = time.Now() + + if lb.Probe != nil && !lb.probing { + lb.probing = true + go lb.probeHosts() + } +} + +// resume re-admits host to host selection. +func (lb *LoadBalancer) resume(host string) { + lb.mu.Lock() + delete(lb.timeout, host) + lb.mu.Unlock() +} + +// isSuspended reports whether host is currently excluded from host +// selection. Callers must hold lb.mu. +func (lb *LoadBalancer) isSuspended(host string, now time.Time) bool { + t, ok := lb.timeout[host] + if !ok { + return false + } + if lb.Probe != nil { + return true + } + return now.Sub(t) <= timeout(lb.Timeout) +} + +// probeHosts probes all suspended hosts, once per ProbeInterval, and +// re-admits those that respond. It returns once no host is suspended +// anymore. A new probeHosts is started by the next suspend. +func (lb *LoadBalancer) probeHosts() { + interval := probeInterval(lb.ProbeInterval) + for { + hosts := lb.suspendedHosts() + if len(hosts) == 0 { + return + } + + var wg sync.WaitGroup + for _, host := range hosts { + wg.Add(1) + go func() { + defer wg.Done() + + ctx, cancel := context.WithTimeout(context.Background(), interval) + defer cancel() + + if lb.Probe(ctx, host) == nil { + lb.resume(host) + } + }() + } + wg.Wait() + + time.Sleep(interval) + } +} + +// suspendedHosts returns the currently suspended hosts. It stops +// probing if no host is suspended, such that the emptiness check +// and the hand-off to the next suspend happen atomically. +func (lb *LoadBalancer) suspendedHosts() []string { + lb.mu.Lock() + defer lb.mu.Unlock() + + if len(lb.timeout) == 0 { + lb.probing = false + return nil + } + + hosts := make([]string, 0, len(lb.timeout)) + for host := range lb.timeout { + hosts = append(hosts, host) + } + return hosts +} + func timeout(d time.Duration) time.Duration { if d <= 0 { return 30 * time.Second @@ -161,6 +266,13 @@ func timeout(d time.Duration) time.Duration { return d } +func probeInterval(d time.Duration) time.Duration { + if d <= 0 { + return 5 * time.Second + } + return d +} + func isRetryable(err error) bool { if err == nil { return false diff --git a/kms/internal/https/retry_test.go b/kms/internal/https/retry_test.go new file mode 100644 index 0000000..b36cd6f --- /dev/null +++ b/kms/internal/https/retry_test.go @@ -0,0 +1,202 @@ +// Copyright 2025 - MinIO, Inc. All rights reserved. +// Use of this source code is governed by the AGPLv3 +// license that can be found in the LICENSE file. + +package https + +import ( + "context" + "errors" + "net/http" + "net/url" + "testing" + "time" +) + +// errDown is returned by probes and round trips for a host that is down. +var errDown = errors.New("host is down") + +// roundTripFunc is an http.RoundTripper that reports which hosts it +// was asked for. +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) } + +func TestLoadBalancerHostSkipsSuspendedHost(t *testing.T) { + lb := &LoadBalancer{ + Hosts: []string{"a", "b", "c"}, + Probe: func(context.Context, string) error { return errDown }, + ProbeInterval: time.Hour, + } + lb.suspend("b") + + for i := 0; i < 100; i++ { + host, err := lb.Host() + if err != nil { + t.Fatalf("Host: %v", err) + } + if host == "b" { + t.Fatal("Host returned the suspended host 'b'") + } + } +} + +func TestLoadBalancerHostWithAllHostsSuspended(t *testing.T) { + lb := &LoadBalancer{ + Hosts: []string{"a", "b", "c"}, + Probe: func(context.Context, string) error { return errDown }, + ProbeInterval: time.Hour, + } + for _, host := range lb.Hosts { + lb.suspend(host) + } + + host, err := lb.Host() + if err != nil { + t.Fatalf("Host: %v", err) + } + if host == "" { + t.Fatal("Host returned no host while all hosts are suspended") + } +} + +func TestLoadBalancerProbeKeepsUnresponsiveHostSuspended(t *testing.T) { + lb := &LoadBalancer{ + Hosts: []string{"a", "b"}, + Timeout: time.Millisecond, + Probe: func(context.Context, string) error { return errDown }, + ProbeInterval: time.Millisecond, + } + lb.suspend("a") + + // Well past Timeout, which must not re-admit a host that a Probe + // decides about. + time.Sleep(20 * time.Millisecond) + + for i := 0; i < 100; i++ { + if host, _ := lb.Host(); host != "b" { + t.Fatalf("Host = %q, want the only host that responds", host) + } + } +} + +func TestLoadBalancerProbeReadmitsHostOnlyOnceItResponds(t *testing.T) { + live := make(chan struct{}) + probed := make(chan string, 1024) + + lb := &LoadBalancer{ + Hosts: []string{"a", "b"}, + ProbeInterval: time.Millisecond, + } + lb.Probe = func(_ context.Context, host string) error { + probed <- host + select { + case <-live: + return nil + default: + return errDown + } + } + lb.suspend("a") + + // For as long as 'a' does not respond, it must not be re-admitted, + // however often it is probed. + for i := 0; i < 5; i++ { + if host := <-probed; host != "a" { + t.Fatalf("probed host = %q, want the suspended host 'a'", host) + } + if host, _ := lb.Host(); host != "b" { + t.Fatalf("Host = %q, want the only host that is not suspended", host) + } + } + + close(live) + waitFor(t, "'a' to be re-admitted once it responds", func() bool { + return !lb.suspended("a") + }) + + // Once no host is suspended anymore, probing must stop so that it + // does not outlive the outage. + waitFor(t, "probing to stop", func() bool { + lb.mu.RLock() + defer lb.mu.RUnlock() + return !lb.probing + }) +} + +func TestLoadBalancerTimeoutReadmitsHostWithoutProbe(t *testing.T) { + lb := &LoadBalancer{ + Hosts: []string{"a", "b"}, + Timeout: 10 * time.Millisecond, + } + lb.suspend("a") + + if host, _ := lb.Host(); host != "b" { + t.Fatalf("Host = %q, want the only host that is not suspended", host) + } + + waitFor(t, "'a' to be re-admitted after the timeout elapsed", func() bool { + for i := 0; i < 100; i++ { + if host, _ := lb.Host(); host == "a" { + return true + } + } + return false + }) +} + +func TestLoadBalancerRoundTripSuspendsFailedHost(t *testing.T) { + probed := make(chan string, 1024) + + lb := &LoadBalancer{ + Hosts: []string{"a", "b"}, + RoundTripper: roundTripFunc(func(req *http.Request) (*http.Response, error) { + if req.URL.Host == "a" { + return nil, errDown + } + return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil + }), + ProbeInterval: time.Millisecond, + } + lb.Probe = func(_ context.Context, host string) error { + probed <- host + return errDown + } + + resp, err := lb.RoundTrip(&http.Request{URL: &url.URL{Scheme: "https", Host: "a"}}) + if err != nil { + t.Fatalf("RoundTrip did not retry the request with a different host: %v", err) + } + if resp.StatusCode != http.StatusOK { + t.Fatalf("StatusCode = %d, want %d", resp.StatusCode, http.StatusOK) + } + if !lb.suspended("a") { + t.Fatal("RoundTrip did not suspend the host its request failed for") + } + if host := <-probed; host != "a" { + t.Fatalf("probed host = %q, want the suspended host 'a'", host) + } +} + +// suspended reports whether host is currently suspended. It exists for +// tests only; production code consults isSuspended while holding lb.mu. +func (lb *LoadBalancer) suspended(host string) bool { + lb.mu.RLock() + defer lb.mu.RUnlock() + + _, ok := lb.timeout[host] + return ok +} + +func waitFor(t *testing.T, what string, cond func() bool) { + t.Helper() + + const Timeout = 10 * time.Second + for deadline := time.Now().Add(Timeout); time.Now().Before(deadline); { + if cond() { + return + } + time.Sleep(time.Millisecond) + } + t.Fatalf("timed out after %v waiting for %s", Timeout, what) +} From 8ffa3e26a7e26a1a144878daf30da9752efd24b3 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Tue, 15 Sep 2026 19:25:26 -0700 Subject: [PATCH 2/5] kms: stop suspending a host when the caller's context expires `isRetryable` treats every error but `context.Canceled` as retryable, so a request that ran out of the caller's deadline suspends the host it was sent to. A caller's deadline says nothing about the host, and with probe-based re-admission a host suspended this way stays out of host selection until the next probe. Testing `errors.Is(err, context.DeadlineExceeded)` is not enough to tell the two apart. `net.Dialer` implements its `Timeout` with a context deadline, so the dial timeout of an unreachable host matches `context.DeadlineExceeded` as well - and that error must keep suspending the host. The request context tells them apart: it is only expired if the caller's deadline is the one that elapsed. This commit passes the request context to `isRetryable` and treats an error as not retryable if that context is done, since no retry can succeed for a caller that is gone. Signed-off-by: Harshavardhana --- kms/internal/https/retry.go | 16 ++++++---- kms/internal/https/retry_test.go | 55 ++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 6 deletions(-) diff --git a/kms/internal/https/retry.go b/kms/internal/https/retry.go index 1ad8eb5..c44eec8 100644 --- a/kms/internal/https/retry.go +++ b/kms/internal/https/retry.go @@ -140,7 +140,7 @@ func (lb *LoadBalancer) Host() (string, error) { // for subsequent requests or retries. func (lb *LoadBalancer) RoundTrip(req *http.Request) (*http.Response, error) { resp, err := lb.RoundTripper.RoundTrip(req) - if err != nil && isRetryable(err) { + if err != nil && isRetryable(req.Context(), err) { r := slices.Index(lb.Hosts, req.URL.Host) if r < 0 { return resp, err @@ -162,7 +162,7 @@ func (lb *LoadBalancer) RoundTrip(req *http.Request) (*http.Response, error) { req.URL.Host = lb.Hosts[r] resp, err = lb.RoundTripper.RoundTrip(req) - if err == nil || !isRetryable(err) { + if err == nil || !isRetryable(req.Context(), err) { return resp, err } lb.suspend(req.URL.Host) @@ -273,15 +273,19 @@ func probeInterval(d time.Duration) time.Duration { return d } -func isRetryable(err error) bool { +func isRetryable(ctx context.Context, err error) bool { if err == nil { return false } - if errors.Is(err, context.Canceled) { + + // A dial or I/O timeout also matches context.DeadlineExceeded since + // net.Dialer implements its Timeout with a context deadline. Only an + // expired request context tells the two apart: the caller is gone, so + // no retry can succeed and the host is not at fault. + if ctx.Err() != nil { return false } - - return true + return !errors.Is(err, context.Canceled) } func closeResponseBody(resp *http.Response) { diff --git a/kms/internal/https/retry_test.go b/kms/internal/https/retry_test.go index b36cd6f..d27f2e8 100644 --- a/kms/internal/https/retry_test.go +++ b/kms/internal/https/retry_test.go @@ -200,3 +200,58 @@ func waitFor(t *testing.T, what string, cond func() bool) { } t.Fatalf("timed out after %v waiting for %s", Timeout, what) } + +// A dial timeout matches context.DeadlineExceeded because net.Dialer +// implements its Timeout with a context deadline. It is the error an +// unreachable host produces, so it must suspend that host. +func TestLoadBalancerRoundTripSuspendsHostOnTimeoutWithLiveContext(t *testing.T) { + lb := &LoadBalancer{ + Hosts: []string{"a", "b"}, + RoundTripper: roundTripFunc(func(req *http.Request) (*http.Response, error) { + if req.URL.Host == "a" { + return nil, context.DeadlineExceeded + } + return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil + }), + Probe: func(context.Context, string) error { return errDown }, + ProbeInterval: time.Hour, + } + + resp, err := lb.RoundTrip(&http.Request{URL: &url.URL{Scheme: "https", Host: "a"}}) + if err != nil { + t.Fatalf("RoundTrip did not retry the request with a different host: %v", err) + } + if resp.StatusCode != http.StatusOK { + t.Fatalf("StatusCode = %d, want %d", resp.StatusCode, http.StatusOK) + } + if !lb.suspended("a") { + t.Fatal("RoundTrip did not suspend the host that timed out") + } +} + +func TestLoadBalancerRoundTripKeepsHostOnCallerTimeout(t *testing.T) { + hosts := make(chan string, 1024) + lb := &LoadBalancer{ + Hosts: []string{"a", "b"}, + RoundTripper: roundTripFunc(func(req *http.Request) (*http.Response, error) { + hosts <- req.URL.Host + return nil, context.DeadlineExceeded + }), + Probe: func(context.Context, string) error { return errDown }, + ProbeInterval: time.Hour, + } + + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancel() + + req := (&http.Request{URL: &url.URL{Scheme: "https", Host: "a"}}).WithContext(ctx) + if _, err := lb.RoundTrip(req); err == nil { + t.Fatal("RoundTrip did not return the caller's error") + } + if lb.suspended("a") { + t.Fatal("RoundTrip suspended a host because the caller's context expired") + } + if len(hosts) != 1 { + t.Fatalf("RoundTrip sent %d requests, want 1 - it must not retry for a caller that is gone", len(hosts)) + } +} From e705da160351b697b3fa7a6fe6a7771833718ebe Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Tue, 15 Sep 2026 19:25:26 -0700 Subject: [PATCH 3/5] ci: run the tests of the internal packages `go test ./kms ./kes` skips the tests of all internal packages. This commit widens it to `./kms/... ./kes/...` so they run too. Signed-off-by: Harshavardhana --- .github/workflows/go.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index d63268f..7f7a8f6 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -44,7 +44,7 @@ jobs: go-version-file: 'kms/go.mod' - name: Test run: | - go test ./kms ./kes + go test ./kms/... ./kes/... vulncheck: name: Vulncheck From c8f275885ab3ddb0521e7c7983a7d549f04c54f0 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Tue, 15 Sep 2026 19:46:07 -0700 Subject: [PATCH 4/5] ci: pin govulncheck to a version the Go toolchain can build The Vulncheck job installs `govulncheck@latest`, which resolved to `golang.org/x/vuln` v1.8.0. That release requires Go 1.26, while every job derives its toolchain from `kms/go.mod` - Go 1.25 - so the install fails before a scan ever runs: go: golang.org/x/vuln/cmd/govulncheck@latest: golang.org/x/vuln@v1.8.0 requires go >= 1.26.0 (running go 1.25.14; GOTOOLCHAIN=local) This commit pins the tool to v1.7.0, the last release whose floor the pinned toolchain satisfies, the way golangci-lint is already pinned. Both modules scan clean with it on Go 1.25.14. Signed-off-by: Harshavardhana --- .github/workflows/go.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index 7f7a8f6..e40c14d 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -58,7 +58,9 @@ jobs: with: go-version-file: 'kms/go.mod' - name: Get govulncheck - run: go install golang.org/x/vuln/cmd/govulncheck@latest + # Pinned because govulncheck's Go floor moves ahead of the toolchain + # this workflow derives from kms/go.mod: v1.8.0 requires Go 1.26. + run: go install golang.org/x/vuln/cmd/govulncheck@v1.7.0 shell: bash - name: Run govulncheck env: From 8c48faeddf72b440cff882c2b67464931da74a31 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Tue, 15 Sep 2026 20:20:41 -0700 Subject: [PATCH 5/5] kms: document the load balancer helpers and its tests Every function this branch added or changed now carries a doc comment. For the tests the comment states what the test pins, so a future failure says what behavior regressed rather than only which assertion tripped. Signed-off-by: Harshavardhana --- kms/client_test.go | 1 + kms/internal/https/retry.go | 9 +++++++++ kms/internal/https/retry_test.go | 19 +++++++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/kms/client_test.go b/kms/client_test.go index 0139ff2..15c15df 100644 --- a/kms/client_test.go +++ b/kms/client_test.go @@ -16,6 +16,7 @@ type recordingRoundTripper struct { paths chan string } +// RoundTrip records the path it was asked for and replies with 200 OK. func (r *recordingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { r.paths <- req.URL.Path return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil diff --git a/kms/internal/https/retry.go b/kms/internal/https/retry.go index c44eec8..48dfccc 100644 --- a/kms/internal/https/retry.go +++ b/kms/internal/https/retry.go @@ -259,6 +259,8 @@ func (lb *LoadBalancer) suspendedHosts() []string { return hosts } +// timeout returns how long a host stays suspended when no Probe decides +// about it, defaulting to 30 seconds. func timeout(d time.Duration) time.Duration { if d <= 0 { return 30 * time.Second @@ -266,6 +268,8 @@ func timeout(d time.Duration) time.Duration { return d } +// probeInterval returns the delay between two probe rounds, defaulting +// to 5 seconds. func probeInterval(d time.Duration) time.Duration { if d <= 0 { return 5 * time.Second @@ -273,6 +277,9 @@ func probeInterval(d time.Duration) time.Duration { return d } +// isRetryable reports whether a request that failed with err should be +// retried with a different host, and therefore whether the host it was +// sent to should be suspended. func isRetryable(ctx context.Context, err error) bool { if err == nil { return false @@ -288,6 +295,8 @@ func isRetryable(ctx context.Context, err error) bool { return !errors.Is(err, context.Canceled) } +// closeResponseBody drains and closes the body of a response that is +// being discarded, so that its connection can be reused. func closeResponseBody(resp *http.Response) { if resp == nil || resp.Body == nil { return diff --git a/kms/internal/https/retry_test.go b/kms/internal/https/retry_test.go index d27f2e8..e0b91d6 100644 --- a/kms/internal/https/retry_test.go +++ b/kms/internal/https/retry_test.go @@ -20,8 +20,10 @@ var errDown = errors.New("host is down") // was asked for. type roundTripFunc func(*http.Request) (*http.Response, error) +// RoundTrip calls f. func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) } +// Host must not return a suspended host while other hosts are available. func TestLoadBalancerHostSkipsSuspendedHost(t *testing.T) { lb := &LoadBalancer{ Hosts: []string{"a", "b", "c"}, @@ -41,6 +43,8 @@ func TestLoadBalancerHostSkipsSuspendedHost(t *testing.T) { } } +// Host must still return a host once every host is suspended, so that a +// client keeps making progress during a full outage. func TestLoadBalancerHostWithAllHostsSuspended(t *testing.T) { lb := &LoadBalancer{ Hosts: []string{"a", "b", "c"}, @@ -60,6 +64,10 @@ func TestLoadBalancerHostWithAllHostsSuspended(t *testing.T) { } } +// A host that does not respond must stay suspended even after Timeout +// elapsed. This is the behavior probing exists for: re-admitting an +// unreachable host on a timer makes every client pay its dial timeout +// again. func TestLoadBalancerProbeKeepsUnresponsiveHostSuspended(t *testing.T) { lb := &LoadBalancer{ Hosts: []string{"a", "b"}, @@ -80,6 +88,9 @@ func TestLoadBalancerProbeKeepsUnresponsiveHostSuspended(t *testing.T) { } } +// A suspended host must be re-admitted once, and only once, a probe of it +// succeeds. Probing must then stop, so that it does not outlive the +// outage. func TestLoadBalancerProbeReadmitsHostOnlyOnceItResponds(t *testing.T) { live := make(chan struct{}) probed := make(chan string, 1024) @@ -124,6 +135,8 @@ func TestLoadBalancerProbeReadmitsHostOnlyOnceItResponds(t *testing.T) { }) } +// Without a Probe, Timeout keeps its previous meaning and re-admits a +// suspended host once it elapsed. func TestLoadBalancerTimeoutReadmitsHostWithoutProbe(t *testing.T) { lb := &LoadBalancer{ Hosts: []string{"a", "b"}, @@ -145,6 +158,8 @@ func TestLoadBalancerTimeoutReadmitsHostWithoutProbe(t *testing.T) { }) } +// RoundTrip must retry a failed request with another host, suspend the +// host it failed for, and start probing that host. func TestLoadBalancerRoundTripSuspendsFailedHost(t *testing.T) { probed := make(chan string, 1024) @@ -188,6 +203,8 @@ func (lb *LoadBalancer) suspended(host string) bool { return ok } +// waitFor polls cond until it holds, and fails the test if it does not +// within a fixed timeout. func waitFor(t *testing.T, what string, cond func() bool) { t.Helper() @@ -229,6 +246,8 @@ func TestLoadBalancerRoundTripSuspendsHostOnTimeoutWithLiveContext(t *testing.T) } } +// An expired request context means the caller is gone, not that the host +// is unhealthy. RoundTrip must neither suspend the host nor retry. func TestLoadBalancerRoundTripKeepsHostOnCallerTimeout(t *testing.T) { hosts := make(chan string, 1024) lb := &LoadBalancer{