tracefast 0.1.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.
- tracefast/__init__.py +57 -0
- tracefast/_client.py +268 -0
- tracefast/_errors.py +160 -0
- tracefast/_generated/__init__.py +6 -0
- tracefast/_generated/api.py +16460 -0
- tracefast/_generated/types.py +11486 -0
- tracefast/_http.py +524 -0
- tracefast/_version.py +3 -0
- tracefast/py.typed +0 -0
- tracefast/types.py +8 -0
- tracefast-0.1.0.dist-info/METADATA +508 -0
- tracefast-0.1.0.dist-info/RECORD +14 -0
- tracefast-0.1.0.dist-info/WHEEL +4 -0
- tracefast-0.1.0.dist-info/licenses/LICENSE +21 -0
tracefast/__init__.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""The official Python SDK for the TraceFast API.
|
|
2
|
+
|
|
3
|
+
Ethereum blocks, transactions, traces, tokens, contracts, DEX pools, the
|
|
4
|
+
consensus layer, and what TraceFast states about an address. Every method
|
|
5
|
+
returns the whole `{data, meta}` envelope as a dict typed by the TypedDicts in
|
|
6
|
+
`tracefast.types`.
|
|
7
|
+
|
|
8
|
+
Example:
|
|
9
|
+
```python
|
|
10
|
+
import os
|
|
11
|
+
from tracefast import TraceFast
|
|
12
|
+
|
|
13
|
+
with TraceFast(api_key=os.environ["TRACEFAST_API_KEY"]) as tf:
|
|
14
|
+
latest = tf.blocks.latest()
|
|
15
|
+
print(latest["data"]["number"])
|
|
16
|
+
```
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from . import types as types
|
|
20
|
+
from ._client import AsyncTraceFast, TraceFast
|
|
21
|
+
from ._errors import (
|
|
22
|
+
APIConnectionError,
|
|
23
|
+
APITimeoutError,
|
|
24
|
+
AuthenticationError,
|
|
25
|
+
BadRequestError,
|
|
26
|
+
InternalServerError,
|
|
27
|
+
NotFoundError,
|
|
28
|
+
PermissionDeniedError,
|
|
29
|
+
RateLimitError,
|
|
30
|
+
TraceFastError,
|
|
31
|
+
UnexpectedResponseError,
|
|
32
|
+
UnprocessableEntityError,
|
|
33
|
+
)
|
|
34
|
+
from ._generated import CATALOGUE_VERSION
|
|
35
|
+
from ._version import VERSION
|
|
36
|
+
|
|
37
|
+
__version__ = VERSION
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"CATALOGUE_VERSION",
|
|
41
|
+
"VERSION",
|
|
42
|
+
"APIConnectionError",
|
|
43
|
+
"APITimeoutError",
|
|
44
|
+
"AsyncTraceFast",
|
|
45
|
+
"AuthenticationError",
|
|
46
|
+
"BadRequestError",
|
|
47
|
+
"InternalServerError",
|
|
48
|
+
"NotFoundError",
|
|
49
|
+
"PermissionDeniedError",
|
|
50
|
+
"RateLimitError",
|
|
51
|
+
"TraceFast",
|
|
52
|
+
"TraceFastError",
|
|
53
|
+
"UnexpectedResponseError",
|
|
54
|
+
"UnprocessableEntityError",
|
|
55
|
+
"__version__",
|
|
56
|
+
"types",
|
|
57
|
+
]
|
tracefast/_client.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
"""The two clients: `TraceFast` (sync) and `AsyncTraceFast` (async)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from types import TracebackType
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from ._generated.api import AsyncClientBase, ClientBase
|
|
10
|
+
from ._http import (
|
|
11
|
+
DEFAULT_BASE_URL,
|
|
12
|
+
DEFAULT_MAX_RETRIES,
|
|
13
|
+
DEFAULT_MAX_RETRY_WAIT,
|
|
14
|
+
DEFAULT_TIMEOUT,
|
|
15
|
+
AsyncHttp,
|
|
16
|
+
Settings,
|
|
17
|
+
SyncHttp,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class TraceFast(ClientBase):
|
|
22
|
+
"""The TraceFast API client.
|
|
23
|
+
|
|
24
|
+
Example:
|
|
25
|
+
```python
|
|
26
|
+
import os
|
|
27
|
+
from tracefast import TraceFast
|
|
28
|
+
|
|
29
|
+
with TraceFast(api_key=os.environ["TRACEFAST_API_KEY"]) as tf:
|
|
30
|
+
res = tf.contracts.proxy("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48")
|
|
31
|
+
print(res["data"], res["meta"])
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
api_key: Your TraceFast API key (`tf_live_…`). Server-side only. It is
|
|
36
|
+
sent in the `x-api-key` header and nowhere else. It must be made of
|
|
37
|
+
visible ASCII characters; anything else raises `ValueError`.
|
|
38
|
+
base_url: Default `https://tracefast.xyz/api/v1`. Must be `https`
|
|
39
|
+
(plain `http` only for a loopback host).
|
|
40
|
+
chain_id: Default `1`, Ethereum mainnet — the only chain served today.
|
|
41
|
+
timeout: Seconds allowed for each phase of an attempt — connecting,
|
|
42
|
+
sending, waiting for and reading the answer. Default 30.
|
|
43
|
+
max_retries: Retries of answers that say "try again" (`429` with a short
|
|
44
|
+
`Retry-After`, `503`, a connection failure). Default 2; `0` turns
|
|
45
|
+
retries off.
|
|
46
|
+
max_retry_wait: The longest `Retry-After` the client waits out, in
|
|
47
|
+
seconds. A `429` asking for longer is raised at once. Default 60.
|
|
48
|
+
user_agent: Appended to the `User-Agent` header, e.g. `my-app/1.2`.
|
|
49
|
+
http_client: An httpx client to send the requests with (proxies,
|
|
50
|
+
transports). Redirects are still never followed. The SDK does not
|
|
51
|
+
close a client it was given.
|
|
52
|
+
|
|
53
|
+
Raises:
|
|
54
|
+
ValueError: The key, `base_url` or a number is not valid. The message
|
|
55
|
+
never repeats the key.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
_owns_client: bool
|
|
59
|
+
|
|
60
|
+
def __init__(
|
|
61
|
+
self,
|
|
62
|
+
api_key: str,
|
|
63
|
+
*,
|
|
64
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
65
|
+
chain_id: int = 1,
|
|
66
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
67
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
68
|
+
max_retry_wait: float = DEFAULT_MAX_RETRY_WAIT,
|
|
69
|
+
user_agent: str | None = None,
|
|
70
|
+
http_client: httpx.Client | None = None,
|
|
71
|
+
) -> None:
|
|
72
|
+
# Check everything before a connection pool exists.
|
|
73
|
+
settings = Settings(
|
|
74
|
+
api_key=api_key,
|
|
75
|
+
base_url=base_url,
|
|
76
|
+
chain_id=chain_id,
|
|
77
|
+
timeout=timeout,
|
|
78
|
+
max_retries=max_retries,
|
|
79
|
+
max_retry_wait=max_retry_wait,
|
|
80
|
+
user_agent=user_agent,
|
|
81
|
+
)
|
|
82
|
+
if http_client is not None and not isinstance(http_client, httpx.Client):
|
|
83
|
+
raise TypeError("TraceFast: http_client must be an httpx.Client")
|
|
84
|
+
self._owns_client = http_client is None
|
|
85
|
+
super().__init__(SyncHttp(settings, http_client if http_client is not None else httpx.Client()))
|
|
86
|
+
|
|
87
|
+
def with_options(
|
|
88
|
+
self,
|
|
89
|
+
*,
|
|
90
|
+
api_key: str | None = None,
|
|
91
|
+
base_url: str | None = None,
|
|
92
|
+
chain_id: int | None = None,
|
|
93
|
+
timeout: float | None = None,
|
|
94
|
+
max_retries: int | None = None,
|
|
95
|
+
max_retry_wait: float | None = None,
|
|
96
|
+
user_agent: str | None = None,
|
|
97
|
+
) -> TraceFast:
|
|
98
|
+
"""A copy of this client with some options changed.
|
|
99
|
+
|
|
100
|
+
The copy shares this client's connections: it is cheap to make for one
|
|
101
|
+
call or one part of a program. Closing the copy does nothing; closing
|
|
102
|
+
this client closes the connections of both. An option left as None
|
|
103
|
+
keeps its value.
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
The new client.
|
|
107
|
+
|
|
108
|
+
Raises:
|
|
109
|
+
ValueError: A changed option is not valid.
|
|
110
|
+
"""
|
|
111
|
+
settings = self._http.settings.replace(
|
|
112
|
+
api_key=api_key,
|
|
113
|
+
base_url=base_url,
|
|
114
|
+
chain_id=chain_id,
|
|
115
|
+
timeout=timeout,
|
|
116
|
+
max_retries=max_retries,
|
|
117
|
+
max_retry_wait=max_retry_wait,
|
|
118
|
+
user_agent=user_agent,
|
|
119
|
+
)
|
|
120
|
+
copy = object.__new__(type(self))
|
|
121
|
+
ClientBase.__init__(copy, SyncHttp(settings, self._http.client, self._http.sleep))
|
|
122
|
+
copy._owns_client = False
|
|
123
|
+
return copy
|
|
124
|
+
|
|
125
|
+
def close(self) -> None:
|
|
126
|
+
"""Close the connections, unless the `httpx.Client` was given or this is a copy."""
|
|
127
|
+
if self._owns_client:
|
|
128
|
+
self._http.client.close()
|
|
129
|
+
|
|
130
|
+
def __enter__(self) -> TraceFast:
|
|
131
|
+
return self
|
|
132
|
+
|
|
133
|
+
def __exit__(
|
|
134
|
+
self,
|
|
135
|
+
exc_type: type[BaseException] | None,
|
|
136
|
+
exc: BaseException | None,
|
|
137
|
+
tb: TracebackType | None,
|
|
138
|
+
) -> None:
|
|
139
|
+
self.close()
|
|
140
|
+
|
|
141
|
+
def __repr__(self) -> str:
|
|
142
|
+
return f"TraceFast(base_url={self._http.base_url!r}, chain_id={self._http.chain_id!r})"
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class AsyncTraceFast(AsyncClientBase):
|
|
146
|
+
"""The TraceFast API client for `asyncio`.
|
|
147
|
+
|
|
148
|
+
The same namespaces and methods as `TraceFast`; every method is a coroutine
|
|
149
|
+
and every `…_pages` and `…_items` method an async iterator. Cancelling the
|
|
150
|
+
task cancels the call: `asyncio.CancelledError` is never caught.
|
|
151
|
+
|
|
152
|
+
Example:
|
|
153
|
+
```python
|
|
154
|
+
import os
|
|
155
|
+
from tracefast import AsyncTraceFast
|
|
156
|
+
|
|
157
|
+
async with AsyncTraceFast(api_key=os.environ["TRACEFAST_API_KEY"]) as tf:
|
|
158
|
+
res = await tf.blocks.latest()
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
api_key: Your TraceFast API key (`tf_live_…`). Server-side only. It is
|
|
163
|
+
sent in the `x-api-key` header and nowhere else. It must be made of
|
|
164
|
+
visible ASCII characters; anything else raises `ValueError`.
|
|
165
|
+
base_url: Default `https://tracefast.xyz/api/v1`. Must be `https`
|
|
166
|
+
(plain `http` only for a loopback host).
|
|
167
|
+
chain_id: Default `1`, Ethereum mainnet — the only chain served today.
|
|
168
|
+
timeout: Seconds allowed for each phase of an attempt — connecting,
|
|
169
|
+
sending, waiting for and reading the answer. Default 30.
|
|
170
|
+
max_retries: Retries of answers that say "try again" (`429` with a short
|
|
171
|
+
`Retry-After`, `503`, a connection failure). Default 2; `0` turns
|
|
172
|
+
retries off.
|
|
173
|
+
max_retry_wait: The longest `Retry-After` the client waits out, in
|
|
174
|
+
seconds. A `429` asking for longer is raised at once. Default 60.
|
|
175
|
+
user_agent: Appended to the `User-Agent` header, e.g. `my-app/1.2`.
|
|
176
|
+
http_client: An httpx client to send the requests with (proxies,
|
|
177
|
+
transports). Redirects are still never followed. The SDK does not
|
|
178
|
+
close a client it was given.
|
|
179
|
+
|
|
180
|
+
Raises:
|
|
181
|
+
ValueError: The key, `base_url` or a number is not valid. The message
|
|
182
|
+
never repeats the key.
|
|
183
|
+
"""
|
|
184
|
+
|
|
185
|
+
_owns_client: bool
|
|
186
|
+
|
|
187
|
+
def __init__(
|
|
188
|
+
self,
|
|
189
|
+
api_key: str,
|
|
190
|
+
*,
|
|
191
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
192
|
+
chain_id: int = 1,
|
|
193
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
194
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
195
|
+
max_retry_wait: float = DEFAULT_MAX_RETRY_WAIT,
|
|
196
|
+
user_agent: str | None = None,
|
|
197
|
+
http_client: httpx.AsyncClient | None = None,
|
|
198
|
+
) -> None:
|
|
199
|
+
settings = Settings(
|
|
200
|
+
api_key=api_key,
|
|
201
|
+
base_url=base_url,
|
|
202
|
+
chain_id=chain_id,
|
|
203
|
+
timeout=timeout,
|
|
204
|
+
max_retries=max_retries,
|
|
205
|
+
max_retry_wait=max_retry_wait,
|
|
206
|
+
user_agent=user_agent,
|
|
207
|
+
)
|
|
208
|
+
if http_client is not None and not isinstance(http_client, httpx.AsyncClient):
|
|
209
|
+
raise TypeError("AsyncTraceFast: http_client must be an httpx.AsyncClient")
|
|
210
|
+
self._owns_client = http_client is None
|
|
211
|
+
super().__init__(AsyncHttp(settings, http_client if http_client is not None else httpx.AsyncClient()))
|
|
212
|
+
|
|
213
|
+
def with_options(
|
|
214
|
+
self,
|
|
215
|
+
*,
|
|
216
|
+
api_key: str | None = None,
|
|
217
|
+
base_url: str | None = None,
|
|
218
|
+
chain_id: int | None = None,
|
|
219
|
+
timeout: float | None = None,
|
|
220
|
+
max_retries: int | None = None,
|
|
221
|
+
max_retry_wait: float | None = None,
|
|
222
|
+
user_agent: str | None = None,
|
|
223
|
+
) -> AsyncTraceFast:
|
|
224
|
+
"""A copy of this client with some options changed.
|
|
225
|
+
|
|
226
|
+
The copy shares this client's connections: it is cheap to make for one
|
|
227
|
+
call or one part of a program. Closing the copy does nothing; closing
|
|
228
|
+
this client closes the connections of both. An option left as None
|
|
229
|
+
keeps its value.
|
|
230
|
+
|
|
231
|
+
Returns:
|
|
232
|
+
The new client.
|
|
233
|
+
|
|
234
|
+
Raises:
|
|
235
|
+
ValueError: A changed option is not valid.
|
|
236
|
+
"""
|
|
237
|
+
settings = self._http.settings.replace(
|
|
238
|
+
api_key=api_key,
|
|
239
|
+
base_url=base_url,
|
|
240
|
+
chain_id=chain_id,
|
|
241
|
+
timeout=timeout,
|
|
242
|
+
max_retries=max_retries,
|
|
243
|
+
max_retry_wait=max_retry_wait,
|
|
244
|
+
user_agent=user_agent,
|
|
245
|
+
)
|
|
246
|
+
copy = object.__new__(type(self))
|
|
247
|
+
AsyncClientBase.__init__(copy, AsyncHttp(settings, self._http.client, self._http.sleep))
|
|
248
|
+
copy._owns_client = False
|
|
249
|
+
return copy
|
|
250
|
+
|
|
251
|
+
async def close(self) -> None:
|
|
252
|
+
"""Close the connections, unless the `httpx.AsyncClient` was given or this is a copy."""
|
|
253
|
+
if self._owns_client:
|
|
254
|
+
await self._http.client.aclose()
|
|
255
|
+
|
|
256
|
+
async def __aenter__(self) -> AsyncTraceFast:
|
|
257
|
+
return self
|
|
258
|
+
|
|
259
|
+
async def __aexit__(
|
|
260
|
+
self,
|
|
261
|
+
exc_type: type[BaseException] | None,
|
|
262
|
+
exc: BaseException | None,
|
|
263
|
+
tb: TracebackType | None,
|
|
264
|
+
) -> None:
|
|
265
|
+
await self.close()
|
|
266
|
+
|
|
267
|
+
def __repr__(self) -> str:
|
|
268
|
+
return f"AsyncTraceFast(base_url={self._http.base_url!r}, chain_id={self._http.chain_id!r})"
|
tracefast/_errors.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""The errors of the SDK: `TraceFastError` and one subclass per kind of failure."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TraceFastError(Exception):
|
|
9
|
+
"""Every failure of a TraceFast call.
|
|
10
|
+
|
|
11
|
+
A refusal from the API, an answer that is not the API's, a network failure
|
|
12
|
+
or a timeout. Branch on `code`, `reason` and the subclass — never on
|
|
13
|
+
`message`, which is for humans and may be reworded.
|
|
14
|
+
|
|
15
|
+
Attributes:
|
|
16
|
+
status: HTTP status of the answer; `0` when no answer arrived.
|
|
17
|
+
code: The stable word to branch on: the API's error registry
|
|
18
|
+
(`bad_request`, `invalid_cursor`, `not_found`, `block_not_available`,
|
|
19
|
+
`quota_exceeded`, …), the gateway's (`auth_failed`, `forbidden`,
|
|
20
|
+
`rate_limited`, `concurrency_limited`, `service_degraded`), or the
|
|
21
|
+
SDK's own (`unexpected_response`, `connection_error`, `timeout`).
|
|
22
|
+
reason: The stable sub-code: `error.reason` on the gateway's key, plan
|
|
23
|
+
and limit refusals (`api_key_required`, `plan_scope_missing`, …),
|
|
24
|
+
otherwise `details["reason"]`.
|
|
25
|
+
bucket: On a `429`, which limit refused (`base`, `class:…`,
|
|
26
|
+
`concurrency`, `quota_daily`, `quota_method`, …).
|
|
27
|
+
details: What to act on, when the API states it (`maxAvailableBlock`,
|
|
28
|
+
`maxLimit`, `minimumPlan`, `currentPlan`, `upgrade`, …).
|
|
29
|
+
request_id: The request's id. Quote it when asking for support.
|
|
30
|
+
retry_after: Seconds from the `Retry-After` header, exactly as sent.
|
|
31
|
+
body: The raw `error` object of the answer, so a field this SDK does not
|
|
32
|
+
know survives.
|
|
33
|
+
message: `"<status> <code>: <the API's message>"`, for humans. Never
|
|
34
|
+
parse it.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
status: int
|
|
38
|
+
code: str
|
|
39
|
+
message: str
|
|
40
|
+
reason: str | None
|
|
41
|
+
bucket: str | None
|
|
42
|
+
details: dict[str, Any] | None
|
|
43
|
+
request_id: str | None
|
|
44
|
+
retry_after: float | None
|
|
45
|
+
body: dict[str, Any] | None
|
|
46
|
+
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
*,
|
|
50
|
+
status: int,
|
|
51
|
+
code: str,
|
|
52
|
+
message: str,
|
|
53
|
+
reason: str | None = None,
|
|
54
|
+
bucket: str | None = None,
|
|
55
|
+
details: dict[str, Any] | None = None,
|
|
56
|
+
request_id: str | None = None,
|
|
57
|
+
retry_after: float | None = None,
|
|
58
|
+
body: dict[str, Any] | None = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
text = f"{status} {code}: {message}" if status else f"{code}: {message}"
|
|
61
|
+
super().__init__(text)
|
|
62
|
+
self.status = status
|
|
63
|
+
self.code = code
|
|
64
|
+
self.message = text
|
|
65
|
+
self.reason = reason
|
|
66
|
+
self.bucket = bucket
|
|
67
|
+
self.details = details
|
|
68
|
+
self.request_id = request_id
|
|
69
|
+
self.retry_after = retry_after
|
|
70
|
+
self.body = body
|
|
71
|
+
|
|
72
|
+
def __str__(self) -> str:
|
|
73
|
+
return self.message + (f" (request {self.request_id})" if self.request_id else "")
|
|
74
|
+
|
|
75
|
+
def __repr__(self) -> str:
|
|
76
|
+
return (
|
|
77
|
+
f"{type(self).__name__}(status={self.status!r}, code={self.code!r}, "
|
|
78
|
+
f"reason={self.reason!r}, request_id={self.request_id!r})"
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
def __reduce__(self) -> tuple[Any, ...]:
|
|
82
|
+
# Keyword-only __init__: rebuild from the fields, so the error pickles.
|
|
83
|
+
return (_rebuild, (type(self), self.__dict__.copy()))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _rebuild(cls: type[TraceFastError], state: dict[str, Any]) -> TraceFastError:
|
|
87
|
+
e = cls.__new__(cls)
|
|
88
|
+
Exception.__init__(e, state.get("message", ""))
|
|
89
|
+
e.__dict__.update(state)
|
|
90
|
+
return e
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class BadRequestError(TraceFastError):
|
|
94
|
+
"""`400`: the request is outside the contract; `reason` says which rule."""
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class AuthenticationError(TraceFastError):
|
|
98
|
+
"""`401`: no key, or a key that is not valid."""
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class PermissionDeniedError(TraceFastError):
|
|
102
|
+
"""`403`: the plan does not include the method (`plan_scope_missing`), or the key may not be used."""
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class NotFoundError(TraceFastError):
|
|
106
|
+
"""`404`: nothing at the key the path names, or no such method."""
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class UnprocessableEntityError(TraceFastError):
|
|
110
|
+
"""`422`: well-formed, but the data cannot answer it (`block_not_available`, `coverage_gap`, …)."""
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class RateLimitError(TraceFastError):
|
|
114
|
+
"""`429`: a rate limit, a concurrency cap or a quota; `bucket` says which."""
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class InternalServerError(TraceFastError):
|
|
118
|
+
"""`5xx`: a failure on the API's side."""
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class APIConnectionError(TraceFastError):
|
|
122
|
+
"""`connection_error`: the connection failed or broke before the whole answer arrived."""
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class APITimeoutError(TraceFastError):
|
|
126
|
+
"""`timeout`: no answer within the timeout."""
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class UnexpectedResponseError(TraceFastError):
|
|
130
|
+
"""`unexpected_response`: an answer that is not the API's (a redirect, a proxy page, not JSON)."""
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
_BY_STATUS: dict[int, type[TraceFastError]] = {
|
|
134
|
+
400: BadRequestError,
|
|
135
|
+
401: AuthenticationError,
|
|
136
|
+
403: PermissionDeniedError,
|
|
137
|
+
404: NotFoundError,
|
|
138
|
+
422: UnprocessableEntityError,
|
|
139
|
+
429: RateLimitError,
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def error_class_for(status: int, code: str) -> type[TraceFastError]:
|
|
144
|
+
"""The subclass for the SDK's own code, else for the answer's status."""
|
|
145
|
+
if code == "unexpected_response":
|
|
146
|
+
return UnexpectedResponseError
|
|
147
|
+
if code == "connection_error":
|
|
148
|
+
return APIConnectionError
|
|
149
|
+
if code == "timeout":
|
|
150
|
+
return APITimeoutError
|
|
151
|
+
if status in _BY_STATUS:
|
|
152
|
+
return _BY_STATUS[status]
|
|
153
|
+
if status >= 500:
|
|
154
|
+
return InternalServerError
|
|
155
|
+
return TraceFastError
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def make_error(*, status: int, code: str, message: str, **fields: Any) -> TraceFastError:
|
|
159
|
+
"""Build the error of the right subclass."""
|
|
160
|
+
return error_class_for(status, code)(status=status, code=code, message=message, **fields)
|