flashpi 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.
flashpi/_errors.py ADDED
@@ -0,0 +1,249 @@
1
+ """The errors this package raises."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import re
8
+ import time
9
+ from datetime import UTC, datetime
10
+ from email.utils import parsedate_to_datetime
11
+ from typing import Any, Literal, TypeAlias, cast
12
+
13
+ import httpx
14
+
15
+ from .types import ApiErrorCode, FieldError, Problem
16
+
17
+ WebhookVerificationReason: TypeAlias = Literal[
18
+ "missing_headers",
19
+ "invalid_timestamp",
20
+ "timestamp_out_of_range",
21
+ "no_matching_signature",
22
+ "invalid_secret",
23
+ "invalid_payload",
24
+ ]
25
+ """Why a webhook was rejected by `verify_webhook_signature()` or `unwrap_webhook()`."""
26
+
27
+
28
+ class FlashpiError(Exception):
29
+ """Every error this package raises extends this class.
30
+
31
+ Except for invalid arguments (TypeError and ValueError, as for any Python function) and the
32
+ cancellation of an async call, which raises `asyncio.CancelledError` as usual.
33
+ """
34
+
35
+ message: str
36
+ """What went wrong."""
37
+
38
+ idempotency_key: str | None
39
+ """The Idempotency-Key a failed POST used (the caller's or the one the SDK made). To try the
40
+ same operation again later without issuing twice, pass it back:
41
+ `create(body, idempotency_key=error.idempotency_key)`."""
42
+
43
+ def __init__(self, message: str) -> None:
44
+ super().__init__(message)
45
+ self.message = message
46
+ self.idempotency_key = None
47
+
48
+ def __reduce__(self) -> tuple[Any, ...]:
49
+ # Rebuilt from its state, so the errors survive pickling (Celery, multiprocessing).
50
+ return (_restore, (type(self), self.args, self.__dict__))
51
+
52
+
53
+ def _restore(cls: type[FlashpiError], args: tuple[Any, ...], state: dict[str, Any]) -> FlashpiError:
54
+ error = cls.__new__(cls)
55
+ error.args = args
56
+ error.__dict__.update(state)
57
+ return error
58
+
59
+
60
+ class APIError(FlashpiError):
61
+ """The API answered with an error status.
62
+
63
+ Branch on `code` (stable English slugs such as `validation_failed`), never on `message`, which
64
+ follows the requested language.
65
+ """
66
+
67
+ status: int
68
+ """HTTP status of the answer."""
69
+
70
+ code: ApiErrorCode | None
71
+ """Error code, or None when the answer had no Problem Details (for example a 502)."""
72
+
73
+ title: str | None
74
+ """Short summary of the problem type."""
75
+
76
+ detail: str | None
77
+ """What went wrong in this request."""
78
+
79
+ errors: list[FieldError]
80
+ """Field-level problems of a request body or query (may be empty)."""
81
+
82
+ request_id: str | None
83
+ """Flashpi's id of the request (`x-request-id`): share it with support."""
84
+
85
+ problem: Problem | None
86
+ """The full Problem Details body, with its extension members, when there was one."""
87
+
88
+ headers: httpx.Headers
89
+ """Response headers."""
90
+
91
+ def __init__(
92
+ self,
93
+ status: int,
94
+ headers: httpx.Headers,
95
+ problem: Problem | None,
96
+ body_text: str = "",
97
+ ) -> None:
98
+ super().__init__(_error_message(status, problem, body_text))
99
+ self.status = status
100
+ self.headers = headers
101
+ self.problem = problem
102
+ members: dict[str, object] = cast("dict[str, object]", problem or {})
103
+ code = members.get("code")
104
+ self.code = code if isinstance(code, str) else None
105
+ title = members.get("title")
106
+ self.title = title if isinstance(title, str) else None
107
+ detail = members.get("detail")
108
+ self.detail = detail if isinstance(detail, str) else None
109
+ errors = members.get("errors")
110
+ self.errors = cast("list[FieldError]", errors) if isinstance(errors, list) else []
111
+ request_id = members.get("requestId")
112
+ self.request_id = request_id if isinstance(request_id, str) else headers.get("x-request-id")
113
+
114
+ @property
115
+ def retry_after(self) -> int | None:
116
+ """Seconds the API asked to wait before trying again (`Retry-After`), or None.
117
+
118
+ Daily quota errors point at the next midnight in Ecuador, so this can be hours.
119
+ """
120
+ return parse_retry_after(self.headers.get("retry-after"))
121
+
122
+
123
+ class BadRequestError(APIError):
124
+ """400: the request could not be read (malformed JSON, invalid Idempotency-Key, ...)."""
125
+
126
+
127
+ class AuthenticationError(APIError):
128
+ """401: the API key is missing, malformed, unknown or revoked."""
129
+
130
+
131
+ class PermissionDeniedError(APIError):
132
+ """403: the key may not do this (read-only, another issuer, IP allowlist, suspended account)."""
133
+
134
+
135
+ class NotFoundError(APIError):
136
+ """404: the resource does not exist in this mode (test or live) for this account."""
137
+
138
+
139
+ class ConflictError(APIError):
140
+ """409: the request conflicts with the current state (sequential used, RIDE not ready, ...)."""
141
+
142
+
143
+ class UnprocessableEntityError(APIError):
144
+ """422: the request is well formed but invalid (`validation_failed`, `total_mismatch`, ...)."""
145
+
146
+
147
+ class RateLimitError(APIError):
148
+ """429: a limit was reached; see `retry_after` and the `limit` and `resetsAt` members."""
149
+
150
+
151
+ class InternalServerError(APIError):
152
+ """5xx: Flashpi failed to answer. Requests are retried automatically before this is raised."""
153
+
154
+
155
+ class APIConnectionError(FlashpiError):
156
+ """The request never got an answer (DNS, TLS, connection reset, ...)."""
157
+
158
+
159
+ class APITimeoutError(APIConnectionError):
160
+ """The request took longer than the `timeout` option."""
161
+
162
+
163
+ class WebhookVerificationError(FlashpiError):
164
+ """A webhook did not come from Flashpi, was altered, or is too old: answer 400 and ignore it."""
165
+
166
+ reason: WebhookVerificationReason
167
+ """Why it was rejected."""
168
+
169
+ def __init__(self, reason: WebhookVerificationReason, message: str) -> None:
170
+ super().__init__(message)
171
+ self.reason = reason
172
+
173
+
174
+ _ERROR_CLASSES: dict[int, type[APIError]] = {
175
+ 400: BadRequestError,
176
+ 401: AuthenticationError,
177
+ 403: PermissionDeniedError,
178
+ 404: NotFoundError,
179
+ 409: ConflictError,
180
+ 422: UnprocessableEntityError,
181
+ 429: RateLimitError,
182
+ }
183
+
184
+
185
+ def api_error(status: int, headers: httpx.Headers, body_text: str) -> APIError:
186
+ """The error subclass that matches the status of an answer."""
187
+ error_class = _ERROR_CLASSES.get(status, InternalServerError if status >= 500 else APIError)
188
+ return error_class(status, headers, _parse_problem(body_text), body_text)
189
+
190
+
191
+ def _parse_problem(body_text: str) -> Problem | None:
192
+ if not body_text:
193
+ return None
194
+ try:
195
+ parsed: object = json.loads(body_text)
196
+ except (ValueError, RecursionError):
197
+ # Not JSON: an answer from the edge (CDN or firewall), not from the API.
198
+ return None
199
+ if isinstance(parsed, dict) and isinstance(cast("dict[str, object]", parsed).get("code"), str):
200
+ return cast("Problem", parsed)
201
+ return None
202
+
203
+
204
+ def _error_message(status: int, problem: Problem | None, body_text: str) -> str:
205
+ if problem is not None:
206
+ members = cast("dict[str, object]", problem)
207
+ detail = members.get("detail")
208
+ if not isinstance(detail, str):
209
+ detail = members.get("title")
210
+ code = members.get("code")
211
+ return f"{status} {code}: {detail}" if isinstance(detail, str) else f"{status} {code}"
212
+ excerpt = " ".join(body_text.split())[:200]
213
+ return f"{status} {excerpt}" if excerpt else f"{status} (no response body)"
214
+
215
+
216
+ _DELTA_SECONDS = re.compile(r"[0-9]+")
217
+ # Longer digit strings are past any useful wait (and past int()'s digit limit).
218
+ _MAX_DELTA_DIGITS = 18
219
+
220
+
221
+ def parse_retry_after(value: str | None, now: float | None = None) -> int | None:
222
+ """Seconds from a `Retry-After` value (delta-seconds or an HTTP date), or None.
223
+
224
+ `now` is the current Unix time in seconds (default: the clock).
225
+ """
226
+ if value is None:
227
+ return None
228
+ trimmed = value.strip()
229
+ if _DELTA_SECONDS.fullmatch(trimmed):
230
+ return int(trimmed) if len(trimmed) <= _MAX_DELTA_DIGITS else 10**_MAX_DELTA_DIGITS
231
+ moment = _parse_date(trimmed)
232
+ if moment is None:
233
+ return None
234
+ current = time.time() if now is None else now
235
+ return max(0, math.ceil(moment - current))
236
+
237
+
238
+ def _parse_date(value: str) -> float | None:
239
+ """Unix seconds of an HTTP date (or an ISO 8601 one), or None."""
240
+ try:
241
+ parsed = parsedate_to_datetime(value)
242
+ except (TypeError, ValueError, IndexError, OverflowError):
243
+ try:
244
+ parsed = datetime.fromisoformat(value)
245
+ except ValueError:
246
+ return None
247
+ if parsed.tzinfo is None:
248
+ parsed = parsed.replace(tzinfo=UTC)
249
+ return parsed.timestamp()