crawl

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 24 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 fetcher with net/http/httptrace phase telemetry, positive dwell jitter, conditional GETs (ETag / If-Modified-Since), and strict memory/SSRF guardrails.

Index

Constants

View Source
const (
	DefaultPauseMs       = 2000
	MaxPauseJitterMs     = 30_000
	DefaultTimeoutMs     = 30_000
	DefaultMaxBytes      = 8 << 20
	MaxMaxBytes          = 16 << 20
	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/1.0 (+https://github.com/bartrumb/edgefetch)"

DefaultUserAgent is sent when no custom User-Agent is configured. Always identify crawlers honestly.

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 onto `base` (blocking log-injection control characters).

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

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.

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"`
	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"`
	Kind            classify.Kind `json:"kind"`
	Accept          string        `json:"accept,omitempty"`
	IfNoneMatch     string        `json:"ifNoneMatch,omitempty"`
	IfModifiedSince string        `json:"ifModifiedSince,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"`
	Problem      string           `json:"problem,omitempty"`
	Status       int              `json:"status"`
	ContentType  string           `json:"contentType,omitempty"`
	CfMitigated  string           `json:"cfMitigated,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"`
}

Result reports the outcome, headers of interest, phase timings, and optional body 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 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"`
	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