diff --git a/README.md b/README.md index d5bb284..9df5ab5 100644 --- a/README.md +++ b/README.md @@ -91,13 +91,15 @@ DoH behavior: ## Behavior notes ### Retries - +} - Triggered by network errors, HTTP `5xx`, and HTTP `429` (rate limited). - Other `4xx` (400/401/403/404) are returned immediately — check `resp.StatusCode` yourself. - If the server sends `Retry-After`, that value is used instead of backoff. Both formats are supported: delta-seconds (`5`) and HTTP-date. + The value is honored as-is (not capped by the 60s backoff limit); the client timeout/cancel still bounds the wait. - Otherwise backoff doubles from `baseWait` (`1s → 2s → 4s`) plus 0–500ms jitter, capped at 60s. - Sleep between attempts is context-aware: cancelling the request stops retries immediately. -- When retries are exhausted, `Get`/`Do` return a **nil response** and an error wrapping the last failure. +- When retries are exhausted, `Get`/`Do` return a **nil response** and a `*myhttp.RetryError`. Use + `errors.As` to read `Attempts`, `StatusCode` (`0` for network errors), and `Err` (the last failure). - Request bodies are buffered once and replayed on each attempt, so POST/PUT retries are safe. - **POST requests are NOT retried by default** to prevent duplicate actions (e.g., double orders in trading). Use `WithRetryPOST(true)` to enable retries for POST if your API supports idempotency. - `WithRetry(0, ...)` disables the retry layer entirely. diff --git a/retry.go b/retry.go index fa10e66..f5e1e18 100644 --- a/retry.go +++ b/retry.go @@ -58,6 +58,7 @@ type retryTransport struct { func (t *retryTransport) RoundTrip(req *http.Request) (*http.Response, error) { ctx := req.Context() var lastErr error + var lastStatus int wait := t.wait attempts := 0 @@ -116,8 +117,10 @@ func (t *retryTransport) RoundTrip(req *http.Request) (*http.Response, error) { // Drain sedikit lalu tutup agar koneksi bisa di-reuse. io.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10)) resp.Body.Close() + lastStatus = resp.StatusCode lastErr = fmt.Errorf("HTTP %d", resp.StatusCode) } else { + lastStatus = 0 lastErr = err } @@ -142,9 +145,28 @@ func (t *retryTransport) RoundTrip(req *http.Request) (*http.Response, error) { } } - return nil, fmt.Errorf("gagal setelah %d attempt: %w", attempts, lastErr) + return nil, &RetryError{Attempts: attempts, StatusCode: lastStatus, Err: lastErr} } +// RetryError — error yang dikembalikan ketika semua attempt gagal. +// Gunakan errors.As untuk mengambil detailnya. +type RetryError struct { + Attempts int // jumlah attempt yang sudah dilakukan + StatusCode int // status HTTP terakhir, atau 0 kalau kegagalannya bukan HTTP + Err error // error terakhir (network error, context, atau HTTP status) +} + +func (e *RetryError) Error() string { + if e.StatusCode != 0 { + return fmt.Sprintf("gagal setelah %d attempt: HTTP %d", e.Attempts, e.StatusCode) + } + return fmt.Sprintf("gagal setelah %d attempt: %v", e.Attempts, e.Err) +} + +// Unwrap memungkinkan errors.Is/errors.As menembus ke error aslinya +// (misalnya context.Canceled atau *net.OpError). +func (e *RetryError) Unwrap() error { return e.Err } + // retryableStatus — status yang layak dicoba lagi. func retryableStatus(code int) bool { return code >= 500 || code == http.StatusTooManyRequests diff --git a/retry_test.go b/retry_test.go index 662d5d4..6b1ad96 100644 --- a/retry_test.go +++ b/retry_test.go @@ -1,6 +1,7 @@ package myhttp import ( + "errors" "io" "net/http" "net/http/httptest" @@ -161,6 +162,85 @@ func TestRandomJitterBounds(t *testing.T) { } } +// TestRetryErrorType — kegagalan setelah retry harus jadi *RetryError. +func TestRetryErrorType(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusServiceUnavailable) + })) + defer server.Close() + + client := New(WithRetry(1, 10*time.Millisecond), WithTimeout(5*time.Second)) + _, err := client.Get(server.URL) + if err == nil { + t.Fatal("harusnya error") + } + + var retryErr *RetryError + if !errors.As(err, &retryErr) { + t.Fatalf("error = %T (%v), mau *RetryError", err, err) + } + if retryErr.Attempts != 2 { + t.Errorf("Attempts = %d, mau 2", retryErr.Attempts) + } + if retryErr.StatusCode != http.StatusServiceUnavailable { + t.Errorf("StatusCode = %d, mau 503", retryErr.StatusCode) + } + if !strings.Contains(err.Error(), "HTTP 503") { + t.Errorf("Error() = %q, mau menyebut HTTP 503", err.Error()) + } +} + +// TestRetryErrorNetwork — kegagalan network: StatusCode 0, Attempts tetap terisi. +func TestRetryErrorNetwork(t *testing.T) { + // WithRetry(0, ...) mematikan layer retry sepenuhnya, jadi pakai 1 retry. + client := New(WithRetry(1, 10*time.Millisecond), WithTimeout(2*time.Second)) + _, err := client.Get("http://127.0.0.1:1") + if err == nil { + t.Fatal("harusnya error") + } + + var retryErr *RetryError + if !errors.As(err, &retryErr) { + t.Fatalf("error = %T (%v), mau *RetryError", err, err) + } + if retryErr.StatusCode != 0 { + t.Errorf("StatusCode = %d, mau 0", retryErr.StatusCode) + } + if retryErr.Attempts != 2 { + t.Errorf("Attempts = %d, mau 2 (1 percobaan + 1 retry)", retryErr.Attempts) + } +} + +// TestNextDelay — Retry-After dihormati tanpa cap, backoff lokal tetap di-cap. +func TestNextDelay(t *testing.T) { + tests := []struct { + name string + wait time.Duration + retryAfter time.Duration + jitter time.Duration + wantDelay time.Duration + wantWait time.Duration + }{ + {"retry-after tanpa cap", time.Second, 5 * time.Minute, 300 * time.Millisecond, 5 * time.Minute, time.Second}, + {"backoff normal", time.Second, 0, 200 * time.Millisecond, 1200 * time.Millisecond, 2 * time.Second}, + {"backoff di-cap", 45 * time.Second, 0, 0, 45 * time.Second, maxRetryWait}, + {"delay di-cap", maxRetryWait, 0, 500 * time.Millisecond, maxRetryWait, maxRetryWait}, + {"wait besar tidak overflow", 24 * time.Hour, 0, 0, maxRetryWait, maxRetryWait}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + delay, nextWait := nextDelay(tc.wait, tc.retryAfter, tc.jitter) + if delay != tc.wantDelay { + t.Errorf("delay = %v, mau %v", delay, tc.wantDelay) + } + if nextWait != tc.wantWait { + t.Errorf("nextWait = %v, mau %v", nextWait, tc.wantWait) + } + }) + } +} + // TestParseRetryAfter — unit test parser header func TestParseRetryAfter(t *testing.T) { cases := []struct {