prontuno 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.
- prontuno/__init__.py +33 -0
- prontuno/_base.py +423 -0
- prontuno/_client.py +226 -0
- prontuno/_http.py +216 -0
- prontuno/_pagination.py +74 -0
- prontuno/_version.py +1 -0
- prontuno/errors.py +144 -0
- prontuno/py.typed +0 -0
- prontuno/resources/__init__.py +28 -0
- prontuno/resources/_resource.py +13 -0
- prontuno/resources/api_keys.py +138 -0
- prontuno/resources/domains.py +96 -0
- prontuno/resources/emails.py +332 -0
- prontuno/resources/smtp_credentials.py +156 -0
- prontuno/resources/suppressions.py +121 -0
- prontuno/resources/usage.py +21 -0
- prontuno/resources/webhooks.py +184 -0
- prontuno/types.py +639 -0
- prontuno/webhooks.py +152 -0
- prontuno-0.1.0.dist-info/METADATA +536 -0
- prontuno-0.1.0.dist-info/RECORD +23 -0
- prontuno-0.1.0.dist-info/WHEEL +4 -0
- prontuno-0.1.0.dist-info/licenses/LICENSE.md +9 -0
prontuno/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Official Python SDK for the Prontuno email API."""
|
|
2
|
+
|
|
3
|
+
from ._base import ResponseMetadata
|
|
4
|
+
from ._client import AsyncProntuno, Prontuno
|
|
5
|
+
from ._version import __version__
|
|
6
|
+
from .errors import (
|
|
7
|
+
ProntunoApiError,
|
|
8
|
+
ProntunoConfigError,
|
|
9
|
+
ProntunoConnectionError,
|
|
10
|
+
ProntunoError,
|
|
11
|
+
ProntunoTimeoutError,
|
|
12
|
+
RateLimit,
|
|
13
|
+
WebhookPayloadError,
|
|
14
|
+
WebhookSignatureVerificationError,
|
|
15
|
+
)
|
|
16
|
+
from .webhooks import construct_webhook_event, verify_webhook_signature
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"AsyncProntuno",
|
|
20
|
+
"Prontuno",
|
|
21
|
+
"ProntunoApiError",
|
|
22
|
+
"ProntunoConfigError",
|
|
23
|
+
"ProntunoConnectionError",
|
|
24
|
+
"ProntunoError",
|
|
25
|
+
"ProntunoTimeoutError",
|
|
26
|
+
"RateLimit",
|
|
27
|
+
"ResponseMetadata",
|
|
28
|
+
"WebhookPayloadError",
|
|
29
|
+
"WebhookSignatureVerificationError",
|
|
30
|
+
"__version__",
|
|
31
|
+
"construct_webhook_event",
|
|
32
|
+
"verify_webhook_signature",
|
|
33
|
+
]
|
prontuno/_base.py
ADDED
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
"""Configuration, request preparation, and retry decisions shared by the sync and async clients.
|
|
2
|
+
|
|
3
|
+
Only the I/O differs between ``Prontuno`` and ``AsyncProntuno``; everything that decides what to
|
|
4
|
+
send, whether to retry, and what to return lives here.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import math
|
|
11
|
+
import os
|
|
12
|
+
import random
|
|
13
|
+
import re
|
|
14
|
+
import time
|
|
15
|
+
from collections.abc import Mapping
|
|
16
|
+
from dataclasses import dataclass, replace
|
|
17
|
+
from email.utils import parsedate_to_datetime
|
|
18
|
+
from typing import Any, Literal, cast
|
|
19
|
+
from urllib.parse import quote, urlencode, urlsplit, urlunsplit
|
|
20
|
+
|
|
21
|
+
import httpx
|
|
22
|
+
|
|
23
|
+
from ._version import __version__
|
|
24
|
+
from .errors import (
|
|
25
|
+
ProntunoApiError,
|
|
26
|
+
ProntunoConfigError,
|
|
27
|
+
ProntunoConnectionError,
|
|
28
|
+
ProntunoTimeoutError,
|
|
29
|
+
RateLimit,
|
|
30
|
+
)
|
|
31
|
+
from .types import ApiErrorBody
|
|
32
|
+
|
|
33
|
+
Method = Literal["GET", "POST", "PATCH", "DELETE"]
|
|
34
|
+
QueryValue = str | int | bool | None
|
|
35
|
+
|
|
36
|
+
DEFAULT_BASE_URL = "https://api.prontuno.net/v1"
|
|
37
|
+
DEFAULT_TIMEOUT = 30.0
|
|
38
|
+
DEFAULT_MAX_RETRIES = 2
|
|
39
|
+
DEFAULT_MAX_RESPONSE_SIZE = 10 * 1024 * 1024
|
|
40
|
+
MAX_RETRY_DELAY = 60.0
|
|
41
|
+
USER_AGENT = f"prontuno-python/{__version__}"
|
|
42
|
+
|
|
43
|
+
_CONTROL_CHARACTERS = re.compile(r"[\x00-\x1f\x7f]")
|
|
44
|
+
_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class ResponseMetadata:
|
|
49
|
+
"""Metadata from the most recently completed API response."""
|
|
50
|
+
|
|
51
|
+
request_id: str | None
|
|
52
|
+
rate_limit: RateLimit
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class ClientConfig:
|
|
57
|
+
sending_key: str | None
|
|
58
|
+
management_key: str | None
|
|
59
|
+
base_url: str
|
|
60
|
+
timeout: float
|
|
61
|
+
max_retries: int
|
|
62
|
+
max_response_size: int
|
|
63
|
+
user_agent: str
|
|
64
|
+
|
|
65
|
+
def with_sending_key(self, sending_key: object) -> ClientConfig:
|
|
66
|
+
key = _normalize_key(sending_key, "sending_key")
|
|
67
|
+
if key is None:
|
|
68
|
+
raise ProntunoConfigError("with_sending_key() requires a non-empty sending key")
|
|
69
|
+
return replace(self, sending_key=key)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def build_config(
|
|
73
|
+
*,
|
|
74
|
+
api_key: object,
|
|
75
|
+
sending_key: object,
|
|
76
|
+
management_key: object,
|
|
77
|
+
base_url: object,
|
|
78
|
+
timeout: object,
|
|
79
|
+
max_retries: object,
|
|
80
|
+
max_response_size: object,
|
|
81
|
+
app_info: object,
|
|
82
|
+
) -> ClientConfig:
|
|
83
|
+
shared_key = _normalize_key(api_key, "api_key")
|
|
84
|
+
resolved_sending_key = _normalize_key(sending_key, "sending_key") or shared_key
|
|
85
|
+
resolved_management_key = _normalize_key(management_key, "management_key") or shared_key
|
|
86
|
+
if resolved_sending_key is None and resolved_management_key is None:
|
|
87
|
+
raise ProntunoConfigError(
|
|
88
|
+
"A non-empty Prontuno API key is required (api_key, sending_key, or management_key)"
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
if base_url is None:
|
|
92
|
+
base_url = _base_url_from_env() or DEFAULT_BASE_URL
|
|
93
|
+
|
|
94
|
+
return ClientConfig(
|
|
95
|
+
sending_key=resolved_sending_key,
|
|
96
|
+
management_key=resolved_management_key,
|
|
97
|
+
base_url=normalize_base_url(base_url),
|
|
98
|
+
timeout=validate_timeout(DEFAULT_TIMEOUT if timeout is None else timeout),
|
|
99
|
+
max_retries=validate_max_retries(
|
|
100
|
+
DEFAULT_MAX_RETRIES if max_retries is None else max_retries
|
|
101
|
+
),
|
|
102
|
+
max_response_size=validate_max_response_size(
|
|
103
|
+
DEFAULT_MAX_RESPONSE_SIZE if max_response_size is None else max_response_size
|
|
104
|
+
),
|
|
105
|
+
user_agent=_user_agent(app_info),
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _normalize_key(value: object, name: str) -> str | None:
|
|
110
|
+
if value is None:
|
|
111
|
+
return None
|
|
112
|
+
if not isinstance(value, str):
|
|
113
|
+
raise ProntunoConfigError(f"{name} must be a string")
|
|
114
|
+
stripped = value.strip()
|
|
115
|
+
return stripped or None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _base_url_from_env() -> str | None:
|
|
119
|
+
return os.environ.get("PRONTUNO_BASE_URL", "").strip() or None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def normalize_base_url(value: object) -> str:
|
|
123
|
+
"""Requires HTTPS so the API key is never sent in plain text, except to loopback hosts."""
|
|
124
|
+
if not isinstance(value, str):
|
|
125
|
+
raise ProntunoConfigError("base_url must be a valid absolute URL")
|
|
126
|
+
try:
|
|
127
|
+
parts = urlsplit(value.strip())
|
|
128
|
+
hostname = parts.hostname
|
|
129
|
+
_ = parts.port
|
|
130
|
+
except ValueError:
|
|
131
|
+
raise ProntunoConfigError("base_url must be a valid absolute URL") from None
|
|
132
|
+
if not parts.scheme or not hostname:
|
|
133
|
+
raise ProntunoConfigError("base_url must be a valid absolute URL")
|
|
134
|
+
|
|
135
|
+
scheme = parts.scheme.lower()
|
|
136
|
+
if scheme == "http":
|
|
137
|
+
if hostname.lower() not in _LOOPBACK_HOSTS:
|
|
138
|
+
raise ProntunoConfigError(
|
|
139
|
+
"base_url must use https (plain http is only allowed for loopback hosts)"
|
|
140
|
+
)
|
|
141
|
+
elif scheme != "https":
|
|
142
|
+
raise ProntunoConfigError("base_url must use https")
|
|
143
|
+
if parts.query or parts.fragment:
|
|
144
|
+
raise ProntunoConfigError("base_url must not include a query string or fragment")
|
|
145
|
+
|
|
146
|
+
return urlunsplit((scheme, parts.netloc, parts.path, "", "")).rstrip("/")
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _user_agent(app_info: object) -> str:
|
|
150
|
+
"""The SDK's own identifier comes first, so requests can be traced to an SDK version."""
|
|
151
|
+
if app_info is None:
|
|
152
|
+
return USER_AGENT
|
|
153
|
+
if not isinstance(app_info, str) or _CONTROL_CHARACTERS.search(app_info):
|
|
154
|
+
raise ProntunoConfigError("app_info must be a single-line string")
|
|
155
|
+
trimmed = app_info.strip()
|
|
156
|
+
return f"{USER_AGENT} {trimmed}" if trimmed else USER_AGENT
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def validate_timeout(value: object) -> float:
|
|
160
|
+
if (
|
|
161
|
+
not isinstance(value, int | float)
|
|
162
|
+
or isinstance(value, bool)
|
|
163
|
+
or not math.isfinite(value)
|
|
164
|
+
or value <= 0
|
|
165
|
+
):
|
|
166
|
+
raise ProntunoConfigError("timeout must be a positive number of seconds")
|
|
167
|
+
return float(value)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def validate_max_retries(value: object) -> int:
|
|
171
|
+
if not isinstance(value, int) or isinstance(value, bool) or value < 0:
|
|
172
|
+
raise ProntunoConfigError("max_retries must be a non-negative integer")
|
|
173
|
+
return value
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def validate_max_response_size(value: object) -> int:
|
|
177
|
+
if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
|
|
178
|
+
raise ProntunoConfigError("max_response_size must be a positive integer")
|
|
179
|
+
return value
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def path_id(label: str, value: object) -> str:
|
|
183
|
+
"""Encodes one identifier as a path segment, rejecting values that would change the path."""
|
|
184
|
+
if not isinstance(value, str) or value.strip() == "" or value in (".", ".."):
|
|
185
|
+
raise ProntunoConfigError(f"{label} identifier is required")
|
|
186
|
+
# Matches JavaScript's encodeURIComponent, so every SDK sends the same path.
|
|
187
|
+
return quote(value, safe="!~*'()")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
# --------------------------------------------------------------------------------------------
|
|
191
|
+
# Requests
|
|
192
|
+
# --------------------------------------------------------------------------------------------
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
@dataclass(frozen=True)
|
|
196
|
+
class PreparedRequest:
|
|
197
|
+
method: Method
|
|
198
|
+
url: str
|
|
199
|
+
headers: dict[str, str]
|
|
200
|
+
content: bytes | None
|
|
201
|
+
timeout: float
|
|
202
|
+
max_retries: int
|
|
203
|
+
max_response_size: int
|
|
204
|
+
retry_safe: bool
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def prepare_request(
|
|
208
|
+
config: ClientConfig,
|
|
209
|
+
method: Method,
|
|
210
|
+
path: str,
|
|
211
|
+
*,
|
|
212
|
+
body: object = None,
|
|
213
|
+
query: Mapping[str, QueryValue] | None = None,
|
|
214
|
+
sending: bool = False,
|
|
215
|
+
idempotency_key: str | None = None,
|
|
216
|
+
timeout: float | None = None,
|
|
217
|
+
max_retries: int | None = None,
|
|
218
|
+
max_response_size: int | None = None,
|
|
219
|
+
headers: Mapping[str, str] | None = None,
|
|
220
|
+
) -> PreparedRequest:
|
|
221
|
+
resolved_timeout = validate_timeout(config.timeout if timeout is None else timeout)
|
|
222
|
+
resolved_max_retries = validate_max_retries(
|
|
223
|
+
config.max_retries if max_retries is None else max_retries
|
|
224
|
+
)
|
|
225
|
+
resolved_max_response_size = validate_max_response_size(
|
|
226
|
+
config.max_response_size if max_response_size is None else max_response_size
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
if idempotency_key is not None and not sending:
|
|
230
|
+
# Only sends honour Idempotency-Key; accepting it elsewhere would make retries unsafe.
|
|
231
|
+
raise ProntunoConfigError(
|
|
232
|
+
"idempotency_key is only supported by emails.send() and emails.send_batch()"
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
api_key = config.sending_key if sending else config.management_key
|
|
236
|
+
if api_key is None:
|
|
237
|
+
role, option = ("sending", "sending_key") if sending else ("management", "management_key")
|
|
238
|
+
raise ProntunoConfigError(
|
|
239
|
+
f"{method} /{path} requires a {role} API key; "
|
|
240
|
+
f"pass {option} (or api_key) when creating the client"
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
request_headers = httpx.Headers(headers)
|
|
244
|
+
request_headers["Accept"] = "application/json"
|
|
245
|
+
request_headers["Authorization"] = f"Bearer {api_key}"
|
|
246
|
+
request_headers["User-Agent"] = config.user_agent
|
|
247
|
+
|
|
248
|
+
content: bytes | None = None
|
|
249
|
+
if body is not None:
|
|
250
|
+
request_headers["Content-Type"] = "application/json"
|
|
251
|
+
content = json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
|
252
|
+
if idempotency_key:
|
|
253
|
+
request_headers["Idempotency-Key"] = idempotency_key
|
|
254
|
+
|
|
255
|
+
return PreparedRequest(
|
|
256
|
+
method=method,
|
|
257
|
+
url=_build_url(config.base_url, path, query),
|
|
258
|
+
headers=dict(request_headers.multi_items()),
|
|
259
|
+
content=content,
|
|
260
|
+
timeout=resolved_timeout,
|
|
261
|
+
max_retries=resolved_max_retries,
|
|
262
|
+
max_response_size=resolved_max_response_size,
|
|
263
|
+
retry_safe=method in ("GET", "DELETE") or bool(idempotency_key),
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _build_url(base_url: str, path: str, query: Mapping[str, QueryValue] | None) -> str:
|
|
268
|
+
url = f"{base_url}/{path.lstrip('/')}"
|
|
269
|
+
params = [
|
|
270
|
+
(key, _query_value(value)) for key, value in (query or {}).items() if value is not None
|
|
271
|
+
]
|
|
272
|
+
return f"{url}?{urlencode(params)}" if params else url
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _query_value(value: str | int | bool) -> str:
|
|
276
|
+
if isinstance(value, bool):
|
|
277
|
+
return "true" if value else "false"
|
|
278
|
+
return str(value)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
# --------------------------------------------------------------------------------------------
|
|
282
|
+
# Responses
|
|
283
|
+
# --------------------------------------------------------------------------------------------
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class ResponseSizeError(ProntunoConnectionError):
|
|
287
|
+
"""The response was larger than ``max_response_size``. Never retried."""
|
|
288
|
+
|
|
289
|
+
def __init__(self, max_response_size: int) -> None:
|
|
290
|
+
super().__init__(
|
|
291
|
+
f"Prontuno API response exceeded the maximum size of {max_response_size} bytes"
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def check_declared_size(headers: httpx.Headers, max_response_size: int) -> None:
|
|
296
|
+
try:
|
|
297
|
+
declared = int(headers.get("content-length", ""))
|
|
298
|
+
except ValueError:
|
|
299
|
+
return
|
|
300
|
+
if declared > max_response_size:
|
|
301
|
+
raise ResponseSizeError(max_response_size)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def parse_body(status: int, content: bytes) -> Any:
|
|
305
|
+
"""Parses a response body. Successful responses must be JSON; error bodies may be anything."""
|
|
306
|
+
ok = 200 <= status < 300
|
|
307
|
+
if status == 204:
|
|
308
|
+
return None
|
|
309
|
+
if not content:
|
|
310
|
+
if ok:
|
|
311
|
+
raise ProntunoConnectionError("Prontuno API returned an empty response")
|
|
312
|
+
return None
|
|
313
|
+
|
|
314
|
+
text = content.decode("utf-8", errors="replace")
|
|
315
|
+
try:
|
|
316
|
+
return json.loads(text)
|
|
317
|
+
except ValueError:
|
|
318
|
+
if ok:
|
|
319
|
+
raise ProntunoConnectionError("Prontuno API returned invalid JSON") from None
|
|
320
|
+
return {"error": {"code": "invalid_response", "message": text, "retryable": False}}
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def response_metadata(headers: httpx.Headers) -> ResponseMetadata:
|
|
324
|
+
return ResponseMetadata(
|
|
325
|
+
request_id=headers.get("x-request-id"), rate_limit=RateLimit.from_headers(headers)
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
@dataclass(frozen=True)
|
|
330
|
+
class Retry:
|
|
331
|
+
delay: float
|
|
332
|
+
may_have_applied: bool
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def handle_response(
|
|
336
|
+
request: PreparedRequest,
|
|
337
|
+
attempt: int,
|
|
338
|
+
status: int,
|
|
339
|
+
headers: httpx.Headers,
|
|
340
|
+
parsed: Any,
|
|
341
|
+
*,
|
|
342
|
+
may_have_applied: bool,
|
|
343
|
+
) -> Any:
|
|
344
|
+
"""Returns the result, raises the API error, or returns a ``Retry`` to try again."""
|
|
345
|
+
if 200 <= status < 300:
|
|
346
|
+
return parsed
|
|
347
|
+
|
|
348
|
+
error = ProntunoApiError(
|
|
349
|
+
status=status,
|
|
350
|
+
body=cast("ApiErrorBody", parsed if isinstance(parsed, dict) else {}),
|
|
351
|
+
headers=headers,
|
|
352
|
+
)
|
|
353
|
+
# A DELETE retried after an attempt that may have succeeded finds the resource gone.
|
|
354
|
+
if may_have_applied and request.method == "DELETE" and _is_already_deleted(error):
|
|
355
|
+
return None
|
|
356
|
+
if attempt >= request.max_retries or not _should_retry_response(request, error):
|
|
357
|
+
raise error
|
|
358
|
+
|
|
359
|
+
return Retry(
|
|
360
|
+
delay=retry_delay(attempt, headers),
|
|
361
|
+
may_have_applied=may_have_applied or status == 408 or status >= 500,
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def handle_failure(
|
|
366
|
+
request: PreparedRequest, attempt: int, failure: ProntunoConnectionError
|
|
367
|
+
) -> Retry:
|
|
368
|
+
"""Decides whether a network failure or timeout is retried; raises it otherwise."""
|
|
369
|
+
if isinstance(failure, ResponseSizeError):
|
|
370
|
+
raise failure
|
|
371
|
+
if attempt >= request.max_retries or not request.retry_safe:
|
|
372
|
+
raise failure
|
|
373
|
+
return Retry(delay=retry_delay(attempt), may_have_applied=True)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _is_already_deleted(error: ProntunoApiError) -> bool:
|
|
377
|
+
return error.status == 404 or (error.status == 409 and error.code == "already_revoked")
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _should_retry_response(request: PreparedRequest, error: ProntunoApiError) -> bool:
|
|
381
|
+
if not request.retry_safe:
|
|
382
|
+
return False
|
|
383
|
+
return (
|
|
384
|
+
error.status in (408, 429)
|
|
385
|
+
or error.status >= 500
|
|
386
|
+
or (error.status == 409 and error.code == "idempotency_request_in_progress")
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def retry_delay(attempt: int, headers: httpx.Headers | None = None) -> float:
|
|
391
|
+
retry_after = headers.get("retry-after") if headers is not None else None
|
|
392
|
+
if retry_after:
|
|
393
|
+
try:
|
|
394
|
+
seconds = float(retry_after)
|
|
395
|
+
except ValueError:
|
|
396
|
+
seconds = math.nan
|
|
397
|
+
if math.isfinite(seconds) and seconds >= 0:
|
|
398
|
+
return min(seconds, MAX_RETRY_DELAY)
|
|
399
|
+
try:
|
|
400
|
+
date = parsedate_to_datetime(retry_after)
|
|
401
|
+
except (TypeError, ValueError, IndexError):
|
|
402
|
+
date = None
|
|
403
|
+
if date is not None and date.tzinfo is not None:
|
|
404
|
+
return min(max(date.timestamp() - time.time(), 0.0), MAX_RETRY_DELAY)
|
|
405
|
+
|
|
406
|
+
backoff: float = min(0.5 * 2**attempt, 5.0)
|
|
407
|
+
return backoff * random.uniform(0.75, 1.25)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def wrap_transport_error(error: Exception, timeout: float) -> ProntunoConnectionError:
|
|
411
|
+
if isinstance(error, ProntunoConnectionError):
|
|
412
|
+
return error
|
|
413
|
+
if isinstance(error, httpx.TimeoutException):
|
|
414
|
+
return ProntunoTimeoutError(timeout)
|
|
415
|
+
return ProntunoConnectionError()
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
# Failures that mean the request may not have completed; anything else is a bug and propagates.
|
|
419
|
+
TRANSPORT_ERRORS: tuple[type[Exception], ...] = (
|
|
420
|
+
httpx.RequestError,
|
|
421
|
+
OSError,
|
|
422
|
+
ProntunoConnectionError,
|
|
423
|
+
)
|
prontuno/_client.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from types import TracebackType
|
|
4
|
+
from typing import Self
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
|
|
8
|
+
from ._base import ClientConfig, ResponseMetadata, build_config
|
|
9
|
+
from ._http import AsyncTransport, SyncTransport
|
|
10
|
+
from .errors import ProntunoConfigError
|
|
11
|
+
from .resources.api_keys import ApiKeys, AsyncApiKeys
|
|
12
|
+
from .resources.domains import AsyncDomains, Domains
|
|
13
|
+
from .resources.emails import AsyncEmails, Emails
|
|
14
|
+
from .resources.smtp_credentials import AsyncSmtpCredentials, SmtpCredentials
|
|
15
|
+
from .resources.suppressions import AsyncSuppressions, Suppressions
|
|
16
|
+
from .resources.usage import AsyncUsage, Usage
|
|
17
|
+
from .resources.webhooks import AsyncWebhooks, Webhooks
|
|
18
|
+
|
|
19
|
+
__all__ = ["AsyncProntuno", "Prontuno"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Prontuno:
|
|
23
|
+
"""Client for the Prontuno API.
|
|
24
|
+
|
|
25
|
+
Pass one API key for every request, or separate keys:
|
|
26
|
+
``Prontuno(sending_key=..., management_key=...)``. Sends use the sending key and every other
|
|
27
|
+
request uses the management key.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
api_key: One key for every request. ``sending_key`` and ``management_key`` take
|
|
31
|
+
precedence over it.
|
|
32
|
+
sending_key: Domain-bound sending key, used for ``emails.send()`` and
|
|
33
|
+
``emails.send_batch()``.
|
|
34
|
+
management_key: Management key, used for every other request.
|
|
35
|
+
base_url: API endpoint. Defaults to ``PRONTUNO_BASE_URL``, then
|
|
36
|
+
``https://api.prontuno.net/v1``. Must use HTTPS except for loopback hosts.
|
|
37
|
+
timeout: Seconds allowed for each attempt (default 30).
|
|
38
|
+
max_retries: Retries for transient failures (default 2).
|
|
39
|
+
max_response_size: Largest response body accepted, in bytes (default 10 MiB).
|
|
40
|
+
app_info: Identifies your application, for example ``"my-app/1.2.0"``. It's added after
|
|
41
|
+
the SDK's own ``prontuno-python/<version>`` User-Agent.
|
|
42
|
+
http_client: An ``httpx.Client`` to send requests with. The SDK doesn't close a client
|
|
43
|
+
you pass in.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
emails: Emails
|
|
47
|
+
domains: Domains
|
|
48
|
+
suppressions: Suppressions
|
|
49
|
+
webhooks: Webhooks
|
|
50
|
+
api_keys: ApiKeys
|
|
51
|
+
smtp_credentials: SmtpCredentials
|
|
52
|
+
usage: Usage
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
api_key: str | None = None,
|
|
57
|
+
*,
|
|
58
|
+
sending_key: str | None = None,
|
|
59
|
+
management_key: str | None = None,
|
|
60
|
+
base_url: str | None = None,
|
|
61
|
+
timeout: float | None = None,
|
|
62
|
+
max_retries: int | None = None,
|
|
63
|
+
max_response_size: int | None = None,
|
|
64
|
+
app_info: str | None = None,
|
|
65
|
+
http_client: httpx.Client | None = None,
|
|
66
|
+
) -> None:
|
|
67
|
+
config = build_config(
|
|
68
|
+
api_key=api_key,
|
|
69
|
+
sending_key=sending_key,
|
|
70
|
+
management_key=management_key,
|
|
71
|
+
base_url=base_url,
|
|
72
|
+
timeout=timeout,
|
|
73
|
+
max_retries=max_retries,
|
|
74
|
+
max_response_size=max_response_size,
|
|
75
|
+
app_info=app_info,
|
|
76
|
+
)
|
|
77
|
+
if http_client is not None and not isinstance(http_client, httpx.Client):
|
|
78
|
+
raise ProntunoConfigError("http_client must be an httpx.Client")
|
|
79
|
+
owns_client = http_client is None
|
|
80
|
+
self._setup(config, http_client or httpx.Client(), owns_client=owns_client)
|
|
81
|
+
|
|
82
|
+
def _setup(self, config: ClientConfig, client: httpx.Client, *, owns_client: bool) -> None:
|
|
83
|
+
self._transport = SyncTransport(config, client, owns_client=owns_client)
|
|
84
|
+
self.emails = Emails(self._transport)
|
|
85
|
+
self.domains = Domains(self._transport)
|
|
86
|
+
self.suppressions = Suppressions(self._transport)
|
|
87
|
+
self.webhooks = Webhooks(self._transport)
|
|
88
|
+
self.api_keys = ApiKeys(self._transport)
|
|
89
|
+
self.smtp_credentials = SmtpCredentials(self._transport)
|
|
90
|
+
self.usage = Usage(self._transport)
|
|
91
|
+
|
|
92
|
+
def with_sending_key(self, sending_key: str) -> Prontuno:
|
|
93
|
+
"""Returns a client that sends with another domain's sending key.
|
|
94
|
+
|
|
95
|
+
Every other setting, including the management key, is kept. The new client shares this
|
|
96
|
+
client's connection pool, so close this client (not the copy) when you're done.
|
|
97
|
+
"""
|
|
98
|
+
copy = object.__new__(type(self))
|
|
99
|
+
copy._setup(
|
|
100
|
+
self._transport.config.with_sending_key(sending_key),
|
|
101
|
+
self._transport.client,
|
|
102
|
+
owns_client=False,
|
|
103
|
+
)
|
|
104
|
+
return copy
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def base_url(self) -> str:
|
|
108
|
+
return self._transport.config.base_url
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def last_response(self) -> ResponseMetadata | None:
|
|
112
|
+
"""Request ID and rate-limit values from the most recently completed response."""
|
|
113
|
+
return self._transport.last_response
|
|
114
|
+
|
|
115
|
+
def close(self) -> None:
|
|
116
|
+
"""Closes the connection pool, unless you passed in your own ``http_client``."""
|
|
117
|
+
self._transport.close()
|
|
118
|
+
|
|
119
|
+
def __enter__(self) -> Self:
|
|
120
|
+
return self
|
|
121
|
+
|
|
122
|
+
def __exit__(
|
|
123
|
+
self,
|
|
124
|
+
exc_type: type[BaseException] | None,
|
|
125
|
+
exc: BaseException | None,
|
|
126
|
+
traceback: TracebackType | None,
|
|
127
|
+
) -> None:
|
|
128
|
+
self.close()
|
|
129
|
+
|
|
130
|
+
def __repr__(self) -> str:
|
|
131
|
+
return f"Prontuno(base_url={self.base_url!r})"
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class AsyncProntuno:
|
|
135
|
+
"""Async client for the Prontuno API, with the same options and resources as ``Prontuno``.
|
|
136
|
+
|
|
137
|
+
Use it with ``async with`` or call ``await client.close()`` when you're done.
|
|
138
|
+
``http_client`` must be an ``httpx.AsyncClient``.
|
|
139
|
+
"""
|
|
140
|
+
|
|
141
|
+
emails: AsyncEmails
|
|
142
|
+
domains: AsyncDomains
|
|
143
|
+
suppressions: AsyncSuppressions
|
|
144
|
+
webhooks: AsyncWebhooks
|
|
145
|
+
api_keys: AsyncApiKeys
|
|
146
|
+
smtp_credentials: AsyncSmtpCredentials
|
|
147
|
+
usage: AsyncUsage
|
|
148
|
+
|
|
149
|
+
def __init__(
|
|
150
|
+
self,
|
|
151
|
+
api_key: str | None = None,
|
|
152
|
+
*,
|
|
153
|
+
sending_key: str | None = None,
|
|
154
|
+
management_key: str | None = None,
|
|
155
|
+
base_url: str | None = None,
|
|
156
|
+
timeout: float | None = None,
|
|
157
|
+
max_retries: int | None = None,
|
|
158
|
+
max_response_size: int | None = None,
|
|
159
|
+
app_info: str | None = None,
|
|
160
|
+
http_client: httpx.AsyncClient | None = None,
|
|
161
|
+
) -> None:
|
|
162
|
+
config = build_config(
|
|
163
|
+
api_key=api_key,
|
|
164
|
+
sending_key=sending_key,
|
|
165
|
+
management_key=management_key,
|
|
166
|
+
base_url=base_url,
|
|
167
|
+
timeout=timeout,
|
|
168
|
+
max_retries=max_retries,
|
|
169
|
+
max_response_size=max_response_size,
|
|
170
|
+
app_info=app_info,
|
|
171
|
+
)
|
|
172
|
+
if http_client is not None and not isinstance(http_client, httpx.AsyncClient):
|
|
173
|
+
raise ProntunoConfigError("http_client must be an httpx.AsyncClient")
|
|
174
|
+
owns_client = http_client is None
|
|
175
|
+
self._setup(config, http_client or httpx.AsyncClient(), owns_client=owns_client)
|
|
176
|
+
|
|
177
|
+
def _setup(self, config: ClientConfig, client: httpx.AsyncClient, *, owns_client: bool) -> None:
|
|
178
|
+
self._transport = AsyncTransport(config, client, owns_client=owns_client)
|
|
179
|
+
self.emails = AsyncEmails(self._transport)
|
|
180
|
+
self.domains = AsyncDomains(self._transport)
|
|
181
|
+
self.suppressions = AsyncSuppressions(self._transport)
|
|
182
|
+
self.webhooks = AsyncWebhooks(self._transport)
|
|
183
|
+
self.api_keys = AsyncApiKeys(self._transport)
|
|
184
|
+
self.smtp_credentials = AsyncSmtpCredentials(self._transport)
|
|
185
|
+
self.usage = AsyncUsage(self._transport)
|
|
186
|
+
|
|
187
|
+
def with_sending_key(self, sending_key: str) -> AsyncProntuno:
|
|
188
|
+
"""Returns a client that sends with another domain's sending key.
|
|
189
|
+
|
|
190
|
+
Every other setting, including the management key, is kept. The new client shares this
|
|
191
|
+
client's connection pool, so close this client (not the copy) when you're done.
|
|
192
|
+
"""
|
|
193
|
+
copy = object.__new__(type(self))
|
|
194
|
+
copy._setup(
|
|
195
|
+
self._transport.config.with_sending_key(sending_key),
|
|
196
|
+
self._transport.client,
|
|
197
|
+
owns_client=False,
|
|
198
|
+
)
|
|
199
|
+
return copy
|
|
200
|
+
|
|
201
|
+
@property
|
|
202
|
+
def base_url(self) -> str:
|
|
203
|
+
return self._transport.config.base_url
|
|
204
|
+
|
|
205
|
+
@property
|
|
206
|
+
def last_response(self) -> ResponseMetadata | None:
|
|
207
|
+
"""Request ID and rate-limit values from the most recently completed response."""
|
|
208
|
+
return self._transport.last_response
|
|
209
|
+
|
|
210
|
+
async def close(self) -> None:
|
|
211
|
+
"""Closes the connection pool, unless you passed in your own ``http_client``."""
|
|
212
|
+
await self._transport.close()
|
|
213
|
+
|
|
214
|
+
async def __aenter__(self) -> Self:
|
|
215
|
+
return self
|
|
216
|
+
|
|
217
|
+
async def __aexit__(
|
|
218
|
+
self,
|
|
219
|
+
exc_type: type[BaseException] | None,
|
|
220
|
+
exc: BaseException | None,
|
|
221
|
+
traceback: TracebackType | None,
|
|
222
|
+
) -> None:
|
|
223
|
+
await self.close()
|
|
224
|
+
|
|
225
|
+
def __repr__(self) -> str:
|
|
226
|
+
return f"AsyncProntuno(base_url={self.base_url!r})"
|