Documentation
¶
Overview ¶
Package httpx builds the HTTP client every network call goes through: a disk cache with ETag revalidation, retries with backoff, a per-host concurrency and rate limit, and a guard that stops at an exhausted GitHub rate limit.
Index ¶
- Constants
- Variables
- func CATransport(caFile string) (http.RoundTripper, error)
- func CredentialHeaders() []string
- func Get(ctx context.Context, hc *http.Client, rawURL string, header http.Header) ([]byte, http.Header, error)
- func New(o Options) *http.Client
- func SameOrigin(base, next string) bool
- func TTL(age time.Duration) time.Duration
- func WithAnonymousToken(ctx context.Context) context.Context
- func WithVariant(ctx context.Context, key string, ttl time.Duration) context.Context
- type AgeFunc
- type Cache
- func (c *Cache) Clear() (Removed, error)
- func (c *Cache) Close() error
- func (c *Cache) Info() (Info, error)
- func (c *Cache) LogSummary(ctx context.Context)
- func (c *Cache) Prune(olderThan time.Duration) (Removed, error)
- func (c *Cache) Stats() CacheStats
- func (c *Cache) Wrap(next http.RoundTripper) http.RoundTripper
- type CacheOptions
- type CacheStats
- type Info
- type Limit
- type Mode
- type Options
- type RateLimitError
- type Removed
- type StatusError
Constants ¶
const GitHubAPIHost = "api.github.com"
GitHubAPIHost is the host of the GitHub REST and GraphQL APIs.
const OSVHost = "api.osv.dev"
OSVHost is the host of the OSV API, whose batch query is a read-only POST.
Variables ¶
var ( ErrNotFound = errors.New("not found") )
Errors wrapped by Get for answers that aren't a success.
var ErrOffline = errors.New("not in the cache")
ErrOffline is returned for a request that --offline can't answer from the cache.
var ErrRateLimited = errors.New("rate limit reached")
ErrRateLimited is wrapped by RateLimitError.
Functions ¶
func CATransport ¶
func CATransport(caFile string) (http.RoundTripper, error)
CATransport returns the default transport trusting the PEM certificates in caFile on top of the system pool, for Options.Transport. SSL_CERT_FILE works this way on macOS and Windows too.
func CredentialHeaders ¶ added in v0.11.0
func CredentialHeaders() []string
CredentialHeaders returns the request headers that carry a token: Authorization, and GitLab's PRIVATE-TOKEN and JOB-TOKEN.
func Get ¶ added in v0.11.0
func Get(ctx context.Context, hc *http.Client, rawURL string, header http.Header) ([]byte, http.Header, error)
Get sends a GET for rawURL with header through hc and returns the body and headers of a 2xx answer. Any other answer is a *StatusError.
func New ¶
New returns a client that retries, limits and logs every request. Without o.RetryPOST, a POST is retried only when the server refused it with 429 or a Retry-After, so a create is never sent twice.
func SameOrigin ¶ added in v0.11.0
SameOrigin reports whether next has the scheme and host of base, so a client follows a pagination link only where its token belongs.
func TTL ¶
TTL returns how long an entry stays fresh when the newest thing it describes is age old: 1 hour under 7 days, 1 day under 6 months, else 10 days. An unknown (negative) age gets 1 hour.
func WithAnonymousToken ¶ added in v0.11.0
WithAnonymousToken marks requests made with ctx as carrying an anonymous token, such as an image registry's pull token, so the cache keys them like requests without a token and --offline still finds them.
func WithVariant ¶ added in v0.13.0
WithVariant makes requests sent with ctx cache under a key that also holds key, and stay fresh for ttl. A caller that knows a resource's version, such as an OSV record's modified time, passes it as key: a new version misses the cache instead of reading the old entry.
Types ¶
type AgeFunc ¶
AgeFunc returns the newest timestamp in a response body, such as the newest release's publish date, or the zero time when there is none.
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache is a disk cache for GET and GraphQL POST responses. It keeps an allowlist of response headers and never stores request headers, so tokens stay out of it.
func NewCache ¶
func NewCache(o CacheOptions) *Cache
NewCache returns a cache. Zero options get defaults.
func (*Cache) LogSummary ¶
LogSummary logs the counters at debug level.
func (*Cache) Prune ¶
Prune deletes entries not used for olderThan, unreadable entries, leftover temporary files and entries in an old format. Expired entries stay, since their validators make 304s possible.
func (*Cache) Wrap ¶
func (c *Cache) Wrap(next http.RoundTripper) http.RoundTripper
Wrap puts the cache in front of next, for Options.Wrap. A nil cache returns next.
type CacheOptions ¶
type CacheOptions struct {
Dir string // entries live in Dir/http; empty turns the cache off
Mode Mode
Clock func() time.Time
Logger *slog.Logger
TTLOverride map[string]time.Duration // by host; replaces the age-based TTL
Age AgeFunc // nil means only Last-Modified dates an entry
}
CacheOptions configures NewCache.
type CacheStats ¶
type CacheStats struct {
Requests int64 // sent to the network
NotModified int64 // of Requests, answered 304
Hits int64 // answered from the cache without a request
Stored int64 // new or replaced entries
}
CacheStats counts what the cache did.
type Info ¶
type Info struct {
Dir string `json:"dir"`
Entries int `json:"entries"`
Bytes int64 `json:"bytes"`
Fresh int `json:"fresh"`
Stale int `json:"stale"`
}
Info describes the cache on disk.
type Limit ¶
type Limit struct {
Concurrency int // requests in flight at once
Rate float64 // requests per second; 0 means no rate limit
}
Limit is the request budget for one host.
func DefaultLimits ¶
DefaultLimits returns the per-host limits: 8 concurrent requests to the GitHub API, 4 elsewhere.
type Options ¶
type Options struct {
Logger *slog.Logger
Transport http.RoundTripper // nil means a pooled transport that honours proxy variables
UserAgent string
Limits map[string]Limit // by host
Default Limit // hosts not in Limits
RetryMax int
RetryWaitMin time.Duration
RetryWaitMax time.Duration
Clock func() time.Time
RetryPOST bool // POSTs are reads, such as GraphQL queries, and may be resent
Wrap func(http.RoundTripper) http.RoundTripper // outermost layer, such as a cache; nil means none
// SecretPathHosts are hosts whose URL path is a secret, such as hooks.slack.com; logs show
// their paths as [redacted].
SecretPathHosts []string
}
Options configures New.
type RateLimitError ¶
RateLimitError says that a host refused a request because its rate limit is used up.
func (*RateLimitError) Error ¶
func (e *RateLimitError) Error() string
func (*RateLimitError) Is ¶
func (e *RateLimitError) Is(target error) bool
Is makes errors.Is(err, ErrRateLimited) true.
type Removed ¶
type Removed struct {
Dir string `json:"dir"`
Entries int `json:"entries"`
Bytes int64 `json:"bytes"`
}
Removed says what Cache.Clear or Cache.Prune deleted.
type StatusError ¶ added in v0.11.0
StatusError is an answer Get doesn't treat as a success.
func (*StatusError) Error ¶ added in v0.11.0
func (e *StatusError) Error() string
func (*StatusError) Is ¶ added in v0.11.0
func (e *StatusError) Is(target error) bool
Is makes 404 and 410 match ErrNotFound, and 401 and 403 match ErrUnauthorized.