Documentation
¶
Overview ¶
Package httpclient fetches small and large HTTP resources for repository clients: every body is size-capped, transient failures are retried with jittered exponential backoff, and files are written atomically.
A Client owns one tuned connection pool and one retry policy, both set through Options; share one Client across goroutines. Nothing is configured through package-level state.
Retry classification is exposed as IsRetryable: transport errors, truncated bodies and HTTP 408, 429 and 5xx are retried; 404, certificate failures, size-cap violations and context cancellation are not.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"time"
"github.com/M0Rf30/pkgformat/httpclient"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, "Packages index")
}))
defer srv.Close()
c := httpclient.New(httpclient.Options{
Retry: httpclient.RetryPolicy{Attempts: 3, BaseDelay: 100 * time.Millisecond},
})
body, err := c.FetchBytes(context.Background(), srv.URL, 1<<20)
fmt.Println(string(body), err)
// A body over the cap is an error, never a silent truncation.
_, err = c.FetchBytes(context.Background(), srv.URL, 4)
fmt.Println(errors.Is(err, httpclient.ErrTooLarge))
}
Output: Packages index <nil> true
Index ¶
- Constants
- Variables
- func AtomicWrite(destPath string, fn func(io.Writer) error) error
- func CheckStatus(resp *http.Response, fetchURL string) error
- func IsRetryable(err error) bool
- func LimitedBody(resp *http.Response) io.Reader
- func LimitedBodyN(resp *http.Response, maxBytes int64) io.Reader
- func UpgradeToHTTPS(rawURL string) (string, bool)
- type Client
- func (c *Client) FetchBytes(ctx context.Context, rawURL string, maxBytes int64) ([]byte, error)
- func (c *Client) FetchBytesConditional(ctx context.Context, rawURL string, maxBytes int64, ifModSince time.Time) (body []byte, notModified bool, err error)
- func (c *Client) FetchToFile(ctx context.Context, rawURL, destPath string, maxBytes int64) error
- func (c *Client) HTTP() *http.Client
- func (c *Client) WithRetry(ctx context.Context, label string, fn func() error) error
- func (c *Client) WithRetryPolicy(p RetryPolicy) *Client
- type HTTPStatusError
- type Options
- type RetryPolicy
Examples ¶
Constants ¶
const ( DefaultRetryAttempts = 3 DefaultRetryBaseDelay = 500 * time.Millisecond )
Default retry policy values, applied where a RetryPolicy field is zero.
const DefaultMaxBytes int64 = 2 << 30
DefaultMaxBytes caps individual HTTP responses to 2 GiB when the caller passes no tighter bound. Package indexes are typically a few MB; .deb, .apk and .rpm files top out around a few hundred MB. The cap prevents memory or disk exhaustion from a malicious or buggy mirror serving an unbounded stream.
const DefaultTimeout = 10 * time.Minute
DefaultTimeout bounds a complete HTTP request (connection, TLS handshake, header read, body read) at 10 minutes. Large downloads over slow links still fit; stalled mirrors fail rather than hang.
Variables ¶
var ErrBadLength = errors.New("httpclient: transferred length does not match the announced length")
ErrBadLength is returned when a transfer ends with a different number of bytes than the server announced, or when a resumed partial file does not fit the remote file. It is retryable: the fix is to discard the partial data and start over, which a resumable downloader does before it reports the error.
var ErrTooLarge = errors.New("httpclient: response body exceeds size cap")
ErrTooLarge is returned when a response body exceeds the configured cap.
Functions ¶
func AtomicWrite ¶
AtomicWrite writes to destPath via a unique temp file in the destination directory, fsync and rename, so readers never see a partial file and concurrent writers to the same destination never share a temp file. fn receives a writer for the temp file; if fn returns an error the temp file is removed.
func CheckStatus ¶
CheckStatus returns an *HTTPStatusError if resp.StatusCode is not 2xx. The caller still owns resp.Body.Close().
func IsRetryable ¶
IsRetryable reports whether err looks like a transient network failure worth retrying: transport-level errors (DNS, connection reset or refused, timeouts, mid-body EOF) and HTTP 408, 429 and 5xx responses.
A transfer that ended with the wrong length (ErrBadLength) is retryable too: the retry starts from a clean file. Context cancellation, response-size caps and all other HTTP 4xx codes are not retryable: they are definitive answers, not blips.
func LimitedBody ¶
LimitedBody returns resp.Body capped at DefaultMaxBytes. Reading past the cap fails with ErrTooLarge instead of ending in a silent EOF. The caller still closes resp.Body.
func LimitedBodyN ¶
LimitedBodyN is LimitedBody with a caller-supplied cap. A non-positive cap falls back to DefaultMaxBytes.
func UpgradeToHTTPS ¶
UpgradeToHTTPS rewrites a plain-http URL to https. It returns ok=false for anything that is not parseable http, including URLs already on https.
It helps recover from networks that reset or drop port-80 connections while leaving 443 untouched: many mirrors serve identical content on both schemes, so escalating after a transient http failure is safe.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client fetches size-capped, retried HTTP resources. It is safe for concurrent use and meant to be shared: it owns one connection pool.
func (*Client) FetchBytes ¶
FetchBytes downloads rawURL and returns the body, capped at maxBytes; a body over the cap fails with ErrTooLarge. A non-positive maxBytes falls back to DefaultMaxBytes. Transient failures are retried per the client's RetryPolicy.
func (*Client) FetchBytesConditional ¶
func (c *Client) FetchBytesConditional( ctx context.Context, rawURL string, maxBytes int64, ifModSince time.Time, ) (body []byte, notModified bool, err error)
FetchBytesConditional is like FetchBytes but sends If-Modified-Since when ifModSince is non-zero. On HTTP 304 it returns (nil, true, nil) so the caller can use its on-disk copy. On 200 it returns (data, false, nil). On any other outcome it returns (nil, false, err).
It is the warm-cache primitive that lets a repository client skip re-downloading metadata that has not changed on the server. Transient failures are retried per the client's RetryPolicy.
func (*Client) FetchToFile ¶
FetchToFile downloads rawURL and writes it atomically to destPath, capped at maxBytes. Content-Length is checked as a cheap preflight when available. A non-positive maxBytes falls back to DefaultMaxBytes. Transient failures are retried per the client's RetryPolicy; the atomic temp-file and rename write guarantees a failed attempt leaves no partial file.
func (*Client) HTTP ¶
HTTP returns the underlying *http.Client, for callers that need to issue their own requests over the same connection pool and timeout.
func (*Client) WithRetry ¶
WithRetry runs fn until it succeeds, fails with a non-retryable error, or the client's retry budget is exhausted. label identifies the fetch in retry logs (typically the URL). The last error is returned verbatim so callers can still classify it (errors.As on HTTPStatusError, and so on).
Between attempts WithRetry sleeps an exponentially growing delay with ±25% jitter so concurrent workers hitting the same flaky mirror do not retry in lockstep; cancelling ctx ends the wait.
fn must be safe to re-run from scratch: the Fetch methods re-issue the full request and rewrite their output atomically, so a half-read body from a failed attempt is never observable.
func (*Client) WithRetryPolicy ¶
func (c *Client) WithRetryPolicy(p RetryPolicy) *Client
WithRetryPolicy returns a Client that shares c's connection pool, timeout, user agent and logger but retries according to p.
type HTTPStatusError ¶
HTTPStatusError is returned by CheckStatus when the response is not 2xx. Callers can use errors.As to extract the status code without parsing the Error() string.
func (*HTTPStatusError) Error ¶
func (e *HTTPStatusError) Error() string
Error returns the error message for HTTPStatusError.
func (*HTTPStatusError) IsClientError ¶
func (e *HTTPStatusError) IsClientError() bool
IsClientError reports whether the status is in the 4xx range. Useful for classifying transient repository failures (auth, rate limit, not found) as non-fatal against systemic failures (network, 5xx, disk full).
type Options ¶
type Options struct {
// HTTPClient, when set, is used as is and Timeout and Transport are
// ignored. Leave nil to get a client tuned for metadata-heavy workloads
// (many small fetches against a handful of mirrors).
HTTPClient *http.Client
// Transport replaces the built-in tuned transport.
Transport http.RoundTripper
// Timeout bounds one complete request; zero selects DefaultTimeout and a
// negative value disables the bound (the request context governs).
Timeout time.Duration
// Retry is the transient-failure policy of the Fetch methods.
Retry RetryPolicy
// UserAgent, when non-empty, is sent with every request the Client builds.
UserAgent string
// Logger receives one warning per retried failure. Nil is silent.
Logger *slog.Logger
}
Options configures a Client. The zero value is valid.
type RetryPolicy ¶
type RetryPolicy struct {
// Attempts is the total number of tries, including the first. Zero selects
// DefaultRetryAttempts; 1 disables retrying.
Attempts int
// BaseDelay is the first backoff interval, doubled on every further retry
// and jittered by ±25%. Zero selects DefaultRetryBaseDelay; a negative
// value retries immediately.
BaseDelay time.Duration
}
RetryPolicy controls how a logical fetch is retried on transient failures. The zero value selects the defaults.