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
- 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 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 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 Crawler
- func (c *Crawler) AllowsRobotsBypass(host string) bool
- 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) SetRobotsBypassHosts(hosts []string)
- type FetchCall
- type FetchReply
- type Options
- type Request
- type Result
- type Summary
- type Timing
Constants ¶
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 )
const ( MaxRequestsPerCall = 400 MaxCallBodyBytes = 1 << 20 // 1 MiB request payload ceiling DefaultMaxSeconds = 600 MaxMaxSeconds = 1800 MaxConcurrentServerCalls = 4 )
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 ¶
Bool returns a pointer to v for configuring optional tri-state boolean fields on Options.
func CallLogger ¶
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 ¶
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 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 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 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) 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 ¶
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.
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) 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"`
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 ¶
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`.
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`.