Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(sdk-go): return a 429 whose Retry-After outlasts the timeout

Yudhi Armyndharis90b4d8178ffc
diff --git a/sdk/go/client_test.go b/sdk/go/client_test.go
index 464904d61..0434eeac1 100644
--- a/sdk/go/client_test.go
+++ b/sdk/go/client_test.go
@@ -421,6 +421,26 @@ func TestRetryHonorsRetryAfter(t *testing.T) {
}
}
+// A Retry-After longer than the time left on the request cannot be honored, so
+// the 429 goes back to the caller at once instead of sleeping out the timeout
+// and surfacing as a *TimeoutError that hides the rate limit.
+func TestRetryReturnsResponseWhenRetryAfterOutlastsDeadline(t *testing.T) {
+ rt := &retryAfterTransport{header: "60"}
+ c := newTestClient(t, rt, WithTimeout(500*time.Millisecond), WithRetry(DefaultRetryPolicy()))
+
+ start := time.Now()
+ _, err := c.Messages.SendText(context.Background(), "s1", SendTextRequest{ChatID: "x", Text: "y"})
+ if !errors.Is(err, ErrRateLimited) {
+ t.Fatalf("expected ErrRateLimited, got %v", err)
+ }
+ if elapsed := time.Since(start); elapsed > 250*time.Millisecond {
+ t.Fatalf("expected the 429 back at once, waited %s", elapsed)
+ }
+ if rt.calls != 1 {
+ t.Fatalf("expected 1 attempt, got %d", rt.calls)
+ }
+}
+
func TestParseRetryAfterHTTPDate(t *testing.T) {
resp := &http.Response{Header: http.Header{"Retry-After": {time.Now().Add(2 * time.Second).UTC().Format(http.TimeFormat)}}}
d, ok := parseRetryAfter(resp)
diff --git a/sdk/go/retry.go b/sdk/go/retry.go
index 85f039506..171fe924d 100644
--- a/sdk/go/retry.go
+++ b/sdk/go/retry.go
@@ -77,7 +77,9 @@ type RetryPolicy struct {
// Defaults (via DefaultRetryPolicy) to 429, 500, 502, 503, 504.
RetryableStatuses []int
// RespectRetryAfter honors a Retry-After header on a 429/503 response,
- // using it as the delay when it is longer than the computed backoff.
+ // using it as the delay when it is longer than the computed backoff. A
+ // delay that would outlast the request deadline is not waited out: the
+ // response is returned as-is.
RespectRetryAfter bool
}
@@ -187,15 +189,22 @@ func retryMiddleware(p RetryPolicy, log Logger) Middleware {
return resp, err
}
+ delay := p.backoff(attempt)
+ if resp != nil && p.RespectRetryAfter {
+ if ra, ok := parseRetryAfter(resp); ok && ra > delay {
+ delay = ra
+ }
+ }
+ // A wait that outlasts the request deadline can only end in a
+ // timeout. Return this attempt's result now, so the caller gets
+ // the typed 429/503 at once instead of a *TimeoutError later.
+ if dl, ok := req.Context().Deadline(); ok && time.Until(dl) < delay {
+ return resp, err
+ }
+
// Drain and close the response body so the connection can be
// reused before the next attempt.
- delay := p.backoff(attempt)
if resp != nil {
- if p.RespectRetryAfter {
- if ra, ok := parseRetryAfter(resp); ok && ra > delay {
- delay = ra
- }
- }
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
}