first commit
This commit is contained in:
commit
dd50a0d05e
31 files changed
+5299
No files matched your search
Executable
+203
@@ -0,0 +1,203 @@
|
||||
"""A very small JSON-over-HTTP client with retries and testable transport."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import socket
|
||||
import ssl
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Mapping, Protocol
|
||||
|
||||
from .errors import ApiError
|
||||
|
||||
RETRY_STATUSES = (429, 502, 503, 504)
|
||||
# POST is deliberately excluded: retrying a DNS create after a 502 could leave a
|
||||
# duplicate record behind. Everything else here is safe to replay.
|
||||
RETRYABLE_METHODS = frozenset({"GET", "HEAD", "PUT", "PATCH", "DELETE"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Response:
|
||||
status: int
|
||||
body: bytes
|
||||
headers: Mapping[str, str] = field(default_factory=dict)
|
||||
|
||||
def json(self) -> Any:
|
||||
try:
|
||||
return json.loads(self.body.decode("utf-8") or "null")
|
||||
except (UnicodeDecodeError, json.JSONDecodeError) as exc: # pragma: no cover - defensive
|
||||
raise ApiError(f"response is not valid JSON: {exc}") from exc
|
||||
|
||||
def text(self) -> str:
|
||||
return self.body.decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
class Transport(Protocol):
|
||||
def request(
|
||||
self,
|
||||
method: str,
|
||||
url: str,
|
||||
headers: Mapping[str, str],
|
||||
body: bytes | None,
|
||||
timeout: float,
|
||||
) -> Response: ...
|
||||
|
||||
|
||||
class UrllibTransport:
|
||||
"""Real network transport built on urllib (no third-party dependencies)."""
|
||||
|
||||
def __init__(self, *, verify_tls: bool = True) -> None:
|
||||
if verify_tls:
|
||||
self._context: ssl.SSLContext | None = None
|
||||
else:
|
||||
self._context = ssl._create_unverified_context() # noqa: SLF001 - documented API gap
|
||||
|
||||
def request(
|
||||
self,
|
||||
method: str,
|
||||
url: str,
|
||||
headers: Mapping[str, str],
|
||||
body: bytes | None,
|
||||
timeout: float,
|
||||
) -> Response:
|
||||
req = urllib.request.Request(url, data=body, headers=dict(headers), method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout, context=self._context) as resp:
|
||||
return Response(
|
||||
status=resp.status,
|
||||
body=resp.read(),
|
||||
headers={k.lower(): v for k, v in resp.headers.items()},
|
||||
)
|
||||
except urllib.error.HTTPError as exc:
|
||||
# Keep the payload: Cloudflare and Proxmox both put useful detail there.
|
||||
return Response(
|
||||
status=exc.code,
|
||||
body=exc.read() or b"",
|
||||
headers={k.lower(): v for k, v in (exc.headers or {}).items()},
|
||||
)
|
||||
except urllib.error.URLError as exc:
|
||||
raise ApiError(f"cannot reach {url}: {exc.reason}") from exc
|
||||
except socket.timeout as exc:
|
||||
raise ApiError(f"timeout while calling {url}") from exc
|
||||
|
||||
|
||||
class JsonClient:
|
||||
"""Base URL + auth headers + JSON encoding/decoding + bounded retries."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str,
|
||||
*,
|
||||
transport: Transport | None = None,
|
||||
timeout: float = 20.0,
|
||||
retries: int = 2,
|
||||
backoff: float = 0.5,
|
||||
default_headers: Mapping[str, str] | None = None,
|
||||
sleep=time.sleep,
|
||||
) -> None:
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.transport = transport or UrllibTransport()
|
||||
self.timeout = timeout
|
||||
self.retries = max(0, retries)
|
||||
self.backoff = backoff
|
||||
self.default_headers = {"Accept": "application/json", **dict(default_headers or {})}
|
||||
self._sleep = sleep
|
||||
|
||||
# -- public API -----------------------------------------------------
|
||||
def get(self, path: str, params: Mapping[str, Any] | None = None) -> Any:
|
||||
return self.request("GET", path, params=params)
|
||||
|
||||
def post(self, path: str, body: Any) -> Any:
|
||||
return self.request("POST", path, json_body=body)
|
||||
|
||||
def patch(self, path: str, body: Any) -> Any:
|
||||
return self.request("PATCH", path, json_body=body)
|
||||
|
||||
def put(self, path: str, body: Any) -> Any:
|
||||
return self.request("PUT", path, json_body=body)
|
||||
|
||||
def delete(self, path: str) -> Any:
|
||||
return self.request("DELETE", path)
|
||||
|
||||
def request(
|
||||
self,
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
params: Mapping[str, Any] | None = None,
|
||||
json_body: Any = None,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
) -> Any:
|
||||
url = self.base_url + path
|
||||
if params:
|
||||
query = urllib.parse.urlencode(
|
||||
{k: v for k, v in params.items() if v is not None}, doseq=True
|
||||
)
|
||||
if query:
|
||||
url = f"{url}?{query}"
|
||||
|
||||
body = None if json_body is None else json.dumps(json_body).encode("utf-8")
|
||||
request_headers = dict(self.default_headers)
|
||||
if body is not None:
|
||||
request_headers["Content-Type"] = "application/json"
|
||||
if headers:
|
||||
request_headers.update(headers)
|
||||
|
||||
attempts = self.retries + 1
|
||||
last: Response | None = None
|
||||
for attempt in range(1, attempts + 1):
|
||||
last = self.transport.request(method, url, request_headers, body, self.timeout)
|
||||
retryable = last.status == 429 or (
|
||||
last.status in RETRY_STATUSES and method.upper() in RETRYABLE_METHODS
|
||||
)
|
||||
if last.status < 400 or not retryable or attempt == attempts:
|
||||
break
|
||||
delay = self.backoff * (2 ** (attempt - 1))
|
||||
retry_after = last.headers.get("retry-after")
|
||||
if retry_after:
|
||||
try:
|
||||
delay = max(delay, float(retry_after))
|
||||
except ValueError:
|
||||
pass
|
||||
self._sleep(delay)
|
||||
|
||||
assert last is not None
|
||||
if last.status >= 400:
|
||||
raise ApiError(
|
||||
self._error_message(method, url, last),
|
||||
status=last.status,
|
||||
payload=_safe_json(last),
|
||||
url=url,
|
||||
)
|
||||
if not last.body:
|
||||
return None
|
||||
return last.json()
|
||||
|
||||
# -- helpers --------------------------------------------------------
|
||||
@staticmethod
|
||||
def _error_message(method: str, url: str, response: Response) -> str:
|
||||
detail = ""
|
||||
payload = _safe_json(response)
|
||||
if isinstance(payload, dict):
|
||||
errors = payload.get("errors")
|
||||
if isinstance(errors, list) and errors:
|
||||
detail = "; ".join(
|
||||
str(e.get("message") if isinstance(e, dict) else e) for e in errors
|
||||
)
|
||||
elif payload.get("message"):
|
||||
detail = str(payload["message"])
|
||||
if not detail:
|
||||
detail = response.text().strip()[:300]
|
||||
suffix = f": {detail}" if detail else ""
|
||||
return f"{method} {url} -> HTTP {response.status}{suffix}"
|
||||
|
||||
|
||||
def _safe_json(response: Response) -> Any:
|
||||
try:
|
||||
return response.json()
|
||||
except ApiError:
|
||||
return None
|
||||
Reference in new issue
Block a user