|
| 1 | +// Package client provides an HTTP client with retry logic for registry APIs. |
| 2 | +package client |
| 3 | + |
| 4 | +import ( |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "io" |
| 8 | + "math" |
| 9 | + "math/rand" |
| 10 | + "net/http" |
| 11 | + "strconv" |
| 12 | + "time" |
| 13 | +) |
| 14 | + |
| 15 | +// RateLimiter controls request pacing. |
| 16 | +type RateLimiter interface { |
| 17 | + Wait(ctx context.Context) error |
| 18 | +} |
| 19 | + |
| 20 | +// Client is an HTTP client with retry logic for registry APIs. |
| 21 | +type Client struct { |
| 22 | + HTTPClient *http.Client |
| 23 | + UserAgent string |
| 24 | + MaxRetries int |
| 25 | + BaseDelay time.Duration |
| 26 | + RateLimiter RateLimiter |
| 27 | +} |
| 28 | + |
| 29 | +// DefaultClient returns a client with sensible defaults. |
| 30 | +func DefaultClient() *Client { |
| 31 | + return &Client{ |
| 32 | + HTTPClient: &http.Client{ |
| 33 | + Timeout: 30 * time.Second, |
| 34 | + }, |
| 35 | + UserAgent: "registries", |
| 36 | + MaxRetries: 5, |
| 37 | + BaseDelay: 50 * time.Millisecond, |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +// GetJSON fetches a URL and decodes the JSON response into v. |
| 42 | +func (c *Client) GetJSON(ctx context.Context, url string, v any) error { |
| 43 | + body, err := c.GetBody(ctx, url) |
| 44 | + if err != nil { |
| 45 | + return err |
| 46 | + } |
| 47 | + return json.Unmarshal(body, v) |
| 48 | +} |
| 49 | + |
| 50 | +// GetBody fetches a URL and returns the response body. |
| 51 | +func (c *Client) GetBody(ctx context.Context, url string) ([]byte, error) { |
| 52 | + var lastErr error |
| 53 | + |
| 54 | + for attempt := 0; attempt <= c.MaxRetries; attempt++ { |
| 55 | + if attempt > 0 { |
| 56 | + delay := c.BaseDelay * time.Duration(math.Pow(2, float64(attempt-1))) |
| 57 | + jitter := time.Duration(float64(delay) * (rand.Float64() * 0.1)) |
| 58 | + delay += jitter |
| 59 | + |
| 60 | + select { |
| 61 | + case <-ctx.Done(): |
| 62 | + return nil, ctx.Err() |
| 63 | + case <-time.After(delay): |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + if c.RateLimiter != nil { |
| 68 | + if err := c.RateLimiter.Wait(ctx); err != nil { |
| 69 | + return nil, err |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + body, err := c.doRequest(ctx, url) |
| 74 | + if err == nil { |
| 75 | + return body, nil |
| 76 | + } |
| 77 | + |
| 78 | + lastErr = err |
| 79 | + |
| 80 | + var httpErr *HTTPError |
| 81 | + if ok := isHTTPError(err, &httpErr); ok { |
| 82 | + if httpErr.StatusCode == 404 { |
| 83 | + return nil, err |
| 84 | + } |
| 85 | + if httpErr.StatusCode == 429 || httpErr.StatusCode >= 500 { |
| 86 | + continue |
| 87 | + } |
| 88 | + return nil, err |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + return nil, lastErr |
| 93 | +} |
| 94 | + |
| 95 | +func (c *Client) doRequest(ctx context.Context, url string) ([]byte, error) { |
| 96 | + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| 97 | + if err != nil { |
| 98 | + return nil, err |
| 99 | + } |
| 100 | + |
| 101 | + req.Header.Set("User-Agent", c.UserAgent) |
| 102 | + req.Header.Set("Accept", "application/json") |
| 103 | + |
| 104 | + resp, err := c.HTTPClient.Do(req) |
| 105 | + if err != nil { |
| 106 | + return nil, err |
| 107 | + } |
| 108 | + defer func() { _ = resp.Body.Close() }() |
| 109 | + |
| 110 | + body, err := io.ReadAll(resp.Body) |
| 111 | + if err != nil { |
| 112 | + return nil, err |
| 113 | + } |
| 114 | + |
| 115 | + if resp.StatusCode >= 400 { |
| 116 | + httpErr := &HTTPError{ |
| 117 | + StatusCode: resp.StatusCode, |
| 118 | + URL: url, |
| 119 | + Body: string(body), |
| 120 | + } |
| 121 | + if resp.StatusCode == 429 { |
| 122 | + if retryAfter := resp.Header.Get("Retry-After"); retryAfter != "" { |
| 123 | + if seconds, err := strconv.Atoi(retryAfter); err == nil { |
| 124 | + return nil, &RateLimitError{RetryAfter: seconds} |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | + return nil, httpErr |
| 129 | + } |
| 130 | + |
| 131 | + return body, nil |
| 132 | +} |
| 133 | + |
| 134 | +func isHTTPError(err error, target **HTTPError) bool { |
| 135 | + if httpErr, ok := err.(*HTTPError); ok { |
| 136 | + *target = httpErr |
| 137 | + return true |
| 138 | + } |
| 139 | + return false |
| 140 | +} |
| 141 | + |
| 142 | +// GetText fetches a URL and returns the response body as a string. |
| 143 | +func (c *Client) GetText(ctx context.Context, url string) (string, error) { |
| 144 | + body, err := c.GetBody(ctx, url) |
| 145 | + if err != nil { |
| 146 | + return "", err |
| 147 | + } |
| 148 | + return string(body), nil |
| 149 | +} |
| 150 | + |
| 151 | +// Head sends a HEAD request and returns the status code. |
| 152 | +func (c *Client) Head(ctx context.Context, url string) (int, error) { |
| 153 | + req, err := http.NewRequestWithContext(ctx, http.MethodHead, url, nil) |
| 154 | + if err != nil { |
| 155 | + return 0, err |
| 156 | + } |
| 157 | + |
| 158 | + req.Header.Set("User-Agent", c.UserAgent) |
| 159 | + |
| 160 | + resp, err := c.HTTPClient.Do(req) |
| 161 | + if err != nil { |
| 162 | + return 0, err |
| 163 | + } |
| 164 | + _ = resp.Body.Close() |
| 165 | + |
| 166 | + return resp.StatusCode, nil |
| 167 | +} |
| 168 | + |
| 169 | +// WithRateLimiter returns a copy of the client with the given rate limiter. |
| 170 | +func (c *Client) WithRateLimiter(rl RateLimiter) *Client { |
| 171 | + copy := *c |
| 172 | + copy.RateLimiter = rl |
| 173 | + return © |
| 174 | +} |
| 175 | + |
| 176 | +// WithUserAgent returns a copy of the client with the given user agent. |
| 177 | +func (c *Client) WithUserAgent(ua string) *Client { |
| 178 | + copy := *c |
| 179 | + copy.UserAgent = ua |
| 180 | + return © |
| 181 | +} |
| 182 | + |
| 183 | +// Option configures a Client. |
| 184 | +type Option func(*Client) |
| 185 | + |
| 186 | +// WithTimeout sets the HTTP client timeout. |
| 187 | +func WithTimeout(d time.Duration) Option { |
| 188 | + return func(c *Client) { |
| 189 | + c.HTTPClient.Timeout = d |
| 190 | + } |
| 191 | +} |
| 192 | + |
| 193 | +// WithMaxRetries sets the maximum number of retries. |
| 194 | +func WithMaxRetries(n int) Option { |
| 195 | + return func(c *Client) { |
| 196 | + c.MaxRetries = n |
| 197 | + } |
| 198 | +} |
| 199 | + |
| 200 | +// NewClient creates a new client with the given options. |
| 201 | +func NewClient(opts ...Option) *Client { |
| 202 | + c := DefaultClient() |
| 203 | + for _, opt := range opts { |
| 204 | + opt(c) |
| 205 | + } |
| 206 | + return c |
| 207 | +} |
0 commit comments