cairnpost 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.
- cairnpost/__init__.py +96 -0
- cairnpost/_answer.py +28 -0
- cairnpost/_batch.py +60 -0
- cairnpost/_client.py +175 -0
- cairnpost/_codes.py +61 -0
- cairnpost/_deliveries.py +62 -0
- cairnpost/_email.py +183 -0
- cairnpost/_emails.py +133 -0
- cairnpost/_errors.py +202 -0
- cairnpost/_events.py +117 -0
- cairnpost/_message.py +204 -0
- cairnpost/_pages.py +50 -0
- cairnpost/_parse.py +15 -0
- cairnpost/_payload.py +76 -0
- cairnpost/_problem.py +55 -0
- cairnpost/_read.py +166 -0
- cairnpost/_received.py +173 -0
- cairnpost/_status.py +148 -0
- cairnpost/_suppressions.py +126 -0
- cairnpost/_templates.py +177 -0
- cairnpost/_transport.py +271 -0
- cairnpost/_verify.py +176 -0
- cairnpost/_version.py +3 -0
- cairnpost/_webhooks.py +255 -0
- cairnpost/py.typed +0 -0
- cairnpost-0.1.0.dist-info/METADATA +469 -0
- cairnpost-0.1.0.dist-info/RECORD +29 -0
- cairnpost-0.1.0.dist-info/WHEEL +4 -0
- cairnpost-0.1.0.dist-info/licenses/LICENSE +21 -0
cairnpost/__init__.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""The Python client for CairnPost, a self-hostable gateway for transactional email.
|
|
2
|
+
|
|
3
|
+
It sends email, reads what became of it, manages suppressions, templates
|
|
4
|
+
and webhook endpoints, reads the email that comes in, and verifies the
|
|
5
|
+
webhooks CairnPost sends. It uses the standard library only.
|
|
6
|
+
|
|
7
|
+
The client never retries by itself. An error says what happened and
|
|
8
|
+
whether trying again is right (see `CairnPostError`); the application
|
|
9
|
+
decides.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from ._batch import BatchResult, failed
|
|
13
|
+
from ._client import DEFAULT_MAX_ANSWER_BYTES, DEFAULT_TIMEOUT, CairnPost
|
|
14
|
+
from ._codes import ErrorCode
|
|
15
|
+
from ._deliveries import Delivery, DeliveryState
|
|
16
|
+
from ._email import Attachment, Email, Sent, UseTemplate
|
|
17
|
+
from ._emails import Emails
|
|
18
|
+
from ._errors import (
|
|
19
|
+
CairnPostError,
|
|
20
|
+
NotCapturingError,
|
|
21
|
+
TransportError,
|
|
22
|
+
TransportReason,
|
|
23
|
+
is_not_found,
|
|
24
|
+
is_wrong_address,
|
|
25
|
+
may_have_sent,
|
|
26
|
+
)
|
|
27
|
+
from ._events import BounceType, EventEmail, EventReceived, EventSuppression, EventType, WebhookEvent
|
|
28
|
+
from ._message import Content, FileInfo, Message, MessageEvent, Recipient, State
|
|
29
|
+
from ._pages import Page
|
|
30
|
+
from ._received import Received, ReceivedContent, ReceivedEmails, ReceivedHeader
|
|
31
|
+
from ._status import CapturedEmail, Health, Limits, Quota
|
|
32
|
+
from ._suppressions import Reason, Suppression, Suppressions
|
|
33
|
+
from ._templates import Template, TemplateList, Templates, TemplateVariable
|
|
34
|
+
from ._verify import DEFAULT_TOLERANCE, RequestHeaders, Verifier, WebhookError, WebhookRefusal
|
|
35
|
+
from ._version import __version__
|
|
36
|
+
from ._webhooks import Webhook, Webhooks, WebhookTest
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"DEFAULT_MAX_ANSWER_BYTES",
|
|
40
|
+
"DEFAULT_TIMEOUT",
|
|
41
|
+
"DEFAULT_TOLERANCE",
|
|
42
|
+
"Attachment",
|
|
43
|
+
"BatchResult",
|
|
44
|
+
"BounceType",
|
|
45
|
+
"CairnPost",
|
|
46
|
+
"CairnPostError",
|
|
47
|
+
"CapturedEmail",
|
|
48
|
+
"Content",
|
|
49
|
+
"Delivery",
|
|
50
|
+
"DeliveryState",
|
|
51
|
+
"Email",
|
|
52
|
+
"Emails",
|
|
53
|
+
"ErrorCode",
|
|
54
|
+
"EventEmail",
|
|
55
|
+
"EventReceived",
|
|
56
|
+
"EventSuppression",
|
|
57
|
+
"EventType",
|
|
58
|
+
"FileInfo",
|
|
59
|
+
"Health",
|
|
60
|
+
"Limits",
|
|
61
|
+
"Message",
|
|
62
|
+
"MessageEvent",
|
|
63
|
+
"NotCapturingError",
|
|
64
|
+
"Page",
|
|
65
|
+
"Quota",
|
|
66
|
+
"Reason",
|
|
67
|
+
"Received",
|
|
68
|
+
"ReceivedContent",
|
|
69
|
+
"ReceivedEmails",
|
|
70
|
+
"ReceivedHeader",
|
|
71
|
+
"Recipient",
|
|
72
|
+
"RequestHeaders",
|
|
73
|
+
"Sent",
|
|
74
|
+
"State",
|
|
75
|
+
"Suppression",
|
|
76
|
+
"Suppressions",
|
|
77
|
+
"Template",
|
|
78
|
+
"TemplateList",
|
|
79
|
+
"TemplateVariable",
|
|
80
|
+
"Templates",
|
|
81
|
+
"TransportError",
|
|
82
|
+
"TransportReason",
|
|
83
|
+
"UseTemplate",
|
|
84
|
+
"Verifier",
|
|
85
|
+
"Webhook",
|
|
86
|
+
"WebhookError",
|
|
87
|
+
"WebhookEvent",
|
|
88
|
+
"WebhookRefusal",
|
|
89
|
+
"WebhookTest",
|
|
90
|
+
"Webhooks",
|
|
91
|
+
"__version__",
|
|
92
|
+
"failed",
|
|
93
|
+
"is_not_found",
|
|
94
|
+
"is_wrong_address",
|
|
95
|
+
"may_have_sent",
|
|
96
|
+
]
|
cairnpost/_answer.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from typing import TypeVar
|
|
5
|
+
|
|
6
|
+
from ._errors import TransportError
|
|
7
|
+
from ._read import Misshapen
|
|
8
|
+
|
|
9
|
+
T = TypeVar("T")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def reading(answer: object, read: Callable[[object], T]) -> T:
|
|
13
|
+
"""Runs a reader over an answer; one of another shape is not CairnPost's."""
|
|
14
|
+
try:
|
|
15
|
+
return read(answer)
|
|
16
|
+
except Misshapen:
|
|
17
|
+
pass
|
|
18
|
+
# Raised out here, with nothing behind it, and without the answer left
|
|
19
|
+
# in this frame for a traceback to show.
|
|
20
|
+
del answer
|
|
21
|
+
raise TransportError("not_cairnpost")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def place_of(place: int) -> str:
|
|
25
|
+
"""A file's place as a path takes it."""
|
|
26
|
+
if isinstance(place, bool) or not isinstance(place, int) or place < 1:
|
|
27
|
+
raise ValueError("cairnpost: a file's place counts from 1")
|
|
28
|
+
return str(place)
|
cairnpost/_batch.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
from ._codes import known
|
|
7
|
+
from ._email import Sent, read_sent
|
|
8
|
+
from ._errors import CairnPostError
|
|
9
|
+
from ._problem import problem_from
|
|
10
|
+
from ._read import Misshapen, fields, has, items
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
14
|
+
class BatchResult:
|
|
15
|
+
"""What became of one email of a batch: `sent`, or `error`.
|
|
16
|
+
|
|
17
|
+
`error` is the `CairnPostError` a send of this email alone would have
|
|
18
|
+
raised: `retryable` and `may_have_sent` read it the same way.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
sent: Sent | None = None
|
|
22
|
+
error: CairnPostError | None = None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def failed(results: Sequence[BatchResult]) -> int:
|
|
26
|
+
"""Counts the emails of a batch that did not go."""
|
|
27
|
+
return sum(1 for r in results if r.error is not None)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def read_batch(v: object, later: Sequence[bool]) -> list[BatchResult]:
|
|
31
|
+
"""Reads a batch's answer.
|
|
32
|
+
|
|
33
|
+
One that does not answer for each email asked is not CairnPost's:
|
|
34
|
+
which emails went is not known.
|
|
35
|
+
"""
|
|
36
|
+
results = items(has(fields(v), "data"), "data", fields)
|
|
37
|
+
if len(results) != len(later):
|
|
38
|
+
raise Misshapen
|
|
39
|
+
return [_one(o, waits) for o, waits in zip(results, later, strict=True)]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _one(o: dict[str, object], later: bool) -> BatchResult:
|
|
43
|
+
if o.get("error") is None:
|
|
44
|
+
return BatchResult(sent=read_sent(o, later))
|
|
45
|
+
e = fields(o["error"])
|
|
46
|
+
status = e.get("statusCode")
|
|
47
|
+
if isinstance(status, bool) or not isinstance(status, int) or not 400 <= status <= 599:
|
|
48
|
+
raise Misshapen
|
|
49
|
+
# Under a name this client does not know, only the status is believed,
|
|
50
|
+
# as for an answer that is not CairnPost's.
|
|
51
|
+
wait = e.get("retry_after")
|
|
52
|
+
seconds: float | None = None
|
|
53
|
+
if (
|
|
54
|
+
known(e.get("name")) is not None
|
|
55
|
+
and isinstance(wait, int | float)
|
|
56
|
+
and not isinstance(wait, bool)
|
|
57
|
+
and wait > 0
|
|
58
|
+
):
|
|
59
|
+
seconds = float(wait)
|
|
60
|
+
return BatchResult(error=problem_from(status, e, seconds))
|
cairnpost/_client.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import re
|
|
5
|
+
import ssl
|
|
6
|
+
from urllib.parse import urlsplit
|
|
7
|
+
|
|
8
|
+
from ._answer import reading
|
|
9
|
+
from ._codes import ErrorCode
|
|
10
|
+
from ._emails import Emails
|
|
11
|
+
from ._errors import CairnPostError, NotCapturingError, is_wrong_address
|
|
12
|
+
from ._received import ReceivedEmails
|
|
13
|
+
from ._status import CapturedEmail, Health, Limits, read_captured, read_health, read_limits
|
|
14
|
+
from ._suppressions import Suppressions
|
|
15
|
+
from ._templates import Templates
|
|
16
|
+
from ._transport import Call, Transport, header_safe
|
|
17
|
+
from ._version import __version__
|
|
18
|
+
from ._webhooks import Webhooks
|
|
19
|
+
|
|
20
|
+
#: How long a call may take, in seconds. It is longer than the server gives
|
|
21
|
+
#: its slowest answer, a batch: by the server's own settings that is 30
|
|
22
|
+
#: seconds for the request to arrive, a minute of starting emails, and the
|
|
23
|
+
#: last send and its record (10 and 20 seconds), two minutes in all. A
|
|
24
|
+
#: client that gave up sooner would not know whether its emails went. A
|
|
25
|
+
#: server set to give a send or a batch longer wants a client given longer.
|
|
26
|
+
DEFAULT_TIMEOUT = 150.0
|
|
27
|
+
|
|
28
|
+
#: How much of an answer is read unless `max_answer_bytes` says otherwise.
|
|
29
|
+
#: Only a development server's list of captured emails comes near it.
|
|
30
|
+
DEFAULT_MAX_ANSWER_BYTES = 64 * 1024 * 1024
|
|
31
|
+
|
|
32
|
+
_PATH = re.compile(r"[\x21-\x7e]*", re.ASCII)
|
|
33
|
+
_BAD_URL = "cairnpost: the base URL must be http:// or https:// and name a host"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class CairnPost:
|
|
37
|
+
"""Calls one CairnPost server with one API key.
|
|
38
|
+
|
|
39
|
+
It never retries by itself: an error says what happened and whether
|
|
40
|
+
trying again is right (see `CairnPostError`); the application decides.
|
|
41
|
+
It may be used from several threads at once.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
__slots__ = ("_t", "emails", "received", "suppressions", "templates", "webhooks")
|
|
45
|
+
|
|
46
|
+
#: Sending emails and reading what became of them.
|
|
47
|
+
emails: Emails
|
|
48
|
+
#: The addresses not sent to. Admin key.
|
|
49
|
+
suppressions: Suppressions
|
|
50
|
+
#: The URLs told what becomes of emails. Admin key.
|
|
51
|
+
webhooks: Webhooks
|
|
52
|
+
#: The templates emails are sent from. Admin key.
|
|
53
|
+
templates: Templates
|
|
54
|
+
#: The emails that came for the server's addresses. Admin key.
|
|
55
|
+
received: ReceivedEmails
|
|
56
|
+
|
|
57
|
+
def __init__(
|
|
58
|
+
self,
|
|
59
|
+
base_url: str,
|
|
60
|
+
api_key: str,
|
|
61
|
+
*,
|
|
62
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
63
|
+
max_answer_bytes: int = DEFAULT_MAX_ANSWER_BYTES,
|
|
64
|
+
user_agent: str | None = None,
|
|
65
|
+
tls: ssl.SSLContext | None = None,
|
|
66
|
+
) -> None:
|
|
67
|
+
"""Makes a client for the server at `base_url` ("https://mail.example.com") using `api_key`.
|
|
68
|
+
|
|
69
|
+
A send key may send and read its own emails; the calls marked
|
|
70
|
+
"admin key" need an admin key.
|
|
71
|
+
|
|
72
|
+
`timeout` is how long a call may take, in seconds: keep it above
|
|
73
|
+
the server's send and batch timeouts. `max_answer_bytes` is how
|
|
74
|
+
much of an answer is read; a larger one is an error that says so.
|
|
75
|
+
A refusal is not counted: 64 KiB of one are read whatever this
|
|
76
|
+
says, and a longer one is its status alone.
|
|
77
|
+
`user_agent` is the application's name, put before the client's
|
|
78
|
+
own in the User-Agent header; a name a header cannot carry is
|
|
79
|
+
ignored. `tls` is how an https server is trusted; the system's own
|
|
80
|
+
certificates when left out.
|
|
81
|
+
"""
|
|
82
|
+
try:
|
|
83
|
+
url = urlsplit(base_url if isinstance(base_url, str) else "")
|
|
84
|
+
host, port = url.hostname, url.port
|
|
85
|
+
except ValueError:
|
|
86
|
+
raise ValueError(_BAD_URL) from None
|
|
87
|
+
if (
|
|
88
|
+
url.scheme not in ("http", "https")
|
|
89
|
+
or not host
|
|
90
|
+
or url.username is not None
|
|
91
|
+
or url.password is not None
|
|
92
|
+
):
|
|
93
|
+
raise ValueError(_BAD_URL)
|
|
94
|
+
# A path is sent as it is written: one that cannot be is said
|
|
95
|
+
# here, not at every call.
|
|
96
|
+
if not _PATH.fullmatch(url.path):
|
|
97
|
+
raise ValueError("cairnpost: the base URL's path must be written as a URL carries it (no spaces)")
|
|
98
|
+
# A key read from a file often ends in a newline; one with anything
|
|
99
|
+
# else a header cannot carry is refused here, not at the first call.
|
|
100
|
+
key = api_key.strip() if isinstance(api_key, str) else ""
|
|
101
|
+
if not header_safe(key) or " " in key:
|
|
102
|
+
raise ValueError("cairnpost: an API key is required, and holds no spaces or control characters")
|
|
103
|
+
if isinstance(timeout, bool) or not isinstance(timeout, int | float) or not 0 < timeout < math.inf:
|
|
104
|
+
raise ValueError("cairnpost: timeout must be a number of seconds above 0")
|
|
105
|
+
if (
|
|
106
|
+
isinstance(max_answer_bytes, bool)
|
|
107
|
+
or not isinstance(max_answer_bytes, int)
|
|
108
|
+
or max_answer_bytes < 1
|
|
109
|
+
):
|
|
110
|
+
raise ValueError("cairnpost: max_answer_bytes must be a whole number above 0")
|
|
111
|
+
agent = "cairnpost-python/" + __version__
|
|
112
|
+
if user_agent and header_safe(user_agent):
|
|
113
|
+
agent = user_agent + " " + agent
|
|
114
|
+
secure = url.scheme == "https"
|
|
115
|
+
self._t = Transport(
|
|
116
|
+
secure=secure,
|
|
117
|
+
host=host,
|
|
118
|
+
# Always said: a host with colons in it (IPv6) is not then read as "host:port".
|
|
119
|
+
port=port or (443 if secure else 80),
|
|
120
|
+
prefix=url.path.rstrip("/"),
|
|
121
|
+
key=key,
|
|
122
|
+
agent=agent,
|
|
123
|
+
timeout=float(timeout),
|
|
124
|
+
max_answer_bytes=max_answer_bytes,
|
|
125
|
+
tls=(tls or ssl.create_default_context()) if secure else None,
|
|
126
|
+
)
|
|
127
|
+
self.emails = Emails(self._t)
|
|
128
|
+
self.suppressions = Suppressions(self._t)
|
|
129
|
+
self.webhooks = Webhooks(self._t)
|
|
130
|
+
self.templates = Templates(self._t)
|
|
131
|
+
self.received = ReceivedEmails(self._t)
|
|
132
|
+
|
|
133
|
+
def __repr__(self) -> str:
|
|
134
|
+
# Never the key.
|
|
135
|
+
return f"<CairnPost client, {self._t!r}>"
|
|
136
|
+
|
|
137
|
+
def health(self) -> Health:
|
|
138
|
+
"""Asks the server how it is. It needs no key.
|
|
139
|
+
|
|
140
|
+
A server that is up but cannot reach its database is answered, not
|
|
141
|
+
an error: see `Health.ok`. With a base URL that is wrong it fails
|
|
142
|
+
as any call does, and `is_wrong_address` says so: it is the call
|
|
143
|
+
to check a configuration with.
|
|
144
|
+
"""
|
|
145
|
+
return reading(self._t.read_json(Call(method="GET", path=("health",), plain=True)), read_health)
|
|
146
|
+
|
|
147
|
+
def limits(self) -> Limits:
|
|
148
|
+
"""Answers the mail provider's sending allowance, so an application knows before it runs out."""
|
|
149
|
+
return reading(self._t.read_json(Call(method="GET", path=("limits",))), read_limits)
|
|
150
|
+
|
|
151
|
+
def captured(self) -> list[CapturedEmail]:
|
|
152
|
+
"""Answers the emails a server running the capture driver holds, newest first.
|
|
153
|
+
|
|
154
|
+
That is what would have been sent. For development and tests. A
|
|
155
|
+
server that delivers for real has no such list: the error is then
|
|
156
|
+
a `NotCapturingError`, unless `health` fails too, in which case
|
|
157
|
+
the base URL is what is wrong. Admin key.
|
|
158
|
+
"""
|
|
159
|
+
try:
|
|
160
|
+
return reading(self._t.read_json(Call(method="GET", path=("capture", "emails"))), read_captured)
|
|
161
|
+
except CairnPostError as err:
|
|
162
|
+
if err.code is not ErrorCode.ROUTE_NOT_FOUND:
|
|
163
|
+
raise
|
|
164
|
+
wrong = err
|
|
165
|
+
# The path is not there. If the server is, it is one that does not
|
|
166
|
+
# capture; if nothing of CairnPost's is at that address, the first
|
|
167
|
+
# error says so. Health failing any other way is its own error.
|
|
168
|
+
try:
|
|
169
|
+
self.health()
|
|
170
|
+
except CairnPostError as down:
|
|
171
|
+
if not is_wrong_address(down):
|
|
172
|
+
raise
|
|
173
|
+
else:
|
|
174
|
+
raise NotCapturingError
|
|
175
|
+
raise wrong
|
cairnpost/_codes.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from enum import StrEnum
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ErrorCode(StrEnum):
|
|
7
|
+
"""Names of the errors CairnPost answers, as `CairnPostError.code` holds them."""
|
|
8
|
+
|
|
9
|
+
VALIDATION = "validation_error"
|
|
10
|
+
REJECTED_BY_UPSTREAM = "rejected_by_upstream"
|
|
11
|
+
#: The mail provider refused the email, and the sending domain's DNS
|
|
12
|
+
#: lacks a record the provider asks. The domain is likely not set up
|
|
13
|
+
#: with the provider, which then refuses every email from it: this is
|
|
14
|
+
#: the sender failing, not one bad email. A server before 0.1.1 says
|
|
15
|
+
#: REJECTED_BY_UPSTREAM instead.
|
|
16
|
+
SENDER_DOMAIN_NOT_READY = "sender_domain_not_ready"
|
|
17
|
+
RECIPIENT_SUPPRESSED = "recipient_suppressed"
|
|
18
|
+
IDEMPOTENT_MISMATCH = "invalid_idempotent_request"
|
|
19
|
+
IDEMPOTENT_IN_FLIGHT = "concurrent_idempotent_requests"
|
|
20
|
+
MISSING_KEY = "missing_api_key"
|
|
21
|
+
INVALID_KEY = "invalid_api_key"
|
|
22
|
+
DOMAIN_NOT_ALLOWED = "domain_not_allowed"
|
|
23
|
+
ADMIN_KEY_REQUIRED = "admin_key_required"
|
|
24
|
+
NOT_FOUND = "not_found"
|
|
25
|
+
#: The server has nothing at the path asked for: the base URL is
|
|
26
|
+
#: wrong, or the server is older than this client.
|
|
27
|
+
ROUTE_NOT_FOUND = "route_not_found"
|
|
28
|
+
#: The path is there and does not take the method: the server is older
|
|
29
|
+
#: or newer than this client.
|
|
30
|
+
METHOD_NOT_ALLOWED = "method_not_allowed"
|
|
31
|
+
TOO_LARGE = "request_too_large"
|
|
32
|
+
#: The request did not arrive whole in time. Nothing was done with it.
|
|
33
|
+
REQUEST_INCOMPLETE = "request_incomplete"
|
|
34
|
+
RATE_LIMITED = "rate_limit_exceeded"
|
|
35
|
+
UPSTREAM_UNKNOWN = "upstream_unknown"
|
|
36
|
+
UPSTREAM_DOWN = "upstream_unavailable"
|
|
37
|
+
UNAVAILABLE = "unavailable"
|
|
38
|
+
#: The email to cancel or move does not wait to be sent: it is being
|
|
39
|
+
#: sent, was sent, or was cancelled.
|
|
40
|
+
NOT_SCHEDULED = "not_scheduled"
|
|
41
|
+
#: The emails waiting to be sent hold as much as the server keeps.
|
|
42
|
+
#: Nothing was kept or sent.
|
|
43
|
+
SCHEDULE_FULL = "schedule_full"
|
|
44
|
+
#: A batch ended before this email's turn. Nothing of it was sent.
|
|
45
|
+
NOT_STARTED = "not_started"
|
|
46
|
+
#: The sending domain already has a template of that name.
|
|
47
|
+
NAME_TAKEN = "name_taken"
|
|
48
|
+
#: What was to be changed was changed by others at the same time. Read
|
|
49
|
+
#: it and try again.
|
|
50
|
+
CHANGED_MEANWHILE = "changed_meanwhile"
|
|
51
|
+
INTERNAL = "internal_error"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def known(name: object) -> ErrorCode | None:
|
|
55
|
+
"""The name as one of CairnPost's own; None for any other."""
|
|
56
|
+
if not isinstance(name, str):
|
|
57
|
+
return None
|
|
58
|
+
try:
|
|
59
|
+
return ErrorCode(name)
|
|
60
|
+
except ValueError:
|
|
61
|
+
return None
|
cairnpost/_deliveries.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from enum import StrEnum
|
|
6
|
+
|
|
7
|
+
from ._read import count, fields, maybe_text, maybe_time, said, text, time
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class DeliveryState(StrEnum):
|
|
11
|
+
"""States of a webhook delivery."""
|
|
12
|
+
|
|
13
|
+
#: Owed; it will be tried, or tried again.
|
|
14
|
+
PENDING = "pending"
|
|
15
|
+
#: The endpoint took it.
|
|
16
|
+
DELIVERED = "delivered"
|
|
17
|
+
#: Every try was used up.
|
|
18
|
+
FAILED = "failed"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
22
|
+
class Delivery:
|
|
23
|
+
"""One webhook owed to one endpoint, and how it went."""
|
|
24
|
+
|
|
25
|
+
#: Also the webhook's id as its receiver sees it (`WebhookEvent.id`).
|
|
26
|
+
id: str
|
|
27
|
+
#: The email the webhook is about; None for one about no email sent
|
|
28
|
+
#: (`address.suppressed`, `email.received`).
|
|
29
|
+
email_id: str | None
|
|
30
|
+
#: The received email the webhook is about, for an `email.received`.
|
|
31
|
+
inbound_id: str | None
|
|
32
|
+
#: The webhook's type (see `EventType`).
|
|
33
|
+
type: str
|
|
34
|
+
#: One of `DeliveryState`.
|
|
35
|
+
state: str
|
|
36
|
+
attempts: int
|
|
37
|
+
#: The endpoint's status at the last try; None for none.
|
|
38
|
+
last_status: int | None
|
|
39
|
+
#: Why the last try failed; None if it did not.
|
|
40
|
+
last_failure: str | None
|
|
41
|
+
created_at: datetime
|
|
42
|
+
attempted_at: datetime | None
|
|
43
|
+
delivered_at: datetime | None
|
|
44
|
+
next_attempt_at: datetime | None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def read_delivery(v: object) -> Delivery:
|
|
48
|
+
o = fields(v)
|
|
49
|
+
return Delivery(
|
|
50
|
+
id=said(o, "id"),
|
|
51
|
+
email_id=maybe_text(o, "email_id"),
|
|
52
|
+
inbound_id=maybe_text(o, "inbound_id"),
|
|
53
|
+
type=text(o, "type"),
|
|
54
|
+
state=text(o, "state"),
|
|
55
|
+
attempts=count(o, "attempts"),
|
|
56
|
+
last_status=count(o, "last_status") or None,
|
|
57
|
+
last_failure=maybe_text(o, "last_failure"),
|
|
58
|
+
created_at=time(o, "created_at"),
|
|
59
|
+
attempted_at=maybe_time(o, "attempted_at"),
|
|
60
|
+
delivered_at=maybe_time(o, "delivered_at"),
|
|
61
|
+
next_attempt_at=maybe_time(o, "next_attempt_at"),
|
|
62
|
+
)
|
cairnpost/_email.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
from collections.abc import Mapping, Sequence
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from datetime import UTC, datetime
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from ._read import Misshapen, fields, maybe_time, said, texts
|
|
10
|
+
from ._transport import header_safe
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
14
|
+
class Attachment:
|
|
15
|
+
"""A file sent with an email."""
|
|
16
|
+
|
|
17
|
+
#: The name its reader sees: a name, not a path.
|
|
18
|
+
filename: str
|
|
19
|
+
#: The file's bytes.
|
|
20
|
+
content: bytes | bytearray | memoryview
|
|
21
|
+
#: Its media type ("application/pdf"); left out, the server tells it
|
|
22
|
+
#: from the filename.
|
|
23
|
+
content_type: str | None = None
|
|
24
|
+
#: Makes the file part of the HTML body, which shows it as "cid:" and
|
|
25
|
+
#: this name; left out, it is a file beside the email.
|
|
26
|
+
content_id: str | None = None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
30
|
+
class UseTemplate:
|
|
31
|
+
"""Names a template to make an email from, and gives its variables their values.
|
|
32
|
+
|
|
33
|
+
A variable the template has a default for may be left out; one it has
|
|
34
|
+
none for must be given, and a value for a variable it does not name is
|
|
35
|
+
refused. A value is written as it is in the subject and the text, and
|
|
36
|
+
escaped in the HTML.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
name: str
|
|
40
|
+
variables: Mapping[str, str] = field(default_factory=dict)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
44
|
+
class Email:
|
|
45
|
+
"""One email, to one address or several."""
|
|
46
|
+
|
|
47
|
+
#: The sender: "app@example.com" or "App <app@example.com>". (`from`
|
|
48
|
+
#: is a word of Python's own.)
|
|
49
|
+
from_: str
|
|
50
|
+
#: Who the email is for: one address at least. `cc` are copied in the
|
|
51
|
+
#: open, `bcc` without the others seeing them. No address twice; the
|
|
52
|
+
#: server says how many an email may name in all (50 by default).
|
|
53
|
+
to: Sequence[str]
|
|
54
|
+
cc: Sequence[str] = ()
|
|
55
|
+
bcc: Sequence[str] = ()
|
|
56
|
+
reply_to: str | None = None
|
|
57
|
+
#: Required, unless a `template` gives one.
|
|
58
|
+
subject: str | None = None
|
|
59
|
+
#: The bodies; at least one is required, unless a `template` gives them.
|
|
60
|
+
html: str | None = None
|
|
61
|
+
text: str | None = None
|
|
62
|
+
#: Extra headers.
|
|
63
|
+
headers: Mapping[str, str] = field(default_factory=dict)
|
|
64
|
+
#: Files to send with it.
|
|
65
|
+
attachments: Sequence[Attachment] = ()
|
|
66
|
+
#: Makes the email from a template the server keeps, in place of
|
|
67
|
+
#: `html` and `text`, which must then be left out. A `subject` given
|
|
68
|
+
#: with it is used instead of the template's.
|
|
69
|
+
template: UseTemplate | None = None
|
|
70
|
+
#: Has the email sent at that time and not now: the server keeps it
|
|
71
|
+
#: until then. It must have a zone, be a time to come, and be as far
|
|
72
|
+
#: ahead as the server allows (30 days by default).
|
|
73
|
+
scheduled_at: datetime | None = None
|
|
74
|
+
#: Makes a repeated send one email: the same key with the same content
|
|
75
|
+
#: answers the first one's id. Use one for anything that may be
|
|
76
|
+
#: retried. It is remembered for a day by default. Printable ASCII,
|
|
77
|
+
#: with no space at either end.
|
|
78
|
+
idempotency_key: str | None = None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
82
|
+
class Sent:
|
|
83
|
+
"""The server's answer to a send."""
|
|
84
|
+
|
|
85
|
+
#: The email's id: one, however many addresses it went to.
|
|
86
|
+
id: str
|
|
87
|
+
#: The addresses it was not sent to, because they are on the sending
|
|
88
|
+
#: domain's suppression list. Empty when it went to all. An email with
|
|
89
|
+
#: nobody left in `to` or `cc` is an error instead
|
|
90
|
+
#: (`recipient_suppressed`): a `bcc` alone is not sent.
|
|
91
|
+
suppressed: list[str]
|
|
92
|
+
#: When the email will be sent, for one asked for with `scheduled_at`:
|
|
93
|
+
#: it waits, and nothing was sent yet. None for an email that was sent.
|
|
94
|
+
scheduled_at: datetime | None = None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _addresses(name: str, value: object) -> list[str]:
|
|
98
|
+
# A lone address would otherwise be sent letter by letter.
|
|
99
|
+
if isinstance(value, str) or not isinstance(value, Sequence):
|
|
100
|
+
raise ValueError(f"cairnpost: {name} must be a list of addresses; nothing was sent")
|
|
101
|
+
return list(value)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def wire_of(e: Email) -> dict[str, Any]:
|
|
105
|
+
"""An email as the server takes it.
|
|
106
|
+
|
|
107
|
+
Only the fields it names, since it refuses any other. A field that
|
|
108
|
+
holds nothing is left out.
|
|
109
|
+
"""
|
|
110
|
+
w: dict[str, Any] = {"from": e.from_, "to": _addresses("to", e.to)}
|
|
111
|
+
if e.cc:
|
|
112
|
+
w["cc"] = _addresses("cc", e.cc)
|
|
113
|
+
if e.bcc:
|
|
114
|
+
w["bcc"] = _addresses("bcc", e.bcc)
|
|
115
|
+
if e.reply_to:
|
|
116
|
+
w["reply_to"] = e.reply_to
|
|
117
|
+
w["subject"] = e.subject or ""
|
|
118
|
+
if e.html:
|
|
119
|
+
w["html"] = e.html
|
|
120
|
+
if e.text:
|
|
121
|
+
w["text"] = e.text
|
|
122
|
+
if e.headers:
|
|
123
|
+
w["headers"] = dict(e.headers)
|
|
124
|
+
if e.attachments:
|
|
125
|
+
w["attachments"] = [_file(f) for f in e.attachments]
|
|
126
|
+
if e.scheduled_at is not None:
|
|
127
|
+
w["scheduled_at"] = instant(e.scheduled_at)
|
|
128
|
+
if e.template is not None:
|
|
129
|
+
w["template"] = {"name": e.template.name}
|
|
130
|
+
if e.template.variables:
|
|
131
|
+
w["template"]["variables"] = dict(e.template.variables)
|
|
132
|
+
return w
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _file(f: Attachment) -> dict[str, str]:
|
|
136
|
+
if not isinstance(f.content, bytes | bytearray | memoryview):
|
|
137
|
+
raise ValueError("cairnpost: an attachment's content must be bytes; nothing was sent")
|
|
138
|
+
w = {"filename": f.filename, "content": base64.b64encode(f.content).decode("ascii")}
|
|
139
|
+
if f.content_type:
|
|
140
|
+
w["content_type"] = f.content_type
|
|
141
|
+
if f.content_id:
|
|
142
|
+
w["content_id"] = f.content_id
|
|
143
|
+
return w
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def instant(at: datetime) -> str:
|
|
147
|
+
"""A time as the server reads one."""
|
|
148
|
+
# A time with no zone means one thing here and another on the server.
|
|
149
|
+
if not isinstance(at, datetime) or at.tzinfo is None or at.utcoffset() is None:
|
|
150
|
+
raise ValueError("cairnpost: a time to send the email at must have a zone (tzinfo); nothing was sent")
|
|
151
|
+
return at.astimezone(UTC).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def idempotency(key: str | None) -> dict[str, str]:
|
|
155
|
+
"""The header that makes a send safe to repeat; none for no key."""
|
|
156
|
+
if key is None:
|
|
157
|
+
return {}
|
|
158
|
+
# A key a header cannot carry as it is would be dropped or changed on
|
|
159
|
+
# the way, and the send would quietly not be idempotent. An empty one
|
|
160
|
+
# is no key at all, where one was meant.
|
|
161
|
+
if not header_safe(key):
|
|
162
|
+
raise ValueError(
|
|
163
|
+
"cairnpost: the idempotency_key must be printable ASCII, not empty, with no space at either end; "
|
|
164
|
+
"nothing was sent"
|
|
165
|
+
)
|
|
166
|
+
return {"Idempotency-Key": key}
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def read_sent(v: object, later: bool) -> Sent:
|
|
170
|
+
"""Reads the answer to one send.
|
|
171
|
+
|
|
172
|
+
One with no id is not CairnPost's: whatever is at that address, the
|
|
173
|
+
email is not known to have been sent. Nor is one that does not say an
|
|
174
|
+
email asked for later waits: a server too old to know the field would
|
|
175
|
+
have refused it.
|
|
176
|
+
"""
|
|
177
|
+
o = fields(v)
|
|
178
|
+
sent = Sent(
|
|
179
|
+
id=said(o, "id"), suppressed=texts(o, "suppressed"), scheduled_at=maybe_time(o, "scheduled_at")
|
|
180
|
+
)
|
|
181
|
+
if (sent.scheduled_at is not None) != later:
|
|
182
|
+
raise Misshapen
|
|
183
|
+
return sent
|