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.
- OutcomeStop: origin rate-limit or block (`403`, `429`, `503`) — halts remaining queued URLs for the same host (`not_tried`) and records cooldowns in `internal/politeness`.
- 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 IsAutoPageContentType(contentType string) bool
- func IsEligibleForWaybackFallback(status int, outcome, wafCategory, urlStr, method string, hasAuthHeaders bool) bool
- func RefineBlockedInfoMap(in RefineBlockedMapInput) map[string]any
- func StopsHost(kind Kind, o Outcome) bool
- type BlockedRefinement
- type ContentStateInput
- type ContentStateResult
- 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 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 IsEligibleForWaybackFallback ¶ added in v2.8.17
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.17
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).
Types ¶
type BlockedRefinement ¶ added in v2.8.17
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.17
func RefineBlockedInfo(urlStr string, status int, outcome string, waf *WAFMatch, existingSuggestion string) BlockedRefinement
RefineBlockedInfo normalizes block metadata across SSRF, HTTPS->HTTP scheme downgrades, RFC 9309 §2.3.1.4 `robots_unreachable`, non-challenge HTTP 429 rate limits, iCIMS ATS portals, robots disallows, and WAF challenges.
type ContentStateInput ¶ added in v2.8.17
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.17
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.17
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.17
func ClassifyContentStateFull(in ContentStateInput) ContentStateResult
ClassifyContentStateFull evaluates ContentStateInput with full ATS silent-redirect, validThrough expiry, and rendered-iframe awareness.
type IframeScanResult ¶ added in v2.8.17
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.17
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, 429, or 503 — halt remaining URLs for this host OutcomeRateLimited Outcome = "rate_limited" // Explicit rate-limit outcome — 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, 429, 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.17
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.17
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.17
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`).