diff --git a/README.md b/README.md index 9df5ab5..f106b90 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,7 @@ DoH behavior: | `WithRetryPOST(enable bool)` | Allow retrying POST requests. `false` prevents duplicate actions (e.g., trading orders) | `false` | | `WithRateLimit(reqPerSec int)` | Max requests per second per client. `0` disables | `0` (disabled) | | `WithTimeout(d time.Duration)` | Timeout for the whole call, including retries | `15s` | +| `WithAttemptTimeout(d time.Duration)` | Max wait for response headers per attempt; `0` disables. Prevents one hung attempt from consuming the whole timeout | `0` | | `WithUserAgent(ua string)` | Default `User-Agent` header | `myhttp/1.0` | | `WithDNS(dnsURL string)` | Enable DNS over HTTPS (DoH) for secure resolution. Empty string defaults to Quad9 | `""` (disabled) | | `WithDNSFallback(enable bool)` | Fall back to the system resolver when DoH fails or is misconfigured | `false` | @@ -83,9 +84,11 @@ DoH behavior: |---|---| | `New` | `New(opts ...Option) *Client` | | `Get` | `Get(url string) (*http.Response, error)` | +| `GetContext` | `GetContext(ctx context.Context, url string) (*http.Response, error)` | | `Do` | `Do(req *http.Request) (*http.Response, error)` | +| `CloseIdleConnections` | `CloseIdleConnections()` | -`Get` is a shortcut. For POST, PUT, DELETE, or any request with custom headers, build an `*http.Request` and send it with `Do`. +`Get` is a shortcut for `GetContext(context.Background(), url)`. For POST, PUT, DELETE, or any request with custom headers, build an `*http.Request` and send it with `Do`. Call `CloseIdleConnections()` when a client is no longer used. ## Behavior notes @@ -111,6 +114,7 @@ DoH behavior: ### Timeout - `WithTimeout` covers the **entire call**, including all retries and backoff sleeps — not each individual attempt. +- `WithAttemptTimeout` bounds each attempt's wait for response headers, so a single hung attempt can't consume the whole `WithTimeout` budget. - Example: `WithRetry(3, time.Second)` can sleep ~7s in backoff alone, so keep the timeout comfortably above that. ### Response body diff --git a/client.go b/client.go index 4be602e..db9dd25 100644 --- a/client.go +++ b/client.go @@ -1,6 +1,7 @@ package myhttp import ( + "context" "fmt" "net/http" "time" @@ -28,12 +29,7 @@ func New(opts ...Option) *Client { } // Tentukan base transport: Pakai custom DNS jika diaktifkan, jika tidak pakai Default - var baseTransport http.RoundTripper - if cfg.dnsURL != "" { - baseTransport = newDNSTransport(cfg.dnsURL, cfg.dnsFallback) - } else { - baseTransport = http.DefaultTransport - } + baseTransport := newBaseTransport(cfg) // Build RoundTripper chain: // base (DNS or Default) → retry → ratelimit → ua @@ -63,6 +59,29 @@ func New(opts ...Option) *Client { } } +// newBaseTransport — bikin base RoundTripper sesuai config. +func newBaseTransport(cfg options) http.RoundTripper { + if cfg.dnsURL != "" { + tr := newDNSTransport(cfg.dnsURL, cfg.dnsFallback) + if cfg.attemptTimeout > 0 { + tr.ResponseHeaderTimeout = cfg.attemptTimeout + } + return tr + } + + if cfg.attemptTimeout <= 0 { + return http.DefaultTransport + } + + // Jangan ubah http.DefaultTransport global: clone dulu. + if tr, ok := http.DefaultTransport.(*http.Transport); ok { + clone := tr.Clone() + clone.ResponseHeaderTimeout = cfg.attemptTimeout + return clone + } + return http.DefaultTransport +} + // uaTransport — inject User-Agent type uaTransport struct { base http.RoundTripper @@ -80,9 +99,30 @@ func (t *uaTransport) RoundTrip(req *http.Request) (*http.Response, error) { return t.base.RoundTrip(r) } -// Get — shortcut untuk GET request +func (t *uaTransport) CloseIdleConnections() { + closeIdleConnections(t.base) +} + +// closeIdler — RoundTripper yang mendukung penutupan koneksi idle. +type closeIdler interface { + CloseIdleConnections() +} + +// closeIdleConnections meneruskan CloseIdleConnections ke transport di bawahnya. +func closeIdleConnections(rt http.RoundTripper) { + if c, ok := rt.(closeIdler); ok { + c.CloseIdleConnections() + } +} + +// Get — shortcut untuk GET request tanpa context. func (c *Client) Get(url string) (*http.Response, error) { - req, err := http.NewRequest(http.MethodGet, url, nil) + return c.GetContext(context.Background(), url) +} + +// GetContext — shortcut GET yang bisa dibatalkan lewat context. +func (c *Client) GetContext(ctx context.Context, url string) (*http.Response, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return nil, fmt.Errorf("bikin request: %w", err) } @@ -93,3 +133,8 @@ func (c *Client) Get(url string) (*http.Response, error) { func (c *Client) Do(req *http.Request) (*http.Response, error) { return c.http.Do(req) } + +// CloseIdleConnections — tutup semua koneksi idle milik client. +func (c *Client) CloseIdleConnections() { + c.http.CloseIdleConnections() +} diff --git a/client_test.go b/client_test.go index f60d403..46c65c0 100644 --- a/client_test.go +++ b/client_test.go @@ -2,11 +2,13 @@ package myhttp import ( "context" + "errors" "io" "net/http" "net/http/httptest" "net/url" "strings" + "sync" "sync/atomic" "testing" "time" @@ -47,19 +49,22 @@ func TestRetryOn5xx(t *testing.T) { // TestUserAgent — memastikan UA ter-inject func TestUserAgent(t *testing.T) { - var gotUA string + gotUA := make(chan string, 1) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gotUA = r.Header.Get("User-Agent") + gotUA <- r.Header.Get("User-Agent") w.WriteHeader(200) })) defer server.Close() client := New(WithUserAgent("shinobi-bot/1.0")) - resp, _ := client.Get(server.URL) + resp, err := client.Get(server.URL) + if err != nil { + t.Fatalf("request gagal: %v", err) + } defer resp.Body.Close() - if gotUA != "shinobi-bot/1.0" { - t.Errorf("UA = %q, mau %q", gotUA, "shinobi-bot/1.0") + if ua := <-gotUA; ua != "shinobi-bot/1.0" { + t.Errorf("UA = %q, mau %q", ua, "shinobi-bot/1.0") } } @@ -102,7 +107,10 @@ func TestRateLimit(t *testing.T) { client := New(WithRateLimit(5)) // 5 req/detik = 200ms/req start := time.Now() for i := 0; i < 3; i++ { - resp, _ := client.Get(server.URL) + resp, err := client.Get(server.URL) + if err != nil { + t.Fatalf("request #%d gagal: %v", i+1, err) + } resp.Body.Close() } elapsed := time.Since(start) @@ -112,14 +120,92 @@ func TestRateLimit(t *testing.T) { } } +// TestAttemptTimeout — satu attempt yang hang harus dipotong, lalu retry. +func TestAttemptTimeout(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + <-r.Context().Done() // tunggu client membatalkan request + })) + defer server.Close() + + client := New( + WithRetry(1, 10*time.Millisecond), + WithAttemptTimeout(50*time.Millisecond), + WithTimeout(5*time.Second), + ) + + start := time.Now() + _, err := client.Get(server.URL) + elapsed := time.Since(start) + + if err == nil { + t.Fatal("harusnya error karena semua attempt timeout") + } + + 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 elapsed > 3*time.Second { + t.Errorf("terlalu lama: %v (timeout per attempt tidak bekerja)", elapsed) + } +} + +// TestGetContextCanceled — GetContext harus menghormati context yang dibatalkan. +func TestGetContextCanceled(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + client := New(WithRetry(0, 0), WithTimeout(5*time.Second)) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + if _, err := client.GetContext(ctx, server.URL); err == nil { + t.Fatal("harusnya error karena context dibatalkan") + } +} + +// closeIdleSpy — transport palsu untuk memastikan CloseIdleConnections diteruskan. +type closeIdleSpy struct{ closed bool } + +func (s *closeIdleSpy) RoundTrip(*http.Request) (*http.Response, error) { + return nil, errors.New("tidak dipakai") +} + +func (s *closeIdleSpy) CloseIdleConnections() { s.closed = true } + +// TestCloseIdleConnectionsChain — CloseIdleConnections harus sampai ke transport dasar. +func TestCloseIdleConnectionsChain(t *testing.T) { + spy := &closeIdleSpy{} + transport := &uaTransport{ + base: newRateLimitTransport(&retryTransport{base: spy}, 1), + userAgent: "test/1.0", + } + + transport.CloseIdleConnections() + if !spy.closed { + t.Error("CloseIdleConnections tidak diteruskan sampai transport dasar") + } + + // Client nyata tidak boleh panic. + New().CloseIdleConnections() +} + // TestRetryPostBody — Memastikan body POST tidak hilang saat retry // PENTING: HARUS aktifkan WithRetryPOST(true) agar test ini jalan func TestRetryPostBody(t *testing.T) { var attempts int32 + var mu sync.Mutex var receivedBody string server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) + mu.Lock() receivedBody = string(body) + mu.Unlock() n := atomic.AddInt32(&attempts, 1) if n < 3 { w.WriteHeader(http.StatusInternalServerError) // Paksa retry @@ -146,8 +232,11 @@ func TestRetryPostBody(t *testing.T) { if resp.StatusCode != 200 { t.Errorf("Status = %d, mau 200", resp.StatusCode) } - if receivedBody != `{"pair":"ethidr"}` { - t.Errorf("Body hilang saat retry! Diterima: %q", receivedBody) + mu.Lock() + gotBody := receivedBody + mu.Unlock() + if gotBody != `{"pair":"ethidr"}` { + t.Errorf("Body hilang saat retry! Diterima: %q", gotBody) } } diff --git a/ratelimit.go b/ratelimit.go index f668c36..0615e7b 100644 --- a/ratelimit.go +++ b/ratelimit.go @@ -42,3 +42,7 @@ func (t *rateLimitTransport) RoundTrip(req *http.Request) (*http.Response, error return t.base.RoundTrip(req) } + +func (t *rateLimitTransport) CloseIdleConnections() { + closeIdleConnections(t.base) +} diff --git a/retry.go b/retry.go index f5e1e18..4fcf846 100644 --- a/retry.go +++ b/retry.go @@ -148,6 +148,10 @@ func (t *retryTransport) RoundTrip(req *http.Request) (*http.Response, error) { return nil, &RetryError{Attempts: attempts, StatusCode: lastStatus, Err: lastErr} } +func (t *retryTransport) CloseIdleConnections() { + closeIdleConnections(t.base) +} + // RetryError — error yang dikembalikan ketika semua attempt gagal. // Gunakan errors.As untuk mengambil detailnya. type RetryError struct {