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.
- cleanedweb/__init__.py +76 -0
- cleanedweb/_async.py +537 -0
- cleanedweb/_core.py +246 -0
- cleanedweb/_sync.py +527 -0
- cleanedweb/_version.py +1 -0
- cleanedweb/exceptions.py +275 -0
- cleanedweb/models.py +338 -0
- cleanedweb/py.typed +0 -0
- cleanedweb-0.1.0.dist-info/METADATA +123 -0
- cleanedweb-0.1.0.dist-info/RECORD +12 -0
- cleanedweb-0.1.0.dist-info/WHEEL +4 -0
- cleanedweb-0.1.0.dist-info/licenses/LICENSE +21 -0
cleanedweb/_core.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""Request building, response parsing and catalog matching shared by both clients (no I/O)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import uuid
|
|
8
|
+
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
|
9
|
+
from urllib.parse import quote
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from ._version import __version__
|
|
14
|
+
from .exceptions import CleanedWebError, error_from_response
|
|
15
|
+
from .models import ApiContract, CatalogApi, EndpointContract, RunResult
|
|
16
|
+
|
|
17
|
+
DEFAULT_BASE_URL = "https://api.cleanedweb.com"
|
|
18
|
+
DEFAULT_APP_URL = "https://app.cleanedweb.com"
|
|
19
|
+
DEFAULT_SITE_URL = "https://cleanedweb.com"
|
|
20
|
+
USER_AGENT = f"cleanedweb-python/{__version__}"
|
|
21
|
+
|
|
22
|
+
#: ``409`` codes of ``/result`` that only mean "not ready yet": retry with the same key.
|
|
23
|
+
RESULT_PENDING_CODES = frozenset({"result_not_available", "result_not_complete", "result_not_running"})
|
|
24
|
+
RETRYABLE_STATUSES = frozenset({429, 502, 503, 504})
|
|
25
|
+
LIST_PAGE_SIZE = 100
|
|
26
|
+
MIN_POLL_SECONDS = 1.0
|
|
27
|
+
MAX_POLL_SECONDS = 60.0
|
|
28
|
+
DEFAULT_POLL_SECONDS = 30.0
|
|
29
|
+
|
|
30
|
+
_IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:\-]{1,200}$")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def new_idempotency_key() -> str:
|
|
34
|
+
return str(uuid.uuid4())
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def validate_idempotency_key(key: str) -> str:
|
|
38
|
+
if not isinstance(key, str) or not _IDEMPOTENCY_RE.match(key):
|
|
39
|
+
raise ValueError("idempotency_key must be 1-200 characters: letters, digits, '.', '_', ':', '-'")
|
|
40
|
+
return key
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def seg(value: str) -> str:
|
|
44
|
+
"""Percent-encode one path segment."""
|
|
45
|
+
return quote(str(value), safe="")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def catalog_run_path(api_id: str, endpoint_id: str) -> str:
|
|
49
|
+
return f"/v1/catalog/public/apis/{seg(api_id)}/endpoints/{seg(endpoint_id)}"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def build_run_body(
|
|
53
|
+
*,
|
|
54
|
+
input: Optional[Dict[str, Any]],
|
|
55
|
+
max_items: Optional[int],
|
|
56
|
+
timeout_seconds: Optional[int],
|
|
57
|
+
wait_seconds: Optional[int],
|
|
58
|
+
fields: Optional[Iterable[str]] = None,
|
|
59
|
+
nulls: Optional[bool] = None,
|
|
60
|
+
extra: Optional[Dict[str, Any]] = None,
|
|
61
|
+
) -> Dict[str, Any]:
|
|
62
|
+
if max_items is not None and (
|
|
63
|
+
isinstance(max_items, bool) or not isinstance(max_items, int) or max_items < 1
|
|
64
|
+
):
|
|
65
|
+
raise ValueError("max_items must be an integer >= 1")
|
|
66
|
+
body: Dict[str, Any] = {"input": dict(input or {})}
|
|
67
|
+
if max_items is not None:
|
|
68
|
+
body["max_items"] = max_items
|
|
69
|
+
if timeout_seconds is not None:
|
|
70
|
+
body["timeout_seconds"] = timeout_seconds
|
|
71
|
+
if wait_seconds is not None:
|
|
72
|
+
body["wait_seconds"] = wait_seconds
|
|
73
|
+
if fields is not None:
|
|
74
|
+
body["fields"] = list(fields)
|
|
75
|
+
if nulls is not None:
|
|
76
|
+
body["nulls"] = nulls
|
|
77
|
+
for key, value in (extra or {}).items():
|
|
78
|
+
if value is not None:
|
|
79
|
+
body[key] = value
|
|
80
|
+
return body
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def effective_wait_seconds(wait: bool, wait_seconds: Optional[int]) -> Optional[int]:
|
|
84
|
+
"""``wait=False`` asks the server not to hold the request: it answers ``202`` right away."""
|
|
85
|
+
if not wait and wait_seconds is None:
|
|
86
|
+
return 0
|
|
87
|
+
return wait_seconds
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def http_timeout_for(wait_seconds: Optional[int], default: float) -> float:
|
|
91
|
+
"""The server holds a run request up to ``wait_seconds`` (default 90): leave room for it."""
|
|
92
|
+
held = 90 if wait_seconds is None else wait_seconds
|
|
93
|
+
return max(default, held + 30.0)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def parse_body(response: httpx.Response) -> Any:
|
|
97
|
+
if not response.content:
|
|
98
|
+
return None
|
|
99
|
+
try:
|
|
100
|
+
return json.loads(response.content)
|
|
101
|
+
except ValueError:
|
|
102
|
+
return response.text[:500]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def raise_for_response(response: httpx.Response, *, idempotency_key: Optional[str] = None) -> Any:
|
|
106
|
+
"""Return the JSON body of a 2xx answer, or raise the typed error."""
|
|
107
|
+
body = parse_body(response)
|
|
108
|
+
if response.status_code >= 300:
|
|
109
|
+
if response.status_code < 400: # a redirect means the request went to the wrong origin
|
|
110
|
+
raise CleanedWebError(
|
|
111
|
+
f"HTTP {response.status_code} redirect from {response.request.url}: "
|
|
112
|
+
"nothing ran; check the base_url (runs go to https://api.cleanedweb.com)"
|
|
113
|
+
)
|
|
114
|
+
raise error_from_response(
|
|
115
|
+
response.status_code, body, dict(response.headers), idempotency_key=idempotency_key
|
|
116
|
+
)
|
|
117
|
+
return body
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def retry_delay(attempt: int, retry_after: Optional[float], max_delay: float) -> Optional[float]:
|
|
121
|
+
"""Seconds to wait before retrying, or ``None`` when the server asks for longer than allowed."""
|
|
122
|
+
if retry_after is not None:
|
|
123
|
+
return retry_after if retry_after <= max_delay else None
|
|
124
|
+
return float(min(max_delay, 0.5 * (2**attempt)))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def poll_delay(retry_after: Optional[float], poll_after: Optional[float]) -> float:
|
|
128
|
+
value = retry_after if retry_after is not None else poll_after
|
|
129
|
+
if value is None:
|
|
130
|
+
value = DEFAULT_POLL_SECONDS
|
|
131
|
+
return min(MAX_POLL_SECONDS, max(MIN_POLL_SECONDS, float(value)))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def run_result(response: httpx.Response, body: Any, *, idempotency_key: Optional[str]) -> RunResult:
|
|
135
|
+
if not isinstance(body, dict):
|
|
136
|
+
raise CleanedWebError(f"HTTP {response.status_code} without a JSON object body")
|
|
137
|
+
return RunResult.from_response(
|
|
138
|
+
response.status_code, body, dict(response.headers), idempotency_key=idempotency_key
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# --- catalog matching -------------------------------------------------------------------------
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def normalize_site(value: str) -> str:
|
|
146
|
+
"""``https://www.Example.com/a?b`` -> ``example.com``; a bare name stays a lowercase name."""
|
|
147
|
+
text = value.strip().lower()
|
|
148
|
+
text = re.sub(r"^[a-z][a-z0-9+.\-]*://", "", text)
|
|
149
|
+
text = text.split("/", 1)[0].split("?", 1)[0].split("#", 1)[0]
|
|
150
|
+
text = text.split("@")[-1].split(":", 1)[0]
|
|
151
|
+
return text[4:] if text.startswith("www.") else text
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def merge_index(apis: List[CatalogApi], index: Iterable[Dict[str, Any]]) -> List[CatalogApi]:
|
|
155
|
+
"""Add ``slug`` and ``key_fields`` from ``catalog/index.json`` to live-list items."""
|
|
156
|
+
by_id = {str(e.get("api_id")): e for e in index if isinstance(e, dict)}
|
|
157
|
+
for api in apis:
|
|
158
|
+
entry = by_id.get(api.api_id)
|
|
159
|
+
if entry:
|
|
160
|
+
api.slug = entry.get("slug") or api.slug
|
|
161
|
+
api.key_fields = [str(f) for f in entry.get("key_fields") or []] or api.key_fields
|
|
162
|
+
return apis
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def matches_site(api: CatalogApi, site: str) -> bool:
|
|
166
|
+
needle = normalize_site(site)
|
|
167
|
+
if not needle:
|
|
168
|
+
return True
|
|
169
|
+
domain = normalize_site(api.site_domain)
|
|
170
|
+
haystack = (domain, api.site_name.lower(), api.name.lower())
|
|
171
|
+
return any(needle in h for h in haystack if h)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def matches_text(api: CatalogApi, q: str) -> bool:
|
|
175
|
+
words = [w for w in re.split(r"\s+", q.lower().strip()) if w]
|
|
176
|
+
text = " ".join([api.name, api.description, api.site_domain, api.site_name, *api.key_fields]).lower()
|
|
177
|
+
return all(w in text for w in words)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def has_fields(known: Iterable[str], wanted: Iterable[str]) -> bool:
|
|
181
|
+
have = {k.lower() for k in known}
|
|
182
|
+
return all(w.lower() in have for w in wanted)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def contract_has_fields(contract: ApiContract, wanted: Iterable[str]) -> bool:
|
|
186
|
+
return any(has_fields(e.output_fields, wanted) for e in contract.endpoints)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def split_by_fields(
|
|
190
|
+
candidates: List[CatalogApi], wanted: List[str]
|
|
191
|
+
) -> Tuple[List[CatalogApi], List[CatalogApi]]:
|
|
192
|
+
matched = [c for c in candidates if has_fields(c.key_fields, wanted)]
|
|
193
|
+
unresolved = [c for c in candidates if c not in matched]
|
|
194
|
+
return matched, unresolved
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def find_slug(index: Iterable[Dict[str, Any]], api_id_or_slug: str) -> Optional[Dict[str, Any]]:
|
|
198
|
+
for entry in index:
|
|
199
|
+
if isinstance(entry, dict) and api_id_or_slug in (entry.get("slug"), entry.get("api_id")):
|
|
200
|
+
return entry
|
|
201
|
+
return None
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def contract_from_site(data: Dict[str, Any]) -> ApiContract:
|
|
205
|
+
"""Build an :class:`ApiContract` from ``cleanedweb.com/catalog/<slug>/contract.json``."""
|
|
206
|
+
raw_source = data.get("source")
|
|
207
|
+
source: Dict[str, Any] = raw_source if isinstance(raw_source, dict) else {}
|
|
208
|
+
endpoints = [EndpointContract.from_dict(e) for e in data.get("endpoints") or [] if isinstance(e, dict)]
|
|
209
|
+
return ApiContract(
|
|
210
|
+
api_id=str(data.get("api_id", "")),
|
|
211
|
+
name=str(data.get("name", "")),
|
|
212
|
+
description=str(data.get("description", "")),
|
|
213
|
+
slug=data.get("slug"),
|
|
214
|
+
site_domain=str(source.get("domain", "")),
|
|
215
|
+
category=str(data.get("category", "")),
|
|
216
|
+
limitations=[str(x) for x in data.get("limitations") or []],
|
|
217
|
+
version=data.get("version"),
|
|
218
|
+
versions=list(data.get("versions") or []),
|
|
219
|
+
endpoints=endpoints,
|
|
220
|
+
raw=data,
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def contract_from_live(detail: Dict[str, Any], contracts: List[Dict[str, Any]]) -> ApiContract:
|
|
225
|
+
"""Build an :class:`ApiContract` from the live API detail and its endpoint contracts."""
|
|
226
|
+
api = CatalogApi.from_dict(detail)
|
|
227
|
+
names = {e.endpoint_id: e for e in api.endpoints}
|
|
228
|
+
endpoints = []
|
|
229
|
+
for item in contracts:
|
|
230
|
+
meta = names.get(str(item.get("endpoint_id", "")))
|
|
231
|
+
endpoints.append(EndpointContract.from_dict(item, default_name=meta.name if meta else ""))
|
|
232
|
+
if not endpoints[-1].description and meta:
|
|
233
|
+
endpoints[-1].description = meta.description
|
|
234
|
+
return ApiContract(
|
|
235
|
+
api_id=api.api_id,
|
|
236
|
+
name=api.name,
|
|
237
|
+
description=api.description,
|
|
238
|
+
slug=api.slug,
|
|
239
|
+
site_domain=api.site_domain,
|
|
240
|
+
category=api.category,
|
|
241
|
+
limitations=api.limitations,
|
|
242
|
+
version=contracts[0].get("version") if contracts else None,
|
|
243
|
+
versions=list(contracts[0].get("versions") or []) if contracts else [],
|
|
244
|
+
endpoints=endpoints,
|
|
245
|
+
raw={"api": detail, "contracts": contracts},
|
|
246
|
+
)
|