SPB Git

Repository Public

errors.py 6.4 KB 158 lines python

1# =============================================================================2#                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : MacLustr Identity7# File             : sdk/python/src/maclustr_identity/errors.py8# Description      : Typed exceptions.9# Module           : maclustr_identity10# Repository       : https://git.spboucher.ai/maclustr-identity11# Project Website  : https://identity.spboucher.ai12# Created          : 2026-12-0113# Last Modified    : 2026-12-0114#15# Author           : Simon-Pierre Boucher16# Position         : Professor of Finance17# Institution      : Université du Québec en Outaouais (UQO)18# Organization     : SP Boucher19# Website          : https://spboucher.ai20# Git              : https://git.spboucher.ai21#22# Preferred Contact: admin@spboucher.ai23# Technical Contact: dev@spboucher.ai24# Security/Admin   : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License          : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Typed exceptions. API errors mirror the envelope {"error": {"type", "code", "message", "param", "request_id"}}."""42from __future__ import annotations4344from email.utils import parsedate_to_datetime45from typing import Any, Mapping464748class MacLustrIdentityError(Exception):49    """Base class of every error raised by this SDK."""5051    def __init__(self, message: str, *, status: int | None = None, type: str | None = None, code: str | None = None,52                 param: str | None = None, request_id: str | None = None, headers: Mapping[str, str] | None = None) -> None:53        super().__init__(message)54        self.message = message55        #: HTTP status, or None when no response was received.56        self.status = status57        #: Error family sent by the API, for example ``invalid_request_error``.58        self.type = type or "api_error"59        #: Machine-readable code, for example ``resource_missing``.60        self.code = code or "unknown_error"61        #: Offending request parameter, when the API names one.62        self.param = param63        #: Value of the Request-Id header: quote it when asking for support.64        self.request_id = request_id65        self.headers = dict(headers or {})6667    def __repr__(self) -> str:68        return f"{self.__class__.__name__}(status={self.status!r}, code={self.code!r}, message={self.message!r}, request_id={self.request_id!r})"697071class InvalidRequestError(MacLustrIdentityError):72    """400, 411, 413, 422: the request itself is wrong (``invalid_cursor``, ``payload_too_large``, ``length_required``…)."""737475class AuthenticationError(MacLustrIdentityError):76    """401: missing, invalid, expired or revoked API key."""777879class PermissionDeniedError(MacLustrIdentityError):80    """403: the key lacks a scope, the application is suspended, a compliance gate is closed, or the caller's network is not allowed (``forbidden_network``)."""818283class NotFoundError(MacLustrIdentityError):84    """404: unknown object, or an object of another application or mode."""858687class ConflictError(MacLustrIdentityError):88    """409: state conflict or idempotency-key conflict."""899091class RateLimitError(MacLustrIdentityError):92    """429: too many requests. ``retry_after`` holds the Retry-After header in seconds, when present."""9394    def __init__(self, message: str, *, retry_after: float | None = None, **kwargs: Any) -> None:95        super().__init__(message, **kwargs)96        self.retry_after = retry_after979899class APIServerError(MacLustrIdentityError):100    """5xx: the service failed. ``retry_after`` holds the Retry-After header in seconds, when present (503 ``service_unavailable``)."""101102    def __init__(self, message: str, *, retry_after: float | None = None, **kwargs: Any) -> None:103        super().__init__(message, **kwargs)104        self.retry_after = retry_after105106107class APIConnectionError(MacLustrIdentityError):108    """No response (DNS, TCP, TLS failure or timeout). Treat the identity service as unreachable and fail closed."""109110111class SignatureVerificationError(MacLustrIdentityError):112    """The webhook signature is missing, malformed, expired or does not match. Never process such a payload."""113114115def parse_retry_after(value: str | None, now: float | None = None) -> float | None:116    """Parses Retry-After (delta seconds or HTTP date) into seconds."""117    if not value:118        return None119    try:120        n = float(value)121        if n == n and n not in (float("inf"), float("-inf")):122            return max(0.0, n)123    except ValueError:124        pass125    try:126        import time127        return max(0.0, parsedate_to_datetime(value).timestamp() - (time.time() if now is None else now))128    except (TypeError, ValueError):129        return None130131132def error_from_response(status: int, body: Any, headers: Mapping[str, str]) -> MacLustrIdentityError:133    env = body.get("error") if isinstance(body, dict) else None134    env = env if isinstance(env, dict) else {}135136    def s(key: str) -> str | None:137        v = env.get(key)138        return v if isinstance(v, str) and v else None139140    kw: dict[str, Any] = dict(status=status, type=s("type"), code=s("code"), param=s("param"),141                              request_id=s("request_id") or headers.get("request-id"), headers=headers)142    message = s("message") or f"HTTP {status}"143    if status == 401:144        return AuthenticationError(message, **kw)145    if status == 403:146        return PermissionDeniedError(message, **kw)147    if status == 404:148        return NotFoundError(message, **kw)149    if status == 409:150        return ConflictError(message, **kw)151    if status == 429:152        return RateLimitError(message, retry_after=parse_retry_after(headers.get("retry-after")), **kw)153    if status >= 500:154        return APIServerError(message, retry_after=parse_retry_after(headers.get("retry-after")), **kw)155    if status >= 400:156        return InvalidRequestError(message, **kw)157    return MacLustrIdentityError(message, **kw)158
Files main
Menu

Theme