cernisdata 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.
cernisdata/_client.py ADDED
@@ -0,0 +1,975 @@
1
+ """CernisData and AsyncCernisData clients. The namespaced endpoint methods live in _generated.py and call into here."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import os
8
+ import random
9
+ import re
10
+ import time
11
+ import uuid
12
+ from email.utils import parsedate_to_datetime
13
+ from typing import Any, AsyncIterator, Awaitable, Callable, Iterator, Mapping, TypeVar
14
+ from urllib.parse import quote
15
+
16
+ import httpx
17
+
18
+ from ._errors import (
19
+ APIConnectionError,
20
+ CernisDataError,
21
+ NotFoundError,
22
+ TimeoutError,
23
+ error_from_response,
24
+ )
25
+ from ._generated import (
26
+ DEFAULT_BASE_URL,
27
+ ENDPOINTS,
28
+ FILTERS,
29
+ AsyncCompanies,
30
+ AsyncContacts,
31
+ AsyncPeople,
32
+ AsyncSignals,
33
+ AsyncWeb,
34
+ Companies,
35
+ Contacts,
36
+ People,
37
+ Signals,
38
+ Web,
39
+ )
40
+ from ._types import Envelope, JobItem, JobStatus, RequestRecord, Wallet
41
+ from ._version import __version__
42
+ from ._webhooks import verify_webhook
43
+
44
+ R = TypeVar("R")
45
+
46
+ _BY_ID: dict[str, dict[str, Any]] = {e["id"]: e for e in ENDPOINTS}
47
+ _ENDPOINT_POSTS = {e["path"] for e in ENDPOINTS if e["method"] == "POST"}
48
+ _PENDING = {"pending", "queued", "running"}
49
+ _MAX_RETRY_AFTER = 60.0
50
+ _UPPER = re.compile(r"[A-Z]")
51
+
52
+ # ---------------------------------------------------------------------------------------------------------------
53
+ # Input helpers
54
+
55
+
56
+ def _to_snake(key: str) -> str:
57
+ return _UPPER.sub(lambda m: "_" + m.group(0).lower(), key)
58
+
59
+
60
+ def snake_keys(value: Any) -> Any:
61
+ """camelCase keys to snake_case, deep. Drops None values."""
62
+ if isinstance(value, Mapping):
63
+ return {_to_snake(str(k)): snake_keys(v) for k, v in value.items() if v is not None}
64
+ if isinstance(value, (list, tuple, set, frozenset)):
65
+ return [snake_keys(v) for v in value]
66
+ return value
67
+
68
+
69
+ def _as_list(v: Any) -> Any:
70
+ return [v] if isinstance(v, str) else v
71
+
72
+
73
+ def _normalize_lists(obj: dict[str, Any], fields: tuple[str, ...]) -> dict[str, Any]:
74
+ for f in fields:
75
+ v = obj.get(f)
76
+ if v is None:
77
+ continue
78
+ if isinstance(v, dict):
79
+ obj[f] = {side: _as_list(x) for side, x in v.items()}
80
+ else:
81
+ obj[f] = _as_list(v)
82
+ return obj
83
+
84
+
85
+ def prepare_input(endpoint: Mapping[str, Any] | None, params: Mapping[str, Any] | None) -> dict[str, Any]:
86
+ """What goes on the wire: snake_case keys, flat filter fields moved into ``filters``, single strings turned into lists."""
87
+ data: dict[str, Any] = snake_keys(params or {})
88
+ if not endpoint:
89
+ return data
90
+ group_name = endpoint.get("filters")
91
+ if group_name:
92
+ group = FILTERS[group_name]
93
+ filters = dict(data["filters"]) if isinstance(data.get("filters"), dict) else {}
94
+ for f in group["fields"]:
95
+ if f in data:
96
+ filters[f] = data.pop(f)
97
+ if filters or "filters" in data:
98
+ data["filters"] = _normalize_lists(filters, group["lists"])
99
+ if endpoint.get("lists"):
100
+ _normalize_lists(data, endpoint["lists"])
101
+ return data
102
+
103
+
104
+ def _query_params(query: Mapping[str, Any] | None) -> list[tuple[str, str]]:
105
+ out: list[tuple[str, str]] = []
106
+
107
+ def text(v: Any) -> str:
108
+ return ("true" if v else "false") if isinstance(v, bool) else str(v)
109
+
110
+ for k, v in (query or {}).items():
111
+ if v is None:
112
+ continue
113
+ if isinstance(v, Mapping):
114
+ out.extend((f"{k}[{kk}]", text(vv)) for kk, vv in v.items() if vv is not None)
115
+ elif isinstance(v, (list, tuple)):
116
+ out.append((k, ",".join(text(x) for x in v)))
117
+ else:
118
+ out.append((k, text(v)))
119
+ return out
120
+
121
+
122
+ def _retry_after(headers: httpx.Headers) -> float | None:
123
+ v = (headers.get("retry-after") or "").strip()
124
+ if not v:
125
+ return None
126
+ try:
127
+ return max(0.0, float(v))
128
+ except ValueError:
129
+ pass
130
+ try:
131
+ return max(0.0, parsedate_to_datetime(v).timestamp() - time.time())
132
+ except (TypeError, ValueError):
133
+ return None
134
+
135
+
136
+ def _new_key() -> str:
137
+ return f"idk_{uuid.uuid4().hex}"
138
+
139
+
140
+ def _job_path(job_id: str) -> str:
141
+ return f"/v1/jobs/{quote(job_id, safe='')}"
142
+
143
+
144
+ # ---------------------------------------------------------------------------------------------------------------
145
+ # Retry plan, shared by the sync and async transports
146
+
147
+
148
+ class _Attempts:
149
+ """One logical request: decides headers per attempt and whether an outcome is final or worth a retry."""
150
+
151
+ def __init__(
152
+ self,
153
+ client: _BaseClient,
154
+ method: str,
155
+ path: str,
156
+ *,
157
+ query: Mapping[str, Any] | None,
158
+ body: Any,
159
+ idempotency_key: str | None,
160
+ timeout: float | None,
161
+ max_retries: int | None,
162
+ idempotent: bool | None,
163
+ headers: Mapping[str, str] | None,
164
+ ) -> None:
165
+ if not client.base_url:
166
+ raise CernisDataError(
167
+ 0,
168
+ {"error": {"code": "missing_base_url", "message": "No API base URL. Pass base_url to CernisData(base_url=...) or set CERNIS_DATA_BASE_URL."}},
169
+ )
170
+ self.client = client
171
+ self.method = method
172
+ self.url = client.base_url + path
173
+ self.params = _query_params(query)
174
+ self.headers: dict[str, str] = {
175
+ "accept": "application/json",
176
+ "user-agent": f"cernisdata-python/{__version__}",
177
+ "x-cernisdata-surface": client.surface,
178
+ **client._headers,
179
+ **(headers or {}),
180
+ }
181
+ if client.api_key:
182
+ self.headers["authorization"] = f"Bearer {client.api_key}"
183
+ self.content: bytes | None = None
184
+ if body is not None:
185
+ self.headers["content-type"] = "application/json"
186
+ self.content = json.dumps(body, separators=(",", ":")).encode()
187
+ if timeout:
188
+ self.headers["x-timeout-ms"] = str(min(120_000, max(1_000, round(timeout * 1000))))
189
+ self.timeout = timeout or client.timeout
190
+ # POSTs to endpoints carry an Idempotency-Key, so a retry never charges twice. Other POSTs (keys,
191
+ # checkout) are only retried when the API refused them before doing anything (429).
192
+ self.idempotent = method != "POST" or bool(idempotent if idempotent is not None else path in _ENDPOINT_POSTS)
193
+ self.user_key = idempotency_key or self.headers.get("idempotency-key")
194
+ self.key = (self.user_key or _new_key()) if method == "POST" and self.idempotent else None
195
+ self.max_retries = client.max_retries if max_retries is None else max_retries
196
+ self.attempt = 0
197
+
198
+ def next_headers(self) -> dict[str, str]:
199
+ if self.key:
200
+ self.headers["idempotency-key"] = self.key
201
+ return self.headers
202
+
203
+ def on_exception(self, exc: httpx.TransportError) -> float:
204
+ if isinstance(exc, httpx.TimeoutException):
205
+ err: CernisDataError = TimeoutError(0, {"error": {"code": "timeout", "message": f"No answer within {self.timeout} s."}})
206
+ else:
207
+ err = APIConnectionError(0, {"error": {"code": "connection_error", "message": f"Could not reach the API: {exc}"}})
208
+ # The request may have reached the server, so retry only with the same Idempotency-Key (or for GETs).
209
+ if self.attempt >= self.max_retries or not self.idempotent:
210
+ raise err from exc
211
+ return self._backoff()
212
+
213
+ def on_response(self, status: int, text: str, headers: httpx.Headers) -> tuple[int, Any] | float:
214
+ ok = 200 <= status < 300
215
+ try:
216
+ body: Any = json.loads(text) if text else None
217
+ except ValueError:
218
+ body = text if ok else {"error": {"code": "bad_response", "message": text[:200]}}
219
+ if ok:
220
+ return status, body
221
+ after = _retry_after(headers)
222
+ err = error_from_response(status, body, after)
223
+ answered = isinstance(body, dict) and isinstance(body.get("error"), dict) and isinstance(body["error"].get("code"), str)
224
+ retryable = status == 429 or (status >= 500 and status != 501 and err.code != "deadline_exceeded")
225
+ if not retryable or self.attempt >= self.max_retries or (not self.idempotent and status != 429):
226
+ raise err
227
+ if status >= 500 and answered and self.method == "POST":
228
+ # The API recorded this attempt as failed (not charged). The same key would now be refused, so the
229
+ # retry needs a fresh one. A key you chose is never swapped: that error is yours to handle.
230
+ if self.user_key:
231
+ raise err
232
+ self.key = _new_key()
233
+ if after is not None and after > _MAX_RETRY_AFTER:
234
+ raise err
235
+ return after if after is not None else self._backoff()
236
+
237
+ def _backoff(self) -> float:
238
+ base = min(8.0, 0.5 * 2**self.attempt)
239
+ self.attempt += 1
240
+ return base / 2 + self.client._random() * (base / 2)
241
+
242
+
243
+ class _BaseClient:
244
+ api_key: str | None
245
+ #: Empty when no base URL is configured; calls then raise a CernisDataError explaining how to set one.
246
+ base_url: str
247
+
248
+ def __init__(
249
+ self,
250
+ *,
251
+ api_key: str | None,
252
+ base_url: str | None,
253
+ surface: str,
254
+ timeout: float,
255
+ max_retries: int,
256
+ wait_timeout: float,
257
+ poll_interval: float,
258
+ headers: Mapping[str, str] | None,
259
+ ) -> None:
260
+ self.api_key = api_key if api_key is not None else (os.environ.get("CERNIS_DATA_API_KEY") or None)
261
+ url = (base_url or os.environ.get("CERNIS_DATA_BASE_URL") or DEFAULT_BASE_URL or "").rstrip("/")
262
+ self.base_url = url[:-3] if url.endswith("/v1") else url
263
+ self.surface = surface
264
+ self.timeout = timeout
265
+ self.max_retries = max_retries
266
+ self.wait_timeout = wait_timeout
267
+ self.poll_interval = poll_interval
268
+ self._headers = dict(headers or {})
269
+ self._random: Callable[[], float] = random.random
270
+ self._clock: Callable[[], float] = time.monotonic
271
+
272
+ def __repr__(self) -> str:
273
+ return f"{type(self).__name__}(base_url={self.base_url!r})"
274
+
275
+ def _endpoint(self, endpoint_id: str) -> dict[str, Any]:
276
+ e = _BY_ID.get(endpoint_id)
277
+ if not e:
278
+ raise NotFoundError(404, {"error": {"code": "not_found", "message": f"Unknown endpoint {endpoint_id}"}})
279
+ return e
280
+
281
+ def _attempts(self, method: str, path: str, **kw: Any) -> _Attempts:
282
+ return _Attempts(
283
+ self,
284
+ method,
285
+ path,
286
+ query=kw.get("query"),
287
+ body=kw.get("body"),
288
+ idempotency_key=kw.get("idempotency_key"),
289
+ timeout=kw.get("timeout"),
290
+ max_retries=kw.get("max_retries"),
291
+ idempotent=kw.get("idempotent"),
292
+ headers=kw.get("headers"),
293
+ )
294
+
295
+ def _endpoint_request(self, e: Mapping[str, Any], params: Mapping[str, Any] | None, opts: dict[str, Any]) -> tuple[str, str, dict[str, Any]]:
296
+ data = prepare_input(e, params)
297
+ if e["method"] == "GET":
298
+ return "GET", e["path"], {"query": data, **opts}
299
+ return "POST", e["path"], {"body": data, "idempotent": True, **opts}
300
+
301
+ def _deadline(self, wait_timeout: float | None) -> tuple[float, Callable[[float], bool]]:
302
+ until = self._clock() + (self.wait_timeout if wait_timeout is None else wait_timeout)
303
+ return until, lambda interval: self._clock() + interval > until
304
+
305
+
306
+ def _wait_timeout_error(what: str) -> TimeoutError:
307
+ return TimeoutError(0, {"error": {"code": "wait_timeout", "message": f"{what} is still running. Poll it again later."}})
308
+
309
+
310
+ def _still_pending(status: int, body: Any) -> bool:
311
+ return status == 202 or (isinstance(body, dict) and body.get("status") in _PENDING)
312
+
313
+
314
+ def _page_items(page: Any) -> list[Any]:
315
+ data = page.get("data") if isinstance(page, dict) else None
316
+ if isinstance(data, list):
317
+ return data
318
+ if isinstance(data, dict) and isinstance(data.get("results"), list):
319
+ return data["results"]
320
+ return []
321
+
322
+
323
+ def _next_cursor(page: Any) -> str | None:
324
+ meta = page.get("meta") if isinstance(page, dict) else None
325
+ return meta.get("next_cursor") if isinstance(meta, dict) else None
326
+
327
+
328
+ # ---------------------------------------------------------------------------------------------------------------
329
+ # Jobs
330
+
331
+
332
+ class _JobBase:
333
+ id: str
334
+ status: str
335
+ total: int
336
+ done: int
337
+ #: The last raw response for this job.
338
+ raw: dict[str, Any]
339
+
340
+ def __init__(self, client: Any, raw: dict[str, Any]) -> None:
341
+ self._client = client
342
+ self.id = raw.get("job_id") or raw.get("request_id") or ""
343
+ self.total = 0
344
+ self.done = 0
345
+ self._update(raw)
346
+
347
+ def _update(self, raw: dict[str, Any]) -> None:
348
+ self.raw = raw
349
+ self.status = raw.get("status", "")
350
+ self.total = raw.get("total", self.total) or 0
351
+ self.done = raw.get("done", self.done) or 0
352
+
353
+ @property
354
+ def finished(self) -> bool:
355
+ return self.status not in _PENDING
356
+
357
+ def __repr__(self) -> str:
358
+ return f"{type(self).__name__}(id={self.id!r}, status={self.status!r}, done={self.done}, total={self.total})"
359
+
360
+
361
+ class Job(_JobBase):
362
+ """A bulk job. ``job.wait()`` then ``for item in job.results()``."""
363
+
364
+ _client: CernisData
365
+
366
+ def refresh(self) -> Job:
367
+ """Fetch the current status."""
368
+ self._update(self._client.job(self.id))
369
+ return self
370
+
371
+ def wait(self, *, poll_interval: float | None = None, wait_timeout: float | None = None) -> Job:
372
+ """Poll until the job is no longer running."""
373
+ self._client._poll(lambda: self if self.refresh().finished else None, poll_interval, wait_timeout, f"Job {self.id}")
374
+ return self
375
+
376
+ def results(self) -> Iterator[JobItem]:
377
+ """Every item with its result, 100 per request. Works while the job runs too (finished items only)."""
378
+ after: int | None = None
379
+ while True:
380
+ page = self._client.job(self.id, after=after)
381
+ yield from page.get("items") or []
382
+ after = page.get("next_after")
383
+ if after is None:
384
+ return
385
+
386
+
387
+ class AsyncJob(_JobBase):
388
+ """A bulk job. ``await job.wait()`` then ``async for item in job.results()``."""
389
+
390
+ _client: AsyncCernisData
391
+
392
+ async def refresh(self) -> AsyncJob:
393
+ self._update(await self._client.job(self.id))
394
+ return self
395
+
396
+ async def wait(self, *, poll_interval: float | None = None, wait_timeout: float | None = None) -> AsyncJob:
397
+ async def check() -> AsyncJob | None:
398
+ return self if (await self.refresh()).finished else None
399
+
400
+ await self._client._poll(check, poll_interval, wait_timeout, f"Job {self.id}")
401
+ return self
402
+
403
+ async def results(self) -> AsyncIterator[JobItem]:
404
+ after: int | None = None
405
+ while True:
406
+ page = await self._client.job(self.id, after=after)
407
+ for item in page.get("items") or []:
408
+ yield item
409
+ after = page.get("next_after")
410
+ if after is None:
411
+ return
412
+
413
+
414
+ # ---------------------------------------------------------------------------------------------------------------
415
+ # Account namespaces
416
+
417
+
418
+ class _Requests:
419
+ def __init__(self, client: CernisData) -> None:
420
+ self._c = client
421
+
422
+ def list(self, *, limit: int | None = None, before: int | None = None) -> dict[str, Any]:
423
+ """Recent requests, newest first. Pass ``before=page["next_before"]`` for the next page."""
424
+ return self._c.request("GET", "/v1/requests", query={"limit": limit, "before": before})
425
+
426
+ def iter(self, *, limit: int | None = None, max_items: int | None = None) -> Iterator[RequestRecord]:
427
+ """Every request, newest first, across pages."""
428
+ before, n = None, 0
429
+ while True:
430
+ page = self.list(limit=limit, before=before)
431
+ for r in page.get("requests") or []:
432
+ yield r
433
+ n += 1
434
+ if max_items and n >= max_items:
435
+ return
436
+ before = page.get("next_before")
437
+ if before is None:
438
+ return
439
+
440
+ def retrieve(self, request_id: str) -> Any:
441
+ """The stored answer of a request (async requests: the envelope once ready)."""
442
+ return self._c.job(request_id)
443
+
444
+ def wait(self, request_id: str, *, poll_interval: float | None = None, wait_timeout: float | None = None) -> Envelope:
445
+ """Wait for a pending async request and return its envelope. Raises its error if it failed."""
446
+ return self._c._wait_for_request(request_id, poll_interval, wait_timeout, None)
447
+
448
+
449
+ class _AsyncRequests:
450
+ def __init__(self, client: AsyncCernisData) -> None:
451
+ self._c = client
452
+
453
+ async def list(self, *, limit: int | None = None, before: int | None = None) -> dict[str, Any]:
454
+ return await self._c.request("GET", "/v1/requests", query={"limit": limit, "before": before})
455
+
456
+ async def iter(self, *, limit: int | None = None, max_items: int | None = None) -> AsyncIterator[RequestRecord]:
457
+ before, n = None, 0
458
+ while True:
459
+ page = await self.list(limit=limit, before=before)
460
+ for r in page.get("requests") or []:
461
+ yield r
462
+ n += 1
463
+ if max_items and n >= max_items:
464
+ return
465
+ before = page.get("next_before")
466
+ if before is None:
467
+ return
468
+
469
+ async def retrieve(self, request_id: str) -> Any:
470
+ return await self._c.job(request_id)
471
+
472
+ async def wait(self, request_id: str, *, poll_interval: float | None = None, wait_timeout: float | None = None) -> Envelope:
473
+ return await self._c._wait_for_request(request_id, poll_interval, wait_timeout, None)
474
+
475
+
476
+ class _Jobs:
477
+ def __init__(self, client: CernisData) -> None:
478
+ self._c = client
479
+
480
+ def retrieve(self, job_id: str) -> Job:
481
+ """A bulk job by id, as a Job you can wait on and read results from."""
482
+ return Job(self._c, self._c.job(job_id))
483
+
484
+
485
+ class _AsyncJobs:
486
+ def __init__(self, client: AsyncCernisData) -> None:
487
+ self._c = client
488
+
489
+ async def retrieve(self, job_id: str) -> AsyncJob:
490
+ return AsyncJob(self._c, await self._c.job(job_id))
491
+
492
+
493
+ class _Keys:
494
+ def __init__(self, client: CernisData) -> None:
495
+ self._c = client
496
+
497
+ def list(self) -> dict[str, Any]:
498
+ return self._c.request("GET", "/v1/keys")
499
+
500
+ def create(self, *, name: str | None = None, scopes: list[str] | None = None) -> dict[str, Any]:
501
+ """Create a key. Scopes: "*" or categories (people, company, contact, signals, web). The key is shown once."""
502
+ return self._c.request("POST", "/v1/keys", json={"name": name, "scopes": scopes})
503
+
504
+ def revoke(self, key_id: str) -> dict[str, Any]:
505
+ return self._c.request("DELETE", f"/v1/keys/{quote(key_id, safe='')}")
506
+
507
+
508
+ class _AsyncKeys:
509
+ def __init__(self, client: AsyncCernisData) -> None:
510
+ self._c = client
511
+
512
+ async def list(self) -> dict[str, Any]:
513
+ return await self._c.request("GET", "/v1/keys")
514
+
515
+ async def create(self, *, name: str | None = None, scopes: list[str] | None = None) -> dict[str, Any]:
516
+ return await self._c.request("POST", "/v1/keys", json={"name": name, "scopes": scopes})
517
+
518
+ async def revoke(self, key_id: str) -> dict[str, Any]:
519
+ return await self._c.request("DELETE", f"/v1/keys/{quote(key_id, safe='')}")
520
+
521
+
522
+ class _Billing:
523
+ def __init__(self, client: CernisData) -> None:
524
+ self._c = client
525
+
526
+ def checkout(self, *, amount_usd: float) -> dict[str, Any]:
527
+ """A checkout link to add credits."""
528
+ return self._c.request("POST", "/v1/billing/checkout", json={"amount_usd": amount_usd})
529
+
530
+
531
+ class _AsyncBilling:
532
+ def __init__(self, client: AsyncCernisData) -> None:
533
+ self._c = client
534
+
535
+ async def checkout(self, *, amount_usd: float) -> dict[str, Any]:
536
+ return await self._c.request("POST", "/v1/billing/checkout", json={"amount_usd": amount_usd})
537
+
538
+
539
+ class _Webhooks:
540
+ verify = staticmethod(verify_webhook)
541
+
542
+ def __init__(self, client: CernisData) -> None:
543
+ self._c = client
544
+
545
+ def secret(self) -> dict[str, Any]:
546
+ """The signing secret for job webhooks. Needs a full-access key."""
547
+ return self._c.request("GET", "/v1/webhooks/secret")
548
+
549
+ def rotate_secret(self) -> dict[str, Any]:
550
+ return self._c.request("POST", "/v1/webhooks/secret/rotate")
551
+
552
+ def deliveries(self) -> dict[str, Any]:
553
+ return self._c.request("GET", "/v1/webhooks/deliveries")
554
+
555
+
556
+ class _AsyncWebhooks:
557
+ verify = staticmethod(verify_webhook)
558
+
559
+ def __init__(self, client: AsyncCernisData) -> None:
560
+ self._c = client
561
+
562
+ async def secret(self) -> dict[str, Any]:
563
+ return await self._c.request("GET", "/v1/webhooks/secret")
564
+
565
+ async def rotate_secret(self) -> dict[str, Any]:
566
+ return await self._c.request("POST", "/v1/webhooks/secret/rotate")
567
+
568
+ async def deliveries(self) -> dict[str, Any]:
569
+ return await self._c.request("GET", "/v1/webhooks/deliveries")
570
+
571
+
572
+ # ---------------------------------------------------------------------------------------------------------------
573
+ # Clients
574
+
575
+
576
+ class CernisData(_BaseClient):
577
+ """Synchronous client.
578
+
579
+ ``CernisData()`` reads CERNIS_DATA_API_KEY and CERNIS_DATA_BASE_URL. Timeouts are in seconds.
580
+ """
581
+
582
+ people: People
583
+ companies: Companies
584
+ contacts: Contacts
585
+ signals: Signals
586
+ web: Web
587
+
588
+ verify_webhook = staticmethod(verify_webhook)
589
+
590
+ def __init__(
591
+ self,
592
+ api_key: str | None = None,
593
+ *,
594
+ base_url: str | None = None,
595
+ timeout: float = 60.0,
596
+ max_retries: int = 2,
597
+ wait_timeout: float = 300.0,
598
+ poll_interval: float = 1.0,
599
+ headers: Mapping[str, str] | None = None,
600
+ http_client: httpx.Client | None = None,
601
+ surface: str = "sdk",
602
+ ) -> None:
603
+ super().__init__(
604
+ api_key=api_key,
605
+ base_url=base_url,
606
+ surface=surface,
607
+ timeout=timeout,
608
+ max_retries=max_retries,
609
+ wait_timeout=wait_timeout,
610
+ poll_interval=poll_interval,
611
+ headers=headers,
612
+ )
613
+ self._owns_http = http_client is None
614
+ self._http = http_client or httpx.Client()
615
+ self._sleep: Callable[[float], None] = time.sleep
616
+ self.people = People(self)
617
+ self.companies = Companies(self)
618
+ self.contacts = Contacts(self)
619
+ self.signals = Signals(self)
620
+ self.web = Web(self)
621
+ self.requests = _Requests(self)
622
+ self.jobs = _Jobs(self)
623
+ self.keys = _Keys(self)
624
+ self.billing = _Billing(self)
625
+ self.webhooks = _Webhooks(self)
626
+
627
+ def close(self) -> None:
628
+ if self._owns_http:
629
+ self._http.close()
630
+
631
+ def __enter__(self) -> CernisData:
632
+ return self
633
+
634
+ def __exit__(self, *exc: object) -> None:
635
+ self.close()
636
+
637
+ # --- Low level ---------------------------------------------------------------------------------------------
638
+
639
+ def _send(self, method: str, path: str, **kw: Any) -> tuple[int, Any]:
640
+ a = self._attempts(method, path, **kw)
641
+ while True:
642
+ try:
643
+ resp = self._http.request(method, a.url, params=a.params, content=a.content, headers=a.next_headers(), timeout=a.timeout)
644
+ except httpx.TransportError as exc:
645
+ delay = a.on_exception(exc)
646
+ else:
647
+ out = a.on_response(resp.status_code, resp.text, resp.headers)
648
+ if isinstance(out, tuple):
649
+ return out
650
+ delay = out
651
+ self._sleep(delay)
652
+
653
+ def request(
654
+ self,
655
+ method: str,
656
+ path: str,
657
+ *,
658
+ query: Mapping[str, Any] | None = None,
659
+ json: Any = None,
660
+ idempotency_key: str | None = None,
661
+ timeout: float | None = None,
662
+ max_retries: int | None = None,
663
+ headers: Mapping[str, str] | None = None,
664
+ ) -> Any:
665
+ """Raw request against the API. Returns the parsed JSON body and raises a CernisDataError subclass on any non 2xx answer."""
666
+ body = None if json is None else {k: v for k, v in json.items() if v is not None} if isinstance(json, dict) else json
667
+ return self._send(
668
+ method.upper(), path, query=query, body=body, idempotency_key=idempotency_key, timeout=timeout, max_retries=max_retries, headers=headers
669
+ )[1]
670
+
671
+ def call(
672
+ self,
673
+ endpoint_id: str,
674
+ params: Mapping[str, Any] | None = None,
675
+ *,
676
+ wait: bool = False,
677
+ idempotency_key: str | None = None,
678
+ timeout: float | None = None,
679
+ max_retries: int | None = None,
680
+ ) -> Any:
681
+ """Call an endpoint by id, e.g. ``call("company.enrich", {"domain": "stripe.com"})``. No waiting unless ``wait=True``."""
682
+ e = self._endpoint(endpoint_id)
683
+ opts = {"idempotency_key": idempotency_key, "timeout": timeout, "max_retries": max_retries}
684
+ if wait:
685
+ return self._invoke(endpoint_id, params, wait=True, **opts)
686
+ method, path, kw = self._endpoint_request(e, params, opts)
687
+ return self._send(method, path, **kw)[1]
688
+
689
+ def _invoke(
690
+ self,
691
+ endpoint_id: str,
692
+ params: Mapping[str, Any] | None,
693
+ *,
694
+ wait: bool = True,
695
+ poll_interval: float | None = None,
696
+ wait_timeout: float | None = None,
697
+ idempotency_key: str | None = None,
698
+ timeout: float | None = None,
699
+ max_retries: int | None = None,
700
+ ) -> Any:
701
+ e = self._endpoint(endpoint_id)
702
+ method, path, kw = self._endpoint_request(e, params, {"idempotency_key": idempotency_key, "timeout": timeout, "max_retries": max_retries})
703
+ res = self._send(method, path, **kw)[1]
704
+ if e["mode"] == "job":
705
+ return Job(self, res)
706
+ if e["mode"] == "async" and wait and isinstance(res, dict) and res.get("status") == "pending" and res.get("job_id"):
707
+ return self._wait_for_request(res["job_id"], poll_interval, wait_timeout, max_retries)
708
+ return res
709
+
710
+ def _paginate(
711
+ self,
712
+ endpoint_id: str,
713
+ params: Mapping[str, Any] | None,
714
+ *,
715
+ max_items: int | None = None,
716
+ max_pages: int | None = None,
717
+ timeout: float | None = None,
718
+ max_retries: int | None = None,
719
+ ) -> Iterator[Any]:
720
+ e = self._endpoint(endpoint_id)
721
+ data = prepare_input(e, params)
722
+ cursor, count, pages = data.get("cursor"), 0, 0
723
+ while True:
724
+ method, path, kw = self._endpoint_request(e, {**data, "cursor": cursor}, {"timeout": timeout, "max_retries": max_retries})
725
+ page = self._send(method, path, **kw)[1]
726
+ items = _page_items(page)
727
+ for item in items:
728
+ yield item
729
+ count += 1
730
+ if max_items and count >= max_items:
731
+ return
732
+ pages += 1
733
+ cursor = _next_cursor(page)
734
+ if not cursor or not items or (max_pages and pages >= max_pages):
735
+ return
736
+
737
+ def _poll(self, check: Callable[[], R | None], poll_interval: float | None, wait_timeout: float | None, what: str) -> R:
738
+ _, expired = self._deadline(wait_timeout)
739
+ interval = poll_interval or self.poll_interval
740
+ while True:
741
+ r = check()
742
+ if r is not None:
743
+ return r
744
+ if expired(interval):
745
+ raise _wait_timeout_error(what)
746
+ self._sleep(interval)
747
+ interval = min(5.0, interval * 1.5)
748
+
749
+ def _wait_for_request(self, request_id: str, poll_interval: float | None, wait_timeout: float | None, max_retries: int | None) -> Envelope:
750
+ def check() -> Any:
751
+ status, body = self._send("GET", _job_path(request_id), max_retries=max_retries)
752
+ return None if _still_pending(status, body) else body
753
+
754
+ return self._poll(check, poll_interval, wait_timeout, f"Request {request_id}")
755
+
756
+ # --- Account ------------------------------------------------------------------------------------------------
757
+
758
+ def catalog(self) -> dict[str, Any]:
759
+ """Every endpoint with its price and status. No key needed."""
760
+ return self.request("GET", "/v1/catalog")
761
+
762
+ def wallet(self) -> Wallet:
763
+ """Balance and the free allowance (``free_requests``: limit, used, remaining)."""
764
+ return self.request("GET", "/v1/wallet")
765
+
766
+ def usage(self, *, days: int | None = None) -> dict[str, Any]:
767
+ """Requests and spend per endpoint per day."""
768
+ return self.request("GET", "/v1/usage", query={"days": days})
769
+
770
+ def job(self, job_id: str, *, after: int | None = None) -> JobStatus | Any:
771
+ """Raw status of a job or pending request. ``after`` pages through job items."""
772
+ return self.request("GET", _job_path(job_id), query={"after": after})
773
+
774
+ def wait(self, job_id: str, *, poll_interval: float | None = None, wait_timeout: float | None = None) -> Any:
775
+ """Poll a job or pending request until it is no longer pending and return its last raw response."""
776
+ def check() -> Any:
777
+ status, body = self._send("GET", _job_path(job_id))
778
+ return None if _still_pending(status, body) else body
779
+
780
+ return self._poll(check, poll_interval, wait_timeout, f"Job {job_id}")
781
+
782
+
783
+ class AsyncCernisData(_BaseClient):
784
+ """Asyncio client. Same API as CernisData, every call is awaited and iterators are ``async for``."""
785
+
786
+ people: AsyncPeople
787
+ companies: AsyncCompanies
788
+ contacts: AsyncContacts
789
+ signals: AsyncSignals
790
+ web: AsyncWeb
791
+
792
+ verify_webhook = staticmethod(verify_webhook)
793
+
794
+ def __init__(
795
+ self,
796
+ api_key: str | None = None,
797
+ *,
798
+ base_url: str | None = None,
799
+ timeout: float = 60.0,
800
+ max_retries: int = 2,
801
+ wait_timeout: float = 300.0,
802
+ poll_interval: float = 1.0,
803
+ headers: Mapping[str, str] | None = None,
804
+ http_client: httpx.AsyncClient | None = None,
805
+ surface: str = "sdk",
806
+ ) -> None:
807
+ super().__init__(
808
+ api_key=api_key,
809
+ base_url=base_url,
810
+ surface=surface,
811
+ timeout=timeout,
812
+ max_retries=max_retries,
813
+ wait_timeout=wait_timeout,
814
+ poll_interval=poll_interval,
815
+ headers=headers,
816
+ )
817
+ self._owns_http = http_client is None
818
+ self._http = http_client or httpx.AsyncClient()
819
+ self._sleep: Callable[[float], Awaitable[None]] = asyncio.sleep
820
+ self.people = AsyncPeople(self)
821
+ self.companies = AsyncCompanies(self)
822
+ self.contacts = AsyncContacts(self)
823
+ self.signals = AsyncSignals(self)
824
+ self.web = AsyncWeb(self)
825
+ self.requests = _AsyncRequests(self)
826
+ self.jobs = _AsyncJobs(self)
827
+ self.keys = _AsyncKeys(self)
828
+ self.billing = _AsyncBilling(self)
829
+ self.webhooks = _AsyncWebhooks(self)
830
+
831
+ async def close(self) -> None:
832
+ if self._owns_http:
833
+ await self._http.aclose()
834
+
835
+ async def __aenter__(self) -> AsyncCernisData:
836
+ return self
837
+
838
+ async def __aexit__(self, *exc: object) -> None:
839
+ await self.close()
840
+
841
+ async def _send(self, method: str, path: str, **kw: Any) -> tuple[int, Any]:
842
+ a = self._attempts(method, path, **kw)
843
+ while True:
844
+ try:
845
+ resp = await self._http.request(method, a.url, params=a.params, content=a.content, headers=a.next_headers(), timeout=a.timeout)
846
+ except httpx.TransportError as exc:
847
+ delay = a.on_exception(exc)
848
+ else:
849
+ out = a.on_response(resp.status_code, resp.text, resp.headers)
850
+ if isinstance(out, tuple):
851
+ return out
852
+ delay = out
853
+ await self._sleep(delay)
854
+
855
+ async def request(
856
+ self,
857
+ method: str,
858
+ path: str,
859
+ *,
860
+ query: Mapping[str, Any] | None = None,
861
+ json: Any = None,
862
+ idempotency_key: str | None = None,
863
+ timeout: float | None = None,
864
+ max_retries: int | None = None,
865
+ headers: Mapping[str, str] | None = None,
866
+ ) -> Any:
867
+ body = None if json is None else {k: v for k, v in json.items() if v is not None} if isinstance(json, dict) else json
868
+ return (
869
+ await self._send(
870
+ method.upper(), path, query=query, body=body, idempotency_key=idempotency_key, timeout=timeout, max_retries=max_retries, headers=headers
871
+ )
872
+ )[1]
873
+
874
+ async def call(
875
+ self,
876
+ endpoint_id: str,
877
+ params: Mapping[str, Any] | None = None,
878
+ *,
879
+ wait: bool = False,
880
+ idempotency_key: str | None = None,
881
+ timeout: float | None = None,
882
+ max_retries: int | None = None,
883
+ ) -> Any:
884
+ e = self._endpoint(endpoint_id)
885
+ opts = {"idempotency_key": idempotency_key, "timeout": timeout, "max_retries": max_retries}
886
+ if wait:
887
+ return await self._invoke(endpoint_id, params, wait=True, **opts)
888
+ method, path, kw = self._endpoint_request(e, params, opts)
889
+ return (await self._send(method, path, **kw))[1]
890
+
891
+ async def _invoke(
892
+ self,
893
+ endpoint_id: str,
894
+ params: Mapping[str, Any] | None,
895
+ *,
896
+ wait: bool = True,
897
+ poll_interval: float | None = None,
898
+ wait_timeout: float | None = None,
899
+ idempotency_key: str | None = None,
900
+ timeout: float | None = None,
901
+ max_retries: int | None = None,
902
+ ) -> Any:
903
+ e = self._endpoint(endpoint_id)
904
+ method, path, kw = self._endpoint_request(e, params, {"idempotency_key": idempotency_key, "timeout": timeout, "max_retries": max_retries})
905
+ res = (await self._send(method, path, **kw))[1]
906
+ if e["mode"] == "job":
907
+ return AsyncJob(self, res)
908
+ if e["mode"] == "async" and wait and isinstance(res, dict) and res.get("status") == "pending" and res.get("job_id"):
909
+ return await self._wait_for_request(res["job_id"], poll_interval, wait_timeout, max_retries)
910
+ return res
911
+
912
+ async def _paginate(
913
+ self,
914
+ endpoint_id: str,
915
+ params: Mapping[str, Any] | None,
916
+ *,
917
+ max_items: int | None = None,
918
+ max_pages: int | None = None,
919
+ timeout: float | None = None,
920
+ max_retries: int | None = None,
921
+ ) -> AsyncIterator[Any]:
922
+ e = self._endpoint(endpoint_id)
923
+ data = prepare_input(e, params)
924
+ cursor, count, pages = data.get("cursor"), 0, 0
925
+ while True:
926
+ method, path, kw = self._endpoint_request(e, {**data, "cursor": cursor}, {"timeout": timeout, "max_retries": max_retries})
927
+ page = (await self._send(method, path, **kw))[1]
928
+ items = _page_items(page)
929
+ for item in items:
930
+ yield item
931
+ count += 1
932
+ if max_items and count >= max_items:
933
+ return
934
+ pages += 1
935
+ cursor = _next_cursor(page)
936
+ if not cursor or not items or (max_pages and pages >= max_pages):
937
+ return
938
+
939
+ async def _poll(self, check: Callable[[], Awaitable[R | None]], poll_interval: float | None, wait_timeout: float | None, what: str) -> R:
940
+ _, expired = self._deadline(wait_timeout)
941
+ interval = poll_interval or self.poll_interval
942
+ while True:
943
+ r = await check()
944
+ if r is not None:
945
+ return r
946
+ if expired(interval):
947
+ raise _wait_timeout_error(what)
948
+ await self._sleep(interval)
949
+ interval = min(5.0, interval * 1.5)
950
+
951
+ async def _wait_for_request(self, request_id: str, poll_interval: float | None, wait_timeout: float | None, max_retries: int | None) -> Envelope:
952
+ async def check() -> Any:
953
+ status, body = await self._send("GET", _job_path(request_id), max_retries=max_retries)
954
+ return None if _still_pending(status, body) else body
955
+
956
+ return await self._poll(check, poll_interval, wait_timeout, f"Request {request_id}")
957
+
958
+ async def catalog(self) -> dict[str, Any]:
959
+ return await self.request("GET", "/v1/catalog")
960
+
961
+ async def wallet(self) -> Wallet:
962
+ return await self.request("GET", "/v1/wallet")
963
+
964
+ async def usage(self, *, days: int | None = None) -> dict[str, Any]:
965
+ return await self.request("GET", "/v1/usage", query={"days": days})
966
+
967
+ async def job(self, job_id: str, *, after: int | None = None) -> JobStatus | Any:
968
+ return await self.request("GET", _job_path(job_id), query={"after": after})
969
+
970
+ async def wait(self, job_id: str, *, poll_interval: float | None = None, wait_timeout: float | None = None) -> Any:
971
+ async def check() -> Any:
972
+ status, body = await self._send("GET", _job_path(job_id))
973
+ return None if _still_pending(status, body) else body
974
+
975
+ return await self._poll(check, poll_interval, wait_timeout, f"Job {job_id}")