fleetfetch

package
v0.111.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 23 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package fleetfetch is the canonical caller-side client for go-infrastructure-fetch-cache.0exec.com — the fleet-wide HTTP fetch cache. Use it from any producer that fetches a user-supplied URL for analysis (HTML scrapers, structured-data extractors, tech fingerprinters, etc.).

Without fleetfetch, every producer in a domainscope-style fanout does its own HTTPS fetch of the target URL — 20 producers per categorize request = 20× redundant upstream traffic, 20 slightly- different snapshots of the page, and 20× chances of being blocked or rate-limited by the origin.

With fleetfetch, the first producer to ask for a given URL triggers one upstream fetch via the cache; the other 19 receive the same cached bytes microseconds later (singleflight collapse on the cache side). All 20 producers analyze identical bytes. Origin sees one request from the fleet, not twenty.

Drop-in usage for HTML-fetching producers

Before (each producer does its own fetch):

client := safehttp.NewClient(
    safehttp.WithTimeout(10*time.Second),
    safehttp.WithUserAgent(ua.Build(ServiceID, Version)),
)
resp, err := client.Get(ctx, url)

After (producer routes through the shared cache):

client := fleetfetch.NewClient(
    fleetfetch.WithAPIKey(os.Getenv("FLEET_API_KEY")),
)
r, err := client.Get(ctx, url)
// r.Body is the upstream body; r.Hit / r.AgeSeconds tell you
// whether you saved an upstream round-trip.

When NOT to use fleetfetch

  • Authenticated fetches where the caller supplies session cookies or auth headers (the cache can't safely share those between callers).
  • Non-idempotent operations (POST, PUT, DELETE).
  • Crawlers fetching one-shot unique URLs (cache hit rate = 0%).
  • Live probe semantics where freshness < cache TTL matters (port scans, http3 detection, live RBL lookups).

For those, keep using safehttp directly.

Resilience

If the cache itself returns an untyped 5xx, rejects the request (4xx with no X-FetchCache-* headers), or is unreachable at the transport level (connection refused / DNS / no route), fleetfetch transparently falls back to a direct safehttp.NewClient fetch (with SSRF guard intact). The caller sees that degradation through Response.ViaFallback and metric result="fallback". An upstream 5xx carrying X-FetchCache-Fetched-At is instead returned as-is so negative caching is not defeated.

A canonical load_shed 503 is also distinct from an outage. Default/static fetches may degrade to equivalent direct bytes, but rendered modes return ErrRenderBusy (metric result="busy") with Retry-After preserved on the typed *RenderBusyError. This prevents a saturated renderer from causing one unshared direct origin request per waiting service and prevents raw HTML from being mistaken for post-JS evidence.

A *slow* cache is treated differently from a *dead* one. When the request to the cache exceeds the client timeout — typically a cold miss while the cache fetches a slow origin — the default is NOT to fall back: direct-fetching the same slow origin would hit the same latency, bypass the cache's singleflight de-dup, and register as direct egress (proxy bypass). Instead Get returns ErrCacheTimeout (metric result="timeout"), which the caller can retry against a now-warming cache. Opt into best-effort direct fetch on timeout with WithFallbackOnTimeout when a body matters more than avoiding egress.

Response size

A Client keeps at most DefaultMaxBodyBytes (32 MiB) of a response body, whichever path served it. A longer body is cut there and Response.Truncated is set; the fetch is not an error. WithMaxBodyBytes sets another limit, the environment variable FLEET_FETCH_MAX_BODY_BYTES changes it for clients that set none, and WithUnboundedBody (or the variable at 0) removes it, which is discouraged: the pages a scraper fetches are chosen by strangers, and one oversized response then takes all of a worker's memory.

Endpoint

Default endpoint is http://go_infrastructure_fetch_cache:18205 — the cache container's Docker DNS name, reachable from containers on the same Docker network without the public gateway or an environment proxy. The configured service API key is still sent. The internal cache hop bypasses environment proxies and, when Fleet Graph is enabled with a writer key, is recorded as a service-to-service call.

External callers (outside the fleet network) should override with the public gateway URL via env:

export FLEET_FETCH_CACHE_URL=https://infrastructure-fetch-cache.0exec.com
export FLEET_FETCH_CACHE_API_KEY_FILE=/run/secrets/fetch-cache-api-key

Cross-host callers should use a service-scoped API key and the configured proxy_egress route. Internal callers also send the key required by the fetch-cache service's current access policy.

Index

Constants

View Source
const (
	// RenderDefault sends no render param — the cache uses its
	// SSRF-safe direct fetch (pre-v0.2 behavior). Cheapest; lowest
	// latency; no JS execution.
	RenderDefault = ""
	// RenderJS asks the cache to route through go-js-proxy (chromedp).
	// Returns post-JS DOM. Falls back through go-html-proxy and
	// finally direct if either proxy is unhealthy. Cache key is
	// distinct from default so JS-rendered and curl shapes don't
	// collide.
	RenderJS = "js"
	// RenderHTML asks the cache to route through go-html-proxy
	// (Webshare egress + UA rotation). No JS execution. Cheaper than
	// js but still better than direct for origins that block fleet IPs.
	RenderHTML = "html"
	// RenderJSNetwork asks the cache to route through go-js-proxy-network
	// (chromedp). Returns the post-JS DOM as the body PLUS the full
	// outbound network request log on the X-FetchCache-Network response
	// header. Use FetchNetwork to get the DOM + parsed []NetworkEntry in
	// one call. Cache key is distinct from js/default. Requires
	// go_infrastructure_fetch_cache v0.3+; older caches ignore the param
	// and serve the default shape (no network log).
	RenderJSNetwork = "js-network"
)

Render mode wire constants. These are the values sent as ?render=<mode> to go_infrastructure_fetch_cache v0.2+. Older caches ignore the param and serve the default (direct) shape, so clients can opt in without coordinating a fleet-wide cache upgrade.

View Source
const DefaultMaxBodyBytes int64 = 32 << 20

DefaultMaxBodyBytes is the most of a response body a Client keeps unless it is told otherwise (WithMaxBodyBytes, WithUnboundedBody, or EnvMaxBodyBytes): 32 MiB. Bytes past it are dropped and Response.Truncated is set; the fetch is not an error.

Why 32 MiB: it is what this module already applies to fetch-proxy responses (client.DefaultBodyCap), and it is above every limit that a fleet service chose for a page or a JSON reply when it set one with WithMaxBodyBytes (1 to 5 MiB for almost all of the 50 or so call sites, 8 MiB for three; one image fetcher takes 12) and above jsbundle.DefaultMaxScriptBytes (8 MiB). A lower figure would cut documents that are legitimately large and are read by callers that do not look at Truncated: the sitemap protocol allows 50 MiB uncompressed, and a silent cut at 8 MiB breaks sitemap and large-feed fetchers. A response of any size now costs at most this much memory (the read buffer can grow to about twice that while it fills). It is a ceiling for memory, not a promise about content: a service that parses larger documents says so with WithMaxBodyBytes (a sitemap fetcher that wants the full 50 MiB: 50<<20) or WithUnboundedBody.

View Source
const DefaultURL = "http://go_infrastructure_fetch_cache:18205"

DefaultURL is the canonical fleet fetch-cache endpoint, addressed by Docker container DNS so producers in the same Docker network reach it without going through the public gateway (no public TLS handshake or proxy_egress detour through Webshare). The client still sends its configured service API key.

Override at runtime via the FLEET_FETCH_CACHE_URL env var or per client via WithCacheURL. External callers (outside the fleet network) should set the env to the public URL:

FLEET_FETCH_CACHE_URL=https://infrastructure-fetch-cache.0exec.com
View Source
const EnvAPIKey = "FLEET_FETCH_CACHE_API_KEY"

EnvAPIKey is the env var name read by NewClient when no WithAPIKey is set.

View Source
const EnvAPIKeyFile = "FLEET_FETCH_CACHE_API_KEY_FILE"

EnvAPIKeyFile is a read-only mounted-secret path used when neither WithAPIKey nor EnvAPIKey supplies a credential.

View Source
const EnvCacheURL = "FLEET_FETCH_CACHE_URL"

EnvCacheURL is the env var name read by NewClient when no WithCacheURL is set.

View Source
const EnvMaxBodyBytes = "FLEET_FETCH_MAX_BODY_BYTES"

EnvMaxBodyBytes overrides DefaultMaxBodyBytes for every Client that does not set its own limit with an option: a positive number of bytes is the limit, and 0 means no limit at all, which is discouraged (a single response from a hostile or broken site can then take all of a worker's memory). An unparsable or negative value is ignored, with one log line.

View Source
const EnvSource = "FLEET_FETCH_SOURCE"

EnvSource is the process-wide default source read by NewClient when no request-scoped source or explicit WithSource option overrides it. Supported values are "live" and "commoncrawl". Common Crawl remains archive-only: a missing capture or cache error never falls back to live origin traffic.

View Source
const ForwardHeaderPrefix = "X-FF-Forward-"

ForwardHeaderPrefix prefixes any caller-supplied per-request header sent to the fleet fetch cache. The cache strips this prefix and re-attaches the header to the upstream request, while also folding it into the cache key so that different header sets (e.g. Accept: application/rdap+json vs. default) don't collide.

View Source
const NetworkHeader = "X-FetchCache-Network"

NetworkHeader is the response header the fetch cache emits (js-network mode) carrying the JSON-encoded network log. Exported so consumers that hold a raw *Response can re-parse it without re-deriving the name.

View Source
const PublicURL = "https://infrastructure-fetch-cache.0exec.com"

PublicURL is the externally-resolvable HTTPS endpoint exposed at the gateway. Use it when calling from outside the fleet's Docker network. Use a scoped X-API-Key on internal and public paths. The internal DefaultURL avoids the public proxy but does not bypass auth.

Variables

View Source
var (
	ErrCacheTimeout = errors.New("fleetfetch: cache request timed out")

	// ErrCacheAuth is returned when the cache itself rejects this client's
	// credential with 401 or 403. It is terminal for the Client: because the
	// API key cannot change after construction, the client opens an auth
	// circuit and subsequent calls fail fast until a new Client is created.
	ErrCacheAuth = errors.New("fleetfetch: cache authentication rejected")

	// ErrRenderBusy is the sentinel wrapped by *RenderBusyError when the
	// fetch cache explicitly sheds a rendered request. It is distinct from
	// a cache transport outage and from an upstream 503 replayed by the
	// cache. Callers may use errors.Is(err, ErrRenderBusy), then errors.As
	// to inspect Retry-After without parsing an error string.
	ErrRenderBusy = errors.New("fleetfetch: renderer at capacity")

	// ErrProxyConnectForbidden means the fallback HTTP proxy rejected the
	// CONNECT tunnel with a target-policy 403. This is not a fetch-cache
	// failure, even when a preceding cache 502 is also present in the chain.
	ErrProxyConnectForbidden = errors.New("fleetfetch: proxy CONNECT forbidden by target policy")
)

ErrCacheTimeout is returned by Get when the call to the fetch cache exceeds the client timeout and WithFallbackOnTimeout was not set. It signals "the cache is reachable but slow" (typically a cold miss on a slow origin), as distinct from "the cache is down" (which still transparently falls back to a direct fetch). Callers can retry — a second attempt usually lands on a now-warm cache entry.

Functions

func FromContext

func FromContext(ctx context.Context, req *http.Request) *http.Request

FromContext is a convenience for handlers that want to ensure the outbound request inherits the inbound request's context (for cancellation + deadline propagation). Use when calling resp, err := client.Do(req.WithContext(ctx)).

func NewHTTPClient

func NewHTTPClient(opts ...Option) *http.Client

NewHTTPClient returns a standard *http.Client whose RoundTripper routes every GET through the fleet fetch cache. For Common Crawl source, HEAD is represented by an archive GET and its body is suppressed. Other non-GET requests fall through to the default transport so the caller can keep using the same client for POST/PUT without a code path split.

This is the drop-in retrofit shape for services that currently use safehttp.NewClient or net/http.Client.Get + .Do(req): swap the constructor, keep every other line. resp.Body / resp.StatusCode / resp.Header / resp.Request.URL all behave like an ordinary HTTP response, but the bytes come from Redis when the URL is already cached at the requested render mode.

client := fleetfetch.NewHTTPClient(
    fleetfetch.WithRender(fleetfetch.RenderJS),
    fleetfetch.WithTimeout(15*time.Second),
)
resp, err := client.Get("https://stripe.com")
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)

The returned client has CheckRedirect set to refuse following redirects — the cache resolves the final URL upstream and stores it as Response.FinalURL, which this adapter surfaces via resp.Request.URL. Following them on the consumer side would re-fetch without the cache and lose the share.

Per-request headers attached via http.Request.Header are forwarded to the upstream fetch using the same X-FF-Forward-* prefix shape the cache expects, so the cache key includes them and entries with different headers don't conflate.

func SetDefaultCaller

func SetDefaultCaller(id string)

SetDefaultCaller sets the process-wide X-Fleet-Caller value. Idempotent and safe for concurrent use. server.New calls this automatically from AppName; call it directly only when building fleetfetch clients without the standard server and unable to set FLEET_SERVICE_ID in the environment. An empty or all-invalid id clears the default (header is then omitted unless an env fallback or per-client WithCaller applies).

func SetDefaultObserver

func SetDefaultObserver(o Observer)

SetDefaultObserver installs a process-wide observer. Pass nil to disable. Wired by promx.AutoWire.

func SetTimeout

func SetTimeout(httpClient *http.Client, d time.Duration)

SetTimeout updates the underlying *http.Client.Timeout AND the fleetfetch client's per-request timeout. Useful when a service builds the client once at init and later wants to tighten the window for a specific call path.

Goroutine-safety note: this mutates the *http.Client. Don't call it concurrently with in-flight requests.

func WithRequestSource

func WithRequestSource(ctx context.Context, source Source) context.Context

WithRequestSource attaches a per-inbound-request fetch source to ctx. The server package uses this after validating the source query parameter.

Types

type CacheAuthError

type CacheAuthError struct {
	StatusCode  int
	CircuitOpen bool
}

CacheAuthError describes a cache-side 401/403. CircuitOpen is true on calls rejected locally after an earlier authentication failure; false on the first response received from the cache.

func (*CacheAuthError) Error

func (e *CacheAuthError) Error() string

func (*CacheAuthError) Unwrap

func (e *CacheAuthError) Unwrap() error

Unwrap makes errors.Is(err, ErrCacheAuth) work while errors.As retains the status and whether the error came from the open circuit.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client wraps the HTTP plumbing for talking to the fleet fetch cache, with transparent fallback to a SSRF-safe direct fetch when the cache is unreachable. Safe for concurrent use.

func NewClient

func NewClient(opts ...Option) *Client

NewClient returns a Client wired with sensible defaults. Reads FLEET_FETCH_SOURCE, FLEET_FETCH_CACHE_URL and either FLEET_FETCH_CACHE_API_KEY or the protected FLEET_FETCH_CACHE_API_KEY_FILE path when corresponding options aren't given. Explicit options override environment defaults.

func (*Client) FetchNetwork

func (c *Client) FetchNetwork(ctx context.Context, targetURL string) (*Response, []NetworkEntry, error)

FetchNetwork fetches targetURL with render=js-network and returns the rendered DOM (Response.Body) together with the page's outbound network request log parsed from the X-FetchCache-Network header. One render per (url, js-network) is shared fleet-wide via the cache, so the FIRST caller of a given domain pays the cold-render cost (up to ~60s) and every subsequent caller gets a cache hit (~ms) with the same log replayed.

This is the consumer-facing API for request-fingerprint detection: a detector calls FetchNetwork(domain) and walks the returned []NetworkEntry URLs for tool signatures (GA /g/collect, api.segment.io, *.ingest.sentry.io).

The returned slice is nil (not an error) when the cache served a non-network shape — e.g. an older cache that doesn't honor js-network, or a fallback to a DOM-only renderer when go-js-proxy-network was unhealthy. Callers should treat a nil/empty log as "no network signal available", not as a hard failure (the DOM in Response.Body is still usable). Inspect Response.Render / Response.Via to tell whether the network renderer actually served the request.

On cache-unreachable fallback (Response.ViaFallback == true) there is no network log — the direct SSRF fetch can't capture one — so the slice is nil. The error is non-nil only on a genuine fetch failure.

func (*Client) Get

func (c *Client) Get(ctx context.Context, targetURL string) (*Response, error)

Get fetches targetURL through the cache. Genuine cache-service/network failures fall back to a direct SSRF-safe fetch. Cached upstream failures are returned as-is, and typed load shedding for rendered modes returns ErrRenderBusy rather than silently substituting unrendered bytes.

func (*Client) GetFromSource

func (c *Client) GetFromSource(ctx context.Context, targetURL string, source Source) (*Response, error)

GetFromSource fetches a URL from the selected source with default rendering.

func (*Client) GetRendered

func (c *Client) GetRendered(ctx context.Context, targetURL string, mode string) (*Response, error)

GetRendered fetches targetURL with a per-call render override. Pass RenderJS / RenderHTML / RenderDefault. Useful when the client-wide default doesn't fit a particular call (e.g. a JS-rendering client that needs a single cheap default-mode lookup).

func (*Client) GetWithHeaders

func (c *Client) GetWithHeaders(ctx context.Context, targetURL string, headers http.Header) (*Response, error)

GetWithHeaders is Get with per-request headers forwarded to the upstream fetch. Headers are sent to the cache prefixed with ForwardHeaderPrefix; the cache strips the prefix, attaches them to the upstream request, and includes them in the cache key so requests with different header sets don't share an entry.

Default headers configured via WithDefaultHeaders are merged in first; per-request headers win on collisions. Pass nil to get the same behavior as Get.

func (*Client) GetWithMaxAge

func (c *Client) GetWithMaxAge(ctx context.Context, targetURL string, maxAge time.Duration) (*Response, error)

GetWithMaxAge is Get with an explicit max-age override (in seconds on the wire). maxAge=0 = use cache default (60s).

func (*Client) SourceForRequest

func (c *Client) SourceForRequest(ctx context.Context) Source

SourceForRequest returns the source this client will use for ctx, applying explicit client configuration before a request-scoped override and the environment-derived default. It lets adapters preserve source-specific failure semantics without duplicating fleetfetch's precedence rules.

func (*Client) Stats

func (c *Client) Stats() Stats

type Doer

type Doer interface {
	Get(ctx context.Context, targetURL string) (*Response, error)
	GetWithMaxAge(ctx context.Context, targetURL string, maxAge time.Duration) (*Response, error)
	GetWithHeaders(ctx context.Context, targetURL string, headers http.Header) (*Response, error)
}

Doer is the minimal interface a producer can hold for HTTP fetching. Production code holds a *Client; tests can swap in a stub that points at an httptest.NewServer-style loopback URL. The migrator emits `var fetchClient fleetfetch.Doer = fleetfetch.NewClient(...)` so that the test-only assignment compiles.

*Client and *LoopbackClient both satisfy Doer.

type Event

type Event struct {
	Host       string // hostname of the targetURL (not the cache)
	Result     string
	Status     int
	AgeSeconds int
	Duration   time.Duration
	// Truncated is true when the response handed back was cut at the body limit.
	Truncated bool
}

Event is the per-fetch payload handed to an Observer.

Result is one of:

"hit"       — served from the cache, X-FetchCache-Hit=true
"miss"      — cache fetched upstream then returned to us
"fallback"  — cache unreachable (5xx / rejected / transport
              failure); we direct-fetched via safehttp
"timeout"   — cache reachable but too slow; we did NOT fall back
              (unless WithFallbackOnTimeout) — distinct from
              "fallback" so a slow cache doesn't pollute the
              direct-egress / proxy-bypass metric
"busy"      — cache explicitly shed a rendered request; no direct
              fallback was attempted because it would change semantics
"error"     — both cache and fallback failed, or caller context done
"direct"    — WithoutCache client: cache deliberately skipped, fetched
              direct via the proxy-aware path (returned a response).
              Kept distinct from "hit"/"miss" so by-design cache-bypass
              traffic never reads as cache activity on a dashboard.
"direct_error" — WithoutCache client: the direct fetch itself failed
              (DNS / transport / timeout to origin). Distinct from
              "error" — the cache was never involved.

type LoopbackClient

type LoopbackClient struct {
	HTTP *http.Client
}

LoopbackClient is a Doer for unit tests. It wraps a stdlib *http.Client (typically `httptest.Server.Client()`) and issues direct GETs — no cache, no SSRF guard. Use ONLY in tests. Construct via NewLoopbackClient.

func NewLoopbackClient

func NewLoopbackClient(h *http.Client) *LoopbackClient

NewLoopbackClient returns a Doer that talks directly to URLs via the given *http.Client. Pass nil to use http.DefaultClient.

Typical use in handler_test.go:

srv := httptest.NewServer(...)
defer srv.Close()
prev := fetchClient
fetchClient = fleetfetch.NewLoopbackClient(srv.Client())
defer func() { fetchClient = prev }()

This replaces the pre-migration idiom of swapping the safehttp httpClient.

func (*LoopbackClient) Get

func (l *LoopbackClient) Get(ctx context.Context, targetURL string) (*Response, error)

Get implements Doer.

func (*LoopbackClient) GetWithHeaders

func (l *LoopbackClient) GetWithHeaders(ctx context.Context, targetURL string, headers http.Header) (*Response, error)

GetWithHeaders implements Doer.

func (*LoopbackClient) GetWithMaxAge

func (l *LoopbackClient) GetWithMaxAge(ctx context.Context, targetURL string, _ time.Duration) (*Response, error)

GetWithMaxAge implements Doer. maxAge is ignored — there is no cache.

type NetworkEntry

type NetworkEntry struct {
	URL          string `json:"url"`
	Method       string `json:"method"`
	Status       int    `json:"status"`
	ResourceType string `json:"resource_type"`
	Initiator    string `json:"initiator"`
}

NetworkEntry is one row of the outbound network log captured for a JS-rendered page by go-js-proxy-network and surfaced through the fetch cache on the X-FetchCache-Network header. The field set + JSON tags match go-common/client.NetworkEntry's fingerprint subset: request-fingerprint detectors (analytics / martech / error-monitoring) identify a tool by the URLs a page calls (GA /g/collect, Segment api.segment.io, Sentry *.ingest.sentry.io) even when the loader is bundled/minified — walk these entries' URLs to detect them.

type Observer

type Observer interface {
	ObserveFleetFetch(Event)
}

Observer receives one event per Client.fetch call. Implementations MUST NOT block — callbacks run inline on the producer hot path. The canonical implementation lives in go-common/promx and records fleet_fetch_total / latency / cache-age metrics.

fleetfetch deliberately defines the contract here rather than importing a metrics library: fleetfetch keeps zero metric-stack deps.

func DefaultObserver

func DefaultObserver() Observer

DefaultObserver returns the current process-wide observer or nil.

type Option

type Option func(*Client)

Option configures a Client.

func WithAPIKey

func WithAPIKey(k string) Option

WithAPIKey sets the X-API-Key header sent to the cache. Default order: WithAPIKey → FLEET_FETCH_CACHE_API_KEY env → FLEET_FETCH_CACHE_API_KEY_FILE → none. Cross-host and public-gateway callers should use a service-scoped key from a protected secret source.

func WithCacheURL

func WithCacheURL(u string) Option

WithCacheURL overrides the cache endpoint. Default order: WithCacheURL → FLEET_FETCH_CACHE_URL env → DefaultURL.

func WithCaller

func WithCaller(id string) Option

WithCaller sets the X-Fleet-Caller header this client sends to the fetch cache, identifying the calling service so downstream renderers (go-js-proxy / go-html-proxy) can attribute render load per-enricher. Overrides the process default (SetDefaultCaller) and the env fallback. Most services need not set this: server.New seeds the default from AppName, which every fleetfetch client in the process then inherits.

func WithDefaultHeaders

func WithDefaultHeaders(h http.Header) Option

WithDefaultHeaders sets headers attached to every fetch issued by this client. Per-request headers passed to GetWithHeaders override these on a per-name basis. Common use: a fleet-wide User-Agent or Accept-Language. Values are forwarded through the cache (and therefore included in the cache key) so the cache won't conflate requests with different default headers.

func WithFallbackClient

func WithFallbackClient(h *http.Client) Option

WithFallbackClient replaces the default safehttp-based fallback client. Provide your own if you need a custom user-agent / proxy / observability wrapper on the SSRF-safe path.

func WithFallbackOnTimeout

func WithFallbackOnTimeout() Option

WithFallbackOnTimeout makes a slow cache (a cache request that exceeds the client timeout) fall back to a direct SSRF-safe fetch, the same as a dead cache. Off by default: a timeout usually means the cache is mid-fetch of a slow origin, so direct-fetching the same origin would hit the same latency AND bypass the cache's singleflight de-dup. Leaving this off keeps slow-cache events out of the "direct egress / proxy bypass" metric (they're reported as result="timeout", not result="fallback"). Turn it on only when a best-effort body matters more than avoiding redundant egress.

func WithMaxBodyBytes

func WithMaxBodyBytes(n int64) Option

WithMaxBodyBytes sets the most of a response body the client keeps, for both cache responses and direct fallback responses. Without it the limit is EnvMaxBodyBytes, else DefaultMaxBodyBytes (32 MiB). A longer body is cut at n bytes and Response.Truncated is set; the fetch is not turned into an error. A non-positive n is ignored (the limit stays the default): it used to mean "unlimited", which is now spelled WithUnboundedBody so that nobody gets it by passing an unset configuration value.

A caller that wants to know a body was over its own limit can ask for n+1 bytes and compare len(Body) with n, as many do, or read Response.Truncated.

func WithRender

func WithRender(mode string) Option

WithRender pins the upstream renderer for every fetch issued by this client. Accepts "" (default, direct fetch), "js" (chromedp via go-js-proxy), or "html" (Webshare egress via go-html-proxy). When the cache's allow/deny policy refuses the requested mode for a given host, the cache silently downgrades to direct — the client can inspect Response.Header.Get("X-FetchCache-Render") to tell which mode actually served.

Default unset → no ?render= query param sent → cache uses its pre-v0.2 direct path. Existing producers don't need any code change.

func WithSource

func WithSource(source Source) Option

WithSource selects live fetching (default) or a Common Crawl archive capture. It pins this client, overriding request-scoped source and FLEET_FETCH_SOURCE.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the per-request timeout for both the cache-side call and the fallback direct fetch. Default 15s. This bounds how long a cold miss (where the cache fetches a slow origin) may take before the cache call is considered a timeout — set it generously enough that a normal cold-miss upstream fetch completes inside the cache call rather than tripping ErrCacheTimeout. See WithFallbackOnTimeout for the slow-cache behavior.

Worst-case latency of a single Get/fetch call is up to 2×d, not d, when WithFallbackOnTimeout is also set: a slow cache call runs for the full d before directFetch takes over, and directFetch then opens its own fresh d-length window rather than sharing what's left of the caller's budget. This is deliberate — the cache attempt and the direct fallback are treated as two independent, fully-timed attempts, not one attempt split across a shared budget (see TestGet_CacheTimeout_FallsBackWhenOptedIn / TestNewHTTPClient_SlowCacheFallsBackNot502 in client_test.go, which pin this as intended behavior). Callers that wrap Get in their own ctx.WithTimeout — or derive a caller-side timeout constant from d — must budget for 2×d, not d, or they will see their own context expire mid-fallback and misread it as a fleetfetch bug. Confirmed live 2026-07-05/06 across multiple consumer services (go_domain_open_source_presence, go_domain_tech_eol_flagger, go_api_extractor, go_domain_mobile_app_resolver, go_seasonal_detector, go_cdn_detector) that each independently doubled their own timeout constants after hitting this.

func WithUnboundedBody

func WithUnboundedBody() Option

WithUnboundedBody removes the response-body limit for this client: every body is read whole, whatever its size. It is the explicit opt-out from DefaultMaxBodyBytes and discouraged. A scraping client reads pages that strangers choose, and one multi-gigabyte response then takes all of a worker's memory. Prefer WithMaxBodyBytes with the largest body the service can use. It overrides EnvMaxBodyBytes; the last of it and WithMaxBodyBytes wins.

func WithoutCache

func WithoutCache() Option

WithoutCache makes the client skip the fetch cache entirely: every Get goes straight to the SSRF-safe, proxy-aware direct fetch (via the fallback client, which honors HTTP(S)_PROXY for proxy_egress services).

Use for services that probe speculative, mostly-nonexistent, or one-shot URLs — e.g. a docs-platform detector guessing developer.<dom>.com for every input. Routing those through the cache pays a Docker-internal round-trip AND pollutes the shared cache + its singleflight with throwaway lookups that no other service will ever reuse. WithoutCache turns the call into a single direct fetch instead.

The Response shape is unchanged (Body/Status/FinalURL/Header), with ViaFallback=true to mark that it took the direct path. WithRender has no effect under WithoutCache — rendering requires the cache's headless renderer; a direct fetch returns raw origin bytes. Cacheable, shareable work (e.g. a JS render worth warming once per domain) should keep using a normal cache client.

Observability: these fetches emit fleet_fetch_total with result="direct" (returned a response) or "direct_error" (the direct fetch failed) — never "hit"/"miss"/"fallback"/"error", so by-design cache-bypass traffic is always distinguishable from real cache activity on a dashboard.

type ProxyConnectForbiddenError

type ProxyConnectForbiddenError struct{}

ProxyConnectForbiddenError is returned when the fallback transport receives a clear HTTP-proxy CONNECT 403. Its stable message deliberately omits proxy endpoints, target URLs, and untrusted response text.

func (*ProxyConnectForbiddenError) Error

func (*ProxyConnectForbiddenError) IsProxyConnectForbidden

func (*ProxyConnectForbiddenError) IsProxyConnectForbidden() bool

func (*ProxyConnectForbiddenError) Unwrap

type RenderBusyError

type RenderBusyError struct {
	StatusCode int
	RetryAfter string
	Message    string
}

RenderBusyError preserves the structured load-shed response returned by the fetch cache. RetryAfter is the exact wire value (seconds or HTTP-date) so a coordinator can propagate it without losing information.

func (*RenderBusyError) Error

func (e *RenderBusyError) Error() string

func (*RenderBusyError) RetryDelay

func (e *RenderBusyError) RetryDelay(now time.Time) (time.Duration, bool)

RetryDelay converts Retry-After into a non-negative delay. Both forms allowed by RFC 9110 are accepted: integer seconds and an HTTP date.

func (*RenderBusyError) Unwrap

func (e *RenderBusyError) Unwrap() error

Unwrap makes errors.Is(err, ErrRenderBusy) work while retaining typed Retry-After details through errors.As.

type Response

type Response struct {
	Status int
	Header http.Header
	Body   []byte
	// Truncated is true when the body was longer than the client's limit
	// (DefaultMaxBodyBytes, WithMaxBodyBytes, EnvMaxBodyBytes) and Body holds only
	// its first bytes. Header, including Content-Length, still describes the whole
	// response. The fetch itself succeeded: a caller that cannot use a partial body
	// checks this, and one that needs larger bodies raises the limit.
	Truncated   bool
	FinalURL    string
	Hit         bool      // true if served from cache
	AgeSeconds  int       // age of the cached entry; 0 on miss
	UpstreamMS  int64     // time the original upstream fetch took
	FetchedAt   time.Time // when the cached entry was created
	ViaFallback bool      // true if cache was unreachable and we direct-fetched via safehttp

	// Render reports the renderer mode the cache actually honored
	// for this response. May differ from the requested mode if the
	// cache's allow/deny policy downgraded the request (e.g. asked
	// for "js" but the host wasn't on the allow list → cache served
	// "" / default). Empty string for older caches that don't emit
	// X-FetchCache-Render.
	Render string
	// Via reports which renderer produced this response on a cache
	// miss: "direct", "js-proxy", or "html-proxy". Empty on cache
	// hits (the cache doesn't remember which renderer originally
	// served the cached entry) and on older caches.
	Via string
}

Response is the result of a fetch. Body is the upstream body verbatim; the cache-side metadata is broken out into typed fields so callers can log hit rates without parsing headers themselves.

type Source

type Source string

Source selects the origin of response bytes, independently of Render mode. CommonCrawl returns archived HTTP captures and must never trigger live fallback.

const (
	SourceLive        Source = ""
	SourceCommonCrawl Source = "commoncrawl"
)

func ParseSource

func ParseSource(value string) (Source, error)

ParseSource validates a source name accepted by the source query parameter.

func RequestSourceFromContext

func RequestSourceFromContext(ctx context.Context) (Source, bool)

RequestSourceFromContext returns a request-scoped fetch source when one is present. SourceLive is the empty string, so the bool distinguishes an explicit live override from the absence of a request override.

type Stats

type Stats struct {
	Hits      int64
	Misses    int64
	Fallbacks int64
	Timeouts  int64
	Errors    int64
	// Truncated counts responses whose body was cut at the limit.
	Truncated int64
}

Stats returns a snapshot of the client's lifetime counters. Useful for /metrics exposition or debug endpoints.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL