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/_sync.py ADDED
@@ -0,0 +1,527 @@
1
+ """The synchronous client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import time
7
+ from typing import Any, Dict, Iterable, Iterator, List, Optional
8
+
9
+ import httpx
10
+
11
+ from . import _core as core
12
+ from .exceptions import (
13
+ APIConnectionError,
14
+ APIStatusError,
15
+ CleanedWebError,
16
+ MissingAPIKeyError,
17
+ error_from_response,
18
+ )
19
+ from .models import (
20
+ ApiContract,
21
+ CatalogApi,
22
+ Run,
23
+ RunItemsPage,
24
+ RunList,
25
+ RunResult,
26
+ )
27
+
28
+ __all__ = ["CleanedWeb"]
29
+
30
+
31
+ class CleanedWeb:
32
+ """Client for the CleanedWeb catalog and run APIs.
33
+
34
+ ``api_key`` defaults to ``CLEANEDWEB_API_KEY``. Reading the catalog (``catalog.list``,
35
+ ``get``, ``find``) needs no key; running does (scope ``run``). The key is only ever sent to
36
+ ``base_url``, never to the catalog read origins.
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ api_key: Optional[str] = None,
42
+ *,
43
+ base_url: Optional[str] = None,
44
+ app_url: Optional[str] = None,
45
+ site_url: Optional[str] = None,
46
+ timeout: float = 30.0,
47
+ max_retries: int = 2,
48
+ max_retry_delay: float = 30.0,
49
+ http_client: Optional[httpx.Client] = None,
50
+ ) -> None:
51
+ self._api_key = api_key or os.environ.get("CLEANEDWEB_API_KEY") or None
52
+ self.base_url = (base_url or os.environ.get("CLEANEDWEB_RUN_BASE") or core.DEFAULT_BASE_URL).rstrip(
53
+ "/"
54
+ )
55
+ self.app_url = (app_url or core.DEFAULT_APP_URL).rstrip("/")
56
+ self.site_url = (site_url or core.DEFAULT_SITE_URL).rstrip("/")
57
+ self.timeout = timeout
58
+ self.max_retries = max_retries
59
+ self.max_retry_delay = max_retry_delay
60
+ self._owns_http = http_client is None
61
+ self._http = http_client or httpx.Client(timeout=timeout, follow_redirects=False)
62
+ self._index_cache: Optional[List[Dict[str, Any]]] = None
63
+ self.catalog = Catalog(self)
64
+ self.runs = Runs(self)
65
+ self.sources = Sources(self)
66
+
67
+ def __repr__(self) -> str:
68
+ return f"CleanedWeb(base_url={self.base_url!r}, api_key={'set' if self._api_key else 'unset'})"
69
+
70
+ def __enter__(self) -> CleanedWeb:
71
+ return self
72
+
73
+ def __exit__(self, *exc: Any) -> None:
74
+ self.close()
75
+
76
+ def close(self) -> None:
77
+ if self._owns_http:
78
+ self._http.close()
79
+
80
+ # -- transport ---------------------------------------------------------------------------
81
+
82
+ def _headers(self, auth: bool, idempotency_key: Optional[str]) -> Dict[str, str]:
83
+ headers = {"Accept": "application/json", "User-Agent": core.USER_AGENT}
84
+ if auth:
85
+ if not self._api_key:
86
+ raise MissingAPIKeyError(
87
+ "This call needs an API key with the `run` scope: pass api_key= or set CLEANEDWEB_API_KEY"
88
+ )
89
+ headers["Authorization"] = f"Bearer {self._api_key}"
90
+ if idempotency_key is not None:
91
+ headers["Idempotency-Key"] = idempotency_key
92
+ return headers
93
+
94
+ def _send(
95
+ self,
96
+ method: str,
97
+ url: str,
98
+ *,
99
+ auth: bool = False,
100
+ params: Optional[Dict[str, Any]] = None,
101
+ json: Optional[Dict[str, Any]] = None,
102
+ idempotency_key: Optional[str] = None,
103
+ timeout: Optional[float] = None,
104
+ ) -> tuple[httpx.Response, Any]:
105
+ headers = self._headers(auth, idempotency_key)
106
+ attempt = 0
107
+ while True:
108
+ try:
109
+ response = self._http.request(
110
+ method,
111
+ url,
112
+ params=params,
113
+ json=json,
114
+ headers=headers,
115
+ timeout=timeout if timeout is not None else self.timeout,
116
+ )
117
+ except httpx.HTTPError as exc:
118
+ raise APIConnectionError(
119
+ f"{type(exc).__name__}: {exc}. The request may have reached the server"
120
+ + ("; reuse the same idempotency_key to recover it" if idempotency_key else ""),
121
+ idempotency_key=idempotency_key,
122
+ ) from exc
123
+ if response.status_code in core.RETRYABLE_STATUSES and attempt < self.max_retries:
124
+ error = error_from_response(
125
+ response.status_code, core.parse_body(response), dict(response.headers)
126
+ )
127
+ delay = (
128
+ None
129
+ if error.run_failed
130
+ else core.retry_delay(attempt, error.retry_after, self.max_retry_delay)
131
+ )
132
+ if delay is not None:
133
+ time.sleep(delay)
134
+ attempt += 1
135
+ continue
136
+ body = core.raise_for_response(response, idempotency_key=idempotency_key)
137
+ return response, body
138
+
139
+ def _get_json(self, url: str, **kwargs: Any) -> Any:
140
+ return self._send("GET", url, **kwargs)[1]
141
+
142
+ def _index(self) -> List[Dict[str, Any]]:
143
+ if self._index_cache is None:
144
+ data = self._get_json(f"{self.site_url}/catalog/index.json")
145
+ apis = data.get("apis") if isinstance(data, dict) else None
146
+ self._index_cache = [a for a in apis or [] if isinstance(a, dict)]
147
+ return self._index_cache
148
+
149
+ def _poll(
150
+ self,
151
+ result: RunResult,
152
+ fetch: Any,
153
+ poll_timeout: Optional[float],
154
+ ) -> RunResult:
155
+ """Read ``fetch()`` until the run ends. Never resends the run request."""
156
+ deadline = None if poll_timeout is None else time.monotonic() + poll_timeout
157
+ while not result.complete:
158
+ delay = core.poll_delay(result.retry_after, result.poll_after_seconds)
159
+ if deadline is not None and time.monotonic() + delay > deadline:
160
+ return result
161
+ time.sleep(delay)
162
+ try:
163
+ result = fetch()
164
+ except APIStatusError as exc:
165
+ if exc.status_code == 409 and exc.code in core.RESULT_PENDING_CODES:
166
+ result = RunResult(
167
+ complete=False,
168
+ status_code=202,
169
+ idempotency_key=result.idempotency_key,
170
+ run=result.run,
171
+ retry_after=exc.retry_after,
172
+ )
173
+ continue
174
+ raise
175
+ return result
176
+
177
+
178
+ class Catalog:
179
+ def __init__(self, client: CleanedWeb) -> None:
180
+ self._c = client
181
+
182
+ def list(
183
+ self,
184
+ *,
185
+ q: Optional[str] = None,
186
+ category: Optional[str] = None,
187
+ sort: Optional[str] = None,
188
+ limit: int = 20,
189
+ offset: int = 0,
190
+ ) -> List[CatalogApi]:
191
+ """One page of the live catalog list (no key needed)."""
192
+ params: Dict[str, Any] = {"limit": limit, "offset": offset}
193
+ for key, value in (("q", q), ("category", category), ("sort", sort)):
194
+ if value:
195
+ params[key] = value
196
+ data = self._c._get_json(f"{self._c.app_url}/api/catalog/apis", params=params)
197
+ items = data.get("items") if isinstance(data, dict) else None
198
+ return [CatalogApi.from_dict(i) for i in items or [] if isinstance(i, dict)]
199
+
200
+ def iter(
201
+ self,
202
+ *,
203
+ q: Optional[str] = None,
204
+ category: Optional[str] = None,
205
+ sort: Optional[str] = None,
206
+ page_size: int = core.LIST_PAGE_SIZE,
207
+ ) -> Iterator[CatalogApi]:
208
+ """Every API of the live list, page by page."""
209
+ offset = 0
210
+ while True:
211
+ page = self.list(q=q, category=category, sort=sort, limit=page_size, offset=offset)
212
+ yield from page
213
+ if len(page) < page_size:
214
+ return
215
+ offset += page_size
216
+
217
+ def get(self, api_id_or_slug: str) -> ApiContract:
218
+ """The contract of one API: inputs, output fields, saved samples, per endpoint.
219
+
220
+ Takes an ``api_id`` or a catalog slug. Uses the catalog site's ``contract.json`` when the
221
+ API is in the site index, otherwise the live detail and endpoint contracts.
222
+ """
223
+ try:
224
+ entry = core.find_slug(self._c._index(), api_id_or_slug)
225
+ except CleanedWebError:
226
+ entry = None
227
+ if entry and entry.get("slug"):
228
+ data = self._c._get_json(f"{self._c.site_url}/catalog/{core.seg(entry['slug'])}/contract.json")
229
+ return core.contract_from_site(data)
230
+ detail = self._c._get_json(f"{self._c.app_url}/api/catalog/apis/{core.seg(api_id_or_slug)}")
231
+ contracts = []
232
+ for endpoint in CatalogApi.from_dict(detail).endpoints:
233
+ url = (
234
+ f"{self._c.app_url}/api/catalog/apis/{core.seg(api_id_or_slug)}"
235
+ f"/endpoints/{core.seg(endpoint.endpoint_id)}/contract"
236
+ )
237
+ contracts.append(self._c._get_json(url))
238
+ return core.contract_from_live(detail, contracts)
239
+
240
+ def find(
241
+ self,
242
+ *,
243
+ site: Optional[str] = None,
244
+ fields: Optional[Iterable[str]] = None,
245
+ q: Optional[str] = None,
246
+ category: Optional[str] = None,
247
+ limit: int = 20,
248
+ deep: bool = True,
249
+ max_contract_checks: int = 20,
250
+ ) -> List[CatalogApi]:
251
+ """Published APIs for a site (domain, URL or name) that return the given fields.
252
+
253
+ A client-side filter over the live list, joined with the catalog index (which adds
254
+ ``slug`` and ``key_fields``). Field names are matched against ``key_fields``; with
255
+ ``deep`` the contracts of the remaining candidates (at most ``max_contract_checks``)
256
+ are read and their full ``output_schema`` is checked. Nothing runs.
257
+ """
258
+ candidates = list(self._c.catalog.iter(q=q, category=category))
259
+ try:
260
+ core.merge_index(candidates, self._c._index())
261
+ except CleanedWebError:
262
+ pass # the index only adds slug and key_fields
263
+ if site:
264
+ candidates = [c for c in candidates if core.matches_site(c, site)]
265
+ wanted = [f for f in (fields or []) if f]
266
+ if not wanted:
267
+ return candidates[:limit]
268
+ matched, unresolved = core.split_by_fields(candidates, wanted)
269
+ if deep:
270
+ for api in unresolved[:max_contract_checks]:
271
+ if len(matched) >= limit:
272
+ break
273
+ try:
274
+ contract = self.get(api.slug or api.api_id)
275
+ except CleanedWebError:
276
+ continue
277
+ if core.contract_has_fields(contract, wanted):
278
+ matched.append(api)
279
+ return matched[:limit]
280
+
281
+ def run(
282
+ self,
283
+ api_id: str,
284
+ endpoint_id: str,
285
+ input: Optional[Dict[str, Any]] = None,
286
+ *,
287
+ max_items: Optional[int] = None,
288
+ idempotency_key: Optional[str] = None,
289
+ wait: bool = True,
290
+ wait_seconds: Optional[int] = None,
291
+ timeout_seconds: Optional[int] = None,
292
+ fields: Optional[Iterable[str]] = None,
293
+ nulls: Optional[bool] = None,
294
+ version: Optional[int] = None,
295
+ poll_timeout: Optional[float] = None,
296
+ ) -> RunResult:
297
+ """Run a catalog endpoint. Charged per record delivered; start with a small ``max_items``.
298
+
299
+ ``idempotency_key`` is generated when omitted and returned as ``result.idempotency_key``:
300
+ save it before you rely on the call. Resending the same key with the same request returns
301
+ the same run, never a second one. On ``202`` and ``wait=True`` the run is read from
302
+ ``/result`` with that key every ``Retry-After`` seconds until it ends (or ``poll_timeout``
303
+ seconds pass, which returns an incomplete result, ``complete=False``). The POST is never
304
+ resent while waiting. ``wait=False`` returns right after the request is accepted.
305
+ Pin a major with ``version``. Raises a typed error for an API error; see
306
+ :mod:`cleanedweb.exceptions`.
307
+ """
308
+ key = (
309
+ core.validate_idempotency_key(idempotency_key) if idempotency_key else core.new_idempotency_key()
310
+ )
311
+ wait_s = core.effective_wait_seconds(wait, wait_seconds)
312
+ body = core.build_run_body(
313
+ input=input,
314
+ max_items=max_items,
315
+ timeout_seconds=timeout_seconds,
316
+ wait_seconds=wait_s,
317
+ fields=fields,
318
+ nulls=nulls,
319
+ extra={"version": version},
320
+ )
321
+ base = f"{self._c.base_url}{core.catalog_run_path(api_id, endpoint_id)}"
322
+ response, payload = self._c._send(
323
+ "POST",
324
+ f"{base}/run",
325
+ auth=True,
326
+ json=body,
327
+ idempotency_key=key,
328
+ timeout=core.http_timeout_for(wait_s, self._c.timeout),
329
+ )
330
+ result = core.run_result(response, payload, idempotency_key=key)
331
+ if result.complete or not wait:
332
+ return result
333
+ return self._c._poll(result, lambda: self.result(api_id, endpoint_id, key, wait=False), poll_timeout)
334
+
335
+ def result(
336
+ self,
337
+ api_id: str,
338
+ endpoint_id: str,
339
+ idempotency_key: str,
340
+ *,
341
+ wait: bool = True,
342
+ poll_timeout: Optional[float] = None,
343
+ ) -> RunResult:
344
+ """Read the result of an earlier ``run`` with the same key (never collects again).
345
+
346
+ Use it to recover after a timeout or a lost response. Returns an incomplete result
347
+ (``complete=False``) while the run goes on and ``wait`` is false or ``poll_timeout`` passed.
348
+ """
349
+ key = core.validate_idempotency_key(idempotency_key)
350
+ url = f"{self._c.base_url}{core.catalog_run_path(api_id, endpoint_id)}/result"
351
+
352
+ def fetch() -> RunResult:
353
+ response, payload = self._c._send(
354
+ "GET",
355
+ url,
356
+ auth=True,
357
+ idempotency_key=key,
358
+ timeout=core.http_timeout_for(None, self._c.timeout),
359
+ )
360
+ return core.run_result(response, payload, idempotency_key=key)
361
+
362
+ result = fetch()
363
+ if result.complete or not wait:
364
+ return result
365
+ return self._c._poll(result, fetch, poll_timeout)
366
+
367
+
368
+ class Runs:
369
+ def __init__(self, client: CleanedWeb) -> None:
370
+ self._c = client
371
+
372
+ def _url(self, suffix: str = "") -> str:
373
+ return f"{self._c.base_url}/v1/runs{suffix}"
374
+
375
+ def get(self, run_id: str) -> Run:
376
+ return Run.from_dict(self._c._get_json(self._url(f"/{core.seg(run_id)}"), auth=True))
377
+
378
+ def items_page(self, run_id: str, *, cursor: Any = 0, limit: int = 100) -> RunItemsPage:
379
+ data = self._c._get_json(
380
+ self._url(f"/{core.seg(run_id)}/items"), auth=True, params={"cursor": cursor, "limit": limit}
381
+ )
382
+ return RunItemsPage.from_dict(data if isinstance(data, dict) else {})
383
+
384
+ def items(
385
+ self,
386
+ run_id: str,
387
+ *,
388
+ limit: int = 100,
389
+ cursor: Any = 0,
390
+ follow: bool = False,
391
+ poll_interval: float = 2.0,
392
+ ) -> Iterator[Dict[str, Any]]:
393
+ """Iterate the records committed so far, following ``next_cursor`` page by page.
394
+
395
+ Readable while the run runs. With ``follow=True`` it keeps waiting (``poll_interval``
396
+ seconds) for new records until the run ended and every record was read; otherwise it
397
+ stops at the first empty page.
398
+ """
399
+ while True:
400
+ page = self.items_page(run_id, cursor=cursor, limit=limit)
401
+ yield from page.items
402
+ if page.next_cursor is None:
403
+ return
404
+ if not page.items:
405
+ if not follow:
406
+ return
407
+ time.sleep(poll_interval)
408
+ cursor = page.next_cursor
409
+
410
+ def result(self, run_id: str, *, wait: bool = True, poll_timeout: Optional[float] = None) -> RunResult:
411
+ """The final body of a run (``200``), or while it runs an incomplete result (``202``).
412
+ With ``wait`` it polls every ``Retry-After`` seconds until the run ends."""
413
+ url = self._url(f"/{core.seg(run_id)}/result")
414
+
415
+ def fetch() -> RunResult:
416
+ response, payload = self._c._send("GET", url, auth=True)
417
+ return core.run_result(response, payload, idempotency_key=None)
418
+
419
+ result = fetch()
420
+ if result.complete or not wait:
421
+ return result
422
+ return self._c._poll(result, fetch, poll_timeout)
423
+
424
+ def abort(self, run_id: str) -> Run:
425
+ """Stop a run (scope ``run``). Records committed so far stay readable."""
426
+ _, data = self._c._send("POST", self._url(f"/{core.seg(run_id)}/abort"), auth=True)
427
+ return Run.from_dict(data if isinstance(data, dict) else {})
428
+
429
+ def list(
430
+ self,
431
+ *,
432
+ source_id: Optional[str] = None,
433
+ status: Optional[str] = None,
434
+ cursor: Any = None,
435
+ limit: int = 50,
436
+ ) -> RunList:
437
+ """Your runs, newest first (one page)."""
438
+ params: Dict[str, Any] = {"limit": limit}
439
+ for key, value in (("source_id", source_id), ("status", status), ("cursor", cursor)):
440
+ if value is not None:
441
+ params[key] = value
442
+ data = self._c._get_json(self._url(), auth=True, params=params)
443
+ return RunList.from_dict(data if isinstance(data, dict) else {})
444
+
445
+ def iter(
446
+ self, *, source_id: Optional[str] = None, status: Optional[str] = None, limit: int = 50
447
+ ) -> Iterator[Run]:
448
+ """Every run, following ``next_cursor``."""
449
+ cursor: Any = None
450
+ while True:
451
+ page = self.list(source_id=source_id, status=status, cursor=cursor, limit=limit)
452
+ yield from page.runs
453
+ if page.next_cursor is None or not page.runs:
454
+ return
455
+ cursor = page.next_cursor
456
+
457
+
458
+ class Sources:
459
+ def __init__(self, client: CleanedWeb) -> None:
460
+ self._c = client
461
+
462
+ def run(
463
+ self,
464
+ source_id: str,
465
+ input: Optional[Dict[str, Any]] = None,
466
+ *,
467
+ max_items: Optional[int] = None,
468
+ idempotency_key: Optional[str] = None,
469
+ wait: bool = True,
470
+ wait_seconds: Optional[int] = None,
471
+ timeout_seconds: Optional[int] = None,
472
+ expected_version: Optional[str] = None,
473
+ definition_version: Optional[str] = None,
474
+ endpoint: Optional[str] = None,
475
+ fields: Optional[Iterable[str]] = None,
476
+ nulls: Optional[bool] = None,
477
+ poll_timeout: Optional[float] = None,
478
+ base_url: Optional[str] = None,
479
+ ) -> RunResult:
480
+ """Run one of your own private APIs (``POST /v1/sources/{source_id}/run``).
481
+
482
+ Same idempotency and waiting behavior as ``catalog.run``; a ``202`` is followed with
483
+ ``GET /v1/runs/{run_id}/result``. ``expected_version`` (the 64-character definition
484
+ version) makes the call fail with ``VersionConflictError`` if the active definition
485
+ changed; it cannot be combined with ``definition_version``. ``base_url`` overrides the
486
+ origin your API's connection details name.
487
+ """
488
+ if expected_version is not None and definition_version is not None:
489
+ raise ValueError("pass expected_version or definition_version, not both")
490
+ key = (
491
+ core.validate_idempotency_key(idempotency_key) if idempotency_key else core.new_idempotency_key()
492
+ )
493
+ wait_s = core.effective_wait_seconds(wait, wait_seconds)
494
+ body = core.build_run_body(
495
+ input=input,
496
+ max_items=max_items,
497
+ timeout_seconds=timeout_seconds,
498
+ wait_seconds=wait_s,
499
+ fields=fields,
500
+ nulls=nulls,
501
+ extra={
502
+ "expected_version": expected_version,
503
+ "definition_version": definition_version,
504
+ "endpoint": endpoint,
505
+ },
506
+ )
507
+ origin = (base_url or self._c.base_url).rstrip("/")
508
+ response, payload = self._c._send(
509
+ "POST",
510
+ f"{origin}/v1/sources/{core.seg(source_id)}/run",
511
+ auth=True,
512
+ json=body,
513
+ idempotency_key=key,
514
+ timeout=core.http_timeout_for(wait_s, self._c.timeout),
515
+ )
516
+ result = core.run_result(response, payload, idempotency_key=key)
517
+ if result.complete or not wait:
518
+ return result
519
+ run_id = result.run_id
520
+ if not run_id:
521
+ raise CleanedWebError("the 202 answer carried no run_id to read the result with")
522
+
523
+ def fetch() -> RunResult:
524
+ resp, data = self._c._send("GET", f"{origin}/v1/runs/{core.seg(run_id)}/result", auth=True)
525
+ return core.run_result(resp, data, idempotency_key=key)
526
+
527
+ return self._c._poll(result, fetch, poll_timeout)
cleanedweb/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"