Download recipe/http.py from ZipLime/us-treasury-events: direct link, hf CLI and curl.
- Browser
- Download file 11.2 kB
-
https://huggingface.co/datasets/ZipLime/us-treasury-events/resolve/main/recipe/http.py
- Command line
-
hf download hf://datasets/ZipLime/us-treasury-events/recipe/http.py
-
curl -L -o http.py https://huggingface.co/datasets/ZipLime/us-treasury-events/resolve/main/recipe/http.py
11.2 kB
| """Fetching, with a cache that knows which documents can never change. | |
| An archived news release is immutable by definition: it is what the agency | |
| published on a particular morning, and the agency's own archive page is the | |
| promise that it stays that way. A schedule page is the opposite -- it changes | |
| whenever a release moves, which is the whole reason the calendar is a table | |
| here. The cache treats the two differently, and nothing else in the pipeline | |
| has to think about it. | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import hashlib | |
| import json | |
| import logging | |
| import time | |
| from dataclasses import dataclass | |
| from datetime import UTC, datetime | |
| from pathlib import Path | |
| from urllib.parse import urlsplit | |
| import httpx | |
| LOGGER = logging.getLogger(__name__) | |
| # Agencies publish no numeric rate limit. This is deliberately slower than what | |
| # the hosts would tolerate: a backfill is a few thousand documents, it runs | |
| # once, and nothing downstream is latency sensitive. | |
| DEFAULT_RPS = 4.0 | |
| # Census answers 429 well below the rate the other agencies tolerate, and a | |
| # backfill that ignores it loses whole years -- fifty-nine housing releases in | |
| # one run, recorded as unreadable when they were simply never served. These are | |
| # the rates each host is asked at, and they are per host, so one slow agency | |
| # does not hold up the others. | |
| HOST_RPS = { | |
| # Each yield-curve CSV is generated on request and takes about seventeen | |
| # seconds. Spacing the starts closely is what lets several be in flight; | |
| # the concurrency limit in the pipeline is what keeps that polite. | |
| "home.treasury.gov": 4.0, | |
| "www.treasurydirect.gov": 4.0, | |
| } | |
| TIMEOUT = httpx.Timeout(60.0, connect=30.0) | |
| RETRY_STATUS = frozenset({429, 500, 502, 503, 504}) | |
| # A 429 is the host asking for a pause, not a transient error, so it is waited | |
| # out for much longer than a 503. | |
| THROTTLED_BACKOFF = 20.0 | |
| MAX_ATTEMPTS = 5 | |
| # A request that is allowed to come back empty is a probe -- "is there a | |
| # release for this week?" -- and ETA answers such a probe with 502 rather than | |
| # 404. Retrying that five times with exponential backoff costs a minute per | |
| # URL and buys nothing, so a probe gives up quickly. | |
| MAX_ATTEMPTS_WHEN_OPTIONAL = 2 | |
| # How long a "there is nothing here" answer is believed. Long enough that a | |
| # rebuild does not re-probe two thousand URLs, short enough that a release | |
| # published today is found tomorrow. | |
| MISSING_MAX_AGE = 2 * 24 * 3600 | |
| class Artifact: | |
| """One downloaded document and everything needed to prove where it came from.""" | |
| url: str | |
| content: bytes | |
| sha256: str | |
| content_type: str | |
| downloaded_at: datetime | |
| from_cache: bool | |
| def text(self) -> str: | |
| # Agency releases are ASCII with the occasional Windows-1252 dash; a | |
| # strict decode would fail on those and lose a whole release over a | |
| # punctuation mark. | |
| return self.content.decode("utf-8", errors="replace") | |
| def length(self) -> int: | |
| return len(self.content) | |
| def cache_key(url: str) -> str: | |
| return hashlib.sha1(url.encode("utf-8")).hexdigest() | |
| class Fetcher: | |
| """Rate-limited, cached, retrying HTTP client for the agency hosts.""" | |
| def __init__( | |
| self, | |
| *, | |
| user_agent: str, | |
| cache_dir: Path, | |
| requests_per_second: float = DEFAULT_RPS, | |
| client: httpx.AsyncClient | None = None, | |
| force_revalidate: bool = False, | |
| ) -> None: | |
| self.user_agent = user_agent | |
| self.cache_dir = Path(cache_dir) | |
| self.cache_dir.mkdir(parents=True, exist_ok=True) | |
| self._interval = 1.0 / max(requests_per_second, 0.1) | |
| self._host_intervals = { | |
| host: 1.0 / min(rate, max(requests_per_second, 0.1)) | |
| for host, rate in HOST_RPS.items() | |
| } | |
| # `--rebuild` re-reads the pages that change -- the archive indexes and | |
| # the schedules -- and still serves the archived releases from cache. | |
| # An archived release cannot change, so refetching a decade of them to | |
| # pick up a new index entry would be pure waste asked of the agency. | |
| self.force_revalidate = force_revalidate | |
| self._client = client | |
| self._owned = client is None | |
| # One gate per host: BLS being slow is no reason to stall Census. | |
| self._gates: dict[str, asyncio.Lock] = {} | |
| self._last: dict[str, float] = {} | |
| async def __aenter__(self) -> Fetcher: | |
| if self._client is None: | |
| self._client = httpx.AsyncClient( | |
| timeout=TIMEOUT, | |
| follow_redirects=True, | |
| headers={"User-Agent": self.user_agent, "Accept-Encoding": "gzip, deflate"}, | |
| ) | |
| return self | |
| async def __aexit__(self, *_exc) -> None: | |
| if self._owned and self._client is not None: | |
| await self._client.aclose() | |
| self._client = None | |
| def _paths(self, url: str) -> tuple[Path, Path]: | |
| key = cache_key(url) | |
| return self.cache_dir / f"{key}.bin", self.cache_dir / f"{key}.json" | |
| def known_missing(self, url: str, *, max_age_seconds: float = MISSING_MAX_AGE) -> bool: | |
| """Whether this URL was recently found not to exist. | |
| Discovery probes thousands of URLs that will never exist -- a week with | |
| no release, a month Census never archived -- and without this every | |
| rebuild asks the agencies for all of them again. | |
| """ | |
| _, meta = self._paths(url) | |
| if not meta.is_file(): | |
| return False | |
| try: | |
| record = json.loads(meta.read_text(encoding="utf-8")) | |
| except json.JSONDecodeError: | |
| return False | |
| if not record.get("missing"): | |
| return False | |
| age = (datetime.now(UTC) - datetime.fromisoformat(record["checked_at"])).total_seconds() | |
| return age <= max_age_seconds | |
| def _store_missing(self, url: str) -> None: | |
| _, meta = self._paths(url) | |
| meta.write_text( | |
| json.dumps( | |
| {"url": url, "missing": True, "checked_at": datetime.now(UTC).isoformat()}, | |
| indent=2, | |
| ), | |
| encoding="utf-8", | |
| ) | |
| def cached(self, url: str, *, max_age_seconds: float | None = None) -> Artifact | None: | |
| blob, meta = self._paths(url) | |
| if not (blob.is_file() and meta.is_file()): | |
| return None | |
| try: | |
| record = json.loads(meta.read_text(encoding="utf-8")) | |
| except json.JSONDecodeError: | |
| return None | |
| downloaded_at = datetime.fromisoformat(record["downloaded_at"]) | |
| if max_age_seconds is not None: | |
| age = (datetime.now(UTC) - downloaded_at).total_seconds() | |
| if age > max_age_seconds: | |
| return None | |
| content = blob.read_bytes() | |
| digest = hashlib.sha256(content).hexdigest() | |
| if digest != record.get("sha256"): | |
| # A cache entry that does not hash to what it claims is not a cache | |
| # entry. Silently trusting it would put an unprovable value into a | |
| # dataset whose whole promise is provenance. | |
| LOGGER.warning("cache entry for %s does not match its digest; refetching", url) | |
| return None | |
| return Artifact( | |
| url=url, | |
| content=content, | |
| sha256=digest, | |
| content_type=record.get("content_type", ""), | |
| downloaded_at=downloaded_at, | |
| from_cache=True, | |
| ) | |
| def _store(self, url: str, content: bytes, content_type: str) -> Artifact: | |
| blob, meta = self._paths(url) | |
| digest = hashlib.sha256(content).hexdigest() | |
| now = datetime.now(UTC) | |
| blob.write_bytes(content) | |
| meta.write_text( | |
| json.dumps( | |
| { | |
| "url": url, | |
| "sha256": digest, | |
| "content_type": content_type, | |
| "content_length": len(content), | |
| "downloaded_at": now.isoformat(), | |
| }, | |
| indent=2, | |
| ), | |
| encoding="utf-8", | |
| ) | |
| return Artifact( | |
| url=url, | |
| content=content, | |
| sha256=digest, | |
| content_type=content_type, | |
| downloaded_at=now, | |
| from_cache=False, | |
| ) | |
| async def _throttle(self, host: str) -> None: | |
| interval = self._host_intervals.get(host, self._interval) | |
| gate = self._gates.setdefault(host, asyncio.Lock()) | |
| async with gate: | |
| elapsed = time.monotonic() - self._last.get(host, 0.0) | |
| if elapsed < interval: | |
| await asyncio.sleep(interval - elapsed) | |
| self._last[host] = time.monotonic() | |
| async def get( | |
| self, | |
| url: str, | |
| *, | |
| max_age_seconds: float | None = None, | |
| allow_missing: bool = False, | |
| missing_max_age: float = MISSING_MAX_AGE, | |
| ) -> Artifact | None: | |
| """Fetch a document, or return the cached copy. | |
| `max_age_seconds=None` means "this document is immutable" -- an | |
| archived release. Pass a number for anything the agency rewrites. | |
| """ | |
| if self.force_revalidate and max_age_seconds is not None: | |
| max_age_seconds = 0 | |
| hit = self.cached(url, max_age_seconds=max_age_seconds) | |
| if hit is not None: | |
| return hit | |
| if allow_missing and self.known_missing(url, max_age_seconds=missing_max_age): | |
| return None | |
| if self._client is None: | |
| raise RuntimeError("use the Fetcher as an async context manager") | |
| host = urlsplit(url).netloc | |
| last_error: Exception | None = None | |
| attempts = MAX_ATTEMPTS_WHEN_OPTIONAL if allow_missing else MAX_ATTEMPTS | |
| for attempt in range(1, attempts + 1): | |
| await self._throttle(host) | |
| try: | |
| response = await self._client.get(url) | |
| except httpx.HTTPError as error: # pragma: no cover - network dependent | |
| last_error = error | |
| await asyncio.sleep(min(2**attempt, 30)) | |
| continue | |
| if response.status_code == 404 and allow_missing: | |
| self._store_missing(url) | |
| return None | |
| if response.status_code in RETRY_STATUS: | |
| await asyncio.sleep( | |
| THROTTLED_BACKOFF * attempt | |
| if response.status_code == 429 | |
| else min(2**attempt, 30) | |
| ) | |
| last_error = httpx.HTTPStatusError( | |
| f"{response.status_code} for {url}", request=response.request, | |
| response=response, | |
| ) | |
| continue | |
| response.raise_for_status() | |
| return self._store( | |
| url, response.content, response.headers.get("content-type", "").split(";")[0] | |
| ) | |
| if allow_missing: | |
| LOGGER.info("nothing at %s (%s)", url, last_error) | |
| self._store_missing(url) | |
| return None | |
| raise RuntimeError(f"could not fetch {url}: {last_error}") | |
| __all__ = ["Artifact", "Fetcher", "cache_key"] | |