"""Borrou Partner API: a minimal client on ``requests``. v0.1 DRAFT. - OAuth 2.0 client credentials, the access token cached until a minute before it expires. - Every POST and DELETE carries an Idempotency-Key. One key per request: every retry of that request sends the same key, and a new request gets a new one. - Retries on no answer (a timeout or a dropped connection), 429 and 5xx, honouring Retry-After; a 409 only when Borrou sends Retry-After with it (see ``retryable``). - Cursor pagination as a generator. """ from __future__ import annotations import base64 import email.utils import random import threading import time import urllib.parse import uuid from dataclasses import dataclass from typing import Any, Callable, Dict, Iterator, Optional import requests TOKEN_RENEWAL_MARGIN_SECONDS = 60 class BorrouApiError(Exception): """A refusal. Branch on ``code`` (docs/api/ERRORS.md); the message is for people and may change.""" def __init__(self, status: int, code: str, message: str, request_id: Optional[str], retry_after: Optional[int], body: Any): super().__init__(f"{status} {code}: {message}") self.status = status self.code = code self.request_id = request_id self.retry_after = retry_after self.body = body @dataclass class BorrouResponse: status: int body: Any request_id: Optional[str] replayed: bool def retryable(status: int, retry_after: Optional[int]) -> bool: """429 and 5xx are worth another attempt with the same key: a 5xx saved nothing, and 503 price_unavailable or provider_unavailable carry Retry-After. A 409 is a conflict with the state of the loan or the application: retrying it unchanged gets the same answer, and a stored one is replayed as it was. Borrou never answers 409 to a concurrent retry with the same key (that request waits and replays the first one's answer), so a 409 is retried only when Borrou says when.""" if status == 429 or status >= 500: return True return status == 409 and retry_after is not None def backoff_seconds(attempt: int) -> float: """Exponential backoff with full jitter: up to 0.5 s, 1 s, 2 s, ... capped at 30 s.""" return random.uniform(0, min(30.0, 0.5 * 2 ** (attempt - 1))) def retry_after_seconds(value: Optional[str]) -> Optional[int]: """Retry-After as seconds, or as an HTTP date; None when absent or unreadable.""" if not value: return None value = value.strip() if value.isdigit(): return int(value) try: at = email.utils.parsedate_to_datetime(value) except (TypeError, ValueError): return None return max(0, int(at.timestamp() - time.time() + 0.999)) class BorrouClient: def __init__( self, base_url: str, client_id: str, client_secret: str, *, max_attempts: int = 5, max_retry_after_seconds: int = 60, timeout_seconds: float = 30, session: Optional[requests.Session] = None, sleep: Callable[[float], None] = time.sleep, ): """``base_url``: https://api.borrou.capital for the sandbox.""" self.base_url = base_url.rstrip("/") self.client_id = client_id self.client_secret = client_secret self.max_attempts = max_attempts self.max_retry_after_seconds = max_retry_after_seconds self.timeout_seconds = timeout_seconds self.session = session or requests.Session() self.sleep = sleep self._token: Optional[str] = None self._token_expires_at = 0.0 self._token_lock = threading.Lock() def access_token(self) -> str: """The cached access token, renewed a minute before it expires; one renewal at a time.""" with self._token_lock: if self._token is None or time.monotonic() >= self._token_expires_at - TOKEN_RENEWAL_MARGIN_SECONDS: # RFC 6749 ยง2.3.1: the id and the secret form-encoded, then base64 in HTTP Basic. pair = f"{urllib.parse.quote(self.client_id, safe='')}:{urllib.parse.quote(self.client_secret, safe='')}" response = self._send( "POST", "/v1/oauth/token", headers={ "Authorization": "Basic " + base64.b64encode(pair.encode("utf-8")).decode("ascii"), "Content-Type": "application/x-www-form-urlencoded", }, data="grant_type=client_credentials", ) self._token = response.body["access_token"] self._token_expires_at = time.monotonic() + response.body["expires_in"] return self._token def get(self, path: str, params: Optional[Dict[str, Any]] = None) -> BorrouResponse: return self.request("GET", path, params=params) def post(self, path: str, body: Any = None, idempotency_key: Optional[str] = None) -> BorrouResponse: """An idempotent write. Pass ``idempotency_key`` only to retry a request your process lost track of.""" return self.request("POST", path, body=body, idempotency_key=idempotency_key) def delete(self, path: str, idempotency_key: Optional[str] = None) -> BorrouResponse: return self.request("DELETE", path, idempotency_key=idempotency_key) def request( self, method: str, path: str, *, params: Optional[Dict[str, Any]] = None, body: Any = None, idempotency_key: Optional[str] = None, ) -> BorrouResponse: # One key for every attempt of this request, never shared with another request. key = None if method == "GET" else (idempotency_key or str(uuid.uuid4())) renewed = False while True: headers = {"Authorization": f"Bearer {self.access_token()}"} if key: headers["Idempotency-Key"] = key try: return self._send(method, path, headers=headers, params=params, json=body) except BorrouApiError as err: # A token cut off by a credential rotation is refused before anything runs: renew it once. if err.status == 401 and err.code == "invalid_token" and not renewed: with self._token_lock: self._token = None renewed = True continue raise def paginate(self, path: str, params: Optional[Dict[str, Any]] = None, cursor_param: str = "starting_after") -> Iterator[Any]: """Every item of a cursor-paginated list. Lists take ``starting_after`` (applications, clients, loans); the events feed takes ``after``.""" cursor = None while True: query = dict(params or {}) if cursor is not None: query[cursor_param] = cursor page = self.get(path, query).body yield from page["data"] cursor = page["next_cursor"] if page["has_more"] else None if cursor is None: return def _send(self, method: str, path: str, **kwargs: Any) -> BorrouResponse: headers = {"Accept": "application/json", **kwargs.pop("headers", {})} for attempt in range(1, self.max_attempts + 1): try: response = self.session.request(method, self.base_url + path, headers=headers, timeout=self.timeout_seconds, **kwargs) except (requests.ConnectionError, requests.Timeout): # No answer: the write may or may not have happened, which is what the key is for. if attempt >= self.max_attempts: raise self.sleep(backoff_seconds(attempt)) continue try: body = response.json() except ValueError: body = None request_id = response.headers.get("X-Request-Id") if response.ok: return BorrouResponse(response.status_code, body, request_id, response.headers.get("Idempotent-Replayed") == "true") retry_after = retry_after_seconds(response.headers.get("Retry-After")) error = (body or {}).get("error") or {} failure = BorrouApiError( response.status_code, error.get("code", "unknown"), error.get("message", response.reason), error.get("request_id", request_id), retry_after, body, ) too_long = retry_after is not None and retry_after > self.max_retry_after_seconds if attempt >= self.max_attempts or too_long or not retryable(response.status_code, retry_after): raise failure self.sleep(retry_after if retry_after is not None else backoff_seconds(attempt)) raise AssertionError("unreachable")