verifnow 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.
- verifnow/__init__.py +84 -0
- verifnow/_async.py +86 -0
- verifnow/_client.py +403 -0
- verifnow/_errors.py +85 -0
- verifnow/_models.py +499 -0
- verifnow/_transport.py +91 -0
- verifnow/_version.py +8 -0
- verifnow/py.typed +0 -0
- verifnow-0.1.0.dist-info/METADATA +355 -0
- verifnow-0.1.0.dist-info/RECORD +12 -0
- verifnow-0.1.0.dist-info/WHEEL +4 -0
- verifnow-0.1.0.dist-info/licenses/LICENSE +72 -0
verifnow/__init__.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Official Python SDK for the VerifNow validation API.
|
|
2
|
+
|
|
3
|
+
Email, phone, IBAN, VAT, SSN, SIN and NIF validation with one API key. https://www.verifnow.io
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from ._async import AsyncVerifNow
|
|
7
|
+
from ._client import RetryPolicy, VerifNow
|
|
8
|
+
from ._errors import (
|
|
9
|
+
VerifNowAuthError,
|
|
10
|
+
VerifNowConnectionError,
|
|
11
|
+
VerifNowError,
|
|
12
|
+
VerifNowRateLimitError,
|
|
13
|
+
VerifNowRequestError,
|
|
14
|
+
VerifNowResponseError,
|
|
15
|
+
VerifNowServerError,
|
|
16
|
+
)
|
|
17
|
+
from ._models import (
|
|
18
|
+
VALIDATION_RULES,
|
|
19
|
+
CountryVatRates,
|
|
20
|
+
Deliverability,
|
|
21
|
+
EmailDetails,
|
|
22
|
+
EmailSignals,
|
|
23
|
+
IbanDetails,
|
|
24
|
+
NasDetails,
|
|
25
|
+
NifDetails,
|
|
26
|
+
NifType,
|
|
27
|
+
PhoneDetails,
|
|
28
|
+
PhoneLineType,
|
|
29
|
+
QuotaInfo,
|
|
30
|
+
RegionalVatRate,
|
|
31
|
+
RiskLevel,
|
|
32
|
+
SsnDetails,
|
|
33
|
+
TraderNameMatch,
|
|
34
|
+
TraderNameMatchSource,
|
|
35
|
+
ValidationLevel,
|
|
36
|
+
ValidationResult,
|
|
37
|
+
ValidationRule,
|
|
38
|
+
VatDetails,
|
|
39
|
+
VatRates,
|
|
40
|
+
VatSource,
|
|
41
|
+
)
|
|
42
|
+
from ._transport import HttpRequest, HttpResponse, Transport, TransportError
|
|
43
|
+
from ._version import __version__
|
|
44
|
+
|
|
45
|
+
__all__ = [
|
|
46
|
+
"VALIDATION_RULES",
|
|
47
|
+
"AsyncVerifNow",
|
|
48
|
+
"CountryVatRates",
|
|
49
|
+
"Deliverability",
|
|
50
|
+
"EmailDetails",
|
|
51
|
+
"EmailSignals",
|
|
52
|
+
"HttpRequest",
|
|
53
|
+
"HttpResponse",
|
|
54
|
+
"IbanDetails",
|
|
55
|
+
"NasDetails",
|
|
56
|
+
"NifDetails",
|
|
57
|
+
"NifType",
|
|
58
|
+
"PhoneDetails",
|
|
59
|
+
"PhoneLineType",
|
|
60
|
+
"QuotaInfo",
|
|
61
|
+
"RegionalVatRate",
|
|
62
|
+
"RetryPolicy",
|
|
63
|
+
"RiskLevel",
|
|
64
|
+
"SsnDetails",
|
|
65
|
+
"TraderNameMatch",
|
|
66
|
+
"TraderNameMatchSource",
|
|
67
|
+
"Transport",
|
|
68
|
+
"TransportError",
|
|
69
|
+
"ValidationLevel",
|
|
70
|
+
"ValidationResult",
|
|
71
|
+
"ValidationRule",
|
|
72
|
+
"VatDetails",
|
|
73
|
+
"VatRates",
|
|
74
|
+
"VatSource",
|
|
75
|
+
"VerifNow",
|
|
76
|
+
"VerifNowAuthError",
|
|
77
|
+
"VerifNowConnectionError",
|
|
78
|
+
"VerifNowError",
|
|
79
|
+
"VerifNowRateLimitError",
|
|
80
|
+
"VerifNowRequestError",
|
|
81
|
+
"VerifNowResponseError",
|
|
82
|
+
"VerifNowServerError",
|
|
83
|
+
"__version__",
|
|
84
|
+
]
|
verifnow/_async.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""The asyncio client.
|
|
2
|
+
|
|
3
|
+
It runs the synchronous client in a worker thread (``asyncio.to_thread``) rather than shipping its
|
|
4
|
+
own async HTTP stack: that keeps the package free of runtime dependencies, and a validation call
|
|
5
|
+
spends its time waiting on the network, which a thread does as well as a coroutine. Retries and
|
|
6
|
+
backoff happen in the worker thread, so they never block the event loop.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
|
|
14
|
+
from ._client import DEFAULT_BASE_URL, DEFAULT_TIMEOUT, RetryPolicy, VerifNow
|
|
15
|
+
from ._models import CountryVatRates, ValidationResult, ValidationRule, VatRates
|
|
16
|
+
from ._transport import Transport
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class AsyncVerifNow:
|
|
20
|
+
"""Asyncio client for the VerifNow validation API. Same methods as ``VerifNow``, awaitable.
|
|
21
|
+
|
|
22
|
+
>>> client = AsyncVerifNow() # reads VERIFNOW_API_KEY
|
|
23
|
+
>>> result = await client.validate_vat("IE6388047V")
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
api_key: str | None = None,
|
|
29
|
+
*,
|
|
30
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
31
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
32
|
+
retry: RetryPolicy | None = RetryPolicy(), # noqa: B008 - frozen, safe to share
|
|
33
|
+
headers: Mapping[str, str] | None = None,
|
|
34
|
+
transport: Transport | None = None,
|
|
35
|
+
) -> None:
|
|
36
|
+
self._sync = VerifNow(
|
|
37
|
+
api_key,
|
|
38
|
+
base_url=base_url,
|
|
39
|
+
timeout=timeout,
|
|
40
|
+
retry=retry,
|
|
41
|
+
headers=headers,
|
|
42
|
+
transport=transport,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
def __repr__(self) -> str:
|
|
46
|
+
return f"Async{self._sync!r}"
|
|
47
|
+
|
|
48
|
+
async def validate_email(self, value: str, *, timeout: float | None = None) -> ValidationResult:
|
|
49
|
+
return await asyncio.to_thread(self._sync.validate_email, value, timeout=timeout)
|
|
50
|
+
|
|
51
|
+
async def validate_phone(self, value: str, *, timeout: float | None = None) -> ValidationResult:
|
|
52
|
+
return await asyncio.to_thread(self._sync.validate_phone, value, timeout=timeout)
|
|
53
|
+
|
|
54
|
+
async def validate_iban(self, value: str, *, timeout: float | None = None) -> ValidationResult:
|
|
55
|
+
return await asyncio.to_thread(self._sync.validate_iban, value, timeout=timeout)
|
|
56
|
+
|
|
57
|
+
async def validate_vat(
|
|
58
|
+
self,
|
|
59
|
+
value: str,
|
|
60
|
+
*,
|
|
61
|
+
trader_name: str | None = None,
|
|
62
|
+
timeout: float | None = None,
|
|
63
|
+
) -> ValidationResult:
|
|
64
|
+
return await asyncio.to_thread(
|
|
65
|
+
self._sync.validate_vat, value, trader_name=trader_name, timeout=timeout
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
async def validate_nas(self, value: str, *, timeout: float | None = None) -> ValidationResult:
|
|
69
|
+
return await asyncio.to_thread(self._sync.validate_nas, value, timeout=timeout)
|
|
70
|
+
|
|
71
|
+
async def validate_ssn(self, value: str, *, timeout: float | None = None) -> ValidationResult:
|
|
72
|
+
return await asyncio.to_thread(self._sync.validate_ssn, value, timeout=timeout)
|
|
73
|
+
|
|
74
|
+
async def validate_nif(self, value: str, *, timeout: float | None = None) -> ValidationResult:
|
|
75
|
+
return await asyncio.to_thread(self._sync.validate_nif, value, timeout=timeout)
|
|
76
|
+
|
|
77
|
+
async def validate(
|
|
78
|
+
self, rule: ValidationRule, value: str, *, timeout: float | None = None
|
|
79
|
+
) -> ValidationResult:
|
|
80
|
+
return await asyncio.to_thread(self._sync.validate, rule, value, timeout=timeout)
|
|
81
|
+
|
|
82
|
+
async def vat_rates(self, *, timeout: float | None = None) -> VatRates:
|
|
83
|
+
return await asyncio.to_thread(self._sync.vat_rates, timeout=timeout)
|
|
84
|
+
|
|
85
|
+
async def vat_rate(self, country_code: str, *, timeout: float | None = None) -> CountryVatRates:
|
|
86
|
+
return await asyncio.to_thread(self._sync.vat_rate, country_code, timeout=timeout)
|
verifnow/_client.py
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
"""The synchronous client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import time
|
|
9
|
+
from collections.abc import Callable, Mapping
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from email.utils import parsedate_to_datetime
|
|
13
|
+
from typing import Any, Final, TypeVar
|
|
14
|
+
from urllib.parse import quote
|
|
15
|
+
|
|
16
|
+
from ._errors import (
|
|
17
|
+
VerifNowAuthError,
|
|
18
|
+
VerifNowConnectionError,
|
|
19
|
+
VerifNowError,
|
|
20
|
+
VerifNowRateLimitError,
|
|
21
|
+
VerifNowRequestError,
|
|
22
|
+
VerifNowResponseError,
|
|
23
|
+
VerifNowServerError,
|
|
24
|
+
)
|
|
25
|
+
from ._models import (
|
|
26
|
+
VALIDATION_RULES,
|
|
27
|
+
CountryVatRates,
|
|
28
|
+
QuotaInfo,
|
|
29
|
+
ValidationResult,
|
|
30
|
+
ValidationRule,
|
|
31
|
+
VatRates,
|
|
32
|
+
parse_country_vat_rates,
|
|
33
|
+
parse_validation_result,
|
|
34
|
+
parse_vat_rates,
|
|
35
|
+
)
|
|
36
|
+
from ._transport import HttpRequest, HttpResponse, Transport, TransportError, urllib_transport
|
|
37
|
+
from ._version import __version__
|
|
38
|
+
|
|
39
|
+
DEFAULT_BASE_URL: Final = "https://api.verifnow.io"
|
|
40
|
+
DEFAULT_TIMEOUT: Final = 5.0
|
|
41
|
+
API_KEY_ENV: Final = "VERIFNOW_API_KEY"
|
|
42
|
+
|
|
43
|
+
T = TypeVar("T")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True, slots=True)
|
|
47
|
+
class RetryPolicy:
|
|
48
|
+
"""Retries for connection failures, timeouts, 5xx and short 429s.
|
|
49
|
+
|
|
50
|
+
``attempts`` is the number of retries after the first failure, so the default makes up to three
|
|
51
|
+
requests. Delays are in seconds and double each attempt, capped at ``max_backoff``.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
attempts: int = 2
|
|
55
|
+
backoff: float = 0.2
|
|
56
|
+
max_backoff: float = 2.0
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class VerifNow:
|
|
60
|
+
"""Client for the VerifNow validation API.
|
|
61
|
+
|
|
62
|
+
>>> from verifnow import VerifNow
|
|
63
|
+
>>> client = VerifNow() # reads VERIFNOW_API_KEY
|
|
64
|
+
>>> result = client.validate_email("user@exmaple.com")
|
|
65
|
+
>>> result.valid, result.email_details.signals.suggested_domain
|
|
66
|
+
(False, 'example.com')
|
|
67
|
+
|
|
68
|
+
The client holds no per-request state: create one and share it across threads.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def __init__(
|
|
72
|
+
self,
|
|
73
|
+
api_key: str | None = None,
|
|
74
|
+
*,
|
|
75
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
76
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
77
|
+
retry: RetryPolicy | None = RetryPolicy(),
|
|
78
|
+
headers: Mapping[str, str] | None = None,
|
|
79
|
+
transport: Transport | None = None,
|
|
80
|
+
) -> None:
|
|
81
|
+
"""Create a client.
|
|
82
|
+
|
|
83
|
+
``api_key`` defaults to the ``VERIFNOW_API_KEY`` environment variable.
|
|
84
|
+
``timeout`` applies to each attempt, in seconds. Pass ``retry=None`` to disable retries.
|
|
85
|
+
``headers`` are added to every request. ``transport`` replaces the ``urllib`` one, for
|
|
86
|
+
tests or custom networking.
|
|
87
|
+
"""
|
|
88
|
+
key = api_key if api_key is not None else os.environ.get(API_KEY_ENV)
|
|
89
|
+
if key is None or not key.strip():
|
|
90
|
+
raise VerifNowError(
|
|
91
|
+
"A VerifNow API key is required. Create one at https://app.verifnow.io and pass it "
|
|
92
|
+
f"as `api_key`, or set the {API_KEY_ENV} environment variable."
|
|
93
|
+
)
|
|
94
|
+
if timeout <= 0:
|
|
95
|
+
raise ValueError("timeout must be a positive number of seconds")
|
|
96
|
+
|
|
97
|
+
if not base_url.lower().startswith(("https://", "http://")):
|
|
98
|
+
# urllib also opens file:// and ftp:// URLs; a validation client has no business there.
|
|
99
|
+
raise ValueError(f"base_url must be an http(s) URL, got {base_url!r}")
|
|
100
|
+
|
|
101
|
+
self._api_key = key.strip()
|
|
102
|
+
# Trailing slashes would produce `//api/v1/...`, which some proxies reject.
|
|
103
|
+
self._base_url = base_url.rstrip("/")
|
|
104
|
+
self._timeout = timeout
|
|
105
|
+
self._retry = retry
|
|
106
|
+
self._headers = dict(headers or {})
|
|
107
|
+
self._transport: Transport = transport or urllib_transport
|
|
108
|
+
self._sleep: Callable[[float], None] = time.sleep
|
|
109
|
+
|
|
110
|
+
def __repr__(self) -> str:
|
|
111
|
+
# Never the key: a repr ends up in logs and tracebacks.
|
|
112
|
+
return f"VerifNow(base_url={self._base_url!r})"
|
|
113
|
+
|
|
114
|
+
# -- validators -------------------------------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
def validate_email(self, value: str, *, timeout: float | None = None) -> ValidationResult:
|
|
117
|
+
"""Validate an email address: syntax, DNS/MX, typo, disposable, role-based, risk score."""
|
|
118
|
+
return self.validate("email", value, timeout=timeout)
|
|
119
|
+
|
|
120
|
+
def validate_phone(self, value: str, *, timeout: float | None = None) -> ValidationResult:
|
|
121
|
+
"""Validate a phone number against its country's numbering plan.
|
|
122
|
+
|
|
123
|
+
The number must include its country code (``+33…`` or ``0033…``). A valid number comes back
|
|
124
|
+
in E.164 as ``normalized_value``, with country and line type in ``phone_details``.
|
|
125
|
+
"""
|
|
126
|
+
return self.validate("phone", value, timeout=timeout)
|
|
127
|
+
|
|
128
|
+
def validate_iban(self, value: str, *, timeout: float | None = None) -> ValidationResult:
|
|
129
|
+
"""Validate an IBAN: the SWIFT registry entry for its country, then its check digits."""
|
|
130
|
+
return self.validate("iban", value, timeout=timeout)
|
|
131
|
+
|
|
132
|
+
def validate_vat(
|
|
133
|
+
self,
|
|
134
|
+
value: str,
|
|
135
|
+
*,
|
|
136
|
+
trader_name: str | None = None,
|
|
137
|
+
timeout: float | None = None,
|
|
138
|
+
) -> ValidationResult:
|
|
139
|
+
"""Validate an EU VAT number against VIES.
|
|
140
|
+
|
|
141
|
+
Pass ``trader_name`` to ask whether the number belongs to that company:
|
|
142
|
+
``vat_details.trader_name_match`` answers ``MATCH``, ``MISMATCH`` or ``NOT_AVAILABLE``.
|
|
143
|
+
|
|
144
|
+
``vat_details.registered`` is ``None`` when VIES could not be consulted. That means unknown,
|
|
145
|
+
never "not registered".
|
|
146
|
+
"""
|
|
147
|
+
extra = {"traderName": trader_name} if trader_name and trader_name.strip() else None
|
|
148
|
+
return self._validate("vat", value, timeout, extra)
|
|
149
|
+
|
|
150
|
+
def validate_nas(self, value: str, *, timeout: float | None = None) -> ValidationResult:
|
|
151
|
+
"""Validate a Canadian Social Insurance Number: format and Luhn check digit."""
|
|
152
|
+
return self.validate("nas", value, timeout=timeout)
|
|
153
|
+
|
|
154
|
+
def validate_ssn(self, value: str, *, timeout: float | None = None) -> ValidationResult:
|
|
155
|
+
"""Validate a US Social Security Number against the numbers the SSA never issues."""
|
|
156
|
+
return self.validate("ssn", value, timeout=timeout)
|
|
157
|
+
|
|
158
|
+
def validate_nif(self, value: str, *, timeout: float | None = None) -> ValidationResult:
|
|
159
|
+
"""Validate a Spanish NIF: a DNI, a NIE, the K/L/M series, or a company NIF."""
|
|
160
|
+
return self.validate("nif", value, timeout=timeout)
|
|
161
|
+
|
|
162
|
+
def validate(
|
|
163
|
+
self, rule: ValidationRule, value: str, *, timeout: float | None = None
|
|
164
|
+
) -> ValidationResult:
|
|
165
|
+
"""Validate a value against any rule. Use it when the rule is chosen at runtime."""
|
|
166
|
+
return self._validate(rule, value, timeout, None)
|
|
167
|
+
|
|
168
|
+
# -- VAT rates --------------------------------------------------------------------------------
|
|
169
|
+
|
|
170
|
+
def vat_rates(self, *, timeout: float | None = None) -> VatRates:
|
|
171
|
+
"""EU VAT rates of every member state, from the Commission's TEDB. Spends no quota."""
|
|
172
|
+
url = f"{self._base_url}/api/v1/vat/rates"
|
|
173
|
+
return self._with_retry(
|
|
174
|
+
lambda: self._request_once("GET", url, None, timeout, lambda p, _q: parse_vat_rates(p))
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
def vat_rate(self, country_code: str, *, timeout: float | None = None) -> CountryVatRates:
|
|
178
|
+
"""One member state's VAT rates. Accepts ``GR`` for Greece as well as ``EL``.
|
|
179
|
+
|
|
180
|
+
A code outside the 27 member states raises ``VerifNowRequestError`` (HTTP 404).
|
|
181
|
+
"""
|
|
182
|
+
if not isinstance(country_code, str) or not country_code.strip():
|
|
183
|
+
raise VerifNowRequestError('A member state code is required, e.g. "FR".')
|
|
184
|
+
url = f"{self._base_url}/api/v1/vat/rates/{quote(country_code.strip(), safe='')}"
|
|
185
|
+
return self._with_retry(
|
|
186
|
+
lambda: self._request_once(
|
|
187
|
+
"GET", url, None, timeout, lambda p, _q: parse_country_vat_rates(p)
|
|
188
|
+
)
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
# -- internals --------------------------------------------------------------------------------
|
|
192
|
+
|
|
193
|
+
def _validate(
|
|
194
|
+
self,
|
|
195
|
+
rule: str,
|
|
196
|
+
value: str,
|
|
197
|
+
timeout: float | None,
|
|
198
|
+
extra: Mapping[str, str] | None,
|
|
199
|
+
) -> ValidationResult:
|
|
200
|
+
if rule not in VALIDATION_RULES:
|
|
201
|
+
raise VerifNowRequestError(
|
|
202
|
+
f'Unknown rule "{rule}". Expected one of: {", ".join(VALIDATION_RULES)}.'
|
|
203
|
+
)
|
|
204
|
+
if not isinstance(value, str) or not value.strip():
|
|
205
|
+
# Caught here rather than server-side: an empty value spends quota and can only fail.
|
|
206
|
+
raise VerifNowRequestError(f'Cannot validate an empty value for rule "{rule}".')
|
|
207
|
+
|
|
208
|
+
url = f"{self._base_url}/api/v1/validate/{rule}"
|
|
209
|
+
body = json.dumps({"value": value, **(extra or {})}).encode()
|
|
210
|
+
return self._with_retry(
|
|
211
|
+
lambda: self._request_once("POST", url, body, timeout, parse_validation_result)
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
def _with_retry(self, attempt_once: Callable[[], T]) -> T:
|
|
215
|
+
max_attempts = 1 + (self._retry.attempts if self._retry else 0)
|
|
216
|
+
for attempt in range(max_attempts):
|
|
217
|
+
try:
|
|
218
|
+
return attempt_once()
|
|
219
|
+
except VerifNowError as error:
|
|
220
|
+
if attempt == max_attempts - 1:
|
|
221
|
+
raise
|
|
222
|
+
delay = self._retry_delay(error, attempt)
|
|
223
|
+
if delay is None:
|
|
224
|
+
raise
|
|
225
|
+
self._sleep(delay)
|
|
226
|
+
raise AssertionError("unreachable") # pragma: no cover
|
|
227
|
+
|
|
228
|
+
def _retry_delay(self, error: VerifNowError, attempt: int) -> float | None:
|
|
229
|
+
"""Seconds to wait before retrying, or ``None`` when the error should surface now.
|
|
230
|
+
|
|
231
|
+
A 429 is retried only when its reset is close: the concurrency limit clears in
|
|
232
|
+
milliseconds, a spent monthly quota does not, and sleeping on it helps nobody.
|
|
233
|
+
"""
|
|
234
|
+
retry = self._retry
|
|
235
|
+
if retry is None: # pragma: no cover - max_attempts is 1 then
|
|
236
|
+
return None
|
|
237
|
+
backoff = min(retry.backoff * math.pow(2, attempt), retry.max_backoff)
|
|
238
|
+
|
|
239
|
+
if isinstance(error, VerifNowRateLimitError):
|
|
240
|
+
wait = error.retry_after or 0.0
|
|
241
|
+
if wait > retry.max_backoff:
|
|
242
|
+
return None
|
|
243
|
+
return max(wait, backoff)
|
|
244
|
+
# A timeout is retried too: the deadline is ours, and the next attempt gets a fresh one.
|
|
245
|
+
if isinstance(error, (VerifNowServerError, VerifNowConnectionError)):
|
|
246
|
+
return backoff
|
|
247
|
+
# 400, 401 and unparseable bodies fail identically on a second attempt.
|
|
248
|
+
return None
|
|
249
|
+
|
|
250
|
+
def _request_once(
|
|
251
|
+
self,
|
|
252
|
+
method: str,
|
|
253
|
+
url: str,
|
|
254
|
+
body: bytes | None,
|
|
255
|
+
timeout: float | None,
|
|
256
|
+
parse: Callable[[Mapping[str, Any], QuotaInfo | None], T],
|
|
257
|
+
) -> T:
|
|
258
|
+
effective_timeout = self._timeout if timeout is None else timeout
|
|
259
|
+
headers = {
|
|
260
|
+
"User-Agent": f"verifnow-python/{__version__}",
|
|
261
|
+
**self._headers,
|
|
262
|
+
"Accept": "application/json",
|
|
263
|
+
"X-API-KEY": self._api_key,
|
|
264
|
+
"X-VerifNow-SDK": f"python/{__version__}",
|
|
265
|
+
}
|
|
266
|
+
if body is not None:
|
|
267
|
+
headers["Content-Type"] = "application/json"
|
|
268
|
+
|
|
269
|
+
try:
|
|
270
|
+
response = self._transport(
|
|
271
|
+
HttpRequest(
|
|
272
|
+
method=method, url=url, headers=headers, body=body, timeout=effective_timeout
|
|
273
|
+
)
|
|
274
|
+
)
|
|
275
|
+
except TransportError as error:
|
|
276
|
+
if error.timed_out:
|
|
277
|
+
message = f"VerifNow request to {url} timed out after {effective_timeout:g}s."
|
|
278
|
+
else:
|
|
279
|
+
message = (
|
|
280
|
+
f"Could not reach the VerifNow API at {url}: {error}. "
|
|
281
|
+
"Check `base_url` and network access."
|
|
282
|
+
)
|
|
283
|
+
raise VerifNowConnectionError(message, timed_out=error.timed_out) from error
|
|
284
|
+
|
|
285
|
+
return _handle_response(response, parse)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _handle_response(
|
|
289
|
+
response: HttpResponse,
|
|
290
|
+
parse: Callable[[Mapping[str, Any], QuotaInfo | None], T],
|
|
291
|
+
) -> T:
|
|
292
|
+
request_id = response.header("X-Request-Id")
|
|
293
|
+
quota = _parse_quota(response)
|
|
294
|
+
status = response.status
|
|
295
|
+
|
|
296
|
+
if 200 <= status < 300:
|
|
297
|
+
try:
|
|
298
|
+
payload = json.loads(response.body)
|
|
299
|
+
except (ValueError, UnicodeDecodeError) as error:
|
|
300
|
+
raise VerifNowResponseError(
|
|
301
|
+
"VerifNow returned a success status with a body that is not valid JSON.",
|
|
302
|
+
status=status,
|
|
303
|
+
request_id=request_id,
|
|
304
|
+
) from error
|
|
305
|
+
if not isinstance(payload, dict):
|
|
306
|
+
raise VerifNowResponseError(
|
|
307
|
+
"VerifNow returned an unexpected response shape.",
|
|
308
|
+
status=status,
|
|
309
|
+
request_id=request_id,
|
|
310
|
+
)
|
|
311
|
+
return parse(payload, quota)
|
|
312
|
+
|
|
313
|
+
message = _error_message(response)
|
|
314
|
+
|
|
315
|
+
if status in (401, 403):
|
|
316
|
+
raise VerifNowAuthError(
|
|
317
|
+
f"VerifNow rejected the API key ({status}): {message}",
|
|
318
|
+
status=status,
|
|
319
|
+
request_id=request_id,
|
|
320
|
+
)
|
|
321
|
+
if status == 429:
|
|
322
|
+
raise VerifNowRateLimitError(
|
|
323
|
+
f"VerifNow rate limit reached: {message}",
|
|
324
|
+
status=status,
|
|
325
|
+
request_id=request_id,
|
|
326
|
+
quota=quota,
|
|
327
|
+
retry_after=_parse_retry_after(response, quota),
|
|
328
|
+
)
|
|
329
|
+
if status >= 500:
|
|
330
|
+
raise VerifNowServerError(
|
|
331
|
+
f"VerifNow returned {status}: {message}", status=status, request_id=request_id
|
|
332
|
+
)
|
|
333
|
+
raise VerifNowRequestError(
|
|
334
|
+
f"VerifNow rejected the request ({status}): {message}",
|
|
335
|
+
status=status,
|
|
336
|
+
request_id=request_id,
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _to_int(value: str | None) -> int | None:
|
|
341
|
+
if value is None:
|
|
342
|
+
return None
|
|
343
|
+
try:
|
|
344
|
+
return int(value.strip())
|
|
345
|
+
except ValueError:
|
|
346
|
+
return None
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _parse_quota(response: HttpResponse) -> QuotaInfo | None:
|
|
350
|
+
limit = _to_int(response.header("X-RateLimit-Limit"))
|
|
351
|
+
remaining = _to_int(response.header("X-RateLimit-Remaining"))
|
|
352
|
+
reset = _to_int(response.header("X-RateLimit-Reset"))
|
|
353
|
+
overage = (response.header("X-Quota-Overage") or "").strip().lower() == "true"
|
|
354
|
+
if limit is None and remaining is None and reset is None and not overage:
|
|
355
|
+
return None
|
|
356
|
+
return QuotaInfo(
|
|
357
|
+
limit=limit,
|
|
358
|
+
remaining=remaining,
|
|
359
|
+
reset_at=None if reset is None else datetime.fromtimestamp(reset, tz=timezone.utc),
|
|
360
|
+
overage=overage,
|
|
361
|
+
)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _parse_retry_after(response: HttpResponse, quota: QuotaInfo | None) -> float | None:
|
|
365
|
+
now = datetime.now(timezone.utc)
|
|
366
|
+
header = response.header("Retry-After")
|
|
367
|
+
if header is not None:
|
|
368
|
+
try:
|
|
369
|
+
seconds = float(header)
|
|
370
|
+
if math.isfinite(seconds):
|
|
371
|
+
return max(0.0, seconds)
|
|
372
|
+
except ValueError:
|
|
373
|
+
pass
|
|
374
|
+
# RFC 9110 also allows an HTTP-date.
|
|
375
|
+
try:
|
|
376
|
+
when = parsedate_to_datetime(header)
|
|
377
|
+
except (TypeError, ValueError):
|
|
378
|
+
when = None
|
|
379
|
+
if when is not None:
|
|
380
|
+
if when.tzinfo is None:
|
|
381
|
+
when = when.replace(tzinfo=timezone.utc)
|
|
382
|
+
return float(max(0, math.ceil((when - now).total_seconds())))
|
|
383
|
+
|
|
384
|
+
if quota is not None and quota.reset_at is not None:
|
|
385
|
+
return float(max(0, math.ceil((quota.reset_at - now).total_seconds())))
|
|
386
|
+
return None
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _error_message(response: HttpResponse) -> str:
|
|
390
|
+
text = response.body.decode("utf-8", errors="replace").strip()
|
|
391
|
+
if not text:
|
|
392
|
+
return "no details"
|
|
393
|
+
try:
|
|
394
|
+
parsed = json.loads(text)
|
|
395
|
+
except ValueError:
|
|
396
|
+
# Not JSON: a proxy or the servlet container's default error page.
|
|
397
|
+
return text[:500]
|
|
398
|
+
if isinstance(parsed, dict):
|
|
399
|
+
for key in ("message", "error"):
|
|
400
|
+
value = parsed.get(key)
|
|
401
|
+
if isinstance(value, str) and value:
|
|
402
|
+
return value
|
|
403
|
+
return text[:500]
|
verifnow/_errors.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Exceptions raised by the SDK.
|
|
2
|
+
|
|
3
|
+
The SDK fails loudly on purpose. A validation client that swallows a network failure and reports
|
|
4
|
+
``valid=True`` turns an outage into silently accepted bad data, and the outage stays invisible until
|
|
5
|
+
someone audits the database. Catch these and decide explicitly: accepting the input on failure is a
|
|
6
|
+
reasonable choice, but it should be a choice.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import TYPE_CHECKING
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from ._models import QuotaInfo
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class VerifNowError(Exception):
|
|
18
|
+
"""Base class for every error this SDK raises.
|
|
19
|
+
|
|
20
|
+
``status`` is the HTTP status when the failure came back from the API rather than the network.
|
|
21
|
+
``request_id`` is the ``X-Request-Id`` response header, useful in a support request.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
message: str,
|
|
27
|
+
*,
|
|
28
|
+
status: int | None = None,
|
|
29
|
+
request_id: str | None = None,
|
|
30
|
+
) -> None:
|
|
31
|
+
super().__init__(message)
|
|
32
|
+
self.message = message
|
|
33
|
+
self.status = status
|
|
34
|
+
self.request_id = request_id
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class VerifNowAuthError(VerifNowError):
|
|
38
|
+
"""The API key is missing, malformed, revoked, or not authorised for this endpoint (401/403)."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class VerifNowRequestError(VerifNowError):
|
|
42
|
+
"""The request was rejected as malformed (400, 404, 422).
|
|
43
|
+
|
|
44
|
+
Retrying is pointless: the payload itself needs to change.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class VerifNowRateLimitError(VerifNowError):
|
|
49
|
+
"""The monthly quota or the concurrency limit was exceeded (429).
|
|
50
|
+
|
|
51
|
+
``retry_after`` is the number of seconds to wait, from ``Retry-After`` or ``X-RateLimit-Reset``.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
message: str,
|
|
57
|
+
*,
|
|
58
|
+
status: int | None = None,
|
|
59
|
+
request_id: str | None = None,
|
|
60
|
+
quota: QuotaInfo | None = None,
|
|
61
|
+
retry_after: float | None = None,
|
|
62
|
+
) -> None:
|
|
63
|
+
super().__init__(message, status=status, request_id=request_id)
|
|
64
|
+
self.quota = quota
|
|
65
|
+
self.retry_after = retry_after
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class VerifNowServerError(VerifNowError):
|
|
69
|
+
"""The API failed to process the request (5xx). Retried automatically before surfacing."""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class VerifNowConnectionError(VerifNowError):
|
|
73
|
+
"""The API could not be reached: DNS failure, refused connection, TLS error, or timeout.
|
|
74
|
+
|
|
75
|
+
A wrong ``base_url`` surfaces here, which is why the message names the URL it tried.
|
|
76
|
+
``timed_out`` is true when the failure was the client-side timeout.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
def __init__(self, message: str, *, timed_out: bool = False) -> None:
|
|
80
|
+
super().__init__(message)
|
|
81
|
+
self.timed_out = timed_out
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class VerifNowResponseError(VerifNowError):
|
|
85
|
+
"""The API returned a success status with a body this SDK could not parse."""
|