SPB Git

Repository Public

_http.py 9.5 KB 199 lines python

1"""HTTP core: authentication, timeouts, safe retries, idempotency keys, typed errors. Standard library only."""2from __future__ import annotations34import builtins5import email.utils6import json7import random8import re9import time10import urllib.error11import urllib.parse12import urllib.request13import uuid14from typing import Any, Callable, Dict, Mapping, Optional, Tuple1516from ._errors import ConnectionError, SPMailError, TimeoutError, error_from_response1718#: (method, url, headers, body, timeout seconds) -> (status, lower-cased headers, body bytes).19#: Must raise the builtin ``TimeoutError`` on a timeout and ``OSError`` on a network failure.20Transport = Callable[[str, str, Dict[str, str], Optional[bytes], float], Tuple[int, Dict[str, str], bytes]]2122_PRINTABLE = re.compile(r"[\x20-\x7e]{1,200}")232425class _NoRedirect(urllib.request.HTTPRedirectHandler):26    """Redirects are never followed: the Authorization header must not travel to another URL."""2728    def redirect_request(self, *args: Any, **kwargs: Any) -> None:  # type: ignore[override]29        return None303132def _default_transport() -> Transport:33    opener = urllib.request.build_opener(_NoRedirect())3435    def send(method: str, url: str, headers: Dict[str, str], body: Optional[bytes], timeout: float) -> Tuple[int, Dict[str, str], bytes]:36        req = urllib.request.Request(url, data=body, method=method, headers=headers)37        try:38            with opener.open(req, timeout=timeout) as res:39                return res.status, {k.lower(): v for k, v in res.headers.items()}, res.read()40        except urllib.error.HTTPError as e:  # non-2xx answers are ordinary answers here41            with e:42                return e.code, {k.lower(): v for k, v in e.headers.items()}, e.read()43        except urllib.error.URLError as e:44            if isinstance(e.reason, builtins.TimeoutError):45                raise builtins.TimeoutError(str(e.reason)) from e46            raise OSError(str(e.reason)) from e4748    return send495051def new_idempotency_key() -> str:52    return f"sdk-{uuid.uuid4()}"535455def _retry_after(headers: Mapping[str, str]) -> Optional[float]:56    v = headers.get("retry-after")57    if not v:58        return None59    v = v.strip()60    if re.fullmatch(r"\d+(\.\d+)?", v):61        return float(v)62    try:63        return max(0.0, email.utils.parsedate_to_datetime(v).timestamp() - time.time())64    except (TypeError, ValueError):65        return None666768def build_query(query: Optional[Mapping[str, Any]]) -> str:69    if not query:70        return ""71    parts = []72    for k, v in query.items():73        if v is None:74            continue75        if isinstance(v, bool):76            s = "true" if v else "false"77        elif isinstance(v, (list, tuple)):78            s = ",".join(str(x) for x in v)79        else:80            s = str(v)81        parts.append(f"{urllib.parse.quote(str(k), safe='')}={urllib.parse.quote(s, safe='')}")82    return "?" + "&".join(parts) if parts else ""838485class HttpClient:86    def __init__(self, api_key: str, base_url: str = "https://mail.spboucher.ai", *, timeout: float = 30.0, max_retries: int = 2,87                 max_retry_delay: float = 60.0, allow_insecure_http: bool = False, transport: Optional[Transport] = None,88                 default_headers: Optional[Mapping[str, str]] = None, sleep: Callable[[float], None] = time.sleep) -> None:89        if not isinstance(api_key, str) or not api_key.strip():90            raise ValueError("spmail: `api_key` is required (use the SPMAIL_API_KEY environment variable, never a literal in source)")91        self.__api_key = api_key.strip()  # name-mangled: not shown by vars()/repr of the public client92        base = base_url.strip().rstrip("/")93        if not base.endswith("/api/v1"):94            base += "/api/v1"95        u = urllib.parse.urlsplit(base)96        if u.scheme not in ("http", "https") or not u.hostname:97            raise ValueError("spmail: `base_url` must be an http(s) URL")98        if u.scheme == "http" and u.hostname not in ("localhost", "127.0.0.1", "::1") and not allow_insecure_http:99            raise ValueError("spmail: refusing a plain http:// base URL (the API key would travel in clear); use https or allow_insecure_http=True")100        if u.username or u.password or u.query:101            raise ValueError("spmail: `base_url` must not carry credentials or a query string")102        self.base_url = base103        self.timeout = timeout104        self.max_retries = max(0, max_retries)105        self.max_retry_delay = max_retry_delay106        self._transport = transport or _default_transport()107        self._default_headers = dict(default_headers or {})108        self._sleep = sleep109110    def __repr__(self) -> str:111        return f"HttpClient(base_url={self.base_url!r})"112113    @staticmethod114    def _backoff(attempt: int) -> float:115        """Exponential backoff with jitter: 0.5 s, 1 s, 2 s ... capped at 8 s."""116        cap = min(8.0, 0.5 * 2 ** attempt)117        return cap / 2 + random.random() * cap / 2118119    def request(self, method: str, path: str, *, query: Optional[Mapping[str, Any]] = None, body: Any = None,120                raw: Optional[Tuple[bytes, str]] = None, idempotent: bool = False, repeatable: bool = False,121                idempotency_key: Optional[str] = None, binary: bool = False, anonymous: bool = False,122                timeout: Optional[float] = None, max_retries: Optional[int] = None) -> Any:123        """One API call. Returns parsed JSON, or ``(bytes, headers)`` when ``binary``."""124        url = f"{self.base_url}{path}{build_query(query)}"125        headers: Dict[str, str] = {"Accept": "application/octet-stream" if binary else "application/json", "User-Agent": "spmail-python/1.0"}126        headers.update(self._default_headers)127        if not anonymous:128            headers["Authorization"] = f"Bearer {self.__api_key}"129        data: Optional[bytes] = None130        if raw is not None:131            data, headers["Content-Type"] = raw132        elif body is not None:133            data = json.dumps(body, ensure_ascii=False).encode("utf-8")134            headers["Content-Type"] = "application/json"135        # One key for the whole call: every retry replays the same key, so a send can never be duplicated.136        key = (idempotency_key or new_idempotency_key()) if idempotent else None137        if key is not None:138            if not _PRINTABLE.fullmatch(key):139                raise ValueError("spmail: `idempotency_key` must be 1-200 printable ASCII characters")140            headers["Idempotency-Key"] = key141        safe = method in ("GET", "PUT", "DELETE") or repeatable or key is not None142        retries = self.max_retries if max_retries is None else max(0, max_retries)143        budget = self.timeout if timeout is None else timeout144145        attempt = 0146        while True:147            try:148                status, res_headers, payload = self._transport(method, url, headers, data, budget)149            except SPMailError:150                raise151            except builtins.TimeoutError as exc:  # socket.timeout is the same class since Python 3.10152                err: SPMailError = TimeoutError(f"No answer from SP Mail within {budget:g} s ({method} {path})", code="timeout")153                err.__cause__ = exc154            except OSError as exc:155                err = ConnectionError(f"Could not reach SP Mail ({method} {path}): {exc}", code="connection_error")156                err.__cause__ = exc157            else:158                if 200 <= status < 300:159                    if binary:160                        return payload, res_headers161                    if status == 204 or not payload:162                        return None163                    try:164                        return json.loads(payload.decode("utf-8"))165                    except ValueError as exc:166                        raise ConnectionError(f"Invalid answer from SP Mail ({method} {path})", code="connection_error") from exc167                code, message, details = "http_error", f"SP Mail answered {status}", None168                try:169                    j = json.loads(payload.decode("utf-8"))170                    e = j.get("error") if isinstance(j, dict) else None171                    if isinstance(e, dict):172                        code, message, details = e.get("code", code), e.get("message", message), e.get("details")173                    elif isinstance(e, str):  # legacy envelope {error, message}174                        code, message = e, j.get("message", message)175                except (ValueError, UnicodeDecodeError):176                    pass177                retry_after = _retry_after(res_headers)178                err = error_from_response(status, code, message, details, res_headers.get("x-request-id"), retry_after)179                if attempt < retries:180                    # 429 rate_limited: refused before being processed - repeating it is safe for any method.181                    if status == 429 and code != "daily_send_limit_exceeded":182                        wait = retry_after + random.random() * 0.25 if retry_after is not None else self._backoff(attempt)183                        if wait <= self.max_retry_delay:184                            self._sleep(wait)185                            attempt += 1186                            continue187                    elif safe and (status in (502, 503, 504) or code == "idempotency_in_progress"):188                        self._sleep(self._backoff(attempt))189                        attempt += 1190                        continue191                raise err192            # network failure or timeout193            if safe and attempt < retries:194                self._sleep(self._backoff(attempt))195                attempt += 1196                continue197            raise err198199
Files main
Menu

Theme