noderings 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.
noderings/_errors.py ADDED
@@ -0,0 +1,203 @@
1
+ """Errors raised by the SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from enum import IntEnum
7
+ from typing import Any
8
+
9
+ import httpx
10
+
11
+ __all__ = [
12
+ "APIConnectionError",
13
+ "APIError",
14
+ "APITimeoutError",
15
+ "AuthenticationError",
16
+ "BadRequestError",
17
+ "Code",
18
+ "ConflictError",
19
+ "InternalServerError",
20
+ "NodeRingsError",
21
+ "NotFoundError",
22
+ "PermissionDeniedError",
23
+ "QuotaExceededError",
24
+ "RateLimitError",
25
+ ]
26
+
27
+
28
+ class Code(IntEnum):
29
+ """A gRPC status code, as the API puts it in error bodies."""
30
+
31
+ OK = 0
32
+ CANCELED = 1
33
+ UNKNOWN = 2
34
+ INVALID_ARGUMENT = 3
35
+ DEADLINE_EXCEEDED = 4
36
+ NOT_FOUND = 5
37
+ ALREADY_EXISTS = 6
38
+ PERMISSION_DENIED = 7
39
+ RESOURCE_EXHAUSTED = 8
40
+ FAILED_PRECONDITION = 9
41
+ ABORTED = 10
42
+ OUT_OF_RANGE = 11
43
+ UNIMPLEMENTED = 12
44
+ INTERNAL = 13
45
+ UNAVAILABLE = 14
46
+ DATA_LOSS = 15
47
+ UNAUTHENTICATED = 16
48
+
49
+
50
+ _CODE_FROM_HTTP = {
51
+ 400: Code.INVALID_ARGUMENT,
52
+ 401: Code.UNAUTHENTICATED,
53
+ 403: Code.PERMISSION_DENIED,
54
+ 404: Code.NOT_FOUND,
55
+ 409: Code.ALREADY_EXISTS,
56
+ 429: Code.RESOURCE_EXHAUSTED,
57
+ 501: Code.UNIMPLEMENTED,
58
+ 503: Code.UNAVAILABLE,
59
+ 504: Code.DEADLINE_EXCEEDED,
60
+ }
61
+
62
+
63
+ class NodeRingsError(Exception):
64
+ """Base class of every error the SDK raises."""
65
+
66
+
67
+ class APIConnectionError(NodeRingsError):
68
+ """The API could not be reached: DNS, connection or TLS failure."""
69
+
70
+
71
+ class APITimeoutError(APIConnectionError):
72
+ """The request timed out."""
73
+
74
+
75
+ class APIError(NodeRingsError):
76
+ """The API answered with an error.
77
+
78
+ Attributes:
79
+ status_code: The HTTP status code.
80
+ code: The API's gRPC status code (:class:`Code`).
81
+ message: The API's message, meant for people.
82
+ details: The structured details, for example a ``google.rpc.ErrorInfo``
83
+ with a reason such as ``VM_LIMIT_REACHED``.
84
+ method, path: The request.
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ status_code: int,
90
+ code: Code,
91
+ message: str,
92
+ details: list[dict[str, Any]],
93
+ method: str,
94
+ path: str,
95
+ headers: httpx.Headers | None = None,
96
+ ) -> None:
97
+ self.status_code = status_code
98
+ self.code = code
99
+ self.message = message
100
+ self.details = details
101
+ self.method = method
102
+ self.path = path
103
+ self.headers = headers or httpx.Headers()
104
+ super().__init__(str(self))
105
+
106
+ def __str__(self) -> str:
107
+ msg = self.message.strip() or httpx.codes.get_reason_phrase(self.status_code)
108
+ return f"{self.method} {self.path}: {msg} (HTTP {self.status_code})"
109
+
110
+ @property
111
+ def reason(self) -> str:
112
+ """The reason of the first ``google.rpc.ErrorInfo`` detail, or ``""``."""
113
+ for d in self.details:
114
+ if str(d.get("@type", "")).endswith("google.rpc.ErrorInfo") and d.get("reason"):
115
+ return str(d["reason"])
116
+ return ""
117
+
118
+ @property
119
+ def is_quota_exceeded(self) -> bool:
120
+ """A plan quota, such as the number of virtual machines, is used up."""
121
+ return self.reason.endswith("LIMIT_REACHED")
122
+
123
+ @property
124
+ def is_busy(self) -> bool:
125
+ """Another operation on the resource is still running. The call succeeds when retried later."""
126
+ return self.code == Code.FAILED_PRECONDITION and "in progress" in self.message.lower()
127
+
128
+
129
+ class BadRequestError(APIError):
130
+ """HTTP 400: the request was rejected as invalid."""
131
+
132
+
133
+ class AuthenticationError(APIError):
134
+ """HTTP 401: the token is missing or was rejected."""
135
+
136
+
137
+ class PermissionDeniedError(APIError):
138
+ """HTTP 403: the token lacks a permission."""
139
+
140
+
141
+ class NotFoundError(APIError):
142
+ """HTTP 404: the resource does not exist."""
143
+
144
+
145
+ class ConflictError(APIError):
146
+ """HTTP 409: the resource already exists, or the change conflicts with its state."""
147
+
148
+
149
+ class RateLimitError(APIError):
150
+ """HTTP 429: the API asked to slow down. The SDK has already retried."""
151
+
152
+
153
+ class QuotaExceededError(APIError):
154
+ """HTTP 429 with a reason ending in ``LIMIT_REACHED``: a plan quota is used up. Not retried."""
155
+
156
+
157
+ class InternalServerError(APIError):
158
+ """HTTP 500 or above."""
159
+
160
+
161
+ def error_from_response(resp: httpx.Response, method: str, path: str) -> APIError:
162
+ code: Code | None = None
163
+ message = ""
164
+ details: list[dict[str, Any]] = []
165
+ try:
166
+ raw = json.loads(resp.content)
167
+ except ValueError:
168
+ raw = None
169
+ if isinstance(raw, dict):
170
+ try:
171
+ code = Code(int(raw.get("code") or 0)) or None
172
+ except ValueError:
173
+ code = Code.UNKNOWN
174
+ message = str(raw.get("message") or "")
175
+ details = [d for d in raw.get("details") or [] if isinstance(d, dict)]
176
+ else:
177
+ message = resp.text.strip()
178
+ if len(message) > 300:
179
+ message = message[:300] + "..."
180
+ if not code:
181
+ code = _CODE_FROM_HTTP.get(resp.status_code, Code.UNKNOWN)
182
+ status = resp.status_code
183
+ cls: type[APIError]
184
+ if status == 400:
185
+ cls = BadRequestError
186
+ elif status == 401:
187
+ cls = AuthenticationError
188
+ elif status == 403:
189
+ cls = PermissionDeniedError
190
+ elif status == 404:
191
+ cls = NotFoundError
192
+ elif status == 409:
193
+ cls = ConflictError
194
+ elif status == 429:
195
+ cls = RateLimitError
196
+ elif status >= 500:
197
+ cls = InternalServerError
198
+ else:
199
+ cls = APIError
200
+ err = cls(status, code, message, details, method, path, resp.headers)
201
+ if status == 429 and err.is_quota_exceeded:
202
+ err = QuotaExceededError(status, code, message, details, method, path, resp.headers)
203
+ return err