fix(metadata): retry discovery HTTP errors and recover in the background (#169)

A provider behind the same Traefik answers 404 while its router is not
loaded, and 502 or 503 while it restarts. GetProviderMetadata returned
these statuses as a plain error, so the startup retries stopped at the
first attempt. After that, nothing retried until a request arrived, and
that request got the 503 page (#147).

- GetProviderMetadata returns a non-200 status as *HTTPError, so the
  startup retries apply to 429 and 5xx.
- RetryConfig gets RetryableStatusCodes. MetadataFetchRetryConfig sets
  it to 404, so only discovery retries a 404.
- If startup discovery fails, the init goroutine retries in the
  background (5 s, doubling up to 60 s, with jitter). It stops when
  metadata is adopted or when Close cancels the instance context.
- GetMetadataWithRecovery takes a context, so Close also ends the
  startup retries.
- Background attempts log at ERROR for the first three and every tenth,
  at DEBUG otherwise. A document with no usable issuer does not end
  recovery. A Close during the startup retries logs at DEBUG only.
- The 503 served while metadata is unavailable or initialization times
  out carries Retry-After: 10, and the startup error log names the
  middleware.

TestMetadataRecoveryOnProviderFailure and the issue152 cold-start test
now serve 400 for a failed discovery, because startup retries 500 and
503 and these tests need init to fail at once.
This commit is contained in:
2026-11-21 04:42:32 +00:00
committed by GitHub
parent a8ae9fa49b
commit f7b96344e4
10 changed files with 532 additions and 18 deletions
+55
View File
@@ -130,6 +130,7 @@ func main() {
// reachable errors.As-replacement site directly under the interpreter.
runCheck("new01-retryexecutor-500-retried", checkNew01RetryExecutorHTTPError500Retried)
runCheck("new01-retryexecutor-400-not-retried", checkNew01RetryExecutorHTTPError400NotRetried)
runCheck("issue147-discovery-status-retried", checkIssue147DiscoveryStatusRetried)
runCheck("new01-retryexecutor-plain-error-no-panic", checkNew01RetryExecutorPlainErrorNoPanic)
runCheck("new01-internal-recovery-httperror-classification", checkNew01InternalRecoveryHTTPErrorClassification)
runCheck("new01-internal-recovery-oidcerror-classification", checkNew01InternalRecoveryOIDCErrorClassification)
@@ -394,6 +395,60 @@ func checkNew01RetryExecutorHTTPError400NotRetried() (string, error) {
return fmt.Sprintf(" calls=%d", calls), nil
}
// checkIssue147DiscoveryStatusRetried pins #147 under the interpreter: a
// discovery 404 and 502 come back from GetProviderMetadata as *HTTPError, and
// MetadataFetchRetryConfig retries both (RetryableStatusCodes for the 404,
// the 5xx rule for the 502) until the document is served.
func checkIssue147DiscoveryStatusRetried() (string, error) {
var hits int32
var srv *httptest.Server
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch atomic.AddInt32(&hits, 1) {
case 1:
w.WriteHeader(http.StatusNotFound)
return
case 2:
w.WriteHeader(http.StatusBadGateway)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(oidc.ProviderMetadata{
Issuer: srv.URL,
AuthURL: srv.URL + "/auth",
TokenURL: srv.URL + "/token",
JWKSURL: srv.URL + "/jwks",
})
}))
defer srv.Close()
cfg := oidc.MetadataFetchRetryConfig()
cfg.MaxAttempts = 4
cfg.InitialDelay = time.Millisecond
cfg.MaxDelay = time.Millisecond
re := oidc.NewRetryExecutor(cfg, oidc.NewLogger("error"))
mc := oidc.NewMetadataCacheWithLogger(nil, oidc.NewLogger("error"))
var issuer string
err := re.ExecuteWithContext(context.Background(), func() error {
metadata, fetchErr := mc.GetProviderMetadata(context.Background(), srv.URL, srv.Client())
if fetchErr != nil {
return fetchErr
}
issuer = metadata.Issuer
return nil
})
if err != nil {
return "", fmt.Errorf("discovery 404/502 were not retried to success: %v (requests=%d)", err, atomic.LoadInt32(&hits))
}
if issuer != srv.URL {
return "", fmt.Errorf("issuer = %q, want %q", issuer, srv.URL)
}
if got := atomic.LoadInt32(&hits); got != 3 {
return "", fmt.Errorf("requests = %d, want 3 (404, 502, 200)", got)
}
return " requests=3", nil
}
// checkNew01RetryExecutorPlainErrorNoPanic pins that a plain (non-HTTPError)
// error reaching isRetryableError's asHTTPError check never panics under
// yaegi -- the exact call shape that panicked pre-fix regardless of err's