Documentation
¶
Overview ¶
Package classify categorizes HTTP status codes, headers, and payload bytes into deterministic crawl outcomes before upstream HTML/JSON/PDF extractors inspect response bodies.
Outcomes & Host Short-Circuiting ¶
Every fetched Kind (`scrape`, `render`, `pdf`, `json`, `feed`, `page`, `text`, `catalog`, `binary`) resolves to one Outcome:
- OutcomeOK: valid 2xx payload matching the expected Kind invariants (for example `%PDF-` magic header on KindPDF or valid RFC 8259 JSON on KindJSON).
- OutcomeChallenge: anti-bot edge mitigation (`cf-mitigated` header) — halts remaining queued URLs for the same host immediately and is never retried.
- OutcomeRateLimited: plain origin `429` (no WAF challenge marker) on every Kind — halts remaining queued URLs for the same host (`not_tried`) and records Retry-After cooldowns in `internal/politeness`.
- OutcomeStop: origin block or overload (`403`, `503`) — halts remaining queued URLs for the same host (`not_tried`).
- OutcomeGone: permanent/missing document (`404`, `410`).
- OutcomeSkip / OutcomeError / OutcomeNotTried: non-fatal skips, transport/schema errors, or short-circuited sibling requests.
Index ¶
- Constants
- func AcceptFor(kind Kind, requested string) (string, error)
- func ApolloRouteSoftRedirect(rawHTML string) (fromPath, toPath string, ok bool)
- func IsAutoPageContentType(contentType string) bool
- func IsDeterministicClientError(status int) bool
- func IsEligibleForWaybackFallback(status int, outcome, wafCategory, urlStr, method string, hasAuthHeaders bool) bool
- func RefineBlockedInfoMap(in RefineBlockedMapInput) map[string]any
- func RetryOnAnotherExecutor(status int, outcome string) bool
- func StopsHost(kind Kind, o Outcome) bool
- type BlockedRefinement
- type ContentStateInput
- type ContentStateResult
- type DetectOnlyResult
- type IframeScanResult
- type Kind
- type Outcome
- type RefineBlockedMapInput
- type WAFChallengeInput
- type WAFMatch
Examples ¶
Constants ¶
const DefaultAgentPageAccept = "text/markdown, text/html;q=0.9, application/xhtml+xml;q=0.8, */*;q=0.7"
DefaultAgentPageAccept negotiates Markdown for Agents first (`G1`), falling back cleanly to HTML.
Variables ¶
This section is empty.
Functions ¶
func AcceptFor ¶
AcceptFor validates `(kind, requestedAccept)` and returns the outbound `Accept` header value.
func ApolloRouteSoftRedirect ¶ added in v2.8.31
ApolloRouteSoftRedirect linearly scans rawHTML (bounded to 2 MiB) for an Apollo `ROOT_QUERY.route(...)` entity carrying a 3xx `redirect_code` whose `relative_url` differs from the requested route URL. It returns the requested and target paths (both with a leading "/") and ok=true only for such a client-side redirect shell.
func IsAutoPageContentType ¶ added in v2.6.0
IsAutoPageContentType reports whether a response `Content-Type` header should be accepted as `OutcomeOK` when a caller omitted an explicit `Kind` (`KindAuto == true`).
func IsDeterministicClientError ¶ added in v2.8.46
IsDeterministicClientError reports whether an origin HTTP status is a 4xx client error that every executor would see identically: the request itself is wrong (unknown resource, bad parameters, forbidden), not the path to the origin. 408 Request Timeout, 425 Too Early and 429 Too Many Requests are excluded because they depend on timing or on the egress IP, so another executor (or a later attempt) can legitimately get a different answer.
func IsEligibleForWaybackFallback ¶ added in v2.8.0
func IsEligibleForWaybackFallback(status int, outcome, wafCategory, urlStr, method string, hasAuthHeaders bool) bool
IsEligibleForWaybackFallback reports whether a failed origin fetch is strictly eligible for Internet Archive (`Wayback CDX`) link-rot recovery: ONLY `5xx` or network/DNS unreachability (`status == 0`) on unauthenticated `GET`/`HEAD` requests — NEVER on `robots.txt`, challenges/WAF, SSRF, `401`, `402`, `403`, `404`, `410`, `429`, or `451`.
func RefineBlockedInfoMap ¶ added in v2.8.0
func RefineBlockedInfoMap(in RefineBlockedMapInput) map[string]any
RefineBlockedInfoMap post-processes `baseBlocked` map metadata with exact Hub parity (`dns_not_found` -> nil, `scheme_downgrade`, `ssrf`, `robots_unreachable`, `rate_limited` + `retryAfterMs`, and `icims.com` ATS guidance).
func RetryOnAnotherExecutor ¶ added in v2.8.46
RetryOnAnotherExecutor is the single failover policy for a failed fetch: it reports whether re-sending the same request through a different executor (another worker node or the Cloudflare container) can plausibly change the answer. `status` is the origin's HTTP status (0 when no response arrived) and `outcome` the fetch outcome string.
It never fails over on a definitive answer: a success, a deterministic 4xx, a 404/410-style miss, a bot challenge, a payment wall, DNS NXDOMAIN, an SSRF block, or a robots / Content-Signal refusal. Re-asking another node for those wastes node capacity and the origin's politeness budget and, for a challenge, would be an evasion attempt. Transport failures (status 0), 5xx, 408, 425 and 429 stay eligible; callers still apply their own budget and Retry-After checks before acting on a true result.
Types ¶
type BlockedRefinement ¶ added in v2.8.0
type BlockedRefinement struct {
Reason string `json:"reason,omitempty"`
Host string `json:"host,omitempty"`
Category string `json:"category,omitempty"`
Vendor string `json:"vendor,omitempty"`
Retryable bool `json:"retryable"`
RetryAfterMs int64 `json:"retryAfterMs,omitempty"`
Message string `json:"message,omitempty"`
Suggestion string `json:"suggestion,omitempty"`
}
BlockedRefinement holds normalized machine-readable block reasons and caller guidance (`waf.ts:refineBlockedInfo`).
func RefineBlockedInfo ¶ added in v2.8.0
type ContentStateInput ¶ added in v2.8.0
type ContentStateInput struct {
Status int `json:"status"`
URL string `json:"url,omitempty"`
FinalURL string `json:"finalUrl,omitempty"`
Title string `json:"title,omitempty"`
Markdown string `json:"markdown"`
RawHTML string `json:"rawHtml,omitempty"`
ValidThrough string `json:"validThrough,omitempty"`
Rendered bool `json:"rendered,omitempty"`
NowMs int64 `json:"nowMs,omitempty"`
}
ContentStateInput provides full context for ClassifyContentStateFull.
type ContentStateResult ¶ added in v2.8.0
type ContentStateResult struct {
State string `json:"state"`
Reason string `json:"reason,omitempty"`
Confidence float64 `json:"confidence"`
}
ContentStateResult describes the semantic availability state of a scraped 2xx page (`R4`).
func ClassifyContentState ¶ added in v2.8.0
func ClassifyContentState(status int, rawHTML, markdown, finalURL, title string) ContentStateResult
ClassifyContentState classifies a response into `"active"`, `"closed_posting"`, `"soft_404"`, `"temporarily_unavailable"`, `"login_wall"`, or `"empty_shell"` while applying word-count and structural vetoes so technical articles discussing HTTP 404 or authentication stay `"active"`.
func ClassifyContentStateFull ¶ added in v2.8.0
func ClassifyContentStateFull(in ContentStateInput) ContentStateResult
ClassifyContentStateFull evaluates ContentStateInput with full ATS silent-redirect, validThrough expiry, and rendered-iframe awareness.
type DetectOnlyResult ¶ added in v2.8.29
type DetectOnlyResult struct {
Matched bool `json:"matched"`
ID string `json:"id,omitempty"`
Status string `json:"status,omitempty"`
Reason string `json:"reason,omitempty"`
Guidance string `json:"guidance,omitempty"`
OfficialAPI string `json:"officialApi,omitempty"`
RecommendedMCP string `json:"recommendedMcp,omitempty"`
HandoffAdapter string `json:"handoffAdapter,omitempty"`
AllowJSONLDFallback bool `json:"allowJsonLdFallback,omitempty"`
}
DetectOnlyResult describes a pre-fetch official-API / user-authorized MCP guidance match.
func ClassifyDetectOnly ¶ added in v2.8.29
func ClassifyDetectOnly(_, _ string) DetectOnlyResult
ClassifyDetectOnly is retired in Round 2 (M0): pre-fetch `detect-only` policy refusals are disabled across the scraper/extractor so no public URL is blocked pre-fetch. Virtual OAuth MCP `closed_api_refusal` lives separately in `internal/mcpfed`.
type IframeScanResult ¶ added in v2.8.0
type IframeScanResult struct {
HasExternalIframe bool `json:"hasExternalIframe"`
IsIcims bool `json:"isIcims,omitempty"`
WidgetHosts []string `json:"widgetHosts,omitempty"`
IframeSrcs []string `json:"iframeSrcs,omitempty"`
}
IframeScanResult reports external or ATS/widget iframes discovered in an HTML document.
func HasExternalOrWidgetIframe ¶ added in v2.8.0
func HasExternalOrWidgetIframe(rawHTML, pageURL string) IframeScanResult
HasExternalOrWidgetIframe linearly scans rawHTML for visible external or ATS/widget `<iframe>` elements, ignoring hidden tracking pixels, tag managers, and CAPTCHA widgets.
type Kind ¶
type Kind string
Kind identifies what resource shape the caller expects from a URL.
const ( KindFeed Kind = "feed" // Structured JSON product feed (`{"products": [...]}`) KindJSON Kind = "json" // Any valid 2xx JSON document KindPage Kind = "page" // Individual HTML or Markdown document (`text/markdown` / `text/html`, 404/410 -> `gone`) KindText Kind = "text" // Auxiliary HTML, Markdown, or XML document (e.g., sitemap or llms.txt) KindCatalog Kind = "catalog" // Full-catalog HTML page where non-2xx fails the host batch KindScrape Kind = "scrape" // Universal smart scrape (HTML, Markdown, PDF, JSON, or XML -> Markdown + metadata) KindRender Kind = "render" // Headless Chromium JS-rendered HTML document (`browser-v1`) KindPDF Kind = "pdf" // PDF document (`%PDF-` extracted via poppler `pdftotext` or pure-Go fallback) KindBinary Kind = "binary" // Binary resource returned as `bodyBase64` + `sha256` )
type Outcome ¶
type Outcome string
Outcome describes how the crawler and caller should act on an HTTP response.
const ( OutcomeOK Outcome = "ok" OutcomeChallenge Outcome = "challenge" // Edge anti-bot challenge (`cf-mitigated`) — never retried OutcomeStop Outcome = "stop" // Origin answered 403 or 503 — halt remaining URLs for this host OutcomeRateLimited Outcome = "rate_limited" // Origin answered HTTP 429 (no WAF challenge) on any kind — halts remaining URLs for this host OutcomePaymentRequired Outcome = "payment_required" // Origin answered HTTP 402 (e.g. x402 / Monetization Gateway) — halt host, never auto-pay OutcomeNotFound Outcome = "not_found" // Document answered HTTP 404 OutcomeGone Outcome = "gone" // Document answered HTTP 410 OutcomeDNSNotFound Outcome = "dns_not_found" // Domain does not exist in DNS (NXDOMAIN) — never retried OutcomeBlockedSSRF Outcome = "blocked_ssrf" // Target or redirect blocked by SSRF policy — never retried OutcomeSkip Outcome = "skip" // Non-200 or non-HTML/Markdown page that can be skipped without failing the host OutcomeError Outcome = "error" // Feed/transport failure OutcomeNotTried Outcome = "not_tried" // Left unsent because an earlier request stopped the host or timed out )
func Classify ¶
Classify evaluates status code, response headers, and body bytes to determine `(Outcome, problem)`.
Note that Go `switch` cases do NOT fall through unless `fallthrough` is written explicitly, and multiple values can share one `case 403, 503:` branch cleanly.
Example ¶
package main
import (
"fmt"
"net/http"
"github.com/bartrumb/edgefetch/v2/internal/classify"
)
func main() {
htmlHdr := http.Header{"Content-Type": []string{"text/html; charset=utf-8"}}
okOut, _ := classify.Classify(classify.KindScrape, 200, htmlHdr, []byte("<main><h1>Docs</h1></main>"))
chalHdr := http.Header{
"Content-Type": []string{"text/html"},
"Cf-Mitigated": []string{"challenge"},
}
chalOut, prob := classify.Classify(classify.KindScrape, 403, chalHdr, []byte("<html></html>"))
fmt.Println("200 scrape:", okOut)
fmt.Println("challenge:", chalOut, "| stopsHost:", classify.StopsHost(classify.KindScrape, chalOut), "|", prob)
}
Output: 200 scrape: ok challenge: challenge | stopsHost: true | Cloudflare challenge (cf-mitigated)
func ClassifyAuto ¶ added in v2.6.0
func ClassifyAuto(kind Kind, kindAuto bool, status int, header map[string][]string, body []byte) (Outcome, string)
ClassifyAuto evaluates `Classify` and promotes structured/text 2xx responses (`application/json`, `application/*+json`, `application/rss+xml`, `application/atom+xml`, `application/xml`, `text/xml`, `text/plain`, `text/markdown`) to `OutcomeOK` when `kindAuto` is true (or `kind == ""`).
type RefineBlockedMapInput ¶ added in v2.8.0
type RefineBlockedMapInput struct {
URL string `json:"url"`
Outcome string `json:"outcome,omitempty"`
Problem string `json:"problem,omitempty"`
Status int `json:"status,omitempty"`
RetryAfter string `json:"retryAfter,omitempty"`
BaseBlocked map[string]any `json:"baseBlocked,omitempty"`
NowMs int64 `json:"nowMs,omitempty"`
}
RefineBlockedMapInput mirrors `waf.ts:refineBlockedInfo` parameters for exact Hub parity.
type WAFChallengeInput ¶ added in v2.8.0
type WAFChallengeInput struct {
Status int `json:"status"`
Headers map[string]string `json:"headers,omitempty"`
RawHTML string `json:"rawHtml,omitempty"`
URL string `json:"url,omitempty"`
Title string `json:"title,omitempty"`
VisibleText string `json:"visibleText,omitempty"`
Markdown string `json:"markdown,omitempty"`
}
WAFChallengeInput provides HTTP response metadata, HTML, and extracted text/Markdown to ClassifyWAFAndChallengeFull.
type WAFMatch ¶
type WAFMatch struct {
Vendor string `json:"vendor"` // "cloudflare", "akamai", "datadome", "perimeterx", "aws-waf", "imperva", "vercel", "fastly", "kasada", "generic"
Category string `json:"category"` // "challenge" | "waf_block" | "rate_limit"
Confidence float64 `json:"confidence"` // 0.0 .. 1.0 (1.0 = authoritative HTTP header)
Signals []string `json:"signals,omitempty"` // Matched header/DOM indicators
Summary string `json:"summary,omitempty"` // Human-readable diagnostic summary
}
WAFMatch describes a detected Web Application Firewall (WAF) or anti-bot challenge interstitial (`R2` & `R3`). EdgeFetch strictly halts on challenges and WAF blocks — never solving, clicking through, or bypassing them.
func ClassifyWAF ¶
ClassifyWAF evaluates response status, HTTP headers, and HTML/JSON body against the 7-vendor WAF & Challenge Signature Catalog (`R2`) while enforcing all 4 Anti-False-Positive Guardrails (`R3`).
func ClassifyWAFAndChallengeFull ¶ added in v2.8.0
func ClassifyWAFAndChallengeFull(in WAFChallengeInput) *WAFMatch
ClassifyWAFAndChallengeFull evaluates HTTP status, headers, raw HTML, Markdown, and visible text against the full 10-vendor WAF & Challenge Signature Catalog (`cloudflare`, `akamai`, `datadome`, `perimeterx`, `aws-waf`, `imperva`, `vercel`, `fastly`, `kasada`, `generic`) while enforcing all 4 Anti-False-Positive Guardrails (`R2` & `R3`).