verifyinboxes 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,364 @@
1
+ """The two clients: `VerifyInboxes` (sync) and `AsyncVerifyInboxes` (async), with the same surface."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import time
6
+ from types import TracebackType
7
+ from typing import Awaitable, Callable, List, Literal, Optional, Sequence, Type, Union, overload
8
+
9
+ import httpx
10
+
11
+ from ._base import (
12
+ CHECK_TIMEOUT,
13
+ DEFAULT_MAX_RETRIES,
14
+ DEFAULT_TIMEOUT,
15
+ MANY_TIMEOUT,
16
+ Answer,
17
+ BaseClient,
18
+ Call,
19
+ Destination,
20
+ Sink,
21
+ caller_interrupted,
22
+ check_timeout,
23
+ connection_error,
24
+ error_from_answer,
25
+ log_answer,
26
+ log_no_answer,
27
+ parse_body,
28
+ )
29
+ from ._exceptions import VerifyInboxesError
30
+ from ._models import PendingCheck, Result
31
+ from ._resources import (
32
+ AccountResource,
33
+ AsyncAccountResource,
34
+ AsyncChecks,
35
+ AsyncDomains,
36
+ AsyncFeedback,
37
+ AsyncIntegrations,
38
+ AsyncLists,
39
+ AsyncNotices,
40
+ AsyncSuppressions,
41
+ AsyncWebhooks,
42
+ Checks,
43
+ Domains,
44
+ Feedback,
45
+ Integrations,
46
+ Lists,
47
+ Notices,
48
+ Suppressions,
49
+ Webhooks,
50
+ )
51
+
52
+ __all__ = ["VerifyInboxes", "AsyncVerifyInboxes"]
53
+
54
+ class VerifyInboxes(BaseClient):
55
+ """The VerifyInboxes API.
56
+
57
+ client = VerifyInboxes() # reads VERIFYINBOXES_API_KEY
58
+ result = client.verify("ann@example.com")
59
+ print(result.verdict, result.safe_to_send)
60
+
61
+ `api_key` is an API key (`bv_...`) or a personal access token (`vi_at_...`); default: the `VERIFYINBOXES_API_KEY`
62
+ environment variable. `base_url` defaults to `VERIFYINBOXES_BASE_URL`, else `https://api.verifyinboxes.com`.
63
+ `timeout` is the seconds one attempt of one request may take (uploads and downloads: at least 600).
64
+ `max_retries` is how many times a request that failed in a way worth retrying is sent again. `user_agent` is your
65
+ product's token, such as `my-app/1.2`, put in front of the library's own in the User-Agent (visible ASCII, no
66
+ space). `http_client` is your own `httpx.Client` (a proxy, TLS settings); the library does not close a client it
67
+ did not make.
68
+ """
69
+
70
+ def __init__(
71
+ self,
72
+ api_key: Optional[str] = None,
73
+ *,
74
+ base_url: Optional[str] = None,
75
+ timeout: Optional[float] = DEFAULT_TIMEOUT,
76
+ max_retries: int = DEFAULT_MAX_RETRIES,
77
+ user_agent: Optional[str] = None,
78
+ http_client: Optional[httpx.Client] = None,
79
+ ) -> None:
80
+ super().__init__(api_key=api_key, base_url=base_url, timeout=timeout, max_retries=max_retries,
81
+ user_agent=user_agent)
82
+ self._owns_http = http_client is None
83
+ self._http = http_client if http_client is not None else httpx.Client(follow_redirects=False)
84
+ # The waits and the clock, replaced by the tests only.
85
+ self._sleep: Callable[[float], None] = time.sleep
86
+ self._clock: Callable[[], float] = time.monotonic
87
+ self.account = AccountResource(self)
88
+ self.checks = Checks(self)
89
+ self.lists = Lists(self)
90
+ self.domains = Domains(self)
91
+ self.suppressions = Suppressions(self)
92
+ self.webhooks = Webhooks(self)
93
+ self.notices = Notices(self)
94
+ self.feedback = Feedback(self)
95
+ self.integrations = Integrations(self)
96
+
97
+ # --- checks ---------------------------------------------------------------------------------------------------
98
+
99
+ @overload
100
+ def verify(self, email: str, *, force_recheck: bool = ..., wait: Literal[True] = ...,
101
+ timeout: Optional[float] = ..., idempotency_key: Optional[str] = ...) -> Result: ...
102
+
103
+ @overload
104
+ def verify(self, email: str, *, force_recheck: bool = ..., wait: bool,
105
+ timeout: Optional[float] = ..., idempotency_key: Optional[str] = ...) -> Union[Result, PendingCheck]: ...
106
+
107
+ def verify(self, email: str, *, force_recheck: bool = False, wait: bool = True,
108
+ timeout: Optional[float] = CHECK_TIMEOUT, idempotency_key: Optional[str] = None) -> Union[Result, PendingCheck]:
109
+ """Check one address and return its result (`job_id` names the check's job).
110
+
111
+ The API answers within about 5 seconds, or says the check is still running: then it is asked every 2 seconds
112
+ until done. After `timeout` seconds (`None`: no limit) `WaitTimeoutError` is raised with the job's id in
113
+ `job_ids`: the check carries on, and `client.checks.wait(job_id)` picks it up. `wait=False` returns a
114
+ `PendingCheck` instead of waiting. `force_recheck` skips the cache.
115
+
116
+ For many addresses use `verify_many` or a list, never a loop of `verify`.
117
+ """
118
+ timeout = check_timeout("timeout", timeout)
119
+ deadline = None if timeout is None else self._clock() + timeout
120
+ return self.checks._verify(email, force_recheck=force_recheck, wait=wait, deadline=deadline, timeout=timeout,
121
+ idempotency_key=idempotency_key)
122
+
123
+ def verify_many(self, emails: Sequence[str], *, timeout: Optional[float] = MANY_TIMEOUT) -> List[Result]:
124
+ """Check several addresses and return their results in the same order.
125
+
126
+ Up to 10 are checked one by one, together. More go as one list (one `POST /v1/jobs`), waited for and read
127
+ back: each result's `job_id` is then the list's. A few hundred addresses take minutes, Microsoft-hosted ones
128
+ longer; raise `timeout` (seconds, default 600) to match. An error names every job the call made in `job_ids`,
129
+ so nothing is lost: wait for them with `checks.wait` or `lists.wait`.
130
+ """
131
+ return self.checks._many(emails, timeout)
132
+
133
+ # --- transport ------------------------------------------------------------------------------------------------
134
+
135
+ def _request(self, call: Call) -> Answer:
136
+ attempt = 0
137
+ unanswered = False
138
+ while True:
139
+ error: VerifyInboxesError
140
+ never_sent = False
141
+ closer = None
142
+ try:
143
+ extra = content = None
144
+ if call.upload is not None:
145
+ extra, content, closer = call.upload.sync_body()
146
+ response = self._http.request(
147
+ call.method, self._url(call.path), params=call.params,
148
+ json=call.json if call.upload is None else None, content=content,
149
+ headers=self._headers(call, extra), timeout=self._timeout(call),
150
+ )
151
+ except httpx.TransportError as exc:
152
+ log_no_answer(call, attempt, exc)
153
+ error, never_sent = connection_error(exc)
154
+ error.__cause__ = exc
155
+ unanswered = True
156
+ else:
157
+ request_id = response.headers.get("x-request-id")
158
+ log_answer(call, attempt, response.status_code, request_id)
159
+ if response.is_success:
160
+ return Answer(response.status_code, request_id,
161
+ parse_body(response.status_code, response.headers, response.content))
162
+ if call.gone_is_done and unanswered and response.status_code == 404:
163
+ return Answer(response.status_code, request_id, None)
164
+ error = error_from_answer(response.status_code, response.headers, response.content)
165
+ finally:
166
+ if closer is not None:
167
+ closer.close()
168
+ delay = self._retry_delay(call, error, attempt, never_sent=never_sent)
169
+ if delay is None:
170
+ raise error
171
+ self._sleep(delay)
172
+ if caller_interrupted():
173
+ raise error # interrupted during the pause: nothing more is sent
174
+ attempt += 1
175
+
176
+ def _download(self, call: Call, destination: Destination) -> int:
177
+ sink = Sink(destination)
178
+ attempt = 0
179
+ while True:
180
+ error: VerifyInboxesError
181
+ never_sent = False
182
+ try:
183
+ with self._http.stream("GET", self._url(call.path), params=call.params, headers=self._headers(call),
184
+ timeout=self._timeout(call)) as response:
185
+ log_answer(call, attempt, response.status_code, response.headers.get("x-request-id"))
186
+ if response.is_success:
187
+ sink.begin()
188
+ for chunk in response.iter_bytes():
189
+ sink.write(chunk)
190
+ return sink.commit()
191
+ error = error_from_answer(response.status_code, response.headers, response.read())
192
+ except httpx.TransportError as exc:
193
+ sink.abort()
194
+ log_no_answer(call, attempt, exc)
195
+ error, never_sent = connection_error(exc)
196
+ error.__cause__ = exc
197
+ except BaseException:
198
+ sink.abort()
199
+ raise
200
+ if not sink.resendable:
201
+ raise error
202
+ delay = self._retry_delay(call, error, attempt, never_sent=never_sent)
203
+ if delay is None:
204
+ raise error
205
+ self._sleep(delay)
206
+ attempt += 1
207
+
208
+ # --- lifetime -------------------------------------------------------------------------------------------------
209
+
210
+ def close(self) -> None:
211
+ """Close the connections. Not needed when the client is used as a context manager."""
212
+ if self._owns_http:
213
+ self._http.close()
214
+
215
+ def __enter__(self) -> "VerifyInboxes":
216
+ return self
217
+
218
+ def __exit__(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException],
219
+ tb: Optional[TracebackType]) -> None:
220
+ self.close()
221
+
222
+
223
+ class AsyncVerifyInboxes(BaseClient):
224
+ """The VerifyInboxes API, for `asyncio`: the same surface as `VerifyInboxes`, every call awaited.
225
+
226
+ async with AsyncVerifyInboxes() as client:
227
+ result = await client.verify("ann@example.com")
228
+ async for row in client.lists.results(job_id):
229
+ ...
230
+ """
231
+
232
+ def __init__(
233
+ self,
234
+ api_key: Optional[str] = None,
235
+ *,
236
+ base_url: Optional[str] = None,
237
+ timeout: Optional[float] = DEFAULT_TIMEOUT,
238
+ max_retries: int = DEFAULT_MAX_RETRIES,
239
+ user_agent: Optional[str] = None,
240
+ http_client: Optional[httpx.AsyncClient] = None,
241
+ ) -> None:
242
+ super().__init__(api_key=api_key, base_url=base_url, timeout=timeout, max_retries=max_retries,
243
+ user_agent=user_agent)
244
+ self._owns_http = http_client is None
245
+ self._http = http_client if http_client is not None else httpx.AsyncClient(follow_redirects=False)
246
+ # The waits and the clock, replaced by the tests only.
247
+ self._sleep: Callable[[float], Awaitable[None]] = asyncio.sleep
248
+ self._clock: Callable[[], float] = time.monotonic
249
+ self.account = AsyncAccountResource(self)
250
+ self.checks = AsyncChecks(self)
251
+ self.lists = AsyncLists(self)
252
+ self.domains = AsyncDomains(self)
253
+ self.suppressions = AsyncSuppressions(self)
254
+ self.webhooks = AsyncWebhooks(self)
255
+ self.notices = AsyncNotices(self)
256
+ self.feedback = AsyncFeedback(self)
257
+ self.integrations = AsyncIntegrations(self)
258
+
259
+ @overload
260
+ async def verify(self, email: str, *, force_recheck: bool = ..., wait: Literal[True] = ...,
261
+ timeout: Optional[float] = ..., idempotency_key: Optional[str] = ...) -> Result: ...
262
+
263
+ @overload
264
+ async def verify(self, email: str, *, force_recheck: bool = ..., wait: bool,
265
+ timeout: Optional[float] = ..., idempotency_key: Optional[str] = ...) -> Union[Result, PendingCheck]: ...
266
+
267
+ async def verify(self, email: str, *, force_recheck: bool = False, wait: bool = True,
268
+ timeout: Optional[float] = CHECK_TIMEOUT,
269
+ idempotency_key: Optional[str] = None) -> Union[Result, PendingCheck]:
270
+ """Check one address and return its result (see `VerifyInboxes.verify`)."""
271
+ timeout = check_timeout("timeout", timeout)
272
+ deadline = None if timeout is None else self._clock() + timeout
273
+ return await self.checks._verify(email, force_recheck=force_recheck, wait=wait, deadline=deadline,
274
+ timeout=timeout, idempotency_key=idempotency_key)
275
+
276
+ async def verify_many(self, emails: Sequence[str], *, timeout: Optional[float] = MANY_TIMEOUT) -> List[Result]:
277
+ """Check several addresses and return their results in the same order (see `VerifyInboxes.verify_many`); up
278
+ to 10 are sent together with `asyncio.gather`."""
279
+ return await self.checks._many(emails, timeout)
280
+
281
+ async def _request(self, call: Call) -> Answer:
282
+ attempt = 0
283
+ unanswered = False
284
+ while True:
285
+ error: VerifyInboxesError
286
+ never_sent = False
287
+ closer = None
288
+ try:
289
+ extra = content = None
290
+ if call.upload is not None:
291
+ extra, content, closer = call.upload.async_body()
292
+ response = await self._http.request(
293
+ call.method, self._url(call.path), params=call.params,
294
+ json=call.json if call.upload is None else None, content=content,
295
+ headers=self._headers(call, extra), timeout=self._timeout(call),
296
+ )
297
+ except httpx.TransportError as exc:
298
+ log_no_answer(call, attempt, exc)
299
+ error, never_sent = connection_error(exc)
300
+ error.__cause__ = exc
301
+ unanswered = True
302
+ else:
303
+ request_id = response.headers.get("x-request-id")
304
+ log_answer(call, attempt, response.status_code, request_id)
305
+ if response.is_success:
306
+ return Answer(response.status_code, request_id,
307
+ parse_body(response.status_code, response.headers, response.content))
308
+ if call.gone_is_done and unanswered and response.status_code == 404:
309
+ return Answer(response.status_code, request_id, None)
310
+ error = error_from_answer(response.status_code, response.headers, response.content)
311
+ finally:
312
+ if closer is not None:
313
+ closer.close()
314
+ delay = self._retry_delay(call, error, attempt, never_sent=never_sent)
315
+ if delay is None:
316
+ raise error
317
+ await self._sleep(delay)
318
+ if caller_interrupted():
319
+ raise error # interrupted during the pause: nothing more is sent
320
+ attempt += 1
321
+
322
+ async def _download(self, call: Call, destination: Destination) -> int:
323
+ sink = Sink(destination)
324
+ attempt = 0
325
+ while True:
326
+ error: VerifyInboxesError
327
+ never_sent = False
328
+ try:
329
+ async with self._http.stream("GET", self._url(call.path), params=call.params,
330
+ headers=self._headers(call), timeout=self._timeout(call)) as response:
331
+ log_answer(call, attempt, response.status_code, response.headers.get("x-request-id"))
332
+ if response.is_success:
333
+ sink.begin()
334
+ async for chunk in response.aiter_bytes():
335
+ sink.write(chunk)
336
+ return sink.commit()
337
+ error = error_from_answer(response.status_code, response.headers, await response.aread())
338
+ except httpx.TransportError as exc:
339
+ sink.abort()
340
+ log_no_answer(call, attempt, exc)
341
+ error, never_sent = connection_error(exc)
342
+ error.__cause__ = exc
343
+ except BaseException:
344
+ sink.abort()
345
+ raise
346
+ if not sink.resendable:
347
+ raise error
348
+ delay = self._retry_delay(call, error, attempt, never_sent=never_sent)
349
+ if delay is None:
350
+ raise error
351
+ await self._sleep(delay)
352
+ attempt += 1
353
+
354
+ async def close(self) -> None:
355
+ """Close the connections. Not needed when the client is used as a context manager."""
356
+ if self._owns_http:
357
+ await self._http.aclose()
358
+
359
+ async def __aenter__(self) -> "AsyncVerifyInboxes":
360
+ return self
361
+
362
+ async def __aexit__(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException],
363
+ tb: Optional[TracebackType]) -> None:
364
+ await self.close()
@@ -0,0 +1,164 @@
1
+ """Everything this library raises.
2
+
3
+ VerifyInboxesError the base of all; also "the API broke its own rules"
4
+ ├── MissingAPIKeyError no key given and VERIFYINBOXES_API_KEY not set
5
+ ├── APIConnectionError the request got no answer
6
+ │ └── APITimeoutError ... in time
7
+ ├── APIError the API answered with an error (any other 4xx)
8
+ │ ├── InvalidRequestError 400, 413, 414, 415, 422
9
+ │ ├── AuthenticationError 401
10
+ │ ├── InsufficientCreditsError 402
11
+ │ ├── PermissionDeniedError 403
12
+ │ ├── NotFoundError 404, 410
13
+ │ ├── ConflictError 409
14
+ │ ├── RateLimitError 429
15
+ │ └── ServerError 5xx
16
+ └── WaitTimeoutError a check or a list was still running when the time to wait ran out
17
+
18
+ Every error has `job_ids`: the jobs the call had made when it failed (a check that timed out, a list being waited
19
+ for), so the credits they hold are never lost: wait for them again with `checks.wait` or `lists.wait`.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type, TypeVar
24
+
25
+ __all__ = [
26
+ "VerifyInboxesError",
27
+ "MissingAPIKeyError",
28
+ "APIConnectionError",
29
+ "APITimeoutError",
30
+ "APIError",
31
+ "InvalidRequestError",
32
+ "AuthenticationError",
33
+ "InsufficientCreditsError",
34
+ "PermissionDeniedError",
35
+ "NotFoundError",
36
+ "ConflictError",
37
+ "RateLimitError",
38
+ "ServerError",
39
+ "WaitTimeoutError",
40
+ ]
41
+
42
+
43
+ class VerifyInboxesError(Exception):
44
+ """The base of every error this library raises. Raised as itself when the API answered something it should not
45
+ have (a page that repeats its cursor, a finished check with no result)."""
46
+
47
+ def __init__(self, message: str, *, job_ids: Optional[Sequence[str]] = None) -> None:
48
+ super().__init__(message)
49
+ self.message = message
50
+ self.job_ids: List[str] = list(job_ids or [])
51
+ """The jobs the call had made when it failed, in the order of its input."""
52
+
53
+ def __reduce__(self) -> Tuple[Callable[..., Any], Tuple[Any, ...]]:
54
+ # Rebuilt without calling __init__ (whose keyword-only arguments pickle cannot give), with every attribute
55
+ # back: an error that crosses a process (a ProcessPoolExecutor, a task queue) or is copied keeps its job ids
56
+ # and request id.
57
+ return _rebuild, (type(self), self.args, dict(self.__dict__))
58
+
59
+
60
+ E = TypeVar("E", bound=VerifyInboxesError)
61
+
62
+
63
+ def _rebuild(cls: Type[E], args: Tuple[Any, ...], state: Dict[str, Any]) -> E:
64
+ """An error as `pickle` and `copy` make it again: through `__new__`, then its attributes."""
65
+ error = cls.__new__(cls, *args)
66
+ error.__dict__.update(state)
67
+ return error
68
+
69
+
70
+ class MissingAPIKeyError(VerifyInboxesError):
71
+ """No API key was given and `VERIFYINBOXES_API_KEY` is not set."""
72
+
73
+
74
+ class APIConnectionError(VerifyInboxesError):
75
+ """The request got no answer: the connection could not be made, or it was closed or reset before the whole answer
76
+ came. A request the API may have run is only sent again when that is safe (see the README's "Retries")."""
77
+
78
+ def __init__(self, message: str = "Could not reach the VerifyInboxes API.", *,
79
+ job_ids: Optional[Sequence[str]] = None) -> None:
80
+ super().__init__(message, job_ids=job_ids)
81
+
82
+
83
+ class APITimeoutError(APIConnectionError):
84
+ """The request got no answer in time."""
85
+
86
+ def __init__(self, message: str = "The VerifyInboxes API did not answer in time.", *,
87
+ job_ids: Optional[Sequence[str]] = None) -> None:
88
+ super().__init__(message, job_ids=job_ids)
89
+
90
+
91
+ class APIError(VerifyInboxesError):
92
+ """The API answered with an error status.
93
+
94
+ `code` is the API's stable error code (`unauthorized`, `not_ready`, `consumer_list`, ...): match on it, and treat
95
+ one you do not know by its `status`. `message` is a sentence for a person. `request_id` is the answer's
96
+ `X-Request-Id`: quote it when you write to support. `retry_after` is the answer's `Retry-After` in seconds.
97
+ """
98
+
99
+ def __init__(
100
+ self,
101
+ message: str,
102
+ *,
103
+ status: int,
104
+ code: Optional[str] = None,
105
+ request_id: Optional[str] = None,
106
+ retry_after: Optional[float] = None,
107
+ body: Any = None,
108
+ job_ids: Optional[Sequence[str]] = None,
109
+ ) -> None:
110
+ super().__init__(message, job_ids=job_ids)
111
+ self.status = status
112
+ self.code = code
113
+ self.request_id = request_id
114
+ self.retry_after = retry_after
115
+ self.body = body
116
+ """The answer's JSON body (its text when it is not JSON)."""
117
+
118
+ def __str__(self) -> str:
119
+ head = f"{self.status} {self.code}" if self.code else f"{self.status}"
120
+ text = f"{head}: {self.message}"
121
+ if self.request_id:
122
+ text += f" (request id {self.request_id})"
123
+ return text
124
+
125
+
126
+ class InvalidRequestError(APIError):
127
+ """400, 413, 414, 415 or 422: the request does not fit (`invalid_request`, `consumer_list`, `empty_list`, ...)."""
128
+
129
+
130
+ class AuthenticationError(APIError):
131
+ """401: the key or token is missing, mistyped, revoked, or (a personal access token) past its hour."""
132
+
133
+
134
+ class InsufficientCreditsError(APIError):
135
+ """402 `insufficient_credits`: the balance does not cover the request. Nothing was charged."""
136
+
137
+
138
+ class PermissionDeniedError(APIError):
139
+ """403: allowed for nobody with this credential (`forbidden`, `review_required`, `account_suspended`, ...)."""
140
+
141
+
142
+ class NotFoundError(APIError):
143
+ """404 `not_found`, or 410 `gone` (a list whose data was deleted)."""
144
+
145
+
146
+ class ConflictError(APIError):
147
+ """409: `not_ready` (the list has not finished), `idempotency_conflict` (the key was used for another request)."""
148
+
149
+
150
+ class RateLimitError(APIError):
151
+ """429: too many requests or lists at once. Retried on its own, unless `retry_after` is over 60 seconds."""
152
+
153
+
154
+ class ServerError(APIError):
155
+ """5xx: something went wrong on the API's side. Retried on its own; this is the last answer's."""
156
+
157
+
158
+ class WaitTimeoutError(VerifyInboxesError):
159
+ """A check or a list was still running when the time given to wait ran out. It carries on, and its credits are
160
+ held: wait for it again by its id (`job_ids`) with `checks.wait` or `lists.wait`."""
161
+
162
+ def __init__(self, message: str, *, job_ids: Sequence[str], timeout: Optional[float]) -> None:
163
+ super().__init__(message, job_ids=job_ids)
164
+ self.timeout = timeout