Documentation
¶
Overview ¶
Package crawl implements a bounded-concurrency, polite HTTP/2 batch fetcher with `net/http/httptrace` phase telemetry, hop-by-hop redirect validation, conditional GETs, `/llms.txt` companion Markdown discovery, and strict memory/SSRF guardrails.
Design Highlights ¶
- Hop-by-hop redirect checks: `http.Client.CheckRedirect` returns `http.ErrUseLastResponse` so every `301`/`302`/`307`/`308` Location target re-verifies PublicHTTPS SSRF rules, per-host locks, `Retry-After` cooldowns, and `/robots.txt` rules on the destination domain.
- Socket reuse under body caps: reads `io.LimitReader(resp.Body, maxBytes+1)` so oversized streams close cleanly while normal responses drain to EOF and return warm HTTP/2 connections to the pool.
- Disk-streamed large PDFs: on Fat nodes, PDFs up to 256 MiB stream directly to an unlinked temporary file so Poppler `pdftotext` seeks the EOF `xref` table without spiking Go's `GOMEMLIMIT` heap.
Index ¶
- Constants
- func Bool(v bool) *bool
- func CallLogger(base *slog.Logger, h http.Header) *slog.Logger
- func NewAuthenticatedHandler(c *Crawler, allow func(*url.URL) error, bearerToken string) http.Handler
- func NewHandler(c *Crawler, allow func(*url.URL) error) http.Handler
- func PublicHTTPS(u *url.URL) error
- func RedactEmbeddedURLs(s string) string
- func SleepCtx(ctx context.Context, d time.Duration) error
- func ValidateCall(call FetchCall, allow func(*url.URL) error) (code, msg string, ok bool)
- func ValidateCallWithCrawler(c *Crawler, call FetchCall, allow func(*url.URL) error) (code, msg string, ok bool)
- func ValidateCustomHeaders(hdrs map[string]string) error
- func ValidateUserAgent(ua string) error
- func WithAllowedHosts(base func(*url.URL) error, hosts []string) func(*url.URL) error
- func WithBlockedHost(base func(*url.URL) error, blockedHost string) func(*url.URL) error
- type ArtifactRef
- type Crawler
- func (c *Crawler) AllowsRobotsBypass(host string) bool
- func (c *Crawler) BrowserInfo() (string, string)
- func (c *Crawler) Capabilities() []string
- func (c *Crawler) Close() error
- func (c *Crawler) Logger() *slog.Logger
- func (c *Crawler) Run(ctx context.Context, reqs []Request, opts Options) []Result
- func (c *Crawler) RunLogged(ctx context.Context, reqs []Request, opts Options, log *slog.Logger) []Result
- func (c *Crawler) RunWithSink(ctx context.Context, reqs []Request, opts Options, log *slog.Logger, ...) []Result
- func (c *Crawler) SetAllowNoSandboxBrowser(allow bool)
- func (c *Crawler) SetBotSigner(s *botauth.Signer)
- func (c *Crawler) SetOtelExporter(exp *otel.Exporter)
- func (c *Crawler) SetRenderer(r *browser.Renderer)
- func (c *Crawler) SetRobotsBypassHosts(hosts []string)
- func (c *Crawler) WarmUp(ctx context.Context) error
- type FetchCall
- type FetchReply
- func ExecuteCall(ctx context.Context, c *Crawler, call FetchCall, log *slog.Logger) FetchReply
- func ExecuteCallWithSink(ctx context.Context, c *Crawler, call FetchCall, log *slog.Logger, ...) FetchReply
- func ExecuteCallWithTrace(ctx context.Context, c *Crawler, call FetchCall, traceHdr http.Header, ...) FetchReply
- type InteractSpec
- type Options
- type Request
- type Result
- type ResultSink
- type Summary
- type Timing
Constants ¶
const ( DefaultPauseMs = 2000 MaxPauseJitterMs = 30_000 DefaultTimeoutMs = 30_000 MaxTimeoutMs = 120_000 DefaultMaxBytes = 8 << 20 MaxMaxBytes = 16 << 20 MaxStreamingPDFBytes = 64 << 20 // 64 MiB default disk-streamed PDF ceiling (override via EDGEFETCH_MAX_PDF_BYTES) DefaultMaxTotalBytes = 16 << 20 // 16 MiB batch body ceiling stays safely below Hub's 20 MiB reply cap & 128 MiB GOMEMLIMIT MaxMaxTotalBytes = 18 << 20 MaxConcurrency = 4 MaxRetries = 3 MaxRedirects = 5 )
const ( MaxRequestsPerCall = 400 MaxCallBodyBytes = 1 << 20 // 1 MiB request payload ceiling DefaultMaxSeconds = 600 MaxMaxSeconds = 1800 MaxConcurrentServerCalls = 4 )
const DefaultUserAgent = "EdgeFetch/2.7 (bot@edgefetch.dev)"
DefaultUserAgent is sent when no custom User-Agent is configured. Always identify crawlers honestly (includes contact mailto for SEC EDGAR Fair Access & OpenAlex/Crossref/NCBI Polite Pools).
Variables ¶
This section is empty.
Functions ¶
func Bool ¶
Bool returns a pointer to v for configuring optional tri-state boolean fields on Options.
func CallLogger ¶
CallLogger attaches sanitized distributed trace identifiers (including W3C `traceparent`) onto `base`.
func NewAuthenticatedHandler ¶
func NewAuthenticatedHandler(c *Crawler, allow func(*url.URL) error, bearerToken string) http.Handler
NewAuthenticatedHandler constructs the HTTP router (/healthz, /fetch) for server mode. When bearerToken is non-empty, POST /fetch requires a constant-time verified Authorization: Bearer <token> header.
func NewHandler ¶
NewHandler constructs an unauthenticated HTTP router (/healthz, /fetch) for loopback or isolated container bridges.
func PublicHTTPS ¶
PublicHTTPS enforces the baseline SSRF URL invariant: https on port 443 with a multi-label DNS hostname (never an IP literal, localhost, or credentialed user:pass@ URL). Paired with politeness.RejectNonPublicPeer at dial time.
func RedactEmbeddedURLs ¶ added in v2.5.5
RedactEmbeddedURLs delegates to `politeness.RedactEmbeddedURLs` so crawl logs, `Result.Problem`, and OTel spans share 100% identical linear-time URL and credential redaction.
func SleepCtx ¶
SleepCtx pauses for `d` or returns early when `ctx` cancels, freeing the underlying timer immediately via `defer t.Stop()`.
func ValidateCall ¶
ValidateCall checks batch bounds, `Accept` kinds, URL rules, and default `robots.txt` enforcement before network IO.
func ValidateCallWithCrawler ¶
func ValidateCallWithCrawler(c *Crawler, call FetchCall, allow func(*url.URL) error) (code, msg string, ok bool)
ValidateCallWithCrawler validates `call`, rejecting `respectRobots: false` unless every target host is explicitly allowlisted on `c` via `SetRobotsBypassHosts` (off by default).
func ValidateCustomHeaders ¶
ValidateCustomHeaders enforces strict header-injection and hop-by-hop/auth header guards on caller-supplied headers. Safe domain headers pass; `Host`, `Authorization`, `Cookie`, `Proxy-*`, `CF-*`, `X-Forwarded-*`, and control bytes fail closed.
func ValidateUserAgent ¶
ValidateUserAgent ensures a configured `User-Agent` is non-empty printable ASCII with zero CR/LF header-injection bytes.
func WithAllowedHosts ¶
WithAllowedHosts restricts base to exact or subdomain matches of hosts when hosts contains non-empty entries.
Types ¶
type ArtifactRef ¶
type ArtifactRef struct {
BlobSHA256 string `json:"blobSha256"`
ContentSHA256 string `json:"contentSha256"`
ContentBytes int `json:"contentBytes"`
StoredBytes int `json:"storedBytes"`
Encoding string `json:"encoding"`
Retention string `json:"retention"`
}
ArtifactRef references a gzipped response body uploaded directly to R2 (`PUT /agent/artifacts/<blobSha256>`) so large page bodies never pass through the `AgentHubDO` Durable Object or accumulate in batch RAM.
type Crawler ¶
type Crawler struct {
// Injectable clock/sleep/jitter hooks make multi-second pacing tests run in < 1 ms without mocking frameworks.
Sleep func(ctx context.Context, d time.Duration) error
Now func() time.Time
Jitter func(d time.Duration) time.Duration
// contains filtered or unexported fields
}
Crawler executes polite, rate-limited HTTP GET batches. Never copy a `Crawler` value after creation (`sync.Mutex` fields must stay at a fixed address).
func NewCrawler ¶
func NewCrawler(transport http.RoundTripper, allow func(*url.URL) error, userAgent string, log *slog.Logger) *Crawler
NewCrawler constructs a `Crawler` whose HTTP redirects are handled hop-by-hop (re-checking URL rules, per-host locks, pacing, and `/robots.txt` on every redirect hop).
func (*Crawler) AllowsRobotsBypass ¶
AllowsRobotsBypass reports whether `host` matches the owner's explicit `robots_bypass_hosts` allowlist.
func (*Crawler) BrowserInfo ¶ added in v2.6.0
BrowserInfo returns the detected headless Chromium version and OS sandbox state ("on", "off", or "unknown").
func (*Crawler) Capabilities ¶
Capabilities returns the runtime feature tokens advertised in `X-Agent-Capabilities` (`artifacts-v1`, plus `browser-v1` when Chromium is present and `pdf-v1` when Poppler `pdftotext` is installed).
func (*Crawler) Close ¶
Close shuts down any running headless Chromium subprocess, loopback SSRF proxy, and OTLP exporter.
func (*Crawler) RunLogged ¶
func (c *Crawler) RunLogged(ctx context.Context, reqs []Request, opts Options, log *slog.Logger) []Result
RunLogged executes `reqs` using a request-scoped structured logger (carrying distributed trace IDs).
func (*Crawler) RunWithSink ¶
func (c *Crawler) RunWithSink(ctx context.Context, reqs []Request, opts Options, log *slog.Logger, sink ResultSink) []Result
RunWithSink executes `reqs` and invokes optional `sink(i, res)` immediately as each fetch finishes so streaming artifact uploaders can free `res.Body` before subsequent URLs execute.
func (*Crawler) SetAllowNoSandboxBrowser ¶ added in v2.7.4
SetAllowNoSandboxBrowser configures whether the headless Chromium renderer may run with `--no-sandbox` when host AppArmor/seccomp policy blocks unprivileged user namespaces (e.g. Home Assistant OS opt-in).
func (*Crawler) SetBotSigner ¶
SetBotSigner attaches an optional IETF RFC 9421 Ed25519 Web Bot Auth request signer.
func (*Crawler) SetOtelExporter ¶
SetOtelExporter attaches an optional non-blocking OpenTelemetry OTLP/HTTP span exporter.
func (*Crawler) SetRenderer ¶
SetRenderer replaces the browser renderer (used by unit tests with mock CDP WebSockets).
func (*Crawler) SetRobotsBypassHosts ¶
SetRobotsBypassHosts configures the owner-controlled host allowlist permitted to set `respectRobots: false`. By default this list is empty, meaning `/robots.txt` is always enforced even if a caller sends `respectRobots: false`.
type FetchCall ¶
type FetchCall struct {
Requests []Request `json:"requests"`
Options Options `json:"options"`
MaxSeconds int `json:"maxSeconds"`
}
FetchCall is the wire payload accepted by `POST /fetch` and WebSocket `dispatch`.
type FetchReply ¶
type FetchReply struct {
Results []Result `json:"results"`
Summary Summary `json:"summary"`
DurationMs int64 `json:"durationMs"`
}
FetchReply is the wire payload returned by `POST /fetch` and uploaded to `POST /agent/reply`.
func ExecuteCall ¶
ExecuteCall enforces `MaxSeconds`, runs `c.RunLogged`, and logs batch summary metrics.
func ExecuteCallWithSink ¶
func ExecuteCallWithSink(ctx context.Context, c *Crawler, call FetchCall, log *slog.Logger, sink ResultSink) FetchReply
ExecuteCallWithSink enforces `MaxSeconds`, runs `c.RunWithSink`, and logs batch summary metrics.
func ExecuteCallWithTrace ¶
func ExecuteCallWithTrace(ctx context.Context, c *Crawler, call FetchCall, traceHdr http.Header, log *slog.Logger, sink ResultSink) FetchReply
ExecuteCallWithTrace enforces `MaxSeconds`, executes `call`, logs batch summary metrics, and emits stitched W3C OTLP spans when `c` has an OpenTelemetry exporter configured.
type InteractSpec ¶
type InteractSpec struct {
SessionID string `json:"sessionId,omitempty"`
KeepSession bool `json:"keepSession,omitempty"`
CloseSession bool `json:"closeSession,omitempty"`
Actions []browser.InteractAction `json:"actions,omitempty"`
}
InteractSpec configures stateful or single-turn headless Chromium interaction (`firecrawl_interact` parity).
type Options ¶
type Options struct {
PauseMs int `json:"pauseMs"`
PauseJitterMs int `json:"pauseJitterMs,omitempty"`
GapMs int `json:"gapMs"`
Concurrency int `json:"concurrency"`
TimeoutMs int `json:"timeoutMs"`
MaxBytes int `json:"maxBytes"`
MaxTotalBytes int `json:"maxTotalBytes,omitempty"`
Retries int `json:"retries"`
IncludeBody bool `json:"includeBody"`
DiscoverLlms *bool `json:"discoverLlms,omitempty"`
RespectRobots *bool `json:"respectRobots,omitempty"`
// Robots is accepted as a wire alias for RespectRobots. When both are omitted, Normalize() defaults to true.
Robots *bool `json:"robots,omitempty"`
}
Options bounds a crawl batch. Zero values take safe defaults in Normalize() (including RespectRobots = true).
func (Options) RobotsEnabled ¶
RobotsEnabled reports whether /robots.txt enforcement is active (defaulting to true when unset).
type Request ¶
type Request struct {
ID string `json:"id"`
URL string `json:"url"`
Method string `json:"method,omitempty"` // "GET" (default) or "POST" (e.g. Workday CXS JSON search)
RequestBody string `json:"requestBody,omitempty"` // Optional UTF-8 POST body when Method == "POST"
ContentType string `json:"contentType,omitempty"` // Optional Content-Type header when Method == "POST"
Kind classify.Kind `json:"kind"`
KindAuto bool `json:"kindAuto,omitempty"`
Accept string `json:"accept,omitempty"`
IfNoneMatch string `json:"ifNoneMatch,omitempty"`
IfModifiedSince string `json:"ifModifiedSince,omitempty"`
Formats []string `json:"formats,omitempty"`
OnlyMainContent *bool `json:"onlyMainContent,omitempty"`
DiscoverLlms *bool `json:"discoverLlms,omitempty"`
PreferLlmsMarkdown *bool `json:"preferLlmsMarkdown,omitempty"`
RedactPII bool `json:"redactPii,omitempty"`
Query string `json:"query,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
RenderMode string `json:"renderMode,omitempty"` // "off" (default), "auto", "always"
Mobile bool `json:"mobile,omitempty"`
ViewportWidth int `json:"viewportWidth,omitempty"`
ViewportHeight int `json:"viewportHeight,omitempty"`
ScreenshotFullPage bool `json:"screenshotFullPage,omitempty"`
ScreenshotQuality int `json:"screenshotQuality,omitempty"`
AcceptLanguage string `json:"acceptLanguage,omitempty"`
WaitForMs int `json:"waitForMs,omitempty"`
WaitSelector string `json:"waitSelector,omitempty"`
MaxPages int `json:"maxPages,omitempty"`
Interact *InteractSpec `json:"interact,omitempty"`
}
Request describes a single URL to fetch within a batch.
type Result ¶
type Result struct {
ID string `json:"id"`
URL string `json:"url"`
Kind classify.Kind `json:"kind"`
Outcome classify.Outcome `json:"outcome"`
BlockedReason string `json:"blockedReason,omitempty"`
Problem string `json:"problem,omitempty"`
Status int `json:"status"`
ContentType string `json:"contentType,omitempty"`
ContentSource string `json:"contentSource,omitempty"`
ResponseHeaders map[string]string `json:"headers,omitempty"`
CfMitigated string `json:"cfMitigated,omitempty"`
WAF *classify.WAFMatch `json:"waf,omitempty"`
ETag string `json:"etag,omitempty"`
LastModified string `json:"lastModified,omitempty"`
RetryAfter string `json:"retryAfter,omitempty"`
RetryAfterMs int64 `json:"retryAfterMs,omitempty"`
Bytes int `json:"bytes"`
Truncated bool `json:"truncated,omitempty"`
BodyOmitted bool `json:"bodyOmitted,omitempty"`
Attempts int `json:"attempts"`
DurationMs int64 `json:"durationMs"`
Timing Timing `json:"timing"`
Body string `json:"body,omitempty"`
BodyEncoding string `json:"bodyEncoding,omitempty"`
Artifact *ArtifactRef `json:"artifact,omitempty"`
ArtifactError string `json:"artifactError,omitempty"`
FinalURL string `json:"finalUrl,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Favicon string `json:"favicon,omitempty"`
Markdown string `json:"markdown,omitempty"`
Text string `json:"text,omitempty"`
Links []string `json:"links,omitempty"`
Images []extract.ImageInfo `json:"images,omitempty"`
Branding *extract.BrandingProfile `json:"branding,omitempty"`
Llms *extract.LlmsDiscovery `json:"llms,omitempty"`
Rendered bool `json:"rendered,omitempty"`
SessionID string `json:"sessionId,omitempty"`
ScreenshotBase64 string `json:"screenshotBase64,omitempty"`
ActionScreenshots []string `json:"actionScreenshots,omitempty"`
ActionScrapes []browser.ActionScrapeSnapshot `json:"actionScrapes,omitempty"`
JavascriptReturns []browser.ActionJSReturn `json:"javascriptReturns,omitempty"`
ActionResults []browser.ActionResult `json:"actionResults,omitempty"`
CapturedJSON []browser.CapturedJSONResponse `json:"capturedJson,omitempty"`
PDFBase64 string `json:"pdfBase64,omitempty"`
PDFEngine string `json:"pdfEngine,omitempty"`
SHA256 string `json:"sha256,omitempty"`
BodyBase64 string `json:"bodyBase64,omitempty"`
// contains filtered or unexported fields
}
Result reports the outcome, headers of interest, phase timings, and optional body or R2 artifact of one `Request`.
func (Result) DecodeBody ¶
DecodeBody returns the exact raw response bytes for `r.Body`, decoding `"base64"` payloads losslessly when the origin response contained non-UTF-8 bytes.
type ResultSink ¶
ResultSink transforms an individual `Result` as soon as its fetch completes (for example, uploading its body to R2 and releasing `res.Body` from memory before the next URL in the batch runs).
type Summary ¶
type Summary struct {
Total int `json:"total"`
ByOutcome map[string]int `json:"byOutcome"`
ByStatus map[string]int `json:"byStatus"`
}
Summary aggregates outcome and status-code histograms across a `FetchReply`.
type Timing ¶
type Timing struct {
DNSMs int64 `json:"dnsMs"`
ConnectMs int64 `json:"connectMs"`
TLSMs int64 `json:"tlsMs"`
TTFBMs int64 `json:"ttfbMs"`
RobotsMs int64 `json:"robotsMs,omitempty"`
ArtifactUploadMs int64 `json:"artifactUploadMs,omitempty"`
Reused bool `json:"reused"`
RemoteAddr string `json:"remoteAddr,omitempty"`
Proto string `json:"proto,omitempty"`
}
Timing records where a single HTTP attempt spent wall-clock milliseconds via Go's `net/http/httptrace` hooks. When `Reused == true` (warm HTTP/2 or keep-alive socket), `DNSMs`, `ConnectMs`, and `TLSMs` are `0`.