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