Repository Public
1# =============================================================================2# SP BOUCHER | INFRASTRUCTURE & AUTOMATION3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : MacLustr Identity7# File : sdk/python/src/maclustr_identity/_base.py8# Description : Request building, response decoding and retry policy9# shared by the sync and async clients.10# Module : maclustr_identity11# Repository : https://git.spboucher.ai/maclustr-identity12# Project Website : https://identity.spboucher.ai13# Created : 2026-12-0114# Last Modified : 2026-12-0115#16# Author : Simon-Pierre Boucher17# Position : Professor of Finance18# Institution : Université du Québec en Outaouais (UQO)19# Organization : SP Boucher20# Website : https://spboucher.ai21# Git : https://git.spboucher.ai22#23# Preferred Contact: admin@spboucher.ai24# Technical Contact: dev@spboucher.ai25# Security/Admin : admin@spboucher.ai26#27# Copyright (c) 202628# Simon-Pierre Boucher29# All rights reserved where applicable. This file is governed by the30# applicable project license, copyright notices and relevant law.31# Existing third-party rights and notices remain unaffected.32#33# License : None specified (no license file in this repository)34#35# Do not embed credentials, private keys, access tokens,36# certificates or confidential personal information.37#38# =============================================================================39# END OF SP BOUCHER SOURCE HEADER40# =============================================================================4142"""Request building, response decoding and retry policy shared by the sync and async clients."""43from __future__ import annotations4445import json46import random47import uuid48from dataclasses import dataclass49from typing import Any, Mapping50from urllib.parse import quote5152import httpx5354from .errors import APIConnectionError, MacLustrIdentityError, error_from_response, parse_retry_after5556DEFAULT_BASE_URL = "https://identity.spboucher.ai"57SDK_VERSION = "0.1.0"58INITIAL_BACKOFF = 0.559MAX_BACKOFF = 8.060MAX_RETRY_AFTER = 60.0616263def backoff_delay(attempt: int, rand: float | None = None) -> float:64 """Exponential backoff with jitter: a random delay in [50 %, 100 %] of min(8 s, 0.5 s * 2^attempt)."""65 ceiling = min(MAX_BACKOFF, INITIAL_BACKOFF * (2 ** attempt))66 return ceiling * (0.5 + (random.random() if rand is None else rand) * 0.5)676869#: 429 codes that are quotas, not a per-minute rate: they will not clear within a retry window.70QUOTA_CODES = frozenset({"daily_session_limit", "too_many_uploads", "too_many_challenges"})717273def should_retry(status: int | None, code: str | None = None) -> bool:74 """Retry policy: network errors (no status), 429 (rate limit, not quotas) and 5xx. Nothing else is ever retried."""75 if status is None:76 return True77 if status == 429:78 return code not in QUOTA_CODES79 return 500 <= status <= 599808182def seg(value: str) -> str:83 """Encodes one path segment."""84 if not isinstance(value, str) or not value:85 raise MacLustrIdentityError("An object id is required.", type="invalid_request_error", code="id_required")86 return quote(value, safe="")878889@dataclass90class PreparedRequest:91 method: str92 url: str93 headers: dict[str, str]94 params: dict[str, Any]95 content: bytes | None969798class BaseClient:99 def __init__(self, api_key: str, *, base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0, max_retries: int = 2) -> None:100 if not isinstance(api_key, str) or not api_key:101 raise MacLustrIdentityError("api_key is required: MacLustrIdentity(api_key=os.environ['MLID_SECRET_KEY']).",102 type="configuration_error", code="api_key_missing")103 if not api_key.startswith(("mlid_sk_test_", "mlid_sk_live_")):104 raise MacLustrIdentityError("api_key must be a secret key starting with mlid_sk_test_ or mlid_sk_live_.",105 type="configuration_error", code="api_key_malformed")106 self.__api_key = api_key107 self.base_url = base_url.rstrip("/")108 self.timeout = timeout109 self.max_retries = max(0, int(max_retries))110 self._random = random.random111112 @property113 def livemode(self) -> bool:114 """True when the key is a live key (``mlid_sk_live_…``)."""115 return self.__api_key.startswith("mlid_sk_live_")116117 def __repr__(self) -> str: # the key never appears in logs or tracebacks118 return f"{self.__class__.__name__}(base_url={self.base_url!r}, livemode={self.livemode})"119120 def _prepare(self, method: str, path: str, *, params: Mapping[str, Any] | None = None, body: Any = None,121 idempotency_key: str | None = None) -> PreparedRequest:122 headers = {"Authorization": f"Bearer {self.__api_key}", "Accept": "application/json",123 "User-Agent": f"maclustr-identity-python/{SDK_VERSION}"}124 content = None125 if method == "POST":126 # The same key is sent on every retry of this call. The service deduplicates every keyed POST (session creation127 # and cancellation, revocation, webhook creation, secret rotation): a retried call never acts twice.128 headers["Idempotency-Key"] = idempotency_key or f"sdk-{uuid.uuid4()}"129 headers["Content-Type"] = "application/json"130 content = json.dumps(body if body is not None else {}).encode()131 clean = {k: v for k, v in (params or {}).items() if v is not None}132 return PreparedRequest(method, f"{self.base_url}/v1{path}", headers, clean, content)133134 @staticmethod135 def _decode(response: httpx.Response) -> Any:136 """Returns the parsed body of a 2xx response, raises the typed error otherwise."""137 headers = {k.lower(): v for k, v in response.headers.items()}138 try:139 parsed = response.json() if response.content else None140 except ValueError:141 parsed = None142 if response.is_success:143 if parsed is None:144 raise MacLustrIdentityError("The service returned a response that is not JSON.", status=response.status_code,145 code="invalid_response", request_id=headers.get("request-id"), headers=headers)146 return parsed147 raise error_from_response(response.status_code, parsed, headers)148149 def _connection_error(self, exc: Exception, timeout: float) -> APIConnectionError:150 timed_out = isinstance(exc, httpx.TimeoutException)151 err = APIConnectionError(f"The identity service did not answer within {timeout} s." if timed_out152 else f"Could not reach the identity service at {self.base_url}.",153 type="connection_error", code="request_timeout" if timed_out else "connection_failed")154 err.__cause__ = exc155 return err156157 def _retry_delay(self, error: MacLustrIdentityError, attempt: int) -> float:158 """Retry-After (429 rate_limited, 503 service_unavailable) capped at 60 s, else exponential backoff with jitter."""159 ra = getattr(error, "retry_after", None)160 if ra is None and error.status is not None:161 ra = parse_retry_after(error.headers.get("retry-after"))162 return min(MAX_RETRY_AFTER, ra) if ra is not None else backoff_delay(attempt, self._random())163164165def clean_params(**kwargs: Any) -> dict[str, Any]:166 return {k: v for k, v in kwargs.items() if v is not None}167