Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER7# File : sdk/python/spider_sdk/errors.py8# Module : Sdk9# Repository : https://git.spboucher.ai/spider10# Project Website : Not specified11# Created : 2026-12-0412# Last Modified : 2026-12-0413#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@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 : ISC33#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 errors of the SPIDER SDK.4243Every error answered by the API has the shape44``{"error": {"code", "message", "details", "request_id"}}``; it is mapped to a subclass of45:class:`APIError` according to the HTTP status and the error code.46"""47from __future__ import annotations4849from collections.abc import Mapping50from typing import Any515253class SpiderError(Exception):54 """Base class of every error raised by the SDK."""555657class TransportError(SpiderError):58 """The request could not be completed (connection refused, reset, timeout) after the allowed retries."""596061class JobTimeoutError(SpiderError, TimeoutError):62 """``wait_for_job`` gave up before the job reached a terminal state (the job itself keeps running)."""6364 def __init__(self, job_id: str, last_status: str | None, timeout: float):65 super().__init__(f"job {job_id} still {last_status or 'unknown'} after {timeout:g} s")66 self.job_id, self.last_status, self.timeout = job_id, last_status, timeout676869class ArtifactIntegrityError(SpiderError):70 """The bytes of an artifact do not match the SHA-256 announced by the server."""7172 def __init__(self, artifact_id: str, expected: str | None, actual: str):73 super().__init__(f"artifact {artifact_id}: expected sha256 {expected or '<missing header>'}, got {actual}")74 self.artifact_id, self.expected, self.actual = artifact_id, expected, actual757677class WebhookVerificationError(SpiderError):78 """A webhook delivery failed verification. ``reason`` is a stable machine-readable word."""7980 def __init__(self, reason: str, message: str):81 super().__init__(message)82 self.reason = reason838485class APIError(SpiderError):86 """An error answered by the SPIDER API."""8788 def __init__(self, status: int, code: str, message: str, details: Any = None, request_id: str | None = None,89 retry_after: float | None = None):90 super().__init__(f"HTTP {status} {code}: {message}" + (f" (request_id={request_id})" if request_id else ""))91 self.status = status92 self.code = code93 self.message = message94 self.details = details95 self.request_id = request_id96 self.retry_after = retry_after979899class AuthError(APIError):100 """401 or 403."""101102103class AuthenticationError(AuthError):104 """401: missing, invalid, expired or revoked API key."""105106107class PermissionDeniedError(AuthError):108 """403: the key lacks a scope, or the source is blocked by policy."""109110111class ValidationError(APIError):112 """400 or 422: the request was refused before anything was created."""113114115class MandatoryPolicyError(ValidationError):116 """422 ``mandatory_policy``: an attempt to disable robots.txt compliance or stop-on-access-denial."""117118119class NotFoundError(APIError):120 """404."""121122123class ConflictError(APIError):124 """409."""125126127class IdempotencyConflictError(ConflictError):128 """409 ``idempotency_conflict``: the Idempotency-Key was already used with a different request."""129130131class RateLimitError(APIError):132 """429 ``rate_limited`` (after the allowed retries)."""133134135class QuotaExceededError(RateLimitError):136 """429 ``quota_exceeded``: a tenant quota (active jobs, jobs per day) is reached."""137138139class ServerError(APIError):140 """5xx."""141142143def _retry_after(headers: Mapping[str, str], details: Any) -> float | None:144 raw = headers.get("retry-after") or headers.get("Retry-After")145 if raw:146 try:147 return max(0.0, float(raw))148 except ValueError:149 pass # HTTP-date form: fall back to the body, then to the SDK's own backoff150 if isinstance(details, Mapping):151 v = details.get("retry_after_s")152 if isinstance(v, (int, float)) and not isinstance(v, bool):153 return max(0.0, float(v))154 return None155156157def error_from_response(status: int, body: Any, headers: Mapping[str, str], text: str = "") -> APIError:158 """Build the typed error for a non-2xx response. ``body`` is the decoded JSON, or None."""159 err = body.get("error") if isinstance(body, Mapping) else None160 if isinstance(err, Mapping):161 code = str(err.get("code") or "http_error")162 message = str(err.get("message") or "")163 details = err.get("details")164 request_id = err.get("request_id")165 else:166 code, message, details, request_id = "http_error", text[:300] or f"HTTP {status}", None, None167 request_id = request_id or headers.get("x-request-id") or headers.get("X-Request-Id")168 cls: type[APIError]169 if status == 401:170 cls = AuthenticationError171 elif status == 403:172 cls = PermissionDeniedError173 elif status in (400, 422):174 cls = MandatoryPolicyError if code == "mandatory_policy" else ValidationError175 elif status == 404:176 cls = NotFoundError177 elif status == 409:178 cls = IdempotencyConflictError if code == "idempotency_conflict" else ConflictError179 elif status == 429:180 cls = QuotaExceededError if code == "quota_exceeded" else RateLimitError181 elif status >= 500:182 cls = ServerError183 else:184 cls = APIError185 return cls(status, code, message, details, request_id, _retry_after(headers, details))186