"""Polite HTTP client: per-host rate limiting, retries with exponential backoff, robots.txt checks. Uses httpx (already a dependency of the anthropic SDK). Never follows cross-host redirects silently for robots-protected hosts. API endpoints (S3, OAI-PMH, Crossref, arXiv API) are consulted under their published usage policies; see docs/data_governance/LICENSE_MATRIX.md. """ from __future__ import annotations import threading import time import urllib.robotparser as robotparser from dataclasses import dataclass, field from urllib.parse import urlparse import httpx USER_AGENT = "HTR-research/0.1 (UQO WP-AI-0002; academic text-mining; contact via project repository)" @dataclass class HostPolicy: min_interval_s: float = 0.34 # ~3 req/s default check_robots: bool = False DEFAULT_POLICIES: dict[str, HostPolicy] = { "pmc-oa-opendata.s3.amazonaws.com": HostPolicy(0.05, False), # AWS Open Data, no published quota "export.arxiv.org": HostPolicy(3.0, False), # arXiv API ToU: 1 request / 3 s "arxiv.org": HostPolicy(3.0, False), "oaipmh.arxiv.org": HostPolicy(3.0, False), "api.crossref.org": HostPolicy(1.0, False), # polite pool, mailto in UA "eutils.ncbi.nlm.nih.gov": HostPolicy(0.34, False), # 3 req/s without key } @dataclass class RateLimiter: policies: dict[str, HostPolicy] = field(default_factory=lambda: dict(DEFAULT_POLICIES)) _last: dict[str, float] = field(default_factory=dict) _lock: threading.Lock = field(default_factory=threading.Lock) def wait(self, host: str) -> None: pol = self.policies.get(host, HostPolicy()) with self._lock: now = time.monotonic() last = self._last.get(host, 0.0) delay = pol.min_interval_s - (now - last) if delay > 0: time.sleep(delay) self._last[host] = time.monotonic() class PoliteClient: def __init__(self, timeout: float = 60.0, max_retries: int = 5, limiter: RateLimiter | None = None, mailto: str | None = None): ua = USER_AGENT + (f" mailto:{mailto}" if mailto else "") self._client = httpx.Client(timeout=timeout, headers={"User-Agent": ua}, follow_redirects=True) self.max_retries = max_retries self.limiter = limiter or RateLimiter() self._robots: dict[str, robotparser.RobotFileParser | None] = {} self.stats = {"requests": 0, "retries": 0, "bytes": 0} def _allowed_by_robots(self, url: str) -> bool: host = urlparse(url).netloc if host not in self._robots: rp = robotparser.RobotFileParser() try: rp.set_url(f"{urlparse(url).scheme}://{host}/robots.txt") rp.read() self._robots[host] = rp except Exception: # noqa: BLE001 self._robots[host] = None rp = self._robots[host] return True if rp is None else rp.can_fetch(USER_AGENT, url) def get(self, url: str, *, params: dict | None = None, check_robots: bool | None = None, accept: str | None = None) -> httpx.Response: host = urlparse(url).netloc pol = self.limiter.policies.get(host, HostPolicy()) if (check_robots if check_robots is not None else pol.check_robots) and not self._allowed_by_robots(url): raise PermissionError(f"robots.txt disallows {url}") headers = {"Accept": accept} if accept else None last_exc: Exception | None = None for attempt in range(self.max_retries + 1): self.limiter.wait(host) try: self.stats["requests"] += 1 r = self._client.get(url, params=params, headers=headers) if r.status_code in (429, 500, 502, 503, 504): retry_after = r.headers.get("Retry-After") wait = float(retry_after) if retry_after and retry_after.isdigit() else min(60.0, 2.0**attempt) time.sleep(wait) self.stats["retries"] += 1 continue self.stats["bytes"] += len(r.content) return r except (httpx.TransportError, httpx.TimeoutException) as e: # pragma: no cover - network last_exc = e time.sleep(min(60.0, 2.0**attempt)) self.stats["retries"] += 1 raise RuntimeError(f"GET {url} failed after {self.max_retries} retries: {last_exc}") def close(self) -> None: self._client.close()