返回 last30days-skill
web_fetch_keyless.py
根目录 / skills / last30days / scripts / lib / web_fetch_keyless.py
1 """Keyless URL-to-markdown fetch (floor tier for engine-side page reads).
2
3 Turns any URL into clean, JS-rendered markdown via Jina Reader's free hosted
4 endpoint (``https://r.jina.ai/{url}``) with no API key. This is a *fallback*
5 tier, never the primary firehose:
6
7 - On agent hosts with a native fetch tool, prefer that (this module exists for
8 headless/cron and hosts without one).
9 - The free tier is rate-limited and returns cached snapshots (staleness), so
10 callers should treat results as best-effort and record when it was used.
11 - The target URL is sent to a third party; only use for public-research fetches.
12
13 Never raises. Returns a typed :class:`KeylessFetchResult` carrying the failure
14 reason on any error, so tiered callers (and the source-health layer) can fall
15 through or report degradation instead of seeing a bare empty string.
16 """
17
18 from __future__ import annotations
19
20 from dataclasses import dataclass
21 import re
22 from typing import Optional
23 from urllib.parse import urlsplit
24
25 from . import http, public_host
26
27 JINA_READER_PREFIX = "https://r.jina.ai/"
28 _RESERVED_HOST_SUFFIXES = frozenset({"localhost", "local", "internal", "localdomain", "arpa"})
29 _VALID_DOMAIN_RE = re.compile(
30 r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+"
31 )
32 _VALID_TLD_RE = re.compile(r"[a-z]{2,63}|xn--[a-z0-9-]{2,59}")
33
34 # Conservative timeout: Jina renders the page server-side, so it is slower than
35 # a plain GET, but we are the floor tier and must not stall the pipeline.
36 DEFAULT_FETCH_TIMEOUT = 30
37 _MAX_MARKDOWN_BYTES = 4 * 1024 * 1024
38
39
40 @dataclass
41 class KeylessFetchResult:
42 """Result of a keyless page fetch.
43
44 ``ok`` is True only when markdown was retrieved. On failure, ``markdown`` is
45 empty and ``reason`` explains why (consumed by the source-health layer).
46 """
47
48 url: str
49 ok: bool
50 markdown: str = ""
51 reason: str = ""
52 cached_snapshot: bool = False
53
54
55 def _looks_like_http_url(url: str) -> bool:
56 if not isinstance(url, str) or not url or "\\" in url:
57 return False
58 if not public_host.is_public_address_syntax(url):
59 return False
60 try:
61 parsed = urlsplit(url)
62 port = parsed.port
63 except ValueError:
64 return False
65 scheme = parsed.scheme.lower()
66 if scheme not in ("http", "https"):
67 return False
68 if parsed.username is not None or parsed.password is not None:
69 return False
70 # Reject percent-escapes, non-ASCII, and backslashes in authority to avoid
71 # RFC-3986 vs WHATWG URL parser differentials at Jina Reader.
72 if not parsed.netloc.isascii() or "%" in parsed.netloc or "\\" in parsed.netloc:
73 return False
74 if port is not None and not (
75 (scheme == "https" and port == 443) or (scheme == "http" and port == 80)
76 ):
77 return False
78 host = (parsed.hostname or "").rstrip(".").lower()
79 if not host or not host.isascii() or not _VALID_DOMAIN_RE.fullmatch(host):
80 return False
81 if public_host._parse_ip_literal(host) is not None:
82 return False
83 labels = host.split(".")
84 if host == "localhost" or labels[-1] in _RESERVED_HOST_SUFFIXES:
85 return False
86 if not _VALID_TLD_RE.fullmatch(labels[-1]):
87 return False
88 return True
89
90
91 def _reader_redirect_guard(target: str) -> bool:
92 if not isinstance(target, str) or not target or "\\" in target:
93 return False
94 if not public_host.is_public_address_syntax(target):
95 return False
96 try:
97 parsed = urlsplit(target)
98 port = parsed.port
99 except ValueError:
100 return False
101 if not parsed.netloc.isascii() or "%" in parsed.netloc or "\\" in parsed.netloc:
102 return False
103 if port is not None and port != 443:
104 return False
105 host = (parsed.hostname or "").rstrip(".").lower()
106 return parsed.scheme.lower() == "https" and (
107 host == "r.jina.ai" or host.endswith(".r.jina.ai")
108 )
109
110
111 def _detect_cached_snapshot(markdown: str) -> bool:
112 """Best-effort detection of Jina's cached-snapshot warning.
113
114 Jina prepends a small metadata/warning header to the text response; when it
115 serves a cached copy it says so. We scan only the leading window to avoid
116 false positives from article bodies that happen to mention caching.
117 """
118 head = markdown[:600].lower()
119 return "cached" in head and "snapshot" in head
120
121
122 def fetch_markdown(
123 url: str,
124 timeout: int = DEFAULT_FETCH_TIMEOUT,
125 retries: int = 2,
126 ) -> KeylessFetchResult:
127 """Fetch ``url`` as clean markdown via the keyless reader endpoint.
128
129 Args:
130 url: The http(s) URL to fetch.
131 timeout: Per-attempt HTTP timeout in seconds.
132 retries: Retry budget (kept low; this is a fail-fast floor tier).
133
134 Returns:
135 A :class:`KeylessFetchResult`. ``ok`` is False with a populated
136 ``reason`` on invalid input, network failure, or empty body.
137 """
138 if not url or not _looks_like_http_url(url):
139 return KeylessFetchResult(url=url or "", ok=False, reason="invalid-url")
140
141 reader_url = f"{JINA_READER_PREFIX}{url}"
142 try:
143 text = http.get_text(
144 reader_url,
145 timeout=timeout,
146 retries=retries,
147 accept="text/plain",
148 public_only=True,
149 redirect_guard=_reader_redirect_guard,
150 max_bytes=_MAX_MARKDOWN_BYTES,
151 decode_errors="replace",
152 )
153 except UnicodeDecodeError:
154 return KeylessFetchResult(url=url, ok=False, reason="decode-error")
155
156 if text is None:
157 return KeylessFetchResult(url=url, ok=False, reason="fetch-failed")
158
159 if not text.strip():
160 return KeylessFetchResult(url=url, ok=False, reason="empty-body")
161
162 return KeylessFetchResult(
163 url=url,
164 ok=True,
165 markdown=text,
166 cached_snapshot=_detect_cached_snapshot(text),
167 )
168
168 lines PYTHON