crawl

package
v2.7.8 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 32 Imported by: 0 modules, 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 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

View Source
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
)
View Source
const (
	MaxRequestsPerCall       = 400
	MaxCallBodyBytes         = 1 << 20 // 1 MiB request payload ceiling
	DefaultMaxSeconds        = 600
	MaxMaxSeconds            = 1800
	MaxConcurrentServerCalls = 4
)
View Source
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

func Bool(v bool) *bool

Bool returns a pointer to v for configuring optional tri-state boolean fields on Options.

func CallLogger

func CallLogger(base *slog.Logger, h http.Header) *slog.Logger

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

func NewHandler(c *Crawler, allow func(*url.URL) error) http.Handler

NewHandler constructs an unauthenticated HTTP router (/healthz, /fetch) for loopback or isolated container bridges.

func PublicHTTPS

func PublicHTTPS(u *url.URL) error

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

func RedactEmbeddedURLs(s string) string

RedactEmbeddedURLs delegates to `politeness.RedactEmbeddedURLs` so crawl logs, `Result.Problem`, and OTel spans share 100% identical linear-time URL and credential redaction.

func SleepCtx

func SleepCtx(ctx context.Context, d time.Duration) error

SleepCtx pauses for `d` or returns early when `ctx` cancels, freeing the underlying timer immediately via `defer t.Stop()`.

func ValidateCall

func ValidateCall(call FetchCall, allow func(*url.URL) error) (code, msg string, ok bool)

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

func ValidateCustomHeaders(hdrs map[string]string) error

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

func ValidateUserAgent(ua string) error

ValidateUserAgent ensures a configured `User-Agent` is non-empty printable ASCII with zero CR/LF header-injection bytes.

func WithAllowedHosts

func WithAllowedHosts(base func(*url.URL) error, hosts []string) func(*url.URL) error

WithAllowedHosts restricts base to exact or subdomain matches of hosts when hosts contains non-empty entries.

func WithBlockedHost

func WithBlockedHost(base func(*url.URL) error, blockedHost string) func(*url.URL) error

WithBlockedHost wraps base so an outbound agent can never be instructed to recursively fetch its own coordination hub.

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

func (c *Crawler) AllowsRobotsBypass(host string) bool

AllowsRobotsBypass reports whether `host` matches the owner's explicit `robots_bypass_hosts` allowlist.

func (*Crawler) BrowserInfo added in v2.6.0

func (c *Crawler) BrowserInfo() (string, string)

BrowserInfo returns the detected headless Chromium version and OS sandbox state ("on", "off", or "unknown").

func (*Crawler) Capabilities

func (c *Crawler) Capabilities() []string

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

func (c *Crawler) Close() error

Close shuts down any running headless Chromium subprocess, loopback SSRF proxy, and OTLP exporter.

func (*Crawler) Logger

func (c *Crawler) Logger() *slog.Logger

Logger exposes the crawler's base structured logger.

func (*Crawler) Run

func (c *Crawler) Run(ctx context.Context, reqs []Request, opts Options) []Result

Run executes `reqs` with `c.log` and returns results in exact input order.

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

func (c *Crawler) SetAllowNoSandboxBrowser(allow bool)

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

func (c *Crawler) SetBotSigner(s *botauth.Signer)

SetBotSigner attaches an optional IETF RFC 9421 Ed25519 Web Bot Auth request signer.

func (*Crawler) SetOtelExporter

func (c *Crawler) SetOtelExporter(exp *otel.Exporter)

SetOtelExporter attaches an optional non-blocking OpenTelemetry OTLP/HTTP span exporter.

func (*Crawler) SetRenderer

func (c *Crawler) SetRenderer(r *browser.Renderer)

SetRenderer replaces the browser renderer (used by unit tests with mock CDP WebSockets).

func (*Crawler) SetRobotsBypassHosts

func (c *Crawler) SetRobotsBypassHosts(hosts []string)

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`.

func (*Crawler) WarmUp added in v2.6.0

func (c *Crawler) WarmUp(ctx context.Context) error

WarmUp verifies crawler HTTP client readiness and probes headless browser version/sandbox state when configured.

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

func ExecuteCall(ctx context.Context, c *Crawler, call FetchCall, log *slog.Logger) FetchReply

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) Normalize

func (o Options) Normalize() Options

Normalize clamps out-of-range or zero fields on a value copy of Options.

func (Options) RobotsEnabled

func (o Options) RobotsEnabled() bool

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

func (r Result) DecodeBody() ([]byte, error)

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

type ResultSink func(idx int, res Result) Result

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`.

func Summarize

func Summarize(results []Result) Summary

Summarize computes `Summary` counts over `results`.

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`.

Jump to

Keyboard shortcuts

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