返回 last30days-skill
http.py
根目录 / skills / last30days / scripts / lib / http.py
1 """HTTP utilities for last30days skill (stdlib only)."""
2
3 import http.client
4 import io
5 import ipaddress
6 import json
7 from collections import OrderedDict
8 from datetime import datetime, timezone
9 from email.utils import parsedate_to_datetime
10 import math
11 import os
12 import random
13 import re
14 import socket
15 import string
16 import threading
17 import time
18 import urllib.error
19 import urllib.request
20 from concurrent.futures import Future
21 from contextlib import contextmanager
22 from contextvars import ContextVar, copy_context
23 from pathlib import Path
24 from typing import Any, Callable, Dict, Optional, Union
25 from urllib.parse import parse_qsl, urlencode, urljoin, urlparse, urlsplit, urlunparse, urlunsplit, quote
26
27 from . import bounded_get, health, proxy, usage
28 from . import log as _log
29
30 DEFAULT_TIMEOUT = 30
31 MAX_RESPONSE_BYTES = 16 * 1024 * 1024
32 MAX_ERROR_BODY_BYTES = 64 * 1024
33
34
35 _URL_USERINFO_RE = re.compile(r"(https?://)[^\s/?#]+@", re.IGNORECASE)
36
37
38 def _is_loopback_http_url(url: str) -> bool:
39 """True for a plaintext URL whose host never leaves the machine."""
40 try:
41 parts = urlsplit(url)
42 host = parts.hostname or ""
43 except ValueError:
44 return False
45 if parts.scheme != "http":
46 return False
47 if host == "localhost":
48 return True
49 try:
50 return ipaddress.ip_address(host).is_loopback
51 except ValueError:
52 return False
53
54
55 def _carries_provider_credential(headers: Dict[str, str]) -> bool:
56 """True when the request carries an API key in a header, not in the URL."""
57 return any(str(name).lower() in proxy._PROVIDER_AUTH_HEADERS for name in headers)
58
59
60 def log(msg: str):
61 """Log debug message to stderr with any embedded URL userinfo scrubbed."""
62 _log.debug(_URL_USERINFO_RE.sub(r"\1", msg))
63
64
65 MAX_RETRIES = 5
66 MAX_429_RETRIES = 2
67 RETRY_DELAY = 2.0
68
69
70 # Longest a 429 retry may sleep on any host. Reddit's x-ratelimit-reset can say
71 # 540s and GitHub's is an epoch timestamp; neither is worth parking a worker
72 # (or the main thread) for. Past this bound the retry is not worth taking, so
73 # the caller's own fallback backoff applies and the request fails fast.
74 MAX_RETRY_DELAY_SECONDS = 60.0
75 # A reset value this large is an absolute epoch timestamp, not delta-seconds.
76 _EPOCH_RESET_THRESHOLD = 100_000_000.0
77 _RFC850_DATE = re.compile(
78 r"[A-Za-z]+, [0-9]{2}-[A-Za-z]{3}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} GMT"
79 )
80
81
82 def _retry_after_date_delay(raw: str, now: float) -> float:
83 retry_at = parsedate_to_datetime(raw)
84 # Obsolete HTTP asctime dates omit GMT but still mean UTC.
85 if retry_at.tzinfo is None:
86 retry_at = retry_at.replace(tzinfo=timezone.utc)
87 if _RFC850_DATE.fullmatch(raw.strip()):
88 # HTTP uses a rolling 50-year limit for RFC 850's two-digit year.
89 current = datetime.fromtimestamp(now, tz=timezone.utc)
90 limit_year = current.year + 50
91 year = limit_year - (limit_year - retry_at.year) % 100
92 if year == limit_year and retry_at.timetuple()[1:6] > current.timetuple()[1:6]:
93 year -= 100
94 retry_at = retry_at.replace(year=year)
95 return retry_at.timestamp() - now
96
97
98 def retry_delay_from_headers(headers, fallback):
99 """Seconds to wait after a 429, read from whichever header the host sent.
100
101 ``Retry-After`` is the standard, but Reddit's keyless search endpoints answer an
102 anonymous 429 with ``x-ratelimit-reset`` (seconds until the window rolls) and
103 no ``Retry-After`` at all::
104
105 HTTP/2 429
106 x-ratelimit-used: 1
107 x-ratelimit-remaining: 0.0
108 x-ratelimit-reset: 42
109
110 Reading only ``Retry-After`` means the caller falls back to exponential
111 backoff -- 3s, 5s, 9s -- every one of which is shorter than the ~42s Reddit
112 actually requires. Each retry re-429s, the budget drains, and the source is
113 reported dead when it was merely early. Honouring the reset header turns a
114 guaranteed zero into a result at the cost of one wait.
115
116 USPTO Patent Public Search names its wait in
117 ``x-rate-limit-retry-after-seconds`` instead.
118
119 ``Retry-After`` accepts both delay-seconds and an HTTP-date. Date values
120 are converted to a delay against the current clock and share the same cap.
121 Returns ``fallback`` when none of these headers names a positive delay.
122 """
123 if not headers:
124 return fallback
125 for name in (
126 "Retry-After",
127 "x-rate-limit-retry-after-seconds",
128 "x-ratelimit-reset",
129 ):
130 raw = headers.get(name)
131 if raw is None:
132 continue
133 try:
134 value = float(raw)
135 except (TypeError, ValueError):
136 if name != "Retry-After" or not isinstance(raw, str):
137 continue
138 try:
139 value = _retry_after_date_delay(raw, time.time())
140 except (TypeError, ValueError, OverflowError, OSError):
141 continue
142 else:
143 if value >= _EPOCH_RESET_THRESHOLD:
144 # GitHub-style absolute reset time.
145 value = value - time.time()
146 if value > 0:
147 return min(value, MAX_RETRY_DELAY_SECONDS)
148 return fallback
149
150 # DNS resolution failures (gaierror) are transient — typically resolved by a
151 # brief backoff and retry. Use a dedicated minimum attempt count + exponential
152 # delays (1s, 2s, 4s) so callers that pass a small `retries` value still get a
153 # meaningful chance to recover from a transient resolution failure.
154 MIN_DNS_RETRIES = 3
155 USER_AGENT = "last30days-skill/3.0 (Assistant Skill)"
156
157 # urllib copies almost all headers across 3xx; strip credentials when origin changes (#1062).
158 _CROSS_ORIGIN_AUTH_HEADERS = frozenset(
159 {
160 "authorization",
161 "cookie",
162 "x-access-token",
163 "x-api-key",
164 "x-csrf-token",
165 "x-goog-api-key",
166 "x-subscription-token",
167 }
168 )
169
170
171 def _request_origin(url: str) -> tuple[str, str, int]:
172 parts = urlsplit(url)
173 scheme = parts.scheme.lower()
174 host = (parts.hostname or "").lower()
175 if parts.port is not None:
176 port = parts.port
177 elif scheme == "https":
178 port = 443
179 elif scheme == "http":
180 port = 80
181 else:
182 port = 0
183 return scheme, host, port
184
185
186 # A request may carry a check on where it is allowed to be redirected: a
187 # caller that fetches an address from remote content (a sitemap) refuses a
188 # redirect to a private network before it is followed, not after.
189 _REDIRECT_GUARD_ATTR = "_last30days_redirect_guard"
190 _PUBLIC_ONLY_ATTR = "_last30days_public_only"
191 _LOCAL_BRIDGE_ONLY_ATTR = "_last30days_local_bridge_only"
192 _IP_VALIDATOR_ATTR = "_last30days_ip_validator"
193 _ALLOWED_HTTP_SCHEMES = frozenset({"http", "https"})
194
195 _LOCAL_BRIDGE_BLOCKED_IPS = frozenset({
196 ipaddress.ip_address("100.100.100.200"),
197 ipaddress.ip_address("fd00:ec2::254"),
198 })
199 _LOCAL_BRIDGE_LAN_NETWORKS = (
200 ipaddress.IPv4Network("10.0.0.0/8"),
201 ipaddress.IPv4Network("172.16.0.0/12"),
202 ipaddress.IPv4Network("192.168.0.0/16"),
203 ipaddress.IPv6Network("fc00::/7"),
204 )
205 _LOCAL_BRIDGE_NAT64_WELL_KNOWN = ipaddress.IPv6Network("64:ff9b::/96")
206 _LOCAL_BRIDGE_NAT64_LOCAL = ipaddress.IPv6Network("64:ff9b:1::/48")
207
208
209 def _is_local_bridge_ip(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
210 """True only for loopback, RFC1918 LAN, or non-IMDS IPv6 ULA addresses."""
211 if (
212 ip in _LOCAL_BRIDGE_BLOCKED_IPS
213 or ip.is_link_local
214 or ip.is_unspecified
215 or ip.is_multicast
216 ):
217 return False
218 if isinstance(ip, ipaddress.IPv6Address):
219 if ip.ipv4_mapped is not None:
220 return _is_local_bridge_ip(ip.ipv4_mapped)
221 if (
222 ip.sixtofour is not None
223 or ip.teredo is not None
224 or ip in _LOCAL_BRIDGE_NAT64_WELL_KNOWN
225 or ip in _LOCAL_BRIDGE_NAT64_LOCAL
226 ):
227 return False
228 return ip.is_loopback or any(ip in net for net in _LOCAL_BRIDGE_LAN_NETWORKS)
229
230
231 def _resolve_local_bridge_addresses(host: str, port: int) -> list[tuple]:
232 """Resolve ``host`` fresh and allow only verified local/LAN bridge IPs."""
233 from . import public_host
234
235 raw_host = (host or "").strip()
236 if raw_host.startswith("[") and raw_host.endswith("]"):
237 raw_host = raw_host[1:-1]
238 dns_host = raw_host.lower()
239 bare = dns_host.removesuffix(".")
240 if not bare or bare.startswith(".") or bare.endswith(".") or ".." in bare:
241 raise public_host.NonPublicAddressError("refused disallowed local-bridge address")
242 literal = public_host._parse_ip_literal(bare)
243 if literal is not None:
244 if not _is_local_bridge_ip(literal):
245 raise public_host.NonPublicAddressError("refused disallowed local-bridge address")
246 family = socket.AF_INET6 if isinstance(literal, ipaddress.IPv6Address) else socket.AF_INET
247 sockaddr = (str(literal), port, 0, 0) if family == socket.AF_INET6 else (str(literal), port)
248 return [(family, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", sockaddr)]
249 # Preserve any single trailing dot for DNS lookup so search-domain expansion cannot redirect it.
250 answers = socket.getaddrinfo(dns_host, port, 0, socket.SOCK_STREAM)
251 if not answers:
252 raise public_host.NonPublicAddressError("refused disallowed local-bridge address")
253 verified: list[tuple] = []
254 for family, socktype, proto, canonname, sockaddr in answers:
255 try:
256 ip = ipaddress.ip_address(sockaddr[0].split("%", 1)[0])
257 except ValueError as exc:
258 raise public_host.NonPublicAddressError("refused disallowed local-bridge address") from exc
259 if not _is_local_bridge_ip(ip):
260 raise public_host.NonPublicAddressError("refused disallowed local-bridge address")
261 verified.append((family, socktype, proto, canonname, sockaddr))
262 return verified
263
264
265 def _create_pinned_connection(
266 address: tuple[str, int],
267 resolver: Callable[[str, int], list[tuple]],
268 timeout: Any = socket._GLOBAL_DEFAULT_TIMEOUT,
269 source_address: Any = None,
270 ) -> socket.socket:
271 """Resolve ``address`` fresh via ``resolver`` and connect only to verified IPs."""
272 from . import public_host
273
274 host, port = address
275 verified = resolver(host, port)
276 last_err: Optional[OSError] = None
277 for af, socktype, proto, _canonname, sockaddr in verified:
278 sock = None
279 try:
280 sock = socket.socket(af, socktype, proto)
281 if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
282 sock.settimeout(timeout)
283 if source_address:
284 sock.bind(source_address)
285 sock.connect(sockaddr)
286 return sock
287 except OSError as exc:
288 last_err = exc
289 if sock is not None:
290 sock.close()
291 if last_err is not None:
292 raise last_err
293 raise public_host.NonPublicAddressError("refused disallowed address")
294
295
296 def _check_http_scheme(url: str) -> str:
297 """Return the normalized scheme for an http(s) URL, or raise ValueError."""
298 if not isinstance(url, str) or not url or url != url.strip():
299 raise ValueError("unsupported URL scheme: <empty>")
300 if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in url):
301 raise ValueError("unsupported URL control characters")
302 parts = urlsplit(url)
303 scheme = parts.scheme.lower()
304 if scheme not in _ALLOWED_HTTP_SCHEMES:
305 raise ValueError(f"unsupported URL scheme: {scheme or '<empty>'}")
306 return scheme
307
308
309 def _create_public_connection(
310 address: tuple[str, int],
311 timeout: Any = socket._GLOBAL_DEFAULT_TIMEOUT,
312 source_address: Any = None,
313 ) -> socket.socket:
314 """Resolve ``address`` fresh once and connect only to verified public IPs."""
315 from . import public_host
316
317 return _create_pinned_connection(
318 address, public_host.resolve_public_addresses, timeout=timeout, source_address=source_address,
319 )
320
321
322 def _create_local_bridge_connection(
323 address: tuple[str, int],
324 timeout: Any = socket._GLOBAL_DEFAULT_TIMEOUT,
325 source_address: Any = None,
326 ) -> socket.socket:
327 """Resolve ``address`` fresh once and connect only to verified local/LAN bridge IPs."""
328 return _create_pinned_connection(
329 address, _resolve_local_bridge_addresses, timeout=timeout, source_address=source_address,
330 )
331
332
333 class _PublicHTTPConnection(http.client.HTTPConnection):
334 """HTTPConnection pinned to the exact public IP resolved at connect time."""
335
336 def __init__(self, *args, **kwargs):
337 super().__init__(*args, **kwargs)
338 self._create_connection = _create_public_connection
339
340 def connect(self):
341 if self._tunnel_host:
342 from . import public_host
343
344 raise public_host.NonPublicAddressError("refused proxied tunnel for public-only request")
345 return super().connect()
346
347
348 class _LocalBridgeHTTPConnection(http.client.HTTPConnection):
349 """HTTPConnection pinned to verified loopback/RFC1918/ULA bridge IPs at connect time."""
350
351 def __init__(self, *args, **kwargs):
352 super().__init__(*args, **kwargs)
353 self._create_connection = _create_local_bridge_connection
354
355 def connect(self):
356 if self._tunnel_host:
357 from . import public_host
358
359 raise public_host.NonPublicAddressError("refused proxied tunnel for local-bridge-only request")
360 return super().connect()
361
362
363 if hasattr(http.client, "HTTPSConnection"):
364
365 class _PublicHTTPSConnection(http.client.HTTPSConnection):
366 """HTTPSConnection pinned to verified public IPs while preserving TLS SNI/hostname."""
367
368 def __init__(self, *args, **kwargs):
369 super().__init__(*args, **kwargs)
370 self._create_connection = _create_public_connection
371
372 def connect(self):
373 if self._tunnel_host:
374 from . import public_host
375
376 raise public_host.NonPublicAddressError("refused proxied tunnel for public-only request")
377 return super().connect()
378
379 class _LocalBridgeHTTPSConnection(http.client.HTTPSConnection):
380 """HTTPSConnection pinned to verified local/LAN bridge IPs while preserving TLS SNI."""
381
382 def __init__(self, *args, **kwargs):
383 super().__init__(*args, **kwargs)
384 self._create_connection = _create_local_bridge_connection
385
386 def connect(self):
387 if self._tunnel_host:
388 from . import public_host
389
390 raise public_host.NonPublicAddressError("refused proxied tunnel for local-bridge-only request")
391 return super().connect()
392
393
394 class _PublicHTTPHandler(urllib.request.HTTPHandler):
395 def http_open(self, req):
396 return self.do_open(_PublicHTTPConnection, req)
397
398
399 class _LocalBridgeHTTPHandler(urllib.request.HTTPHandler):
400 def http_open(self, req):
401 return self.do_open(_LocalBridgeHTTPConnection, req)
402
403
404 if hasattr(http.client, "HTTPSConnection"):
405
406 class _PublicHTTPSHandler(urllib.request.HTTPSHandler):
407 def https_open(self, req):
408 return self.do_open(_PublicHTTPSConnection, req, context=self._context)
409
410 class _LocalBridgeHTTPSHandler(urllib.request.HTTPSHandler):
411 def https_open(self, req):
412 return self.do_open(_LocalBridgeHTTPSConnection, req, context=self._context)
413
414
415 def _resolve_validated_addresses(
416 host: str,
417 port: int,
418 ip_validator: Callable[[Union[ipaddress.IPv4Address, ipaddress.IPv6Address]], bool],
419 ) -> list[tuple]:
420 """Resolve ``host`` fresh once and accept only when every resolved IP passes ``ip_validator``."""
421 from . import public_host
422
423 raw_host = (host or "").strip()
424 if raw_host.startswith("[") and raw_host.endswith("]"):
425 raw_host = raw_host[1:-1]
426 dns_host = raw_host.lower()
427 bare = dns_host.removesuffix(".")
428 if not bare or bare.startswith(".") or bare.endswith(".") or ".." in bare:
429 raise public_host.NonPublicAddressError("refused disallowed address")
430 literal = public_host._parse_ip_literal(bare)
431 if literal is not None:
432 if not ip_validator(literal):
433 raise public_host.NonPublicAddressError("refused disallowed address")
434 family = socket.AF_INET6 if isinstance(literal, ipaddress.IPv6Address) else socket.AF_INET
435 sockaddr = (str(literal), port, 0, 0) if family == socket.AF_INET6 else (str(literal), port)
436 return [(family, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", sockaddr)]
437 # Preserve any single trailing dot for DNS lookup so search-domain expansion cannot redirect it.
438 answers = socket.getaddrinfo(dns_host, port, 0, socket.SOCK_STREAM)
439 if not answers:
440 raise public_host.NonPublicAddressError("refused disallowed address")
441 verified: list[tuple] = []
442 for family, socktype, proto, canonname, sockaddr in answers:
443 try:
444 ip = ipaddress.ip_address(sockaddr[0].split("%", 1)[0])
445 except ValueError as exc:
446 raise public_host.NonPublicAddressError("refused disallowed address") from exc
447 if not ip_validator(ip):
448 raise public_host.NonPublicAddressError("refused disallowed address")
449 verified.append((family, socktype, proto, canonname, sockaddr))
450 return verified
451
452
453 def _make_validated_connection(
454 ip_validator: Callable[[Union[ipaddress.IPv4Address, ipaddress.IPv6Address]], bool],
455 ):
456 def _create_validated_connection(
457 address: tuple[str, int],
458 timeout: Any = socket._GLOBAL_DEFAULT_TIMEOUT,
459 source_address: Any = None,
460 ) -> socket.socket:
461 return _create_pinned_connection(
462 address,
463 lambda host, port: _resolve_validated_addresses(host, port, ip_validator),
464 timeout=timeout,
465 source_address=source_address,
466 )
467
468 return _create_validated_connection
469
470
471 class _ValidatedHTTPHandler(urllib.request.HTTPHandler):
472 def __init__(
473 self,
474 ip_validator: Callable[[Union[ipaddress.IPv4Address, ipaddress.IPv6Address]], bool],
475 ):
476 super().__init__()
477 create_conn = _make_validated_connection(ip_validator)
478
479 class _ValidatedHTTPConnection(http.client.HTTPConnection):
480 def __init__(self, *args, **kwargs):
481 super().__init__(*args, **kwargs)
482 self._create_connection = create_conn
483
484 def connect(self):
485 if self._tunnel_host:
486 from . import public_host
487
488 raise public_host.NonPublicAddressError(
489 "refused proxied tunnel for IP-validated request"
490 )
491 return super().connect()
492
493 self._conn_cls = _ValidatedHTTPConnection
494
495 def http_open(self, req):
496 return self.do_open(self._conn_cls, req)
497
498
499 if hasattr(http.client, "HTTPSConnection"):
500
501 class _ValidatedHTTPSHandler(urllib.request.HTTPSHandler):
502 def __init__(
503 self,
504 ip_validator: Callable[[Union[ipaddress.IPv4Address, ipaddress.IPv6Address]], bool],
505 ):
506 super().__init__()
507 create_conn = _make_validated_connection(ip_validator)
508
509 class _ValidatedHTTPSConnection(http.client.HTTPSConnection):
510 def __init__(self, *args, **kwargs):
511 super().__init__(*args, **kwargs)
512 self._create_connection = create_conn
513
514 def connect(self):
515 if self._tunnel_host:
516 from . import public_host
517
518 raise public_host.NonPublicAddressError(
519 "refused proxied tunnel for IP-validated request"
520 )
521 return super().connect()
522
523 self._conn_cls = _ValidatedHTTPSConnection
524
525 def https_open(self, req):
526 return self.do_open(self._conn_cls, req, context=self._context)
527
528
529 def _build_http_opener(
530 *,
531 bypass_proxy: bool = False,
532 public_only: bool = False,
533 local_bridge_only: bool = False,
534 ip_validator: Optional[Callable[[Union[ipaddress.IPv4Address, ipaddress.IPv6Address]], bool]] = None,
535 ) -> urllib.request.OpenerDirector:
536 """Build an OpenerDirector restricted strictly to HTTP(S) — omitting urllib's
537 default FileHandler, FTPHandler, and DataHandler."""
538 opener = urllib.request.OpenerDirector()
539 pinned = public_only or local_bridge_only or ip_validator is not None
540 if ip_validator is not None:
541 http_handler = _ValidatedHTTPHandler(ip_validator)
542 elif public_only:
543 http_handler = _PublicHTTPHandler()
544 elif local_bridge_only:
545 http_handler = _LocalBridgeHTTPHandler()
546 else:
547 http_handler = urllib.request.HTTPHandler()
548 handlers = [
549 urllib.request.ProxyHandler({}) if (bypass_proxy or pinned) else urllib.request.ProxyHandler(),
550 urllib.request.UnknownHandler(),
551 http_handler,
552 urllib.request.HTTPDefaultErrorHandler(),
553 _StripAuthOnCrossOriginRedirect(),
554 urllib.request.HTTPErrorProcessor(),
555 ]
556 if hasattr(http.client, "HTTPSConnection"):
557 if ip_validator is not None:
558 handlers.append(_ValidatedHTTPSHandler(ip_validator))
559 elif public_only:
560 handlers.append(_PublicHTTPSHandler())
561 elif local_bridge_only:
562 handlers.append(_LocalBridgeHTTPSHandler())
563 else:
564 handlers.append(urllib.request.HTTPSHandler())
565 for handler in handlers:
566 opener.add_handler(handler)
567 return opener
568
569
570 class _StripAuthOnCrossOriginRedirect(urllib.request.HTTPRedirectHandler):
571 def http_error_302(self, req, fp, code, msg, headers):
572 if "location" in headers:
573 newurl = headers["location"]
574 elif "uri" in headers:
575 newurl = headers["uri"]
576 else:
577 return
578 urlparts = urlparse(newurl)
579 if urlparts.scheme not in ("http", "https", ""):
580 raise urllib.error.HTTPError(
581 req.full_url,
582 403,
583 f"redirect refused: unsupported URL scheme: {urlparts.scheme}",
584 headers,
585 fp,
586 )
587 if not urlparts.path and urlparts.netloc:
588 urlparts = list(urlparts)
589 urlparts[2] = "/"
590 newurl = urlunparse(urlparts)
591 newurl = quote(newurl, encoding="iso-8859-1", safe=string.punctuation)
592 newurl = urljoin(req.full_url, newurl)
593 new = self.redirect_request(req, fp, code, msg, headers, newurl)
594 if new is None:
595 return
596 if hasattr(req, "redirect_dict"):
597 visited = new.redirect_dict = req.redirect_dict
598 if (
599 visited.get(newurl, 0) >= self.max_repeats
600 or len(visited) >= self.max_redirections
601 ):
602 raise urllib.error.HTTPError(
603 req.full_url, code, self.inf_msg + msg, headers, fp
604 )
605 else:
606 visited = new.redirect_dict = req.redirect_dict = {}
607 visited[newurl] = visited.get(newurl, 0) + 1
608 # Close without calling unbounded fp.read() on untrusted 3xx bodies.
609 if fp is not None:
610 fp.close()
611 return self.parent.open(new, timeout=req.timeout)
612
613 http_error_301 = http_error_303 = http_error_307 = http_error_308 = http_error_302
614
615 def redirect_request(self, req, fp, code, msg, headers, newurl):
616 try:
617 _check_http_scheme(newurl)
618 except ValueError as exc:
619 raise urllib.error.HTTPError(
620 req.full_url, 403, f"redirect refused: {exc}", headers, fp,
621 ) from exc
622 public_only = bool(getattr(req, _PUBLIC_ONLY_ATTR, False))
623 local_bridge_only = bool(getattr(req, _LOCAL_BRIDGE_ONLY_ATTR, False))
624 if public_only:
625 from . import public_host
626
627 if not public_host.is_public_address_syntax(newurl):
628 raise urllib.error.HTTPError(
629 req.full_url, 403, "redirect refused: non-public address", headers, fp,
630 )
631 ip_validator = getattr(req, _IP_VALIDATOR_ATTR, None)
632 if ip_validator is not None:
633 from . import public_host
634
635 target_host = (urlsplit(newurl).hostname or "").strip().rstrip(".").lower()
636 literal = public_host._parse_ip_literal(target_host) if target_host else None
637 if literal is not None and not ip_validator(literal):
638 raise urllib.error.HTTPError(
639 req.full_url, 403, "redirect refused: disallowed IP address", headers, fp,
640 )
641 guard = getattr(req, _REDIRECT_GUARD_ATTR, None)
642 if guard is not None:
643 req_scheme = (req.type or urlparse(req.full_url).scheme).lower()
644 if req_scheme == "https" and urlparse(newurl).scheme.lower() != "https":
645 raise urllib.error.HTTPError(
646 req.full_url, 403, "redirect refused: HTTPS downgrade", headers, fp,
647 )
648 if not guard(newurl):
649 raise urllib.error.HTTPError(
650 req.full_url, 403, "redirect refused: off the site or to a private address", headers, fp,
651 )
652 new = super().redirect_request(req, fp, code, msg, headers, newurl)
653 if new is None:
654 return None
655 if guard is not None:
656 setattr(new, _REDIRECT_GUARD_ATTR, guard)
657 if public_only:
658 setattr(new, _PUBLIC_ONLY_ATTR, True)
659 if local_bridge_only:
660 setattr(new, _LOCAL_BRIDGE_ONLY_ATTR, True)
661 if ip_validator is not None:
662 setattr(new, _IP_VALIDATOR_ATTR, ip_validator)
663 if _request_origin(req.full_url) != _request_origin(new.full_url):
664 for store in (new.headers, getattr(new, "unredirected_hdrs", None)):
665 if not store:
666 continue
667 for name in list(store):
668 if name.lower() in _CROSS_ORIGIN_AUTH_HEADERS:
669 del store[name]
670 return new
671
672
673 _opener = _build_http_opener(bypass_proxy=False)
674 _direct_opener = _build_http_opener(bypass_proxy=True)
675 _public_opener = _build_http_opener(bypass_proxy=True, public_only=True)
676 _local_bridge_opener = _build_http_opener(bypass_proxy=True, local_bridge_only=True)
677 _DEFAULT_URLOPEN = urllib.request.urlopen
678
679
680 def _open_request(req, timeout, *, bypass_proxy=False):
681 """Honor test patches of urllib.request.urlopen; otherwise use the strip opener."""
682 url = getattr(req, "full_url", None) or str(req)
683 try:
684 _check_http_scheme(url)
685 except ValueError as exc:
686 raise urllib.error.URLError(str(exc)) from exc
687 current = urllib.request.urlopen
688 if current is not _DEFAULT_URLOPEN:
689 return current(req, timeout=timeout)
690 public_only = bool(getattr(req, _PUBLIC_ONLY_ATTR, False))
691 local_bridge_only = bool(getattr(req, _LOCAL_BRIDGE_ONLY_ATTR, False))
692 ip_validator = getattr(req, _IP_VALIDATOR_ATTR, None)
693 if public_only and ip_validator is None:
694 from . import public_host
695
696 if not public_host.is_public_address_syntax(url):
697 raise urllib.error.URLError(
698 public_host.NonPublicAddressError("refused non-public address")
699 )
700 return _public_opener.open(req, timeout=timeout)
701 if local_bridge_only and ip_validator is None:
702 return _local_bridge_opener.open(req, timeout=timeout)
703 if ip_validator is not None:
704 if local_bridge_only:
705 raise ValueError("local_bridge_only and ip_validator are mutually exclusive")
706 effective_validator = ip_validator
707 if public_only:
708 from . import public_host
709
710 if not public_host.is_public_address_syntax(url):
711 raise urllib.error.URLError(
712 public_host.NonPublicAddressError("refused non-public address")
713 )
714
715 def _combined_validator(addr):
716 return public_host._is_public_ip(addr) and bool(ip_validator(addr))
717
718 effective_validator = _combined_validator
719 return _build_http_opener(
720 bypass_proxy=True,
721 public_only=public_only,
722 ip_validator=effective_validator,
723 ).open(req, timeout=timeout)
724 opener = _direct_opener if bypass_proxy else _opener
725 return opener.open(req, timeout=timeout)
726
727
728 def open_request(req, timeout, *, bypass_proxy=False):
729 """Open ``req`` with cross-origin credential stripping (see #1062).
730
731 Public entry point for modules that build their own ``Request`` and would
732 otherwise call ``urllib.request.urlopen`` directly, bypassing the redirect
733 handler installed above.
734 """
735 return _open_request(req, timeout, bypass_proxy=bypass_proxy)
736
737
738 _failure_sink: ContextVar[Optional[list["HTTPError"]]] = ContextVar(
739 "last30days_http_failure_sink",
740 default=None,
741 )
742 _expected_miss_statuses: ContextVar[frozenset[int]] = ContextVar(
743 "last30days_http_expected_miss_statuses",
744 default=frozenset(),
745 )
746 _expected_no_host: ContextVar[Optional[list["HTTPError"]]] = ContextVar(
747 "last30days_http_expected_no_host",
748 default=None,
749 )
750 _on_dispatch_hook: ContextVar[Optional[Callable[[], None]]] = ContextVar(
751 "last30days_http_on_dispatch",
752 default=None,
753 )
754
755 _FIXTURE_FORMAT = "last30days-http-fixture/v1"
756 _FIXTURE_SECRET_KEYS = frozenset(
757 {
758 "api_key", "apikey", "authorization", "cookie", "key", "secret", "token",
759 "password", "passwd", "passphrase", "credential", "bearer", "jwt",
760 }
761 )
762 # Suffixes are matched on the normalized key, where camelCase collapses without
763 # a separator ("accessJwt" -> "accessjwt"), so these are bare rather than
764 # underscore-prefixed. "key" is deliberately absent: it would redact "monkey".
765 _FIXTURE_SECRET_KEY_SUFFIXES = (
766 "_api_key", "apikey", "_authorization", "_cookie", "_secret", "_token",
767 "password", "passwd", "passphrase", "credential", "jwt",
768 )
769 _fixture_lock = threading.Lock()
770 _fixture_state: Optional[dict[str, Any]] = None
771 _NO_FIXTURE = object()
772 _fixture_module_capture: ContextVar[bool] = ContextVar(
773 "last30days_fixture_module_capture",
774 default=False,
775 )
776
777
778 def _is_secret_key(value: object) -> bool:
779 key = re.sub(r"[^a-z0-9]+", "_", str(value).lower()).strip("_")
780 return (
781 key in _FIXTURE_SECRET_KEYS
782 or key.endswith(_FIXTURE_SECRET_KEY_SUFFIXES)
783 )
784
785
786 def _scrub_fixture_value(
787 value: Any,
788 *,
789 key: str = "",
790 redactions: frozenset[str] = frozenset(),
791 ) -> Any:
792 """Remove credentials before a recorded exchange reaches disk."""
793 if key and _is_secret_key(key):
794 return "<redacted>"
795 if isinstance(value, dict):
796 return {
797 str(child_key): _scrub_fixture_value(
798 child_value,
799 key=str(child_key),
800 redactions=redactions,
801 )
802 for child_key, child_value in value.items()
803 }
804 if isinstance(value, list):
805 return [_scrub_fixture_value(item, redactions=redactions) for item in value]
806 if isinstance(value, str):
807 scrubbed = value
808 for secret in sorted(redactions, key=len, reverse=True):
809 if len(secret) >= 4:
810 scrubbed = scrubbed.replace(secret, "<redacted>")
811 return scrubbed
812 return value
813
814
815 _AUTH_SCHEME_RE = re.compile(r"^(?:bearer|basic|token)\s+(\S+)$", re.IGNORECASE)
816
817
818 def _collect_secret_values(value: Any, *, key: str = "") -> set[str]:
819 values: set[str] = set()
820 if key and _is_secret_key(key) and value not in (None, ""):
821 text = str(value)
822 values.add(text)
823 # "Bearer <token>": the bare token is what a response body or an
824 # adapter error message echoes, so redact it on its own too.
825 scheme = _AUTH_SCHEME_RE.match(text.strip())
826 if scheme:
827 values.add(scheme.group(1))
828 return values
829 if isinstance(value, dict):
830 for child_key, child_value in value.items():
831 values.update(_collect_secret_values(child_value, key=str(child_key)))
832 elif isinstance(value, list):
833 for child in value:
834 values.update(_collect_secret_values(child))
835 return values
836
837
838 def _fixture_redactions(
839 url: str,
840 headers: dict[str, str],
841 json_data: Optional[Dict[str, Any]],
842 ) -> frozenset[str]:
843 values: set[str] = set()
844 try:
845 for key, value in parse_qsl(urlsplit(url).query, keep_blank_values=True):
846 if _is_secret_key(key) and value:
847 values.add(value)
848 except ValueError:
849 pass
850 values.update(_collect_secret_values(headers))
851 values.update(_collect_secret_values(json_data))
852 # Session-wide secret values (process env plus resolved config) so a
853 # bearer loaded from .env, Keychain, or pass is scrubbed at the HTTP
854 # seam even when this request carried it only in a header.
855 with _fixture_lock:
856 state = _fixture_state
857 if state is not None and state.get("redactions"):
858 values.update(state["redactions"])
859 return frozenset(values)
860
861
862 def config_secret_values(config: Dict[str, Any]) -> frozenset[str]:
863 """Secret VALUES from a resolved config, for fixture redaction.
864
865 Every key the Keychain/pass loader knows (``env.KEYCHAIN_KEYS``) plus any
866 secret-named key is a credential regardless of which layer supplied it.
867 """
868 values: set[str] = set()
869 try:
870 from . import env as _env
871 secret_keys = set(_env.KEYCHAIN_KEYS)
872 except Exception: # pragma: no cover - env is always importable
873 secret_keys = set()
874 for key, value in (config or {}).items():
875 if not isinstance(value, str) or len(value) < 4:
876 continue
877 if "://" in value:
878 # An endpoint (e.g. an API base URL) is an address, not a credential.
879 continue
880 if key in secret_keys or _is_secret_key(key):
881 values.add(value)
882 return frozenset(values)
883
884
885 def add_fixture_redactions(values) -> None:
886 """Register secret values with the active recording session, if any.
887
888 ``env.get_config`` calls this with the resolved config's secrets so a
889 bearer loaded from a file or a credential store is redacted at both the
890 HTTP seam and the module seam. A no-op outside a recording session.
891 """
892 extra = {v for v in values if isinstance(v, str) and len(v) >= 4}
893 if not extra:
894 return
895 with _fixture_lock:
896 state = _fixture_state
897 if state is None or state["mode"] != "record":
898 return
899 state["redactions"] = frozenset(state.get("redactions") or frozenset()) | extra
900
901
902 def _scrub_fixture_url(url: str) -> str:
903 try:
904 parts = urlsplit(url)
905 query = urlencode(
906 [
907 (key, "<redacted>" if _is_secret_key(key) else value)
908 for key, value in parse_qsl(parts.query, keep_blank_values=True)
909 ]
910 )
911 return urlunsplit((parts.scheme, parts.netloc, parts.path, query, parts.fragment))
912 except ValueError:
913 return url
914
915
916 def _scrub_log_url(url: str) -> str:
917 """Redact secret query parameters for logs, omitting unparseable URLs entirely."""
918 try:
919 parts = urlsplit(url)
920 except ValueError:
921 return "<unparseable url>"
922 query = urlencode(
923 [
924 (key, "<redacted>" if _is_secret_key(key) else value)
925 for key, value in parse_qsl(parts.query, keep_blank_values=True)
926 ]
927 )
928 return urlunsplit((parts.scheme, parts.netloc, parts.path, query, parts.fragment))
929
930
931 def _fixture_request(
932 method: str,
933 url: str,
934 json_data: Optional[Dict[str, Any]],
935 raw: bool,
936 ) -> dict[str, Any]:
937 request_data: dict[str, Any] = {
938 "method": method.upper(),
939 "url": _scrub_fixture_url(url),
940 "raw": bool(raw),
941 }
942 if json_data is not None:
943 request_data["json"] = _scrub_fixture_value(json_data)
944 return request_data
945
946
947 def _fixture_key(request_data: dict[str, Any]) -> str:
948 return json.dumps(request_data, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
949
950
951 @contextmanager
952 def recording_requests(path: str | Path):
953 """Record scrubbed HTTP exchanges to ``path`` for offline eval replay.
954
955 This process-global session is deliberate: source requests run in worker
956 threads, so a ContextVar would not observe the complete pipeline fan-out.
957 Nested or concurrent recording/replay sessions are rejected.
958 """
959 global _fixture_state
960 target = Path(path).expanduser()
961 if target.suffix.lower() != ".json":
962 target = target / "http.json"
963 with _fixture_lock:
964 if _fixture_state is not None:
965 raise RuntimeError("An HTTP fixture session is already active")
966 _fixture_state = {
967 "mode": "record",
968 "path": target,
969 "exchanges": [],
970 "source_exchanges": [],
971 # Secret VALUES from the environment, so module-seam recordings
972 # scrub tokens echoed inside normal string fields (adapter error
973 # messages, parsed item text), not just secret-named keys. The
974 # resolved config's secrets join via add_fixture_redactions once
975 # env.get_config runs inside the session.
976 "redactions": frozenset(
977 value
978 for key, value in os.environ.items()
979 if _is_secret_key(key) and isinstance(value, str) and len(value) >= 4
980 ),
981 }
982 completed = False
983 try:
984 yield target
985 completed = True
986 finally:
987 with _fixture_lock:
988 state = _fixture_state
989 _fixture_state = None
990 if state is not None and completed:
991 target.parent.mkdir(parents=True, exist_ok=True)
992 payload = {
993 "format": _FIXTURE_FORMAT,
994 "exchanges": state["exchanges"],
995 "source_exchanges": state["source_exchanges"],
996 }
997 # A recorded exchange is credential-adjacent by construction:
998 # redaction is key-name driven, so an unrecognized key name leaves
999 # a real value on disk. Create the temp file 0600 at open time
1000 # rather than chmod-ing after the write, or the credentials sit in
1001 # a world-readable file for the length of the write (the parent
1002 # directory is caller-supplied and not guaranteed private).
1003 # Mirrors last30days.save_output. Unlink first so a stale or
1004 # pre-planted temp file cannot be reused with its own wider mode --
1005 # O_CREAT does not alter the mode of an existing file.
1006 temporary = target.with_name(f".{target.name}.tmp")
1007 temporary.unlink(missing_ok=True)
1008 fd = os.open(
1009 temporary,
1010 os.O_CREAT | os.O_EXCL | os.O_WRONLY,
1011 0o600,
1012 )
1013 with os.fdopen(fd, "w", encoding="utf-8") as handle:
1014 handle.write(
1015 json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
1016 )
1017 temporary.replace(target)
1018
1019
1020 @contextmanager
1021 def fixture_module_capture(enabled: bool):
1022 """Suppress nested HTTP recording when a whole adapter result is captured."""
1023 token = _fixture_module_capture.set(enabled)
1024 try:
1025 yield
1026 finally:
1027 _fixture_module_capture.reset(token)
1028
1029
1030 @contextmanager
1031 def replaying_requests(path: str | Path):
1032 """Replay recorded exchanges and fail closed on any unrecorded request."""
1033 global _fixture_state
1034 target = Path(path).expanduser()
1035 if target.is_dir():
1036 target = target / "http.json"
1037 payload = json.loads(target.read_text(encoding="utf-8"))
1038 if payload.get("format") != _FIXTURE_FORMAT:
1039 raise ValueError(f"Unsupported HTTP fixture format in {target}")
1040 queues: dict[str, list[dict[str, Any]]] = {}
1041 for exchange in payload.get("exchanges") or []:
1042 queues.setdefault(_fixture_key(exchange["request"]), []).append(exchange["response"])
1043 source_queues: dict[str, list[Any]] = {}
1044 for exchange in payload.get("source_exchanges") or []:
1045 source_queues.setdefault(_fixture_key(exchange["request"]), []).append(exchange)
1046 with _fixture_lock:
1047 if _fixture_state is not None:
1048 raise RuntimeError("An HTTP fixture session is already active")
1049 _fixture_state = {
1050 "mode": "replay",
1051 "path": target,
1052 "queues": queues,
1053 "source_queues": source_queues,
1054 }
1055 try:
1056 yield target
1057 with _fixture_lock:
1058 unused = sum(len(values) for values in queues.values()) + sum(
1059 len(values) for values in source_queues.values()
1060 )
1061 if unused:
1062 raise AssertionError(f"HTTP fixture replay left {unused} unused exchange(s): {target}")
1063 finally:
1064 with _fixture_lock:
1065 _fixture_state = None
1066
1067
1068 class ResponseHeaders(dict):
1069 """Response headers keyed by lowercased name; lookups ignore case.
1070
1071 ``url`` is the address that answered, after any redirects ('' when not
1072 known, as for a replayed fixture).
1073 """
1074
1075 url = ""
1076
1077 def __init__(self, pairs=()):
1078 super().__init__(
1079 (str(name).lower(), value) for name, value in dict(pairs).items()
1080 )
1081
1082 def __getitem__(self, name):
1083 return super().__getitem__(str(name).lower())
1084
1085 def __contains__(self, name):
1086 return super().__contains__(str(name).lower())
1087
1088 def get(self, name, default=None):
1089 return super().get(str(name).lower(), default)
1090
1091
1092 def _fixture_replay(request_data: dict[str, Any], *, return_headers: bool = False) -> Any:
1093 with _fixture_lock:
1094 state = _fixture_state
1095 if state is None or state["mode"] != "replay":
1096 return _NO_FIXTURE
1097 queue = state["queues"].get(_fixture_key(request_data))
1098 if not queue:
1099 raise AssertionError(
1100 "Unrecorded HTTP request during fixture replay: "
1101 f"{request_data['method']} {request_data['url']}"
1102 )
1103 response = queue.pop(0)
1104 if response.get("error"):
1105 error = response["error"]
1106 recorded_error = HTTPError(
1107 str(error.get("message") or "Recorded HTTP error"),
1108 status_code=error.get("status_code"),
1109 body=error.get("body"),
1110 outcome_state=error.get("outcome_state"),
1111 )
1112 # Callers branch on this (a dead careers host is not asked for its
1113 # second page), so a replay without it makes requests the live run
1114 # never recorded.
1115 recorded_error.no_host = bool(error.get("no_host"))
1116 _raise(recorded_error)
1117 if return_headers:
1118 # An exchange recorded by a request that did not ask for headers has
1119 # none stored; it replays with an empty set.
1120 return response.get("value"), ResponseHeaders(response.get("headers") or {})
1121 return response.get("value")
1122
1123
1124 def _fixture_record(
1125 request_data: dict[str, Any],
1126 *,
1127 value: Any = None,
1128 error: Optional["HTTPError"] = None,
1129 redactions: frozenset[str] = frozenset(),
1130 headers: Optional["ResponseHeaders"] = None,
1131 ) -> None:
1132 if _fixture_module_capture.get():
1133 return
1134 with _fixture_lock:
1135 state = _fixture_state
1136 if state is None or state["mode"] != "record":
1137 return
1138 # Union the session's env-derived secret VALUES in, so a credential
1139 # echoed back inside an ordinary response field is scrubbed on this
1140 # path too, not only on the source-record path. Response scrubbing does
1141 # not feed _fixture_key, so this cannot make a replay key
1142 # machine-dependent.
1143 redactions = redactions | (state.get("redactions") or frozenset())
1144 response: dict[str, Any]
1145 if error is None:
1146 response = {"value": _scrub_fixture_value(value, redactions=redactions)}
1147 if headers is not None:
1148 # Scrubbed like any other value: a secret-named header (a
1149 # session token, Set-Cookie) is stored as "<redacted>".
1150 response["headers"] = _scrub_fixture_value(
1151 dict(headers), redactions=redactions
1152 )
1153 else:
1154 response = {
1155 "error": _scrub_fixture_value(
1156 {
1157 "message": str(error),
1158 "status_code": error.status_code,
1159 "body": error.body,
1160 "outcome_state": error.outcome_state,
1161 },
1162 redactions=redactions,
1163 )
1164 }
1165 if error.no_host:
1166 response["error"]["no_host"] = True
1167 state["exchanges"].append({"request": request_data, "response": response})
1168
1169
1170 def fixture_source_replay(request_data: dict[str, Any]) -> tuple[bool, Any]:
1171 """Return a recorded CLI-backed source result when replay is active."""
1172 scrubbed = _scrub_fixture_value(request_data)
1173 with _fixture_lock:
1174 state = _fixture_state
1175 if state is None or state["mode"] != "replay":
1176 return False, None
1177 queue = state["source_queues"].get(_fixture_key(scrubbed))
1178 if not queue:
1179 raise AssertionError(
1180 "Unrecorded CLI-backed source request during fixture replay: "
1181 f"{request_data.get('source', 'unknown')}"
1182 )
1183 exchange = queue.pop(0)
1184 if exchange.get("type") == "error":
1185 error = exchange.get("error") or {}
1186 raise RecordedSourceError(
1187 str(error.get("message") or "Recorded source error"),
1188 exception_type=str(error.get("exception_type") or "Exception"),
1189 outcome_state=error.get("outcome_state"),
1190 )
1191 return True, exchange.get("value")
1192
1193
1194 def fixture_source_record(request_data: dict[str, Any], value: Any) -> None:
1195 """Record the parsed output of a source adapter that bypasses http.py."""
1196 with _fixture_lock:
1197 state = _fixture_state
1198 if state is None or state["mode"] != "record":
1199 return
1200 session_redactions = state.get("redactions") or frozenset()
1201 state["source_exchanges"].append(
1202 {
1203 "request": _scrub_fixture_value(request_data, redactions=session_redactions),
1204 "value": _scrub_fixture_value(value, redactions=session_redactions),
1205 }
1206 )
1207
1208
1209 def fixture_source_record_error(request_data: dict[str, Any], error: Exception) -> None:
1210 """Record a replayable failure from a source adapter that bypasses http.py."""
1211 with _fixture_lock:
1212 state = _fixture_state
1213 if state is None or state["mode"] != "record":
1214 return
1215 session_redactions = state.get("redactions") or frozenset()
1216 state["source_exchanges"].append(
1217 {
1218 "request": _scrub_fixture_value(request_data, redactions=session_redactions),
1219 "type": "error",
1220 "error": _scrub_fixture_value(
1221 {
1222 "exception_type": type(error).__name__,
1223 "message": str(error),
1224 "outcome_state": getattr(error, "outcome_state", None),
1225 }
1226 , redactions=session_redactions),
1227 }
1228 )
1229
1230
1231 class RecordedSourceError(RuntimeError):
1232 """Failure restored from a recorded module-backed source exchange."""
1233
1234 def __init__(
1235 self,
1236 message: str,
1237 *,
1238 exception_type: str,
1239 outcome_state: Optional[str] = None,
1240 ):
1241 super().__init__(message)
1242 self.exception_type = exception_type
1243 self.outcome_state = outcome_state
1244
1245
1246 def _is_dns_failure(err: urllib.error.URLError) -> bool:
1247 """Return True if a URLError was caused by DNS resolution (gaierror)."""
1248 return isinstance(getattr(err, "reason", None), socket.gaierror)
1249
1250
1251 class HTTPError(Exception):
1252 """HTTP request error with status code."""
1253 def __init__(
1254 self,
1255 message: str,
1256 status_code: Optional[int] = None,
1257 body: Optional[str] = None,
1258 outcome_state: Optional[str] = None,
1259 ):
1260 super().__init__(message)
1261 self.status_code = status_code
1262 self.body = body
1263 # True when no host answered: the name did not resolve or the
1264 # connection was refused. See ``expected_no_host``.
1265 self.no_host = False
1266 self.outcome_state = outcome_state or classify_failure(
1267 status_code=status_code,
1268 message=message,
1269 )
1270
1271
1272 class DeadlineExceeded(HTTPError):
1273 """The caller's shared wall deadline expired across request retries."""
1274
1275 def __init__(self, *, dispatched: bool = False):
1276 super().__init__(
1277 "Request deadline exceeded",
1278 outcome_state=health.TIMEOUT,
1279 )
1280 self.dispatched = dispatched
1281
1282
1283 class ResponseTooLarge(HTTPError):
1284 """An upstream response exceeded the configured byte limit."""
1285
1286 def __init__(self, message: str):
1287 super().__init__(message, outcome_state=health.ERROR)
1288
1289
1290 def _content_length(headers) -> Optional[int]:
1291 if not headers or not hasattr(headers, "get"):
1292 return None
1293 raw = headers.get("Content-Length")
1294 if raw is None or isinstance(raw, bool):
1295 return None
1296 try:
1297 value = int(str(raw).strip())
1298 except (TypeError, ValueError):
1299 return None
1300 return value if value >= 0 else None
1301
1302
1303 _READ_CHUNK_BYTES = 65_536
1304
1305
1306 def _read_bounded(
1307 stream,
1308 max_bytes: int,
1309 *,
1310 truncate: bool = False,
1311 cancel: Optional[threading.Event] = None,
1312 ) -> bytes:
1313 if cancel is not None and cancel.is_set():
1314 raise DeadlineExceeded()
1315 if not truncate:
1316 declared = (
1317 stream.length
1318 if isinstance(stream, http.client.HTTPResponse)
1319 else _content_length(getattr(stream, "headers", None))
1320 )
1321 if isinstance(declared, int) and not isinstance(declared, bool) and declared > max_bytes:
1322 raise ResponseTooLarge(
1323 f"Response Content-Length {declared} exceeds limit of {max_bytes} bytes"
1324 )
1325 limit = max_bytes if truncate else max_bytes + 1
1326 reader = (
1327 stream.fp
1328 if isinstance(stream, urllib.error.HTTPError)
1329 and isinstance(getattr(stream, "fp", None), io.IOBase)
1330 else stream
1331 )
1332 if cancel is not None and isinstance(reader, io.IOBase) and hasattr(reader, "read1"):
1333 chunks: list[bytes] = []
1334 total = 0
1335 while total < limit:
1336 if cancel.is_set():
1337 raise DeadlineExceeded()
1338 chunk = reader.read1(min(_READ_CHUNK_BYTES, limit - total))
1339 if not chunk:
1340 break
1341 chunks.append(chunk)
1342 total += len(chunk)
1343 if cancel.is_set():
1344 raise DeadlineExceeded()
1345 data = b"".join(chunks)
1346 else:
1347 data = stream.read(limit)
1348 if cancel is not None and cancel.is_set():
1349 raise DeadlineExceeded()
1350 if data is None:
1351 return b""
1352 if truncate:
1353 return data[:max_bytes]
1354 if len(data) > max_bytes:
1355 raise ResponseTooLarge(f"Response body exceeded limit of {max_bytes} bytes")
1356 if (
1357 isinstance(stream, http.client.HTTPResponse)
1358 and not stream.chunked
1359 and getattr(stream, "_method", None) != "HEAD"
1360 and isinstance(stream.length, int)
1361 and stream.length > 0
1362 ):
1363 raise http.client.IncompleteRead(data, stream.length)
1364 return data
1365
1366
1367 @contextmanager
1368 def capture_failures():
1369 """Capture terminal request failures in the current retrieval context.
1370
1371 Source modules historically catch ``HTTPError`` and return an empty result.
1372 The context-local sink lets the pipeline retain that failure without shared
1373 mutable state across its worker threads.
1374 """
1375 failures: list[HTTPError] = []
1376 token = _failure_sink.set(failures)
1377 try:
1378 yield failures
1379 finally:
1380 _failure_sink.reset(token)
1381
1382
1383 def has_captured_failures() -> bool:
1384 """Check the current failure sink without replacing or consuming it."""
1385 return bool(_failure_sink.get())
1386
1387
1388 def captured_failures() -> tuple["HTTPError", ...]:
1389 """The failures captured so far in the current context, without replacing or consuming them."""
1390 return tuple(_failure_sink.get() or ())
1391
1392
1393 @contextmanager
1394 def tee_failures():
1395 """Observe failures locally WITHOUT hiding them from the enclosing sink.
1396
1397 ``capture_failures()`` *replaces* the context-local sink, so nesting it
1398 inside a retrieval context swallows the very failure the pipeline needs.
1399 This yields a local list and forwards its contents to the parent sink on
1400 exit, so a swallow site (``get_text`` returns None and drops the status)
1401 can recover what it lost while the pipeline still sees the failure.
1402 """
1403 parent = _failure_sink.get()
1404 local: list[HTTPError] = []
1405 token = _failure_sink.set(local)
1406 try:
1407 yield local
1408 finally:
1409 _failure_sink.reset(token)
1410 if parent is not None:
1411 parent.extend(local)
1412
1413
1414 def other_host_form(host: str) -> str:
1415 """The ``www.`` form of a bare two-label host, or the bare form of a ``www.``
1416 host, or "" when the host has neither (a subdomain such as ``jobs.x.com``).
1417
1418 Some sites answer on only one of the two: ``nvidia.com`` drops the
1419 connection while ``www.nvidia.com`` serves the page.
1420 """
1421 host = (host or "").strip().lower()
1422 if host.startswith("www."):
1423 bare = host[4:]
1424 return bare if "." in bare else ""
1425 return f"www.{host}" if host.count(".") == 1 else ""
1426
1427
1428 def connection_dropped(failures: list[HTTPError]) -> bool:
1429 """True when a request reached no page because the connection was dropped:
1430 no HTTP status, not a timeout, and not a name that failed to resolve or a
1431 refused connection, which say nothing answers there at all."""
1432 return any(
1433 failure.status_code is None
1434 and failure.outcome_state != health.TIMEOUT
1435 and not failure.no_host
1436 for failure in failures
1437 )
1438
1439
1440 def text_on_either_host_form(fetch: Callable[[str], Optional[str]], url: str) -> tuple[Optional[str], str]:
1441 """``fetch(url)``, retried once on the site's other host form when the
1442 connection was dropped. Returns the text and the URL that gave it.
1443
1444 Only one failure is kept for the run's record: the first one when both
1445 forms fail, none when the other form answers.
1446 """
1447 parts = urlsplit(url)
1448 other = other_host_form(parts.hostname or "")
1449 with tee_failures() as failures:
1450 text = fetch(url)
1451 if text or not other or not connection_dropped(failures):
1452 return text, url
1453 first = list(failures)
1454 failures.clear()
1455 other_url = urlunsplit(parts._replace(netloc=other))
1456 text = fetch(other_url)
1457 if text:
1458 return text, other_url
1459 failures[:] = first
1460 return None, url
1461
1462
1463 @contextmanager
1464 def expected_misses(*status_codes: int):
1465 """Exclude adapter-declared probe misses from captured run failures."""
1466 token = _expected_miss_statuses.set(
1467 _expected_miss_statuses.get().union(status_codes)
1468 )
1469 try:
1470 yield
1471 finally:
1472 _expected_miss_statuses.reset(token)
1473
1474
1475 @contextmanager
1476 def expected_no_host():
1477 """Exclude "there is no such host" failures from captured run failures.
1478
1479 For a caller that tries a host it only guessed: a name that does not
1480 resolve, or a connection the host refuses, means nothing is there, not
1481 that a source is down. Yields the failures left out, so the caller can
1482 stop asking that host. Timeouts and HTTP errors are still recorded.
1483 """
1484 dropped: list[HTTPError] = []
1485 token = _expected_no_host.set(dropped)
1486 try:
1487 yield dropped
1488 finally:
1489 _expected_no_host.reset(token)
1490
1491
1492 @contextmanager
1493 def observe_dispatch(callback: Callable[[], None]):
1494 """Invoke ``callback`` once an underlying transport attempt is dispatched.
1495
1496 Nested hooks chain so inner observers do not hide outer ones.
1497 """
1498 parent = _on_dispatch_hook.get()
1499 if parent is None:
1500 combined = callback
1501 else:
1502 def combined() -> None:
1503 parent()
1504 callback()
1505 token = _on_dispatch_hook.set(combined)
1506 try:
1507 yield
1508 finally:
1509 _on_dispatch_hook.reset(token)
1510
1511
1512 def _is_no_host(error: BaseException) -> bool:
1513 """A name that did not resolve or a refused connection, bare or wrapped
1514 in a ``URLError``."""
1515 reason = getattr(error, "reason", error)
1516 return isinstance(reason, (socket.gaierror, ConnectionRefusedError))
1517
1518
1519 def submit_with_context(executor, func, /, *args, **kwargs) -> Future:
1520 """Submit a worker with the caller's failure-capture context."""
1521 context = copy_context()
1522 return executor.submit(context.run, func, *args, **kwargs)
1523
1524
1525 def _record_failure(error: HTTPError) -> None:
1526 if error.status_code in _expected_miss_statuses.get():
1527 return
1528 no_host = _expected_no_host.get()
1529 if no_host is not None and error.no_host:
1530 no_host.append(error)
1531 return
1532 sink = _failure_sink.get()
1533 if sink is not None:
1534 sink.append(error)
1535
1536
1537 def _raise(error: HTTPError) -> None:
1538 _record_failure(error)
1539 raise error
1540
1541
1542 def classify_failure(*, status_code: Optional[int] = None, message: str = "") -> str:
1543 """Map a request failure to the doctor-aligned per-run vocabulary."""
1544 text = message.lower()
1545 if status_code == 429 or any(
1546 marker in text for marker in ("http 429", "status 429", "rate limit", "too many requests")
1547 ):
1548 return health.RATE_LIMITED
1549 # Credit exhaustion is checked before the auth branch: a 402 (or a body
1550 # saying the account has no credits) asks the user to top up, not to
1551 # re-authenticate. Markers stay narrow on purpose: the bare word "credits"
1552 # is not one ("10,000 free credits" is onboarding copy, not a failure).
1553 if status_code == 402 or any(
1554 marker in text
1555 for marker in (
1556 "http 402",
1557 "status 402",
1558 "payment required",
1559 "insufficient credits",
1560 "does not have any credits",
1561 "out of credits",
1562 )
1563 ):
1564 return health.PAYMENT_REQUIRED
1565 if status_code in (401, 403) or any(
1566 marker in text
1567 for marker in (
1568 "http 401",
1569 "http 403",
1570 "status 401",
1571 "status 403",
1572 "unauthorized",
1573 "forbidden",
1574 "authentication failed",
1575 "expired token",
1576 "not signed in",
1577 "not logged in",
1578 "invalid_grant",
1579 "refresh token",
1580 "session expired",
1581 "grok session expired",
1582 )
1583 ):
1584 return health.AUTH_FAILED
1585 if status_code == 408 or "timed out" in text or "timeout" in text:
1586 return health.TIMEOUT
1587 if any(
1588 marker in text
1589 for marker in (
1590 "invalid json",
1591 "json decode",
1592 "schema",
1593 "interstitial",
1594 "non-json",
1595 )
1596 ):
1597 return health.SCHEMA_DRIFT
1598 if any(
1599 marker in text
1600 for marker in (
1601 "url error",
1602 "connection error",
1603 "connection refused",
1604 "connection reset",
1605 "name or service not known",
1606 "temporary failure in name resolution",
1607 "nodename nor servname",
1608 "dns",
1609 "network is unreachable",
1610 )
1611 ):
1612 return health.UNREACHABLE
1613 return health.ERROR
1614
1615
1616 def request(
1617 method: str,
1618 url: str,
1619 headers: Optional[Dict[str, str]] = None,
1620 json_data: Optional[Dict[str, Any]] = None,
1621 params: Optional[Dict[str, Any]] = None,
1622 timeout: float = DEFAULT_TIMEOUT,
1623 retries: int = MAX_RETRIES,
1624 max_429_retries: int = MAX_429_RETRIES,
1625 raw: bool = False,
1626 deadline_monotonic: float | None = None,
1627 cancel: threading.Event | None = None,
1628 owned_get: bool = False,
1629 on_retry: Callable[[], None] | None = None,
1630 bypass_proxy: bool = False,
1631 retry_dns: bool = True,
1632 return_headers: bool = False,
1633 redirect_guard: Callable[[str], bool] | None = None,
1634 sensitive_url: bool = False,
1635 public_only: bool = False,
1636 local_bridge_only: bool = False,
1637 max_bytes: Optional[int] = None,
1638 decode_errors: str = "strict",
1639 ip_validator: Optional[Callable[[Union[ipaddress.IPv4Address, ipaddress.IPv6Address]], bool]] = None,
1640 on_dispatch: Callable[[], None] | None = None,
1641 ) -> Union[Dict[str, Any], str, tuple[Union[Dict[str, Any], str], ResponseHeaders]]:
1642 """Make an HTTP request and return JSON response.
1643
1644 Args:
1645 method: HTTP method (GET, POST, etc.)
1646 url: Request URL
1647 headers: Optional headers dict
1648 json_data: Optional JSON body (for POST)
1649 params: Optional query-string params. Values are stringified. None values
1650 are dropped. If ``url`` already has a query string, ``params`` is appended.
1651 timeout: Request timeout in seconds
1652 retries: Maximum number of attempts (clamped to at least 1; passing
1653 retries=0 executes a single attempt with no retries, including on
1654 DNS failures, whereas retries>=1 honors ``retry_dns``)
1655 max_429_retries: Maximum 429 retries before giving up (separate cap)
1656 raw: If True, return raw response text instead of parsed JSON
1657 deadline_monotonic: Optional absolute monotonic deadline shared by all
1658 attempts and retry delays.
1659 owned_get: Run GET transport in a child that is killed and reaped at
1660 its deadline. Requires deadline_monotonic; other methods are refused.
1661 on_retry: Called before each transport attempt after the first.
1662 bypass_proxy: Use a direct connection for this request and its redirects.
1663 retry_dns: Widen the retry budget to MIN_DNS_RETRIES when the name does
1664 not resolve. Off for a host the caller only guessed, where a name
1665 that does not resolve is the answer.
1666 return_headers: Also return the response headers, for a host that
1667 answers in a header (a session token) rather than the body. Not
1668 available with owned_get, whose child process reports no headers.
1669 sensitive_url: Exclude credential-bearing URLs and their responses
1670 from request diagnostics and fixture capture.
1671 max_bytes: Maximum response body size in bytes (defaults to
1672 ``MAX_RESPONSE_BYTES``). Oversized responses fail fast with
1673 ``ResponseTooLarge``.
1674
1675 Returns:
1676 Parsed JSON response as dict, or raw text string if raw=True. With
1677 return_headers=True, a ``(body, ResponseHeaders)`` tuple instead.
1678
1679 Raises:
1680 HTTPError: On request failure
1681 """
1682 if max_bytes is not None and max_bytes <= 0:
1683 raise ValueError("max_bytes must be positive")
1684 if decode_errors not in ("strict", "replace", "ignore"):
1685 raise ValueError(f"unsupported decode_errors mode: {decode_errors!r}")
1686 effective_max_bytes = MAX_RESPONSE_BYTES if max_bytes is None else max_bytes
1687 if retries <= 0:
1688 retry_dns = False
1689 retries = 1
1690 if owned_get and (method != "GET" or json_data is not None):
1691 raise ValueError("owned transport requires a bodyless GET")
1692 if owned_get and deadline_monotonic is None:
1693 raise ValueError("owned GET requires an operation deadline")
1694 if owned_get and return_headers:
1695 raise ValueError("owned GET does not report response headers")
1696 if public_only and local_bridge_only:
1697 raise ValueError("public_only and local_bridge_only are mutually exclusive")
1698 if local_bridge_only and ip_validator is not None:
1699 raise ValueError("local_bridge_only and ip_validator are mutually exclusive")
1700 if owned_get and (redirect_guard is not None or public_only or local_bridge_only or ip_validator is not None):
1701 raise ValueError("owned GET does not support redirect_guard, public_only, local_bridge_only, or ip_validator")
1702 try:
1703 _check_http_scheme(url)
1704 except ValueError as exc:
1705 _raise(HTTPError(str(exc)))
1706 if public_only:
1707 from . import public_host
1708
1709 if not public_host.is_public_address_syntax(url):
1710 _raise(HTTPError("Refused non-public URL"))
1711 headers = headers or {}
1712 headers.setdefault("User-Agent", USER_AGENT)
1713
1714 # A provider key bound for a plaintext loopback endpoint must not ride the
1715 # ambient HTTP proxy. CONFIGURATION.md promises loopback provider overrides
1716 # bypass proxy settings for the request, "keeping the token on the local
1717 # connection" - `SCRAPECREATORS_BASE_URL` carries its key in `X-api-key`, not
1718 # `Authorization`, so it needs the same rule as the bearer-based providers.
1719 # Keyed on the credential header, not the URL alone: ordinary loopback
1720 # traffic keeps whatever proxy route it was configured with.
1721 if not bypass_proxy and _is_loopback_http_url(url) and _carries_provider_credential(headers):
1722 bypass_proxy = True
1723
1724 if params:
1725 filtered = {k: str(v) for k, v in params.items() if v is not None}
1726 if filtered:
1727 separator = "&" if ("?" in url) else "?"
1728 url = f"{url}{separator}{urlencode(filtered)}"
1729 # Encode any non-ASCII characters to prevent UnicodeEncodeError from
1730 # http.client.HTTPConnection.putrequest (which uses latin-1 internally).
1731 # Only encode path, query, and fragment — not the hostname (netloc), which
1732 # needs IDNA encoding instead of percent-encoding for non-ASCII domains.
1733 parts = urlsplit(url)
1734 safe = '/:@!$&\'()*+,;=-._~%?#[]=+'
1735 url = urlunsplit((
1736 parts.scheme,
1737 parts.netloc,
1738 quote(parts.path, safe=safe),
1739 quote(parts.query, safe=safe),
1740 quote(parts.fragment, safe=safe),
1741 ))
1742
1743 # Proxy mode: a paid call backed by the proxy sentinel goes to the metered
1744 # proxy instead (lib/proxy.py). Rewritten before fixture capture so the
1745 # recorded request carries the proxy URL and the bearer key is redacted.
1746 orig_header_secrets = _collect_secret_values(headers)
1747 usage_url = url
1748 try:
1749 routed = proxy.route(method, url, headers)
1750 except proxy.ProxyUnavailable as exc:
1751 from . import auth_safety
1752
1753 safe_proxy_err = auth_safety.scrub_secrets(str(exc), orig_header_secrets)
1754 unavailable = HTTPError(f"API key proxy: {safe_proxy_err}", exc.status_code)
1755 _raise(unavailable)
1756 call_key = None
1757 if routed is not None:
1758 url = routed.url
1759 headers = routed.headers
1760 call_key = proxy.new_idempotency_key()
1761 headers[proxy.IDEMPOTENCY_HEADER] = call_key
1762
1763 fixture_request = None if sensitive_url else _fixture_request(method, url, json_data, raw)
1764 fixture_redactions = _fixture_redactions(url, headers, json_data) | orig_header_secrets
1765 replayed = _fixture_replay(
1766 fixture_request if fixture_request is not None else {"method": method, "url": "<redacted>"},
1767 return_headers=return_headers,
1768 )
1769 if replayed is not _NO_FIXTURE:
1770 return replayed
1771
1772 data = None
1773 if json_data is not None:
1774 data = json.dumps(json_data).encode('utf-8')
1775 headers.setdefault("Content-Type", "application/json")
1776
1777 req = urllib.request.Request(url, data=data, headers=headers, method=method)
1778 if redirect_guard is not None:
1779 setattr(req, _REDIRECT_GUARD_ATTR, redirect_guard)
1780 if public_only:
1781 setattr(req, _PUBLIC_ONLY_ATTR, True)
1782 if local_bridge_only:
1783 setattr(req, _LOCAL_BRIDGE_ONLY_ATTR, True)
1784 if ip_validator is not None:
1785 setattr(req, _IP_VALIDATOR_ATTR, ip_validator)
1786
1787 from . import auth_safety
1788
1789 def _scrub_error_text(value: Optional[str]) -> Optional[str]:
1790 if value is None:
1791 return None
1792 return auth_safety.scrub_secrets(
1793 _URL_USERINFO_RE.sub(r"\1", value),
1794 fixture_redactions,
1795 )
1796
1797 def log_request(message: str) -> None:
1798 if not sensitive_url:
1799 log(
1800 auth_safety.scrub_secrets(
1801 _scrub_fixture_value(message, redactions=fixture_redactions),
1802 fixture_redactions,
1803 )
1804 )
1805
1806 safe_url = re.sub(r'([?&])(key|api_key|token|secret)=[^&]*', r'\1\2=***', url)
1807 log_request(f"{method} {safe_url}")
1808
1809 last_error = None
1810 rate_limit_count = 0
1811 # DNS failures get a dedicated minimum attempt count + exponential backoff.
1812 # `effective_retries` is the actual loop bound; we expand it on the first
1813 # gaierror if the caller passed a smaller `retries` value than MIN_DNS_RETRIES.
1814 effective_retries = retries
1815 dns_attempts = 0
1816 attempt = 0
1817 response_headers: Optional[ResponseHeaders] = None
1818 dispatch_hook = _on_dispatch_hook.get()
1819 request_dispatched = False
1820
1821 def _notify_dispatch() -> None:
1822 nonlocal request_dispatched
1823 if request_dispatched:
1824 return
1825 request_dispatched = True
1826 if on_dispatch is not None:
1827 on_dispatch()
1828 if dispatch_hook is not None:
1829 dispatch_hook()
1830
1831 def raise_recorded(error: HTTPError) -> None:
1832 if fixture_request is not None:
1833 _fixture_record(fixture_request, error=error, redactions=fixture_redactions)
1834 _raise(error)
1835
1836 def deadline_error() -> HTTPError:
1837 return DeadlineExceeded(dispatched=request_dispatched)
1838
1839 def sleep_before_retry(delay: float) -> bool:
1840 """Sleep only when the full delay fits inside the caller's deadline."""
1841 nonlocal last_error
1842 if cancel is not None and cancel.is_set():
1843 last_error = deadline_error()
1844 return False
1845 if deadline_monotonic is not None:
1846 remaining = deadline_monotonic - time.monotonic()
1847 if remaining <= 0 or delay >= remaining:
1848 last_error = deadline_error()
1849 return False
1850 if cancel is not None:
1851 if cancel.wait(delay):
1852 last_error = deadline_error()
1853 return False
1854 else:
1855 time.sleep(delay)
1856 return True
1857
1858 def open_and_read(
1859 request_timeout: float,
1860 *,
1861 dispatch_notified: bool = False,
1862 ) -> tuple[int, str | None, urllib.error.HTTPError | None]:
1863 nonlocal response_headers
1864 if not dispatch_notified:
1865 _notify_dispatch()
1866 try:
1867 transport = (
1868 _open_request(req, request_timeout, bypass_proxy=True)
1869 if bypass_proxy else _open_request(req, request_timeout)
1870 )
1871 with transport as response:
1872 if routed is not None:
1873 proxy.record_charge(getattr(response, "headers", None), call_key=call_key)
1874 if return_headers:
1875 response_headers = ResponseHeaders(response.headers.items())
1876 final = response.geturl() if hasattr(response, "geturl") else ""
1877 response_headers.url = final if isinstance(final, str) else ""
1878 return (
1879 response.status,
1880 _read_bounded(
1881 response, effective_max_bytes, cancel=cancel,
1882 ).decode('utf-8', errors=decode_errors),
1883 None,
1884 )
1885 except urllib.error.HTTPError as error:
1886 # Error bodies can stall just like successful bodies. Read both
1887 # inside the same deadline-protected worker before classification.
1888 body = None
1889 try:
1890 raw_error = _read_bounded(
1891 error, MAX_ERROR_BODY_BYTES, truncate=True, cancel=cancel,
1892 )
1893 body = raw_error.decode(
1894 'utf-8',
1895 errors='replace' if len(raw_error) == MAX_ERROR_BODY_BYTES else 'strict',
1896 )
1897 except (OSError, UnicodeDecodeError, ValueError):
1898 pass
1899 finally:
1900 if isinstance(getattr(error, "fp", None), http.client.HTTPResponse):
1901 try:
1902 error.close()
1903 except Exception:
1904 pass
1905 return error.code, body, error
1906
1907 def open_and_read_before_deadline(
1908 request_timeout: float,
1909 ) -> tuple[int, str | None, urllib.error.HTTPError | None]:
1910 """Stop waiting at the wall deadline, even during DNS or body reads."""
1911 if owned_get:
1912 try:
1913 owned_kwargs: Dict[str, Any] = {}
1914 if routed is not None:
1915 # Only a proxied call needs the charge header back.
1916 owned_kwargs["with_headers"] = True
1917 if max_bytes is not None:
1918 owned_kwargs["max_bytes"] = max_bytes
1919 if bypass_proxy:
1920 owned_kwargs["bypass_proxy"] = True
1921 if on_dispatch is not None or dispatch_hook is not None:
1922 owned_kwargs["on_start"] = _notify_dispatch
1923 owned = bounded_get.get(
1924 req, timeout=request_timeout,
1925 deadline_monotonic=deadline_monotonic, cancel=cancel,
1926 **owned_kwargs,
1927 )
1928 except bounded_get.GetLaunchError:
1929 cancel_deadline = (
1930 deadline_monotonic
1931 if deadline_monotonic is not None
1932 else time.monotonic() + min(request_timeout, usage._JOURNAL_TIMEOUT_SECONDS)
1933 )
1934 with usage.with_deadline(cancel_deadline):
1935 usage.cancel(charge)
1936 raise
1937 except bounded_get.GetTimeout as exc:
1938 if exc.started:
1939 _notify_dispatch()
1940 else:
1941 cancel_deadline = (
1942 deadline_monotonic
1943 if deadline_monotonic is not None
1944 else time.monotonic() + min(request_timeout, usage._JOURNAL_TIMEOUT_SECONDS)
1945 )
1946 with usage.with_deadline(cancel_deadline):
1947 usage.cancel(charge)
1948 raise deadline_error() from exc
1949 except bounded_get.ResponseTooLarge as exc:
1950 _notify_dispatch()
1951 raise ResponseTooLarge(str(exc)) from exc
1952 except Exception:
1953 _notify_dispatch()
1954 raise
1955 _notify_dispatch()
1956 if routed is not None:
1957 status, body, error, owned_headers = owned
1958 if error is None:
1959 proxy.record_charge(dict(owned_headers), call_key=call_key)
1960 else:
1961 status, body, error = owned
1962 try:
1963 if body is None:
1964 decoded = None
1965 elif error is not None:
1966 decoded = body.decode("utf-8", errors="replace")
1967 else:
1968 decoded = body.decode("utf-8", errors=decode_errors)
1969 except UnicodeDecodeError:
1970 if error is None:
1971 raise
1972 decoded = None
1973 return status, decoded, error
1974 if deadline_monotonic is None and cancel is None:
1975 return open_and_read(request_timeout)
1976 if cancel is not None and cancel.is_set():
1977 raise deadline_error()
1978 wait_deadline = deadline_monotonic or (time.monotonic() + request_timeout)
1979 remaining = wait_deadline - time.monotonic()
1980 if remaining <= 0:
1981 raise deadline_error()
1982 future: Future = Future()
1983 dispatch_lock = threading.Lock()
1984 abandoned = False
1985
1986 def worker() -> None:
1987 try:
1988 with dispatch_lock:
1989 if (
1990 abandoned
1991 or (cancel is not None and cancel.is_set())
1992 or (deadline_monotonic is not None and time.monotonic() >= deadline_monotonic)
1993 ):
1994 raise deadline_error()
1995 _notify_dispatch()
1996 future.set_result(open_and_read(request_timeout, dispatch_notified=True))
1997 except BaseException as exc:
1998 future.set_exception(exc)
1999
2000 def abandon_and_raise(cause: BaseException | None = None) -> None:
2001 nonlocal abandoned
2002 with dispatch_lock:
2003 abandoned = True
2004 err = deadline_error()
2005 if cause is not None:
2006 raise err from cause
2007 raise err
2008
2009 threading.Thread(target=worker, daemon=True).start()
2010 if cancel is None:
2011 try:
2012 return future.result(timeout=remaining)
2013 except TimeoutError as exc:
2014 if future.done():
2015 return future.result()
2016 abandon_and_raise(exc)
2017 while True:
2018 if cancel.is_set():
2019 abandon_and_raise()
2020 remaining = wait_deadline - time.monotonic()
2021 if remaining <= 0:
2022 abandon_and_raise()
2023 try:
2024 return future.result(timeout=min(remaining, 0.1))
2025 except TimeoutError:
2026 # Preserve worker-side socket failures for transport classification.
2027 if future.done():
2028 return future.result()
2029
2030 while attempt < effective_retries:
2031 if cancel is not None and cancel.is_set():
2032 last_error = deadline_error()
2033 break
2034 request_timeout = timeout
2035 if deadline_monotonic is not None:
2036 remaining = deadline_monotonic - time.monotonic()
2037 if remaining <= 0:
2038 last_error = deadline_error()
2039 break
2040 request_timeout = min(timeout, remaining)
2041 begin_deadline = (
2042 deadline_monotonic
2043 if request_timeout == remaining
2044 else (deadline_monotonic - remaining) + request_timeout
2045 )
2046 else:
2047 begin_deadline = time.monotonic() + request_timeout
2048 try:
2049 if attempt > 0 and on_retry is not None:
2050 on_retry()
2051 if routed is not None:
2052 # Another call may have turned this lane off while we waited.
2053 try:
2054 proxy.ensure_open(routed.provider)
2055 except proxy.ProxyUnavailable as exc:
2056 raise_recorded(HTTPError(f"API key proxy: {exc}", exc.status_code))
2057 req.add_header(proxy.DEADLINE_HEADER, proxy.deadline_value(request_timeout))
2058 with usage.with_deadline(begin_deadline):
2059 charge = usage.begin_http(usage_url, method)
2060 response_status, body, response_error = open_and_read_before_deadline(request_timeout)
2061 if body:
2062 try:
2063 parsed_usage = json.loads(body)
2064 except (ValueError, TypeError):
2065 parsed_usage = None
2066 if parsed_usage is not None:
2067 finish_deadline = (
2068 deadline_monotonic
2069 if deadline_monotonic is not None
2070 else time.monotonic() + min(request_timeout, usage._JOURNAL_TIMEOUT_SECONDS)
2071 )
2072 with usage.with_deadline(finish_deadline):
2073 try:
2074 usage.finish(charge, parsed_usage)
2075 except (ValueError, TypeError):
2076 pass
2077 if (cancel is not None and cancel.is_set()) or (
2078 deadline_monotonic is not None
2079 and time.monotonic() >= deadline_monotonic
2080 ):
2081 raise_recorded(deadline_error())
2082 if response_error is not None:
2083 raise response_error
2084 body = body or ""
2085 log_request(f"Response: {response_status} ({len(body)} bytes)")
2086 value = body if raw else (json.loads(body) if body else {})
2087 if fixture_request is not None:
2088 _fixture_record(
2089 fixture_request,
2090 value=value,
2091 redactions=fixture_redactions,
2092 headers=response_headers,
2093 )
2094 if return_headers:
2095 return value, response_headers
2096 return value
2097 except (DeadlineExceeded, ResponseTooLarge) as exc:
2098 if isinstance(exc, DeadlineExceeded) and request_dispatched and not exc.dispatched:
2099 exc.dispatched = True
2100 raise_recorded(exc)
2101 except urllib.error.HTTPError as e:
2102 safe_reason = _scrub_error_text(str(e.reason)) or ""
2103 safe_body = _scrub_error_text(body)
2104 log_request(f"HTTP Error {e.code}: {safe_reason}")
2105 if safe_body:
2106 snippet = " ".join(safe_body.split())
2107 log_request(f"Error body: {snippet[:200]}")
2108 last_error = HTTPError(f"HTTP {e.code}: {safe_reason}", e.code, safe_body)
2109
2110 # A proxy error that ends the lane (out of credits, spend ceiling,
2111 # provider off, duplicate call) is never retried. Pass the original
2112 # body so JSON error codes survive secret-scrubbing truncation.
2113 if routed is not None and proxy.observe_error(
2114 routed.provider, e.code, body, getattr(e, "headers", None), call_key,
2115 ):
2116 raise_recorded(last_error)
2117
2118 # Don't retry client errors (4xx) except rate limits
2119 if 400 <= e.code < 500 and e.code != 429:
2120 raise_recorded(last_error)
2121
2122 # Cap 429 retries separately to avoid wasting latency
2123 if e.code == 429:
2124 rate_limit_count += 1
2125 if rate_limit_count >= max_429_retries:
2126 raise_recorded(last_error)
2127
2128 # HTTP errors respect the caller's original `retries`; only DNS
2129 # failures get the widened `effective_retries` budget.
2130 if attempt < retries - 1:
2131 if e.code == 429:
2132 # Respect Retry-After or x-ratelimit-reset (Reddit sends the
2133 # latter), falling back to exponential backoff: 3s, 5s, 9s...
2134 delay = retry_delay_from_headers(
2135 getattr(e, "headers", None),
2136 RETRY_DELAY * (2 ** attempt) + 1,
2137 )
2138 log_request(f"Rate limited (429). Waiting {delay:.1f}s before retry {attempt + 2}/{retries}")
2139 else:
2140 delay = RETRY_DELAY * (2 ** attempt)
2141 if not sleep_before_retry(delay):
2142 break
2143 else:
2144 # Caller's original retry budget exhausted; an earlier DNS
2145 # failure may have widened `effective_retries`, but that
2146 # widening is DNS-only — don't grant extra HTTP attempts.
2147 break
2148 except urllib.error.URLError as e:
2149 safe_reason = _scrub_error_text(str(e.reason)) or ""
2150 log_request(f"URL Error: {safe_reason}")
2151 reason = getattr(e, "reason", None)
2152 # urllib commonly wraps socket.timeout (an alias of TimeoutError
2153 # since 3.10) in URLError; classify those as timeouts, not
2154 # unreachable hosts, so the recovery guidance is right.
2155 wrapped_timeout = isinstance(reason, TimeoutError) or "timed out" in str(reason).lower()
2156 last_error = HTTPError(
2157 f"URL Error: {safe_reason}",
2158 outcome_state=health.TIMEOUT if wrapped_timeout else health.UNREACHABLE,
2159 )
2160 last_error.no_host = _is_no_host(e)
2161 from . import public_host
2162
2163 if isinstance(reason, public_host.NonPublicAddressError):
2164 raise_recorded(last_error)
2165 if _is_dns_failure(e):
2166 # DNS resolution failures are transient; expand the retry budget
2167 # to MIN_DNS_RETRIES if the caller passed fewer, and use
2168 # exponential backoff (1s, 2s, 4s, ...) instead of the linear
2169 # default. Counts DNS attempts separately so other URLError
2170 # causes don't bypass the regular retry budget.
2171 dns_attempts += 1
2172 if retry_dns and effective_retries < MIN_DNS_RETRIES:
2173 log_request(
2174 f"DNS resolution failed; expanding retry budget from "
2175 f"{effective_retries} to {MIN_DNS_RETRIES}"
2176 )
2177 effective_retries = MIN_DNS_RETRIES
2178 if attempt < effective_retries - 1:
2179 delay = 2 ** (dns_attempts - 1) # 1s, 2s, 4s, 8s, ...
2180 log_request(
2181 f"DNS resolution failure (attempt {dns_attempts}); "
2182 f"retrying in {delay:.1f}s"
2183 )
2184 if not sleep_before_retry(delay):
2185 break
2186 elif attempt < retries - 1:
2187 # Non-DNS URLError (e.g. ConnectionRefused) respects the
2188 # caller's original retry budget, not the DNS-widened bound.
2189 if not sleep_before_retry(RETRY_DELAY * (attempt + 1)):
2190 break
2191 else:
2192 # Caller's original retry budget exhausted; an earlier DNS
2193 # failure widening `effective_retries` does not carry over
2194 # to non-DNS error paths.
2195 break
2196 except json.JSONDecodeError as e:
2197 safe_err = _scrub_error_text(str(e)) or ""
2198 log_request(f"JSON decode error: {safe_err}")
2199 last_error = HTTPError(
2200 f"Invalid JSON response: {safe_err}",
2201 outcome_state=health.SCHEMA_DRIFT,
2202 )
2203 raise_recorded(last_error)
2204 except (OSError, TimeoutError, ConnectionResetError, http.client.HTTPException) as e:
2205 # Handle socket-level errors (connection reset, timeout, etc.),
2206 # and a body cut off mid-read (``IncompleteRead``), which
2207 # ``http.client`` raises as an ``HTTPException``, not an OSError.
2208 safe_err = _scrub_error_text(str(e)) or ""
2209 log_request(f"Connection error: {type(e).__name__}: {safe_err}")
2210 state = health.TIMEOUT if isinstance(e, TimeoutError) else health.UNREACHABLE
2211 last_error = HTTPError(
2212 f"Connection error: {type(e).__name__}: {safe_err}",
2213 outcome_state=state,
2214 )
2215 last_error.no_host = _is_no_host(e)
2216 if attempt < retries - 1:
2217 # Socket errors respect the caller's original retry budget.
2218 if not sleep_before_retry(RETRY_DELAY * (attempt + 1)):
2219 break
2220 else:
2221 # Original budget exhausted; DNS widening doesn't apply here.
2222 break
2223
2224 attempt += 1
2225
2226 if last_error:
2227 raise_recorded(last_error)
2228 error = HTTPError("Request failed with no error details")
2229 raise_recorded(error)
2230
2231
2232 def get(url: str, headers: Optional[Dict[str, str]] = None, **kwargs) -> Dict[str, Any]:
2233 """Make a GET request."""
2234 return request("GET", url, headers=headers, **kwargs)
2235
2236
2237 def post(url: str, json_data: Dict[str, Any], headers: Optional[Dict[str, str]] = None, **kwargs) -> Dict[str, Any]:
2238 """Make a POST request with JSON body."""
2239 return request("POST", url, headers=headers, json_data=json_data, **kwargs)
2240
2241
2242 def post_raw(
2243 url: str,
2244 json_data: Dict[str, Any],
2245 headers: Optional[Dict[str, str]] = None,
2246 decode_errors: str = "strict",
2247 **kwargs,
2248 ) -> str:
2249 """Make a POST request with JSON body and return raw text."""
2250 return request(
2251 "POST",
2252 url,
2253 headers=headers,
2254 json_data=json_data,
2255 raw=True,
2256 decode_errors=decode_errors,
2257 **kwargs,
2258 )
2259
2260
2261 BROWSER_USER_AGENT = (
2262 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
2263 "AppleWebKit/537.36 (KHTML, like Gecko) "
2264 "Chrome/124.0.0.0 Safari/537.36"
2265 )
2266
2267
2268 def get_text(
2269 url: str,
2270 timeout: int = DEFAULT_TIMEOUT,
2271 retries: int = 2,
2272 accept: str = "*/*",
2273 headers: Optional[Dict[str, str]] = None,
2274 deadline_monotonic: float | None = None,
2275 cancel: Optional[threading.Event] = None,
2276 retry_dns: bool = True,
2277 landed: Optional[list] = None,
2278 redirect_guard: Optional[Callable[[str], bool]] = None,
2279 public_only: bool = False,
2280 max_bytes: Optional[int] = None,
2281 decode_errors: str = "strict",
2282 ip_validator: Optional[Callable[[Union[ipaddress.IPv4Address, ipaddress.IPv6Address]], bool]] = None,
2283 ) -> Optional[str]:
2284 """Fetch a URL and return decoded text, or None on any failure.
2285
2286 Keyless helper for Reddit site search and shreddit HTML endpoints, the free path
2287 that replaced the now-403 ``.json`` endpoints. Sends a browser User-Agent
2288 and never raises: returns None on HTTP error, network failure, or timeout
2289 so tiered callers can fall through to the next source.
2290
2291 Args:
2292 url: Request URL
2293 timeout: HTTP timeout per attempt in seconds
2294 retries: Number of retries on failure (kept low — these tiers fail fast)
2295 accept: Accept header value (e.g. "text/html")
2296 headers: Optional extra headers merged over the defaults
2297 deadline_monotonic: Optional absolute monotonic deadline for the call
2298 retry_dns: See ``request``
2299 landed: When given, the address that answered (after redirects) is
2300 appended to it on success, or ``url`` when that is not known.
2301 redirect_guard: When given, a redirect to an address it returns False
2302 for is refused before it is followed, and the call returns None.
2303 max_bytes: Optional response byte cap passed through to ``request``.
2304
2305 Returns:
2306 Decoded response body as text, or None on failure.
2307 """
2308 merged = {
2309 "User-Agent": BROWSER_USER_AGENT,
2310 "Accept": accept,
2311 "Accept-Language": "en-US,en;q=0.9",
2312 }
2313 if headers:
2314 merged.update(headers)
2315 # Passed only when set, so the plain call stays what it always was.
2316 bounds: Dict[str, Any] = {}
2317 if deadline_monotonic is not None:
2318 bounds["deadline_monotonic"] = deadline_monotonic
2319 if cancel is not None:
2320 bounds["cancel"] = cancel
2321 if not retry_dns:
2322 bounds["retry_dns"] = False
2323 if landed is not None:
2324 bounds["return_headers"] = True
2325 if redirect_guard is not None:
2326 bounds["redirect_guard"] = redirect_guard
2327 if public_only:
2328 bounds["public_only"] = True
2329 if max_bytes is not None:
2330 bounds["max_bytes"] = max_bytes
2331 if decode_errors != "strict":
2332 bounds["decode_errors"] = decode_errors
2333 if ip_validator is not None:
2334 bounds["ip_validator"] = ip_validator
2335 try:
2336 answer = request(
2337 "GET", url, headers=merged, timeout=timeout, retries=retries, raw=True,
2338 **bounds,
2339 )
2340 except HTTPError as e:
2341 log(f"get_text failed ({e}): {_scrub_log_url(url)}")
2342 return None
2343 if landed is None:
2344 return answer
2345 body, response_headers = answer
2346 landed.append(getattr(response_headers, "url", "") or url)
2347 return body
2348
2349
2350 class RateLimiter:
2351 """Thread-safe token-bucket throttle for an endpoint family.
2352
2353 The keyless source tiers run under the pipeline's ThreadPoolExecutor, so a
2354 multi-subquery run can fire many requests at the same host at once. A bare
2355 per-request retry budget does not prevent that stampede — it only reacts
2356 after a 429. A token bucket bounds the *sustained* rate while still allowing
2357 a short burst, so legitimate parallelism is preserved (unlike a strict
2358 min-interval gate that would serialize every concurrent caller and could
2359 push later futures past their result timeouts).
2360
2361 ``rate_per_sec`` tokens refill per second; ``burst`` is the bucket capacity
2362 (max simultaneous calls before throttling kicks in). The lock is released
2363 while sleeping so waiting threads don't serialize on each other.
2364 """
2365
2366 def __init__(
2367 self,
2368 rate_per_sec: float,
2369 burst: int | None = None,
2370 sleep: Callable[[float], None] | None = None,
2371 ):
2372 self.rate = rate_per_sec
2373 # Injectable so tests never sleep (#1342); None means time.sleep.
2374 self._sleep = sleep
2375 self.capacity = burst if burst is not None else max(1, int(rate_per_sec))
2376 self._tokens = float(self.capacity)
2377 self._last = time.monotonic()
2378 self._lock = threading.Lock()
2379 # Threads currently blocked in acquire(). Callers that wait on a batch
2380 # of throttled futures size their timeouts from this queue depth.
2381 self._waiting = 0
2382
2383 @property
2384 def waiting(self) -> int:
2385 """Threads currently blocked in :meth:`acquire`."""
2386 with self._lock:
2387 return self._waiting
2388
2389 def acquire(
2390 self,
2391 *,
2392 deadline_monotonic: Optional[float] = None,
2393 cancel: Optional[threading.Event] = None,
2394 ) -> None:
2395 """Consume one token, blocking only when the bucket is empty."""
2396 queued = False
2397 try:
2398 while True:
2399 if cancel is not None and cancel.is_set():
2400 raise DeadlineExceeded()
2401 with self._lock:
2402 now = time.monotonic()
2403 # Clamp elapsed to >= 0: a backward clock reading must never
2404 # drive tokens negative (which would spin this loop forever).
2405 elapsed = max(0.0, now - self._last)
2406 self._tokens = min(self.capacity, self._tokens + elapsed * self.rate)
2407 self._last = now
2408 if deadline_monotonic is not None and now >= deadline_monotonic:
2409 raise DeadlineExceeded()
2410 if self._tokens >= 1.0:
2411 self._tokens -= 1.0
2412 return
2413 wait = (1.0 - self._tokens) / self.rate
2414 if deadline_monotonic is not None:
2415 remaining = deadline_monotonic - now
2416 if remaining <= 0 or wait > remaining:
2417 raise DeadlineExceeded()
2418 sleep_for = min(wait, remaining)
2419 else:
2420 sleep_for = wait
2421 if not queued:
2422 self._waiting += 1
2423 queued = True
2424 if self._sleep is not None:
2425 self._sleep(min(sleep_for, 0.05) if cancel is not None else sleep_for)
2426 elif cancel is not None:
2427 if cancel.wait(min(sleep_for, 0.05)):
2428 raise DeadlineExceeded()
2429 else:
2430 time.sleep(sleep_for)
2431 finally:
2432 if queued:
2433 with self._lock:
2434 self._waiting -= 1
2435
2436
2437 # Shared across all keyless Reddit tiers (site search, listing, shreddit) so their
2438 # combined fan-out is throttled as one family. Burst lets the parallel
2439 # enrichment workers proceed; sustained rate caps the stampede.
2440 # 1 req/sec is slow enough that home IPs survive search + listing + shreddit
2441 # fan-out; raise LAST30DAYS_REDDIT_KEYLESS_RATE to trade 429s for wall-clock.
2442 REDDIT_KEYLESS_RATE_ENV = "LAST30DAYS_REDDIT_KEYLESS_RATE"
2443 DEFAULT_REDDIT_KEYLESS_RATE = 1.0
2444 DEFAULT_REDDIT_KEYLESS_BURST = 2
2445 _REDDIT_429_RETRY_SLEEP_SEC = 1.0
2446 _REDDIT_429_RETRY_JITTER_SEC = 0.5
2447
2448
2449 def parse_reddit_keyless_rate(raw: Optional[str]) -> float:
2450 """Parse LAST30DAYS_REDDIT_KEYLESS_RATE; invalid/non-positive -> default."""
2451 text = (raw or "").strip()
2452 if not text:
2453 return DEFAULT_REDDIT_KEYLESS_RATE
2454 try:
2455 rate = float(text)
2456 except (TypeError, ValueError):
2457 return DEFAULT_REDDIT_KEYLESS_RATE
2458 if not math.isfinite(rate) or rate <= 0:
2459 return DEFAULT_REDDIT_KEYLESS_RATE
2460 return rate
2461
2462
2463 def make_reddit_keyless_limiter(
2464 environ: Optional[Dict[str, str]] = None,
2465 ) -> RateLimiter:
2466 envmap = os.environ if environ is None else environ
2467 return RateLimiter(
2468 rate_per_sec=parse_reddit_keyless_rate(envmap.get(REDDIT_KEYLESS_RATE_ENV)),
2469 burst=DEFAULT_REDDIT_KEYLESS_BURST,
2470 )
2471
2472
2473 REDDIT_KEYLESS_LIMITER = make_reddit_keyless_limiter()
2474
2475
2476 def _sync_reddit_keyless_rate() -> None:
2477 """Apply a process-env override without resetting in-flight tokens."""
2478 rate = parse_reddit_keyless_rate(os.environ.get(REDDIT_KEYLESS_RATE_ENV))
2479 if REDDIT_KEYLESS_LIMITER.rate != rate:
2480 REDDIT_KEYLESS_LIMITER.rate = rate
2481
2482
2483 def _failures_are_429(failures: list[HTTPError]) -> bool:
2484 if not failures:
2485 return False
2486 last = failures[-1]
2487 return last.status_code == 429 or last.outcome_state == health.RATE_LIMITED
2488
2489
2490 def _sleep_reddit_429_retry() -> None:
2491 """Short jittered pause before the single in-lane 429 retry."""
2492 time.sleep(
2493 _REDDIT_429_RETRY_SLEEP_SEC
2494 + random.uniform(0.0, _REDDIT_429_RETRY_JITTER_SEC)
2495 )
2496
2497
2498 # Run-scoped memo for keyless Reddit GETs. Subreddit listing partials, site
2499 # search pages, arctic supplements, and shreddit comment pages depend only on
2500 # the subreddit, sort, or raw topic, and the Reddit lane is dispatched with the
2501 # raw topic for every subquery, so a four-subquery run requested each of them
2502 # four times.
2503 # Memoizing successful bodies for the life of one command turns ~184 requests
2504 # into ~50 on the measured 2026-08-31 run shape. Concurrent requesters for the
2505 # same URL wait on the first fetch instead of issuing their own (all four
2506 # subquery streams start at once, so a result-only cache would miss).
2507 REDDIT_KEYLESS_MEMO_MAX = 512
2508 _REDDIT_KEYLESS_MEMO: "OrderedDict[str, str]" = OrderedDict()
2509 _REDDIT_KEYLESS_INFLIGHT: Dict[str, threading.Event] = {}
2510 _REDDIT_KEYLESS_MEMO_LOCK = threading.Lock()
2511
2512
2513 # Queue depth only counts threads already blocked in acquire(). The other
2514 # lanes' workers submit their requests as they go, so a batch's last fetch can
2515 # start well after the depth seen at wait time. This flat allowance covers
2516 # that (the 2026-08-31 smoke lost three feeds at ~35s with the depth term
2517 # alone; a full run's ~50 distinct keyless requests take ~50s at 1 req/s).
2518 REDDIT_KEYLESS_CONTENTION_SECONDS = 45.0
2519
2520
2521 def reddit_keyless_wait_allowance(batch_size: int) -> float:
2522 """Seconds a batch of *batch_size* throttled fetches may spend waiting for tokens.
2523
2524 Every keyless Reddit lane in a run shares one bucket, so a lane's futures
2525 can sit behind other lanes' requests before their own fetch starts. Size
2526 per-future result timeouts as ``base + this`` instead of a fixed number;
2527 at 1 req/s a fixed 20-second timeout expired on real runs while the fetch
2528 was still queued (issue #985 follow-up).
2529 """
2530 _sync_reddit_keyless_rate()
2531 limiter = REDDIT_KEYLESS_LIMITER
2532 rate = limiter.rate if limiter.rate > 0 else 1.0
2533 return (limiter.waiting + max(0, batch_size)) / rate + REDDIT_KEYLESS_CONTENTION_SECONDS
2534
2535
2536 def reset_reddit_keyless_memo() -> None:
2537 """Forget memoized keyless Reddit bodies. Called once per command, and by tests."""
2538 with _REDDIT_KEYLESS_MEMO_LOCK:
2539 _REDDIT_KEYLESS_MEMO.clear()
2540 _REDDIT_KEYLESS_INFLIGHT.clear()
2541
2542
2543 def _reddit_memo_get(url: str) -> Optional[str]:
2544 with _REDDIT_KEYLESS_MEMO_LOCK:
2545 text = _REDDIT_KEYLESS_MEMO.get(url)
2546 if text is not None:
2547 _REDDIT_KEYLESS_MEMO.move_to_end(url)
2548 return text
2549
2550
2551 def _reddit_memo_put(url: str, text: str) -> None:
2552 with _REDDIT_KEYLESS_MEMO_LOCK:
2553 _REDDIT_KEYLESS_MEMO[url] = text
2554 _REDDIT_KEYLESS_MEMO.move_to_end(url)
2555 while len(_REDDIT_KEYLESS_MEMO) > REDDIT_KEYLESS_MEMO_MAX:
2556 _REDDIT_KEYLESS_MEMO.popitem(last=False)
2557
2558
2559 def reddit_keyless_get_text(
2560 url: str,
2561 timeout: int = DEFAULT_TIMEOUT,
2562 retries: int = 2,
2563 accept: str = "*/*",
2564 headers: Optional[Dict[str, str]] = None,
2565 validate: Optional[Callable[[str], Optional[str]]] = None,
2566 deadline_monotonic: Optional[float] = None,
2567 ) -> Optional[str]:
2568 """get_text for the keyless Reddit tiers, memoized per run and throttled.
2569
2570 Same contract as :func:`get_text` (returns None on any failure) but a URL
2571 already fetched this command is served from the run memo without spending
2572 a limiter token, concurrent requesters for one URL share the in-flight
2573 fetch, and cold fetches are spaced via :data:`REDDIT_KEYLESS_LIMITER` so a
2574 broad multi-query run does not stampede Reddit's keyless endpoints.
2575
2576 ``validate`` lets a caller reject a fetched body before it is memoized. It
2577 returns None for a body the caller recognizes, or a short reason string.
2578 A rejected body is recorded into the failure sink as schema drift and the
2579 call returns None, so an HTTP 200 challenge page is neither reported as a
2580 clean empty result nor served from the memo to later streams.
2581
2582 ``deadline_monotonic`` bounds coalesced waiter waits, limiter acquisition,
2583 and the underlying :func:`get_text` call.
2584 """
2585 cached = _reddit_memo_get(url)
2586 if cached is not None:
2587 return cached
2588 if deadline_monotonic is not None and time.monotonic() >= deadline_monotonic:
2589 _record_failure(DeadlineExceeded())
2590 return None
2591 # Elect one owner per URL. A waiter whose owner failed re-enters the
2592 # election rather than fetching un-gated, so a failed fetch costs one
2593 # retry for the whole group, not one per waiter.
2594 for _round in range(3):
2595 with _REDDIT_KEYLESS_MEMO_LOCK:
2596 cached = _REDDIT_KEYLESS_MEMO.get(url)
2597 if cached is not None:
2598 return cached
2599 if deadline_monotonic is not None and time.monotonic() >= deadline_monotonic:
2600 _record_failure(DeadlineExceeded())
2601 return None
2602 gate = _REDDIT_KEYLESS_INFLIGHT.get(url)
2603 owner = gate is None
2604 if owner:
2605 gate = threading.Event()
2606 _REDDIT_KEYLESS_INFLIGHT[url] = gate
2607 if owner:
2608 break
2609 # The owner may itself be queued in the shared bucket; wait for that
2610 # queue, not just for one socket timeout.
2611 wait_timeout = timeout * max(1, retries) + reddit_keyless_wait_allowance(1)
2612 if deadline_monotonic is not None:
2613 remaining = deadline_monotonic - time.monotonic()
2614 if remaining <= 0:
2615 _record_failure(DeadlineExceeded())
2616 return None
2617 wait_timeout = min(wait_timeout, remaining)
2618 gate.wait(timeout=wait_timeout)
2619 cached = _reddit_memo_get(url)
2620 if cached is not None:
2621 return cached
2622 if deadline_monotonic is not None and time.monotonic() >= deadline_monotonic:
2623 _record_failure(DeadlineExceeded())
2624 return None
2625 else:
2626 # Three failed owners in a row: give up quietly rather than pile on.
2627 return None
2628 try:
2629 _sync_reddit_keyless_rate()
2630 if deadline_monotonic is not None:
2631 if time.monotonic() >= deadline_monotonic:
2632 _record_failure(DeadlineExceeded())
2633 return None
2634 try:
2635 if isinstance(REDDIT_KEYLESS_LIMITER, RateLimiter):
2636 REDDIT_KEYLESS_LIMITER.acquire(deadline_monotonic=deadline_monotonic)
2637 else:
2638 REDDIT_KEYLESS_LIMITER.acquire()
2639 except DeadlineExceeded as exc:
2640 _record_failure(exc)
2641 return None
2642 remaining = deadline_monotonic - time.monotonic()
2643 if remaining <= 0:
2644 _record_failure(DeadlineExceeded())
2645 return None
2646 text = get_text(
2647 url,
2648 timeout=min(timeout, remaining),
2649 retries=retries,
2650 accept=accept,
2651 headers=headers,
2652 deadline_monotonic=deadline_monotonic,
2653 )
2654 else:
2655 REDDIT_KEYLESS_LIMITER.acquire()
2656 text = get_text(url, timeout=timeout, retries=retries, accept=accept, headers=headers)
2657 if text is not None and validate is not None:
2658 problem = validate(text)
2659 if problem:
2660 _record_failure(HTTPError(
2661 f"Unrecognized response ({problem}): {url}",
2662 outcome_state=health.SCHEMA_DRIFT,
2663 ))
2664 return None
2665 if text is not None:
2666 _reddit_memo_put(url, text)
2667 return text
2668 finally:
2669 with _REDDIT_KEYLESS_MEMO_LOCK:
2670 if _REDDIT_KEYLESS_INFLIGHT.get(url) is gate:
2671 _REDDIT_KEYLESS_INFLIGHT.pop(url, None)
2672 gate.set()
2673
2674
2675 def reddit_keyless_get_text_retry_429(
2676 url: str,
2677 timeout: int = DEFAULT_TIMEOUT,
2678 accept: str = "*/*",
2679 headers: Optional[Dict[str, str]] = None,
2680 validate: Optional[Callable[[str], Optional[str]]] = None,
2681 deadline_monotonic: Optional[float] = None,
2682 ) -> tuple[Optional[str], Optional[str]]:
2683 """Limiter-throttled GET with one extra limiter-respecting retry on 429.
2684
2685 Returns ``(body, error)``. The first attempt is captured locally so a
2686 recovered 429 is not left in the pipeline sink. A second 429, or any
2687 non-429 miss, is recorded as before. Internal ``get_text`` retries are
2688 skipped (``retries=1``) so the in-lane retry is the one that re-acquires
2689 the bucket. ``validate`` is passed through to
2690 :func:`reddit_keyless_get_text`; a rejected body is a non-429 miss.
2691 """
2692 # retries=1 on purpose: letting request() sleep out a 42-60s
2693 # x-ratelimit-reset inside a lane worker starves the whole batch (the
2694 # 2026-08-31 smoke lost 14 feeds to future timeouts with retries=2 versus
2695 # 6 with 1). A keyless 429 fails fast, the lane retries once after a short
2696 # jittered pause through the bucket, and the memo keeps the other streams
2697 # from re-requesting the same URL.
2698 req_timeout: float = timeout
2699 if deadline_monotonic is not None:
2700 remaining = deadline_monotonic - time.monotonic()
2701 if remaining <= 0:
2702 err = DeadlineExceeded()
2703 _record_failure(err)
2704 return None, str(err)
2705 req_timeout = min(timeout, remaining)
2706 kwargs: Dict[str, Any] = {
2707 "timeout": req_timeout,
2708 "retries": 1,
2709 "accept": accept,
2710 "headers": headers,
2711 "validate": validate,
2712 }
2713 if deadline_monotonic is not None:
2714 kwargs["deadline_monotonic"] = deadline_monotonic
2715 with capture_failures() as first:
2716 text = reddit_keyless_get_text(url, **kwargs)
2717 if text is not None:
2718 return text, None
2719 if _failures_are_429(first):
2720 if deadline_monotonic is not None:
2721 delay = _REDDIT_429_RETRY_SLEEP_SEC + random.uniform(0.0, _REDDIT_429_RETRY_JITTER_SEC)
2722 remaining = deadline_monotonic - time.monotonic()
2723 if remaining > delay:
2724 time.sleep(delay)
2725 remaining_after = deadline_monotonic - time.monotonic()
2726 if remaining_after > 0:
2727 retry_kwargs = {**kwargs, "timeout": min(timeout, remaining_after)}
2728 with tee_failures() as second:
2729 text = reddit_keyless_get_text(url, **retry_kwargs)
2730 if text is not None:
2731 return text, None
2732 err = second[-1] if second else (first[-1] if first else None)
2733 return None, str(err) if err is not None else "no response"
2734 else:
2735 _sleep_reddit_429_retry()
2736 with tee_failures() as second:
2737 text = reddit_keyless_get_text(url, **kwargs)
2738 if text is not None:
2739 return text, None
2740 err = second[-1] if second else (first[-1] if first else None)
2741 return None, str(err) if err is not None else "no response"
2742 for err in first:
2743 _record_failure(err)
2744 err = first[-1] if first else None
2745 return None, str(err) if err is not None else "no response"
2746
2747
2748 # --- Logged-in Reddit session transport ----------------------------------
2749 #
2750 # The opt-in session (lib/reddit_session.py) is kept apart from the keyless
2751 # family: its own limiter (so a keyless stampede never spends the account's
2752 # pacing, and the reverse), and its own memo, so a page fetched with the
2753 # cookie is never served to a logged-out caller and a logged-out page never
2754 # to the session. Failures stay out of the stream's failure sink: one Reddit
2755 # layer failing is a detail note, not the source's outcome.
2756 REDDIT_SESSION_RATE = 1.0
2757 REDDIT_SESSION_BURST = 2
2758 REDDIT_SESSION_LIMITER = RateLimiter(REDDIT_SESSION_RATE, burst=REDDIT_SESSION_BURST)
2759 REDDIT_SESSION_MEMO_MAX = 128
2760 _REDDIT_SESSION_MEMO: "OrderedDict[str, tuple[int, str]]" = OrderedDict()
2761 _REDDIT_SESSION_MEMO_LOCK = threading.Lock()
2762
2763
2764 def reset_reddit_session_memo() -> None:
2765 with _REDDIT_SESSION_MEMO_LOCK:
2766 _REDDIT_SESSION_MEMO.clear()
2767
2768
2769 def reddit_only_redirect(url: str) -> bool:
2770 """Redirect guard for session requests: https on reddit.com or a subdomain."""
2771 parts = urlsplit(url)
2772 host = (parts.hostname or "").lower()
2773 return parts.scheme == "https" and (host == "reddit.com" or host.endswith(".reddit.com"))
2774
2775
2776 def reddit_session_get(
2777 url: str,
2778 cookie_header: str,
2779 *,
2780 accept: str = "text/html",
2781 timeout: float = 20,
2782 deadline_monotonic: Optional[float] = None,
2783 limiter: Optional[RateLimiter] = None,
2784 ) -> tuple[Optional[int], Optional[str], bool]:
2785 """GET ``url`` with the session cookie: ``(status, body, from_memo)``.
2786
2787 A 200 is memoized per URL in the session namespace; an error status
2788 comes back with its body (a 403 page says whether Reddit logged the
2789 session out) and is not memoized. ``status`` is None when no answer
2790 arrived. Never raises, and never puts the cookie in a log line or an
2791 error string: ``request`` logs only the URL.
2792 """
2793 if not reddit_only_redirect(url):
2794 return None, None, False
2795 with _REDDIT_SESSION_MEMO_LOCK:
2796 cached = _REDDIT_SESSION_MEMO.get(url)
2797 if cached is not None:
2798 _REDDIT_SESSION_MEMO.move_to_end(url)
2799 return cached[0], cached[1], True
2800 (limiter or REDDIT_SESSION_LIMITER).acquire()
2801 headers = {
2802 "User-Agent": BROWSER_USER_AGENT,
2803 "Accept": accept,
2804 "Accept-Language": "en-US,en;q=0.9",
2805 "Cookie": cookie_header,
2806 }
2807 bounds: Dict[str, Any] = {"redirect_guard": reddit_only_redirect}
2808 if deadline_monotonic is not None:
2809 bounds["deadline_monotonic"] = deadline_monotonic
2810 with capture_failures():
2811 try:
2812 body = request(
2813 "GET", url, headers=headers, timeout=timeout, retries=1,
2814 max_429_retries=0, raw=True, **bounds,
2815 )
2816 except HTTPError as error:
2817 return error.status_code, error.body, False
2818 except Exception:
2819 return None, None, False
2820 text = body if isinstance(body, str) else ""
2821 with _REDDIT_SESSION_MEMO_LOCK:
2822 _REDDIT_SESSION_MEMO[url] = (200, text)
2823 _REDDIT_SESSION_MEMO.move_to_end(url)
2824 while len(_REDDIT_SESSION_MEMO) > REDDIT_SESSION_MEMO_MAX:
2825 _REDDIT_SESSION_MEMO.popitem(last=False)
2826 return 200, text, False
2827
2828
2829 def scrapecreators_headers(token: str) -> Dict[str, str]:
2830 """Build ScrapeCreators request headers (x-api-key + JSON content type)."""
2831 return {
2832 "x-api-key": token,
2833 "Content-Type": "application/json",
2834 }
2835
2836
2837 def get_reddit_json(path: str, timeout: int = DEFAULT_TIMEOUT, retries: int = MAX_RETRIES) -> Dict[str, Any]:
2838 """Fetch Reddit thread JSON.
2839
2840 Args:
2841 path: Reddit path (e.g., /r/subreddit/comments/id/title)
2842 timeout: HTTP timeout per attempt in seconds
2843 retries: Number of retries on failure
2844
2845 Returns:
2846 Parsed JSON response
2847 """
2848 # Ensure path starts with /
2849 if not path.startswith('/'):
2850 path = '/' + path
2851
2852 # Remove trailing slash and add .json
2853 path = path.rstrip('/')
2854 if not path.endswith('.json'):
2855 path = path + '.json'
2856
2857 url = f"https://www.reddit.com{path}?raw_json=1"
2858
2859 headers = {
2860 "User-Agent": USER_AGENT,
2861 "Accept": "application/json",
2862 }
2863
2864 return get(url, headers=headers, timeout=timeout, retries=retries)
2865
2865 lines PYTHON