cleanedweb 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.
@@ -0,0 +1,275 @@
1
+ """Exceptions raised by the CleanedWeb clients.
2
+
3
+ Every error derives from :class:`CleanedWebError`. Errors that come from an HTTP answer derive
4
+ from :class:`APIStatusError` and carry the status, the documented ``code`` and the parsed body.
5
+
6
+ Deciding what to do after an error that belongs to a run:
7
+
8
+ * ``err.run_failed`` is ``True``: the run failed and the failure is final for that idempotency
9
+ key (the same answer is replayed for 7 days). Use a **new** key to run again.
10
+ * A connection error, a timeout or a gateway error without that marker proves nothing: the run may
11
+ have started. Keep the idempotency key and read the result with it (``client.catalog.result``)
12
+ before you decide.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import Any, Dict, List, Optional
18
+
19
+ __all__ = [
20
+ "APIConnectionError",
21
+ "APIStatusError",
22
+ "AuthenticationError",
23
+ "CleanedWebError",
24
+ "IdempotencyConflictError",
25
+ "InsufficientCreditError",
26
+ "InvalidRequestError",
27
+ "MissingAPIKeyError",
28
+ "NotFoundError",
29
+ "PermissionDeniedError",
30
+ "RateLimitError",
31
+ "RunFailedError",
32
+ "ServerError",
33
+ "UsageBudgetExceededError",
34
+ "VersionConflictError",
35
+ "VersionNotFoundError",
36
+ "error_from_response",
37
+ ]
38
+
39
+ _RUN_FAILED_MARKERS = ("run_failed", "failed_run_replayed")
40
+
41
+
42
+ class CleanedWebError(Exception):
43
+ """Base class of every error raised by this package."""
44
+
45
+
46
+ class MissingAPIKeyError(CleanedWebError):
47
+ """A call that needs a key was made without one: pass ``api_key=`` or set
48
+ ``CLEANEDWEB_API_KEY``. Catalog reads (``list``, ``get``, ``find``) need no key."""
49
+
50
+
51
+ class APIConnectionError(CleanedWebError):
52
+ """The request did not get an answer (timeout, lost connection, DNS, TLS).
53
+
54
+ The outcome is unknown: for a run, it may have started. ``idempotency_key`` is set when the
55
+ request carried one; reuse it to recover (see ``client.catalog.result``).
56
+ """
57
+
58
+ def __init__(self, message: str, *, idempotency_key: Optional[str] = None) -> None:
59
+ super().__init__(message)
60
+ self.idempotency_key = idempotency_key
61
+
62
+
63
+ class APIStatusError(CleanedWebError):
64
+ """The API answered with an error status."""
65
+
66
+ def __init__(
67
+ self,
68
+ message: str,
69
+ *,
70
+ status_code: int,
71
+ code: Optional[str] = None,
72
+ body: Any = None,
73
+ detail: Any = None,
74
+ headers: Optional[Dict[str, str]] = None,
75
+ retry_after: Optional[float] = None,
76
+ idempotency_key: Optional[str] = None,
77
+ ) -> None:
78
+ super().__init__(message)
79
+ self.message = message
80
+ self.status_code = status_code
81
+ self.code = code
82
+ self.body = body
83
+ self.detail = detail
84
+ self.headers = headers or {}
85
+ self.retry_after = retry_after
86
+ self.idempotency_key = idempotency_key
87
+
88
+ def __str__(self) -> str:
89
+ parts = [f"HTTP {self.status_code}"]
90
+ if self.code:
91
+ parts.append(self.code)
92
+ text = f"{' '.join(parts)}: {self.message}" if self.message else " ".join(parts)
93
+ if self.run_id:
94
+ text += f" (run {self.run_id})"
95
+ return text
96
+
97
+ @property
98
+ def detail_dict(self) -> Dict[str, Any]:
99
+ return self.detail if isinstance(self.detail, dict) else {}
100
+
101
+ @property
102
+ def run_id(self) -> Optional[str]:
103
+ """The failed run, when the error is a failed run's."""
104
+ value = self.detail_dict.get("run_id")
105
+ return value if isinstance(value, str) else None
106
+
107
+ @property
108
+ def error_code(self) -> Optional[str]:
109
+ """``run_failed`` or ``failed_run_replayed`` when the error marks a failed run."""
110
+ value = self.detail_dict.get("error_code")
111
+ return value if value in _RUN_FAILED_MARKERS else None
112
+
113
+ @property
114
+ def run_failed(self) -> bool:
115
+ """True when the run failed: final for the idempotency key, use a new key to run again."""
116
+ return self.error_code is not None
117
+
118
+ @property
119
+ def replayed(self) -> bool:
120
+ return bool(self.detail_dict.get("replayed"))
121
+
122
+ @property
123
+ def unsure(self) -> bool:
124
+ """True when the error does not show whether the run failed (gateway error, timeout)."""
125
+ return not self.run_failed and (self.status_code >= 500 or self.status_code == 408)
126
+
127
+
128
+ class AuthenticationError(APIStatusError):
129
+ """401: no credential, or a key that is invalid, expired or revoked."""
130
+
131
+
132
+ class PermissionDeniedError(APIStatusError):
133
+ """403: the key lacks the scope or the access, or is not tied to a workspace account."""
134
+
135
+
136
+ class NotFoundError(APIStatusError):
137
+ """404: API, endpoint, run or delivery not found (or not accessible)."""
138
+
139
+
140
+ class VersionNotFoundError(NotFoundError):
141
+ """404 ``catalog_version_not_found``: the pinned major never existed. See ``available``."""
142
+
143
+ @property
144
+ def available(self) -> List[int]:
145
+ value = self.detail_dict.get("available")
146
+ return [v for v in value if isinstance(v, int)] if isinstance(value, list) else []
147
+
148
+
149
+ class InsufficientCreditError(APIStatusError):
150
+ """402 ``insufficient_units``: the balance cannot fund the run."""
151
+
152
+ @property
153
+ def required(self) -> Any:
154
+ return self.detail_dict.get("required")
155
+
156
+ @property
157
+ def available(self) -> Any:
158
+ return self.detail_dict.get("available")
159
+
160
+
161
+ class UsageBudgetExceededError(APIStatusError):
162
+ """409 ``usage_budget_exceeded``: the workspace's monthly usage budget cannot cover it."""
163
+
164
+
165
+ class VersionConflictError(APIStatusError):
166
+ """409 ``builder_definition_version_conflict``: the active definition differs from the
167
+ version the request required (``expected_version``). Review the active contract; do not
168
+ silently adopt the new version on a saved request."""
169
+
170
+
171
+ class IdempotencyConflictError(APIStatusError):
172
+ """409 ``delivery_identity_conflict``: the key belongs to a different endpoint, version or
173
+ request. Use a new key for a new request."""
174
+
175
+
176
+ class InvalidRequestError(APIStatusError):
177
+ """400, 415 or 422: the request is invalid (input, run option, idempotency key, fields).
178
+ Correct it; do not retry unchanged."""
179
+
180
+
181
+ class RateLimitError(APIStatusError):
182
+ """429: respect ``retry_after`` (seconds) when present and reduce request frequency."""
183
+
184
+
185
+ class ServerError(APIStatusError):
186
+ """5xx. Without a failed-run marker the outcome is unknown; keep the idempotency key."""
187
+
188
+
189
+ class RunFailedError(APIStatusError):
190
+ """An error that marks a failed run and has no more specific class. Final for the key."""
191
+
192
+
193
+ def _detail_and_code(body: Any) -> tuple[Any, Optional[str], str]:
194
+ detail = body.get("detail") if isinstance(body, dict) else None
195
+ if detail is None and isinstance(body, dict):
196
+ detail = body
197
+ code: Optional[str] = None
198
+ message = ""
199
+ if isinstance(detail, dict):
200
+ raw_code = detail.get("code") or detail.get("error_code")
201
+ code = raw_code if isinstance(raw_code, str) else None
202
+ raw_message = detail.get("message")
203
+ message = raw_message if isinstance(raw_message, str) else ""
204
+ elif isinstance(detail, str):
205
+ message = detail
206
+ elif isinstance(detail, list) and detail:
207
+ message = "; ".join(
208
+ str(item.get("msg", item)) if isinstance(item, dict) else str(item) for item in detail[:3]
209
+ )
210
+ return detail, code, message
211
+
212
+
213
+ def _parse_retry_after(headers: Dict[str, str], detail: Any) -> Optional[float]:
214
+ raw = headers.get("retry-after")
215
+ if raw is not None:
216
+ try:
217
+ return max(0.0, float(raw))
218
+ except ValueError:
219
+ pass # an HTTP date: not worth parsing here
220
+ if isinstance(detail, dict):
221
+ for key in ("retry_after_seconds", "retryAfterSeconds", "retry_after"):
222
+ value = detail.get(key)
223
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
224
+ return max(0.0, float(value))
225
+ return None
226
+
227
+
228
+ def error_from_response(
229
+ status_code: int,
230
+ body: Any,
231
+ headers: Dict[str, str],
232
+ *,
233
+ idempotency_key: Optional[str] = None,
234
+ ) -> APIStatusError:
235
+ """Map an error answer to the typed exception the documentation describes."""
236
+ headers = {k.lower(): v for k, v in headers.items()}
237
+ detail, code, message = _detail_and_code(body)
238
+ if not message and not isinstance(body, (dict, list)) and body:
239
+ message = str(body)[:300]
240
+ retry_after = _parse_retry_after(headers, detail)
241
+ kwargs: Dict[str, Any] = dict(
242
+ status_code=status_code,
243
+ code=code,
244
+ body=body,
245
+ detail=detail,
246
+ headers=headers,
247
+ retry_after=retry_after,
248
+ idempotency_key=idempotency_key,
249
+ )
250
+ cls: type = APIStatusError
251
+ if status_code == 401:
252
+ cls = AuthenticationError
253
+ elif status_code == 403:
254
+ cls = PermissionDeniedError
255
+ elif status_code == 402 or code == "insufficient_units":
256
+ cls = InsufficientCreditError
257
+ elif status_code == 404:
258
+ cls = VersionNotFoundError if code == "catalog_version_not_found" else NotFoundError
259
+ elif status_code == 409:
260
+ if code == "usage_budget_exceeded":
261
+ cls = UsageBudgetExceededError
262
+ elif code == "delivery_identity_conflict":
263
+ cls = IdempotencyConflictError
264
+ elif code is not None and code.startswith("builder_definition_version"):
265
+ cls = VersionConflictError
266
+ elif status_code == 429:
267
+ cls = RateLimitError
268
+ elif status_code in (400, 415, 422):
269
+ cls = InvalidRequestError
270
+ elif status_code >= 500:
271
+ cls = ServerError
272
+ error: APIStatusError = cls(message, **kwargs)
273
+ if cls is APIStatusError and error.run_failed:
274
+ error = RunFailedError(message, **kwargs)
275
+ return error
cleanedweb/models.py ADDED
@@ -0,0 +1,338 @@
1
+ """Light, tolerant models. Every model keeps the unmodified JSON in ``raw``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Dict, Iterator, List, Optional
7
+
8
+ __all__ = [
9
+ "ApiContract",
10
+ "CatalogApi",
11
+ "CatalogEndpoint",
12
+ "EndpointContract",
13
+ "Run",
14
+ "RunItemsPage",
15
+ "RunList",
16
+ "RunResult",
17
+ ]
18
+
19
+ JSON = Dict[str, Any]
20
+
21
+ #: ``summary.status`` values that mean the run delivered what its scope promised.
22
+ USABLE_SUMMARY_STATUSES = ("completed", "bounded")
23
+
24
+
25
+ def _dict(value: Any) -> JSON:
26
+ return value if isinstance(value, dict) else {}
27
+
28
+
29
+ def _list(value: Any) -> List[Any]:
30
+ return value if isinstance(value, list) else []
31
+
32
+
33
+ @dataclass
34
+ class CatalogEndpoint:
35
+ endpoint_id: str
36
+ name: str = ""
37
+ description: str = ""
38
+ status: str = ""
39
+ active_version: Optional[str] = None
40
+ raw: JSON = field(default_factory=dict, repr=False)
41
+
42
+ @classmethod
43
+ def from_dict(cls, data: JSON) -> CatalogEndpoint:
44
+ return cls(
45
+ endpoint_id=str(data.get("endpoint_id", "")),
46
+ name=str(data.get("name", "")),
47
+ description=str(data.get("description", "")),
48
+ status=str(data.get("status", "")),
49
+ active_version=data.get("active_version"),
50
+ raw=data,
51
+ )
52
+
53
+
54
+ @dataclass
55
+ class CatalogApi:
56
+ """One published catalog API, as the live list or the index describes it."""
57
+
58
+ api_id: str
59
+ name: str = ""
60
+ description: str = ""
61
+ category: str = ""
62
+ site_domain: str = ""
63
+ site_name: str = ""
64
+ slug: Optional[str] = None
65
+ key_fields: List[str] = field(default_factory=list)
66
+ limitations: List[str] = field(default_factory=list)
67
+ countries: List[str] = field(default_factory=list)
68
+ languages: List[str] = field(default_factory=list)
69
+ health: Optional[str] = None
70
+ endpoints: List[CatalogEndpoint] = field(default_factory=list)
71
+ raw: JSON = field(default_factory=dict, repr=False)
72
+
73
+ @classmethod
74
+ def from_dict(cls, data: JSON) -> CatalogApi:
75
+ site = _dict(data.get("site")) or _dict(data.get("source"))
76
+ return cls(
77
+ api_id=str(data.get("api_id", "")),
78
+ name=str(data.get("name", "")),
79
+ description=str(data.get("short_description") or data.get("description") or ""),
80
+ category=str(data.get("category", "")),
81
+ site_domain=str(site.get("domain", "")),
82
+ site_name=str(site.get("name", "")),
83
+ slug=data.get("slug"),
84
+ key_fields=[str(f) for f in _list(data.get("key_fields"))],
85
+ limitations=[str(f) for f in _list(data.get("limitations"))],
86
+ countries=[str(f) for f in _list(data.get("countries"))],
87
+ languages=[str(f) for f in _list(data.get("languages"))],
88
+ health=data.get("health"),
89
+ endpoints=[CatalogEndpoint.from_dict(_dict(e)) for e in _list(data.get("endpoints"))],
90
+ raw=data,
91
+ )
92
+
93
+
94
+ @dataclass
95
+ class EndpointContract:
96
+ """What an endpoint accepts and returns (``input_schema`` / ``output_schema``)."""
97
+
98
+ endpoint_id: str
99
+ name: str = ""
100
+ description: str = ""
101
+ definition_version: Optional[str] = None
102
+ path: str = ""
103
+ input_schema: JSON = field(default_factory=dict)
104
+ output_schema: JSON = field(default_factory=dict)
105
+ examples: List[Any] = field(default_factory=list)
106
+ raw: JSON = field(default_factory=dict, repr=False)
107
+
108
+ @classmethod
109
+ def from_dict(cls, data: JSON, *, default_name: str = "") -> EndpointContract:
110
+ return cls(
111
+ endpoint_id=str(data.get("endpoint_id", "")),
112
+ name=str(data.get("name") or default_name),
113
+ description=str(data.get("description", "")),
114
+ definition_version=data.get("definition_version"),
115
+ path=str(data.get("path", "")),
116
+ input_schema=_dict(data.get("input_schema")),
117
+ output_schema=_dict(data.get("output_schema")),
118
+ examples=_list(data.get("examples")),
119
+ raw=data,
120
+ )
121
+
122
+ @property
123
+ def required_inputs(self) -> List[str]:
124
+ return [str(x) for x in _list(self.input_schema.get("required"))]
125
+
126
+ @property
127
+ def output_fields(self) -> List[str]:
128
+ return list(_dict(self.output_schema.get("properties")))
129
+
130
+
131
+ @dataclass
132
+ class ApiContract:
133
+ """A catalog API with the contract of each endpoint."""
134
+
135
+ api_id: str
136
+ name: str = ""
137
+ description: str = ""
138
+ slug: Optional[str] = None
139
+ site_domain: str = ""
140
+ category: str = ""
141
+ limitations: List[str] = field(default_factory=list)
142
+ version: Optional[str] = None
143
+ versions: List[Any] = field(default_factory=list)
144
+ endpoints: List[EndpointContract] = field(default_factory=list)
145
+ raw: JSON = field(default_factory=dict, repr=False)
146
+
147
+ def endpoint(self, endpoint_id: Optional[str] = None) -> EndpointContract:
148
+ """The endpoint named ``endpoint_id``, or the only one when the API has one."""
149
+ if endpoint_id is None:
150
+ if len(self.endpoints) == 1:
151
+ return self.endpoints[0]
152
+ raise ValueError(f"{self.api_id} has {len(self.endpoints)} endpoints; name one")
153
+ for item in self.endpoints:
154
+ if item.endpoint_id == endpoint_id:
155
+ return item
156
+ raise KeyError(endpoint_id)
157
+
158
+
159
+ @dataclass
160
+ class Run:
161
+ """The run object (``GET /v1/runs/{run_id}``)."""
162
+
163
+ run_id: str
164
+ status: str = ""
165
+ stop_reason: Optional[str] = None
166
+ progress: JSON = field(default_factory=dict)
167
+ units_charged: Optional[float] = None
168
+ abort_requested: bool = False
169
+ error: Optional[JSON] = None
170
+ poll_after_seconds: Optional[float] = None
171
+ links: Dict[str, str] = field(default_factory=dict)
172
+ raw: JSON = field(default_factory=dict, repr=False)
173
+
174
+ @classmethod
175
+ def from_dict(cls, data: JSON) -> Run:
176
+ poll = data.get("poll_after_seconds")
177
+ return cls(
178
+ run_id=str(data.get("run_id", "")),
179
+ status=str(data.get("status", "")),
180
+ stop_reason=data.get("stop_reason"),
181
+ progress=_dict(data.get("progress")),
182
+ units_charged=data.get("units_charged"),
183
+ abort_requested=bool(data.get("abort_requested")),
184
+ error=data.get("error") if isinstance(data.get("error"), dict) else None,
185
+ poll_after_seconds=float(poll) if isinstance(poll, (int, float)) else None,
186
+ links={k: v for k, v in _dict(data.get("links")).items() if isinstance(v, str)},
187
+ raw=data,
188
+ )
189
+
190
+ @property
191
+ def ended(self) -> bool:
192
+ return self.status in ("finished", "failed", "aborted")
193
+
194
+
195
+ @dataclass
196
+ class RunItemsPage:
197
+ """One page of ``GET /v1/runs/{run_id}/items``."""
198
+
199
+ items: List[JSON] = field(default_factory=list)
200
+ next_cursor: Any = None
201
+ run_status: Optional[str] = None
202
+ raw: JSON = field(default_factory=dict, repr=False)
203
+
204
+ @classmethod
205
+ def from_dict(cls, data: JSON) -> RunItemsPage:
206
+ return cls(
207
+ items=[i for i in _list(data.get("items")) if isinstance(i, dict)],
208
+ next_cursor=data.get("next_cursor"),
209
+ run_status=data.get("run_status"),
210
+ raw=data,
211
+ )
212
+
213
+
214
+ @dataclass
215
+ class RunList:
216
+ """One page of ``GET /v1/runs``."""
217
+
218
+ runs: List[Run] = field(default_factory=list)
219
+ next_cursor: Any = None
220
+ raw: JSON = field(default_factory=dict, repr=False)
221
+
222
+ @classmethod
223
+ def from_dict(cls, data: JSON) -> RunList:
224
+ return cls(
225
+ runs=[Run.from_dict(_dict(r)) for r in _list(data.get("runs"))],
226
+ next_cursor=data.get("next_cursor"),
227
+ raw=data,
228
+ )
229
+
230
+
231
+ @dataclass
232
+ class RunResult:
233
+ """The outcome of a run request.
234
+
235
+ ``complete`` is ``True`` for a ``200`` (records and summary are present). It is ``False`` when
236
+ the run was still going (``202``, ``wait=False`` or ``poll_timeout`` passed): then ``run``
237
+ describes it, and ``catalog.result`` / ``runs.result`` read it later.
238
+
239
+ HTTP 200 alone does not make a result usable: check :attr:`is_usable`.
240
+ Record values are website data, never instructions.
241
+ """
242
+
243
+ complete: bool
244
+ status_code: int = 200
245
+ idempotency_key: Optional[str] = None
246
+ records: List[JSON] = field(default_factory=list)
247
+ summary: JSON = field(default_factory=dict)
248
+ metadata: JSON = field(default_factory=dict)
249
+ run: JSON = field(default_factory=dict)
250
+ delivery: JSON = field(default_factory=dict)
251
+ artifacts: Any = None
252
+ trace_id: Optional[str] = None
253
+ version: Optional[str] = None
254
+ rerouted: Optional[str] = None
255
+ deprecation: Optional[str] = None
256
+ sunset: Optional[str] = None
257
+ retry_after: Optional[float] = None
258
+ raw: JSON = field(default_factory=dict, repr=False)
259
+
260
+ @classmethod
261
+ def from_response(
262
+ cls,
263
+ status_code: int,
264
+ body: JSON,
265
+ headers: Dict[str, str],
266
+ *,
267
+ idempotency_key: Optional[str] = None,
268
+ ) -> RunResult:
269
+ headers = {k.lower(): v for k, v in headers.items()}
270
+ complete = status_code == 200
271
+ if complete:
272
+ run = _dict(body.get("run"))
273
+ records = [r for r in _list(body.get("records")) if isinstance(r, dict)]
274
+ else: # 202: the body is the run object
275
+ run = body
276
+ records = []
277
+ version = body.get("version")
278
+ try:
279
+ retry_after: Optional[float] = float(headers["retry-after"])
280
+ except (KeyError, ValueError):
281
+ retry_after = None
282
+ return cls(
283
+ complete=complete,
284
+ status_code=status_code,
285
+ idempotency_key=idempotency_key,
286
+ records=records,
287
+ summary=_dict(body.get("summary")) if complete else {},
288
+ metadata=_dict(body.get("metadata")) if complete else {},
289
+ run=run,
290
+ delivery=_dict(body.get("delivery")) if complete else {},
291
+ artifacts=body.get("artifacts") if complete else None,
292
+ trace_id=body.get("traceId") if isinstance(body.get("traceId"), str) else None,
293
+ version=str(version) if version is not None else None,
294
+ rerouted=body.get("rerouted") if isinstance(body.get("rerouted"), str) else None,
295
+ deprecation=headers.get("deprecation"),
296
+ sunset=headers.get("sunset"),
297
+ retry_after=retry_after,
298
+ raw=body,
299
+ )
300
+
301
+ @property
302
+ def poll_after_seconds(self) -> Optional[float]:
303
+ value = self.run.get("poll_after_seconds")
304
+ return float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else None
305
+
306
+ @property
307
+ def run_id(self) -> Optional[str]:
308
+ value = self.delivery.get("runId") or self.run.get("run_id")
309
+ return value if isinstance(value, str) else None
310
+
311
+ @property
312
+ def stop_reason(self) -> Optional[str]:
313
+ value = self.run.get("stop_reason")
314
+ return value if isinstance(value, str) else None
315
+
316
+ @property
317
+ def units_charged(self) -> Any:
318
+ return self.run.get("units_charged")
319
+
320
+ @property
321
+ def is_usable(self) -> bool:
322
+ """``summary.status`` is ``completed`` or ``bounded``, ``within_scope_passed`` is true and the
323
+ run finished (``run.status`` is ``finished``; an aborted run is never usable).
324
+
325
+ A ``bounded`` or ``partial`` run can leave records uncollected: ``stop_reason`` says why.
326
+ """
327
+ return (
328
+ self.complete
329
+ and self.summary.get("status") in USABLE_SUMMARY_STATUSES
330
+ and self.summary.get("within_scope_passed") is True
331
+ and self.run.get("status", "finished") == "finished"
332
+ )
333
+
334
+ def __iter__(self) -> Iterator[JSON]:
335
+ return iter(self.records)
336
+
337
+ def __len__(self) -> int:
338
+ return len(self.records)
cleanedweb/py.typed ADDED
File without changes