disruptapi 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
disruptapi/__init__.py ADDED
@@ -0,0 +1,63 @@
1
+ """Official Python client for DisruptAPI, the travel disruption intelligence API."""
2
+
3
+ from . import types, webhooks
4
+ from ._base_client import (
5
+ DEFAULT_BASE_URL,
6
+ DEFAULT_MAX_RETRIES,
7
+ DEFAULT_TIMEOUT,
8
+ APIResponse,
9
+ RequestSpec,
10
+ )
11
+ from ._client import AsyncDisruptAPI, DisruptAPI
12
+ from ._errors import (
13
+ APIConnectionError,
14
+ APITimeoutError,
15
+ AuthenticationError,
16
+ ConflictError,
17
+ DisruptError,
18
+ InternalServerError,
19
+ NotFoundError,
20
+ GoneError,
21
+ PayloadTooLargeError,
22
+ PermissionDeniedError,
23
+ RateLimitError,
24
+ ValidationError,
25
+ WebhookSignatureError,
26
+ )
27
+ from ._rate_limit import RateLimitInfo
28
+ from ._version import __version__
29
+ from .pagination import AsyncPage, AsyncPaginator, SyncPage
30
+ from .webhooks import construct_event, generate_test_header, verify_signature
31
+
32
+ __all__ = [
33
+ "DisruptAPI",
34
+ "AsyncDisruptAPI",
35
+ "APIResponse",
36
+ "RequestSpec",
37
+ "RateLimitInfo",
38
+ "SyncPage",
39
+ "AsyncPage",
40
+ "AsyncPaginator",
41
+ "DisruptError",
42
+ "AuthenticationError",
43
+ "PermissionDeniedError",
44
+ "NotFoundError",
45
+ "ConflictError",
46
+ "ValidationError",
47
+ "GoneError",
48
+ "PayloadTooLargeError",
49
+ "RateLimitError",
50
+ "InternalServerError",
51
+ "APIConnectionError",
52
+ "APITimeoutError",
53
+ "WebhookSignatureError",
54
+ "verify_signature",
55
+ "construct_event",
56
+ "generate_test_header",
57
+ "webhooks",
58
+ "types",
59
+ "DEFAULT_BASE_URL",
60
+ "DEFAULT_TIMEOUT",
61
+ "DEFAULT_MAX_RETRIES",
62
+ "__version__",
63
+ ]
disruptapi/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """``python -m disruptapi``: the command-line tool."""
2
+
3
+ from .cli import run
4
+
5
+ if __name__ == "__main__":
6
+ run()
@@ -0,0 +1,288 @@
1
+ """HTTP transport shared by the sync and async clients: auth, retries, errors, rate limits."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextvars
7
+ import json
8
+ import os
9
+ import random
10
+ import time
11
+ from dataclasses import dataclass, field
12
+ from datetime import date, datetime, timezone
13
+ from typing import Any, Callable, Dict, Generic, List, Mapping, Optional, TypeVar, Union
14
+ from urllib.parse import quote
15
+
16
+ import httpx
17
+
18
+ from ._errors import APIConnectionError, APITimeoutError, DisruptError, make_api_error
19
+ from ._rate_limit import RateLimitInfo, parse_rate_limit
20
+ from ._version import __version__
21
+
22
+ DEFAULT_BASE_URL = "https://app.disruptapi.com"
23
+ DEFAULT_TIMEOUT = 30.0
24
+ DEFAULT_MAX_RETRIES = 3
25
+ USER_AGENT = f"disruptapi-python/{__version__}"
26
+ _NO_RETRY_429 = {"quota_exceeded", "daily_data_limit"}
27
+
28
+ T = TypeVar("T")
29
+
30
+
31
+ @dataclass
32
+ class APIResponse(Generic[T]):
33
+ """Everything about one HTTP response."""
34
+
35
+ data: T #: the ``data`` member of the envelope
36
+ body: Any #: the whole parsed body (``data`` plus ``meta`` or ``limits``)
37
+ status: int
38
+ headers: httpx.Headers
39
+ rate_limit: RateLimitInfo
40
+ request_id: Optional[str]
41
+
42
+
43
+ @dataclass
44
+ class RequestSpec:
45
+ method: str
46
+ path: str
47
+ query: Optional[Dict[str, Any]] = None
48
+ body: Any = None
49
+ #: POSTs that are safe to repeat (read-only, or keyed upserts). Default: not POST.
50
+ idempotent: Optional[bool] = None
51
+ timeout: Optional[float] = None
52
+ max_retries: Optional[int] = None
53
+ headers: Dict[str, str] = field(default_factory=dict)
54
+
55
+ @property
56
+ def is_idempotent(self) -> bool:
57
+ return self.idempotent if self.idempotent is not None else self.method != "POST"
58
+
59
+
60
+ def format_datetime(v: Union[datetime, date]) -> str:
61
+ """UTC, seconds precision, ``Z``: the form ``since`` is compared against (as text)."""
62
+ if isinstance(v, datetime):
63
+ if v.tzinfo is None:
64
+ v = v.replace(tzinfo=timezone.utc)
65
+ return v.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
66
+ return v.isoformat()
67
+
68
+
69
+ def build_query(query: Optional[Mapping[str, Any]]) -> Dict[str, str]:
70
+ out: Dict[str, str] = {}
71
+ for k, v in (query or {}).items():
72
+ if v is None:
73
+ continue
74
+ if isinstance(v, bool):
75
+ out[k] = "true" if v else "false"
76
+ elif isinstance(v, (list, tuple, set)):
77
+ if v:
78
+ out[k] = ",".join(str(x) for x in v)
79
+ elif isinstance(v, (datetime, date)):
80
+ out[k] = format_datetime(v)
81
+ else:
82
+ out[k] = str(v)
83
+ return out
84
+
85
+
86
+ def path_param(v: str) -> str:
87
+ return quote(str(v), safe="")
88
+
89
+
90
+ def backoff_delay(retry: int, initial: float, maximum: float,
91
+ rand: Callable[[], float] = random.random) -> float:
92
+ """Seconds before retry number ``retry`` (1-based): exponential, with "equal jitter"."""
93
+ base = min(maximum, initial * (2.0 ** (retry - 1)))
94
+ return base / 2 + rand() * (base / 2)
95
+
96
+
97
+ class _BaseClient:
98
+ def __init__(
99
+ self,
100
+ api_key: Optional[str] = None,
101
+ *,
102
+ base_url: Optional[str] = None,
103
+ timeout: float = DEFAULT_TIMEOUT,
104
+ max_retries: int = DEFAULT_MAX_RETRIES,
105
+ initial_retry_delay: float = 0.5,
106
+ max_retry_delay: float = 8.0,
107
+ max_retry_after: float = 60.0,
108
+ default_headers: Optional[Mapping[str, str]] = None,
109
+ ) -> None:
110
+ key = api_key if api_key is not None else os.environ.get("DISRUPT_API_KEY")
111
+ #: The API key, or None (only ``plans()`` works without one).
112
+ self.api_key: Optional[str] = key.strip() if key else None
113
+ self.base_url = (base_url or os.environ.get("DISRUPT_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
114
+ self.timeout = timeout
115
+ self.max_retries = max(0, max_retries)
116
+ self.initial_retry_delay = initial_retry_delay
117
+ self.max_retry_delay = max_retry_delay
118
+ self.max_retry_after = max_retry_after
119
+ self._default_headers = dict(default_headers or {})
120
+ self._last_response: contextvars.ContextVar[Optional[APIResponse[Any]]] = contextvars.ContextVar(
121
+ f"disruptapi_last_response_{id(self)}", default=None)
122
+
123
+ @property
124
+ def last_response(self) -> Optional[APIResponse[Any]]:
125
+ """The latest response seen by this client in the current thread or task."""
126
+ return self._last_response.get()
127
+
128
+ @property
129
+ def last_rate_limit(self) -> Optional[RateLimitInfo]:
130
+ r = self._last_response.get()
131
+ return r.rate_limit if r else None
132
+
133
+ def _headers(self, spec: RequestSpec) -> Dict[str, str]:
134
+ h = {"Accept": "application/json", "User-Agent": USER_AGENT, **self._default_headers, **spec.headers}
135
+ if self.api_key:
136
+ h["Authorization"] = f"Bearer {self.api_key}"
137
+ if spec.body is not None:
138
+ h["Content-Type"] = "application/json"
139
+ return h
140
+
141
+ def _content(self, spec: RequestSpec) -> Optional[bytes]:
142
+ if spec.body is None:
143
+ return None
144
+ return json.dumps(spec.body, ensure_ascii=False, default=_json_default).encode("utf-8")
145
+
146
+ def _process(self, response: httpx.Response) -> APIResponse[Any]:
147
+ try:
148
+ body = response.json() if response.content else None
149
+ except ValueError:
150
+ body = None
151
+ rl = parse_rate_limit(response.headers)
152
+ rid = response.headers.get("x-request-id") or response.headers.get("x-vercel-id")
153
+ data = body.get("data") if isinstance(body, dict) and "data" in body else body
154
+ resp: APIResponse[Any] = APIResponse(data=data, body=body, status=response.status_code,
155
+ headers=response.headers, rate_limit=rl, request_id=rid)
156
+ self._last_response.set(resp)
157
+ if response.is_success:
158
+ if body is None and response.content:
159
+ raise DisruptError("response was not JSON", status=response.status_code, code="invalid_response",
160
+ request_id=rid, headers=response.headers, rate_limit=rl, body=response.text)
161
+ return resp
162
+ raise make_api_error(response, body, rl, rid)
163
+
164
+ def _retry_delay(self, err: DisruptError, retry: int, idempotent: bool) -> Optional[float]:
165
+ """Seconds to wait before retrying, or None when this error must not be retried."""
166
+ rl = err.rate_limit or RateLimitInfo()
167
+ if isinstance(err, APIConnectionError):
168
+ return backoff_delay(retry, self.initial_retry_delay, self.max_retry_delay) if idempotent else None
169
+ status = err.status or 0
170
+ if status == 429:
171
+ # Refused before the handler ran, so safe for every method. Quota and daily
172
+ # budget errors last until the month or UTC day resets.
173
+ if err.code in _NO_RETRY_429 or rl.limit_reason == "quota":
174
+ return None
175
+ if rl.retry_after is not None:
176
+ if rl.retry_after > self.max_retry_after:
177
+ return None
178
+ return rl.retry_after + random.random() * 0.25
179
+ return backoff_delay(retry, self.initial_retry_delay, self.max_retry_delay)
180
+ if status == 409 and err.code == "idempotency_in_progress":
181
+ # The first attempt with this Idempotency-Key is still running: wait for its answer.
182
+ return backoff_delay(retry, self.initial_retry_delay, self.max_retry_delay)
183
+ if (status >= 500 or status == 408) and idempotent:
184
+ if rl.retry_after is not None and rl.retry_after <= self.max_retry_after:
185
+ return rl.retry_after
186
+ return backoff_delay(retry, self.initial_retry_delay, self.max_retry_delay)
187
+ return None
188
+
189
+ def _url(self, spec: RequestSpec) -> str:
190
+ return f"{self.base_url}{spec.path}"
191
+
192
+
193
+ def _json_default(o: Any) -> Any:
194
+ if isinstance(o, (datetime, date)):
195
+ return format_datetime(o)
196
+ raise TypeError(f"{type(o).__name__} is not JSON serialisable")
197
+
198
+
199
+ def _connection_error(exc: Exception, base_url: str, timeout: float) -> APIConnectionError:
200
+ if isinstance(exc, httpx.TimeoutException):
201
+ return APITimeoutError(f"request timed out after {timeout} s", code="timeout")
202
+ return APIConnectionError(f"could not reach {base_url}: {exc}", code="connection_error")
203
+
204
+
205
+ class SyncAPIClient(_BaseClient):
206
+ def __init__(self, api_key: Optional[str] = None, *, http_client: Optional[httpx.Client] = None,
207
+ transport: Optional[httpx.BaseTransport] = None, **kwargs: Any) -> None:
208
+ super().__init__(api_key, **kwargs)
209
+ self._owns_http = http_client is None
210
+ self._http = http_client or httpx.Client(transport=transport, follow_redirects=False)
211
+
212
+ def request(self, spec: RequestSpec) -> APIResponse[Any]:
213
+ """Low-level call. Returns the full response; resource methods use it."""
214
+ max_retries = self.max_retries if spec.max_retries is None else max(0, spec.max_retries)
215
+ timeout = spec.timeout if spec.timeout is not None else self.timeout
216
+ headers, content = self._headers(spec), self._content(spec)
217
+ params = build_query(spec.query)
218
+ retry = 0
219
+ while True:
220
+ try:
221
+ try:
222
+ r = self._http.request(spec.method, self._url(spec), params=params, headers=headers,
223
+ content=content, timeout=timeout)
224
+ except httpx.TransportError as exc:
225
+ raise _connection_error(exc, self.base_url, timeout) from exc
226
+ return self._process(r)
227
+ except DisruptError as err:
228
+ retry += 1
229
+ delay = self._retry_delay(err, retry, spec.is_idempotent)
230
+ if delay is None or retry > max_retries:
231
+ raise
232
+ time.sleep(delay)
233
+
234
+ def close(self) -> None:
235
+ if self._owns_http:
236
+ self._http.close()
237
+
238
+ def __enter__(self: Any) -> Any:
239
+ return self
240
+
241
+ def __exit__(self, *exc: Any) -> None:
242
+ self.close()
243
+
244
+
245
+ class AsyncAPIClient(_BaseClient):
246
+ def __init__(self, api_key: Optional[str] = None, *, http_client: Optional[httpx.AsyncClient] = None,
247
+ transport: Optional[httpx.AsyncBaseTransport] = None, **kwargs: Any) -> None:
248
+ super().__init__(api_key, **kwargs)
249
+ self._owns_http = http_client is None
250
+ self._http = http_client or httpx.AsyncClient(transport=transport, follow_redirects=False)
251
+
252
+ async def request(self, spec: RequestSpec) -> APIResponse[Any]:
253
+ """Low-level call. Returns the full response; resource methods use it."""
254
+ max_retries = self.max_retries if spec.max_retries is None else max(0, spec.max_retries)
255
+ timeout = spec.timeout if spec.timeout is not None else self.timeout
256
+ headers, content = self._headers(spec), self._content(spec)
257
+ params = build_query(spec.query)
258
+ retry = 0
259
+ while True:
260
+ try:
261
+ try:
262
+ r = await self._http.request(spec.method, self._url(spec), params=params, headers=headers,
263
+ content=content, timeout=timeout)
264
+ except httpx.TransportError as exc:
265
+ raise _connection_error(exc, self.base_url, timeout) from exc
266
+ return self._process(r)
267
+ except DisruptError as err:
268
+ retry += 1
269
+ delay = self._retry_delay(err, retry, spec.is_idempotent)
270
+ if delay is None or retry > max_retries:
271
+ raise
272
+ await asyncio.sleep(delay)
273
+
274
+ async def close(self) -> None:
275
+ if self._owns_http:
276
+ await self._http.aclose()
277
+
278
+ async def __aenter__(self: Any) -> Any:
279
+ return self
280
+
281
+ async def __aexit__(self, *exc: Any) -> None:
282
+ await self.close()
283
+
284
+
285
+ __all__: List[str] = [
286
+ "APIResponse", "RequestSpec", "SyncAPIClient", "AsyncAPIClient", "DEFAULT_BASE_URL",
287
+ "DEFAULT_TIMEOUT", "DEFAULT_MAX_RETRIES", "USER_AGENT", "backoff_delay", "build_query", "format_datetime",
288
+ ]
disruptapi/_client.py ADDED
@@ -0,0 +1,117 @@
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ from typing import Any, List, Optional
5
+
6
+ from ._base_client import AsyncAPIClient, SyncAPIClient
7
+ from .resources import _specs as s
8
+ from .resources import async_ as ar
9
+ from .resources import sync as sr
10
+ from .types import Me, Plan, Usage
11
+
12
+
13
+ class DisruptAPI(SyncAPIClient):
14
+ """The sync DisruptAPI client.
15
+
16
+ >>> client = DisruptAPI() # reads DISRUPT_API_KEY
17
+ >>> client.exposure.check([{"id": "BKG-1", "kind": "flight", "carrier": "AS", "origin": "SEA", "destination": "HNL"}])
18
+
19
+ Options: ``base_url`` (default ``https://app.disruptapi.com``, or ``DISRUPT_BASE_URL``),
20
+ ``timeout`` (seconds per attempt, default 30), ``max_retries`` (default 3),
21
+ ``http_client`` or ``transport`` (a custom ``httpx`` client or transport).
22
+ """
23
+
24
+ def __init__(self, api_key: Optional[str] = None, **kwargs: Any) -> None:
25
+ super().__init__(api_key, **kwargs)
26
+ self._init_resources()
27
+
28
+ def _init_resources(self) -> None:
29
+ self.signals = sr.Signals(self)
30
+ self.exposure = sr.Exposure(self)
31
+ self.forecast = sr.Forecasts(self)
32
+ self.failure_layers = sr.FailureLayers(self)
33
+ self.watchlists = sr.Watchlists(self)
34
+ self.airports = sr.Airports(self)
35
+ self.carriers = sr.Carriers(self)
36
+ self.sources = sr.Sources(self)
37
+ self.providers = sr.Providers(self)
38
+ self.events = sr.Events(self)
39
+ self.webhooks = sr.Webhooks(self)
40
+ self.changes = sr.Changes(self)
41
+ self.incidents = sr.Incidents(self)
42
+ self.severities = sr.Severities(self)
43
+ self.flights = sr.Flights(self)
44
+ self.evidence = sr.Evidence(self)
45
+
46
+ def with_options(self, *, timeout: Optional[float] = None, max_retries: Optional[int] = None) -> "DisruptAPI":
47
+ """A copy with other options, sharing the HTTP connection pool."""
48
+ c = copy.copy(self)
49
+ if timeout is not None:
50
+ c.timeout = timeout
51
+ if max_retries is not None:
52
+ c.max_retries = max(0, max_retries)
53
+ c._owns_http = False
54
+ c._init_resources()
55
+ return c
56
+
57
+ def me(self) -> Me:
58
+ """``GET /v1/me``: the organisation, plan and key behind the request."""
59
+ return self.request(s.me()).data # type: ignore[no-any-return]
60
+
61
+ def usage(self, *, days: Optional[int] = None) -> Usage:
62
+ """``GET /v1/usage``: requests per day, by route and by key (``days`` 1 to 365, default 30)."""
63
+ return self.request(s.usage(days)).data # type: ignore[no-any-return]
64
+
65
+ def plans(self) -> List[Plan]:
66
+ """``GET /v1/plans``: every plan with its limits. Needs no key."""
67
+ return self.request(s.plans()).data # type: ignore[no-any-return]
68
+
69
+
70
+ class AsyncDisruptAPI(AsyncAPIClient):
71
+ """The async DisruptAPI client. Same methods as :class:`DisruptAPI`, as coroutines.
72
+
73
+ List methods return an object you can ``await`` (first page) or ``async for`` over
74
+ (every item across pages).
75
+ """
76
+
77
+ def __init__(self, api_key: Optional[str] = None, **kwargs: Any) -> None:
78
+ super().__init__(api_key, **kwargs)
79
+ self._init_resources()
80
+
81
+ def _init_resources(self) -> None:
82
+ self.signals = ar.Signals(self)
83
+ self.exposure = ar.Exposure(self)
84
+ self.forecast = ar.Forecasts(self)
85
+ self.failure_layers = ar.FailureLayers(self)
86
+ self.watchlists = ar.Watchlists(self)
87
+ self.airports = ar.Airports(self)
88
+ self.carriers = ar.Carriers(self)
89
+ self.sources = ar.Sources(self)
90
+ self.providers = ar.Providers(self)
91
+ self.events = ar.Events(self)
92
+ self.webhooks = ar.Webhooks(self)
93
+ self.changes = ar.Changes(self)
94
+ self.incidents = ar.Incidents(self)
95
+ self.severities = ar.Severities(self)
96
+ self.flights = ar.Flights(self)
97
+ self.evidence = ar.Evidence(self)
98
+
99
+ def with_options(self, *, timeout: Optional[float] = None, max_retries: Optional[int] = None) -> "AsyncDisruptAPI":
100
+ """A copy with other options, sharing the HTTP connection pool."""
101
+ c = copy.copy(self)
102
+ if timeout is not None:
103
+ c.timeout = timeout
104
+ if max_retries is not None:
105
+ c.max_retries = max(0, max_retries)
106
+ c._owns_http = False
107
+ c._init_resources()
108
+ return c
109
+
110
+ async def me(self) -> Me:
111
+ return (await self.request(s.me())).data # type: ignore[no-any-return]
112
+
113
+ async def usage(self, *, days: Optional[int] = None) -> Usage:
114
+ return (await self.request(s.usage(days))).data # type: ignore[no-any-return]
115
+
116
+ async def plans(self) -> List[Plan]:
117
+ return (await self.request(s.plans())).data # type: ignore[no-any-return]
disruptapi/_errors.py ADDED
@@ -0,0 +1,154 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from typing import Any, Optional, Type
5
+
6
+ import httpx
7
+
8
+ from ._rate_limit import RateLimitInfo
9
+
10
+
11
+ class DisruptError(Exception):
12
+ """Base class for every error this SDK raises."""
13
+
14
+ def __init__(
15
+ self,
16
+ message: str,
17
+ *,
18
+ status: Optional[int] = None,
19
+ code: str = "error",
20
+ details: Any = None,
21
+ request_id: Optional[str] = None,
22
+ headers: Optional[httpx.Headers] = None,
23
+ rate_limit: Optional[RateLimitInfo] = None,
24
+ body: Any = None,
25
+ ) -> None:
26
+ super().__init__(message)
27
+ self.message = message
28
+ #: HTTP status, when the API answered.
29
+ self.status = status
30
+ #: Stable machine-readable code from ``error.code``. Branch on this.
31
+ self.code = code
32
+ #: ``error.details`` (validation problems on ``invalid_request``).
33
+ self.details = details
34
+ #: ``X-Request-Id`` if sent, otherwise the platform's request id (``x-vercel-id``).
35
+ self.request_id = request_id
36
+ self.headers = headers
37
+ self.rate_limit = rate_limit
38
+ self.body = body
39
+
40
+ def __str__(self) -> str:
41
+ prefix = f"{self.status} {self.code}" if self.status else self.code
42
+ return f"{prefix}: {self.message}"
43
+
44
+ def __repr__(self) -> str:
45
+ return f"{type(self).__name__}(status={self.status!r}, code={self.code!r}, message={self.message!r})"
46
+
47
+
48
+ class AuthenticationError(DisruptError):
49
+ """401: ``missing_api_key`` or ``invalid_api_key``."""
50
+
51
+
52
+ class PermissionDeniedError(DisruptError):
53
+ """403: e.g. ``plan_required``."""
54
+
55
+
56
+ class NotFoundError(DisruptError):
57
+ """404: ``not_found``, or an unknown path."""
58
+
59
+
60
+ class ConflictError(DisruptError):
61
+ """409. Not returned by the v1 API today; reserved."""
62
+
63
+
64
+ class ValidationError(DisruptError):
65
+ """400 or 422: ``invalid_request``, ``limit_too_large``, ``invalid_items``, ``invalid_webhook``, ..."""
66
+
67
+
68
+ class GoneError(DisruptError):
69
+ """410: a change-feed cursor older than the 30 days kept (code ``cursor_expired``; start again
70
+ from ``changes.list()`` with no cursor), or an operation past its sunset date (code ``gone``)."""
71
+
72
+
73
+ class PayloadTooLargeError(DisruptError):
74
+ """413: ``payload_too_large`` (body over 2 MB)."""
75
+
76
+
77
+ class RateLimitError(DisruptError):
78
+ """429: ``rate_limited``, ``quota_exceeded`` or ``daily_data_limit``."""
79
+
80
+ @property
81
+ def retry_after(self) -> Optional[float]:
82
+ return self.rate_limit.retry_after if self.rate_limit else None
83
+
84
+ @property
85
+ def limit_reason(self) -> Optional[str]:
86
+ return self.rate_limit.limit_reason if self.rate_limit else None
87
+
88
+
89
+ class InternalServerError(DisruptError):
90
+ """5xx."""
91
+
92
+
93
+ class APIConnectionError(DisruptError):
94
+ """No response: DNS, connection or TLS failure."""
95
+
96
+
97
+ class APITimeoutError(APIConnectionError):
98
+ """No response within the timeout."""
99
+
100
+
101
+ class WebhookSignatureError(DisruptError):
102
+ """A webhook signature did not verify, or the payload was not valid JSON."""
103
+
104
+
105
+ def error_class_for(status: int) -> Type[DisruptError]:
106
+ if status in (400, 422):
107
+ return ValidationError
108
+ if status == 401:
109
+ return AuthenticationError
110
+ if status == 403:
111
+ return PermissionDeniedError
112
+ if status == 404:
113
+ return NotFoundError
114
+ if status == 409:
115
+ return ConflictError
116
+ if status == 410:
117
+ return GoneError
118
+ if status == 413:
119
+ return PayloadTooLargeError
120
+ if status == 429:
121
+ return RateLimitError
122
+ if status >= 500:
123
+ return InternalServerError
124
+ return DisruptError
125
+
126
+
127
+ def _snake(s: str) -> str:
128
+ return re.sub(r"[^a-z0-9]+", "_", s.strip().lower()).strip("_")
129
+
130
+
131
+ def make_api_error(response: httpx.Response, body: Any, rate_limit: RateLimitInfo,
132
+ request_id: Optional[str]) -> DisruptError:
133
+ """Typed error from an error response: the ``{"error": ...}`` envelope, or the
134
+ framework's ``{"detail": "Not Found"}`` for unknown paths and methods."""
135
+ status = response.status_code
136
+ code = f"http_{status}"
137
+ message = response.reason_phrase or f"HTTP {status}"
138
+ details = None
139
+ if isinstance(body, dict):
140
+ err = body.get("error")
141
+ if isinstance(err, dict):
142
+ code = str(err.get("code") or code)
143
+ message = str(err.get("message") or message)
144
+ details = err.get("details")
145
+ elif isinstance(body.get("detail"), str):
146
+ code = _snake(body["detail"]) or code
147
+ message = body["detail"]
148
+ elif isinstance(body.get("detail"), list):
149
+ code, message, details = "invalid_request", "request did not validate", body["detail"]
150
+ elif not body and response.text:
151
+ message = response.text[:200]
152
+ cls = error_class_for(status)
153
+ return cls(message, status=status, code=code, details=details, request_id=request_id,
154
+ headers=response.headers, rate_limit=rate_limit, body=body)