markedet's picture
Add license files and NOTICE, update license fields
98ee81b verified
Raw History Blame Contribute Delete
4.67 kB
"""Small helpers for calling an official, documented HTTP API politely.
Standard library only. Written for the guides in this dataset.
License: Apache-2.0.
"""
from __future__ import annotations
import json
import random
import re
import time
import urllib.error
import urllib.request
from email.utils import parsedate_to_datetime
from typing import Any, Callable, Iterator
RETRY_STATUSES = {429, 500, 502, 503, 504}
def is_retryable(status: int, headers: Any) -> bool:
"""429 and 5xx are retryable. GitHub also signals rate limits with 403, so a
403 counts only when it carries Retry-After or x-ratelimit-remaining: 0.
A plain 403 is a permissions problem and retrying will not fix it."""
if status in RETRY_STATUSES:
return True
if status == 403 and headers is not None:
return headers.get("Retry-After") is not None or headers.get("x-ratelimit-remaining") == "0"
return False
def parse_link_header(value: str | None) -> dict[str, str]:
"""Parse an RFC 8288 Link header into {rel: url}.
Example: '<https://x/?page=2>; rel="next", <https://x/?page=9>; rel="last"'
"""
links: dict[str, str] = {}
if not value:
return links
for part in re.split(r",\s*(?=<)", value):
m = re.match(r'\s*<([^>]*)>\s*;(.*)', part)
if not m:
continue
url, params = m.groups()
rel = re.search(r'rel="?([^";]+)"?', params)
if rel:
for name in rel.group(1).split():
links[name] = url
return links
def retry_delay(headers: Any, attempt: int, base: float = 1.0, cap: float = 60.0, now: float | None = None) -> float:
"""Seconds to wait before retry number `attempt` (0-based).
Order of preference, following GitHub's documented guidance:
1. Retry-After (delta-seconds, or an HTTP-date as RFC 9110 allows)
2. x-ratelimit-reset (UTC epoch seconds) when x-ratelimit-remaining is 0
3. exponential backoff with full jitter, capped
Server-requested waits are returned as is (never shortened: retrying early
is what gets clients banned). The caller decides whether to wait that long.
"""
now = time.time() if now is None else now
get = headers.get if headers is not None else (lambda k, d=None: d)
ra = get("Retry-After")
if ra is not None:
try:
return max(0.0, float(ra))
except ValueError:
try:
when = parsedate_to_datetime(ra).timestamp()
return max(0.0, when - now)
except (TypeError, ValueError):
pass
if get("x-ratelimit-remaining") == "0" and get("x-ratelimit-reset"):
try:
return max(0.0, float(get("x-ratelimit-reset")) - now)
except ValueError:
pass
return random.uniform(0, min(cap, base * (2 ** attempt)))
def get_json(
url: str,
headers: dict[str, str] | None = None,
*,
max_retries: int = 4,
timeout: float = 20.0,
max_wait: float = 120.0,
sleep: Callable[[float], None] = time.sleep,
) -> tuple[Any, Any]:
"""GET `url`, return (parsed_json, response_headers).
Retries only on RETRY_STATUSES, at most `max_retries` times, then raises.
If the server asks for a wait longer than `max_wait` seconds, raises at once
instead of retrying early: report it to your human or come back later.
Only use this for safe, idempotent requests such as GET.
"""
req_headers = {"Accept": "application/json", "User-Agent": "example-agent/0.1"}
req_headers.update(headers or {})
attempt = 0
while True:
req = urllib.request.Request(url, headers=req_headers)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
return json.loads(resp.read().decode("utf-8")), resp.headers
except urllib.error.HTTPError as err:
if is_retryable(err.code, err.headers) and attempt < max_retries:
delay = retry_delay(err.headers, attempt)
if delay > max_wait:
raise
sleep(delay)
attempt += 1
continue
raise
def paginate(
url: str,
headers: dict[str, str] | None = None,
*,
max_pages: int = 5,
**kwargs: Any,
) -> Iterator[Any]:
"""Yield items from a JSON-array endpoint that paginates with Link headers."""
pages = 0
next_url: str | None = url
while next_url and pages < max_pages:
data, resp_headers = get_json(next_url, headers, **kwargs)
yield from data
pages += 1
next_url = parse_link_header(resp_headers.get("Link")).get("next")