simple-module-mail 0.0.47__tar.gz → 0.0.49__tar.gz
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.
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/.gitignore +6 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/PKG-INFO +3 -3
- simple_module_mail-0.0.49/mail/contracts/__init__.py +5 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/mail/core/data_compatibility.py +5 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/mail/core/settings.py +4 -3
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/mail/core/state.py +1 -0
- simple_module_mail-0.0.49/mail/core/transports.py +89 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/mail/delivery/runtime.py +44 -3
- simple_module_mail-0.0.49/mail/delivery/sender.py +144 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/mail/module.py +27 -2
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/pyproject.toml +3 -3
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/tests/core/data_compatibility/test_mail_data_compatibility.py +3 -0
- simple_module_mail-0.0.49/tests/delivery/runtime/test_mail_reload_failures.py +102 -0
- simple_module_mail-0.0.49/tests/delivery/runtime/test_mail_transports.py +257 -0
- simple_module_mail-0.0.49/tests/delivery/sender/test_mail_address_headers.py +120 -0
- simple_module_mail-0.0.49/tests/delivery/sender/test_mail_headers.py +153 -0
- simple_module_mail-0.0.49/tests/delivery/sender/test_mail_outbox.py +90 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/tests/delivery/sender/test_mail_sender.py +68 -4
- simple_module_mail-0.0.47/mail/delivery/sender.py +0 -94
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/LICENSE +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/README.md +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/mail/__init__.py +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/mail/core/__init__.py +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/mail/core/constants.py +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/mail/delivery/__init__.py +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/mail/py.typed +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/tests/core/module/test_mail_lifecycle.py +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/tests/core/settings/test_mail_settings_migration.py +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.49}/tests/delivery/runtime/test_mail_health.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: simple_module_mail
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.49
|
|
4
4
|
Summary: Outgoing mail (SMTP or console) for simple_module apps, configured from the DB-backed settings
|
|
5
5
|
Project-URL: Homepage, https://github.com/antosubash/simple_module_python
|
|
6
6
|
Project-URL: Repository, https://github.com/antosubash/simple_module_python
|
|
@@ -12,8 +12,8 @@ License-File: LICENSE
|
|
|
12
12
|
Keywords: email,mail,simple-module,smtp
|
|
13
13
|
Requires-Python: >=3.12
|
|
14
14
|
Requires-Dist: aiosmtplib<6,>=3.0
|
|
15
|
-
Requires-Dist: simple-module-core==0.0.
|
|
16
|
-
Requires-Dist: simple-module-settings==0.0.
|
|
15
|
+
Requires-Dist: simple-module-core==0.0.49
|
|
16
|
+
Requires-Dist: simple-module-settings==0.0.49
|
|
17
17
|
Description-Content-Type: text/markdown
|
|
18
18
|
|
|
19
19
|
# simple_module_mail
|
|
@@ -34,5 +34,10 @@ async def check_data_compatibility(db: AsyncSession) -> list[DataCompatibilityIs
|
|
|
34
34
|
message="Obsolete system users.mailer/SMTP settings must move to mail.*; "
|
|
35
35
|
"target values win.",
|
|
36
36
|
severity="warning",
|
|
37
|
+
remediation_text=(
|
|
38
|
+
"From the host's development environment, run "
|
|
39
|
+
f"`uv run smpy migrations prepare {UPGRADE_SETTINGS_NAMESPACE} "
|
|
40
|
+
"--head <host-head-or-label@head>`."
|
|
41
|
+
),
|
|
37
42
|
)
|
|
38
43
|
]
|
|
@@ -6,13 +6,12 @@ secret-field pattern (``simple_module_core.secret_fields.is_secret_field``).
|
|
|
6
6
|
|
|
7
7
|
from __future__ import annotations
|
|
8
8
|
|
|
9
|
-
from typing import Literal
|
|
10
|
-
|
|
11
9
|
from pydantic import Field
|
|
12
10
|
from pydantic_settings import SettingsConfigDict
|
|
13
11
|
from simple_module_core.settings_base import DbBackedSettings
|
|
14
12
|
|
|
15
13
|
from mail.core import constants as c
|
|
14
|
+
from mail.core.transports import TRANSPORT_NAMES
|
|
16
15
|
|
|
17
16
|
|
|
18
17
|
class MailSettings(DbBackedSettings):
|
|
@@ -21,7 +20,9 @@ class MailSettings(DbBackedSettings):
|
|
|
21
20
|
# ``DbBackedSettings`` so the DB is the only source (GH #283).
|
|
22
21
|
model_config = SettingsConfigDict(extra="ignore")
|
|
23
22
|
|
|
24
|
-
|
|
23
|
+
# Keep unknown stored names intact: lenient hydration must not silently
|
|
24
|
+
# turn an uninstalled production provider into successful console delivery.
|
|
25
|
+
backend: str = Field(default=c.BACKEND_CONSOLE, json_schema_extra={"choices": TRANSPORT_NAMES})
|
|
25
26
|
smtp_host: str = ""
|
|
26
27
|
smtp_port: int = Field(default=c.DEFAULT_SMTP_PORT, ge=c.MIN_PORT, le=c.MAX_PORT)
|
|
27
28
|
smtp_username: str = ""
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Process-local factories, registered in hooks shared by web and workers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from simple_module_core.mail import ConsoleMailSender, MailSender
|
|
12
|
+
from simple_module_core.settings_base import DbBackedSettings
|
|
13
|
+
|
|
14
|
+
from mail.core import constants as c
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
MailTransportFactory = Callable[[Any, bool], MailSender]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class MailTransport:
|
|
22
|
+
factory: MailTransportFactory
|
|
23
|
+
settings_model: type[DbBackedSettings] | None = None
|
|
24
|
+
package: str | None = None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _console(settings: Any, log_bodies: bool) -> MailSender:
|
|
28
|
+
return ConsoleMailSender(include_body=log_bodies)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _smtp(settings: Any, log_bodies: bool) -> MailSender:
|
|
32
|
+
from mail.delivery.sender import SmtpMailSender
|
|
33
|
+
|
|
34
|
+
return SmtpMailSender(
|
|
35
|
+
host=settings.smtp_host,
|
|
36
|
+
port=settings.smtp_port,
|
|
37
|
+
username=settings.smtp_username,
|
|
38
|
+
password=settings.smtp_password,
|
|
39
|
+
from_address=settings.smtp_from,
|
|
40
|
+
use_tls=settings.smtp_tls,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
_transports: dict[str, MailTransport] = {
|
|
45
|
+
c.BACKEND_CONSOLE: MailTransport(_console),
|
|
46
|
+
c.BACKEND_SMTP: MailTransport(_smtp),
|
|
47
|
+
}
|
|
48
|
+
# Shared with field metadata so the generic admin select sees later registrations.
|
|
49
|
+
TRANSPORT_NAMES = sorted(_transports)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def register_mail_transport(
|
|
53
|
+
name: str,
|
|
54
|
+
factory: MailTransportFactory,
|
|
55
|
+
*,
|
|
56
|
+
settings_model: type[DbBackedSettings] | None = None,
|
|
57
|
+
package: str | None = None,
|
|
58
|
+
) -> None:
|
|
59
|
+
"""Register a synchronous factory(options, log_bodies) in each process.
|
|
60
|
+
|
|
61
|
+
Call in ``register_event_handlers`` before returning for ``app is None``.
|
|
62
|
+
With a settings model, *package* names its registered module settings;
|
|
63
|
+
otherwise the factory receives ``MailSettings``. Identical registration
|
|
64
|
+
is idempotent; conflicting names (including built-ins) are rejected.
|
|
65
|
+
"""
|
|
66
|
+
if not re.fullmatch(r"[a-z0-9][a-z0-9_-]*", name):
|
|
67
|
+
raise ValueError("Mail transport names must be lowercase slugs")
|
|
68
|
+
if (settings_model is None) != (package is None):
|
|
69
|
+
raise ValueError("Mail transport settings_model and package must be supplied together")
|
|
70
|
+
if settings_model is not None and not issubclass(settings_model, DbBackedSettings):
|
|
71
|
+
raise TypeError("Mail transport settings must inherit DbBackedSettings")
|
|
72
|
+
transport = MailTransport(factory, settings_model, package)
|
|
73
|
+
if name in _transports and _transports[name] != transport:
|
|
74
|
+
raise ValueError(f"Mail transport {name!r} is already registered")
|
|
75
|
+
_transports[name] = transport
|
|
76
|
+
TRANSPORT_NAMES[:] = sorted(_transports)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def get_mail_transport(name: str, *, development: bool = False) -> MailTransport:
|
|
80
|
+
"""Fail clearly for a missing provider; development may log instead."""
|
|
81
|
+
if name in _transports:
|
|
82
|
+
return _transports[name]
|
|
83
|
+
message = (
|
|
84
|
+
f"Unknown mail transport {name!r}; registered transports: {', '.join(TRANSPORT_NAMES)}"
|
|
85
|
+
)
|
|
86
|
+
if not development:
|
|
87
|
+
raise ValueError(message)
|
|
88
|
+
logger.warning("%s; falling back to console", message)
|
|
89
|
+
return _transports[c.BACKEND_CONSOLE]
|
|
@@ -9,11 +9,17 @@ from settings.core.service import SettingService
|
|
|
9
9
|
from settings.module_settings.store import SettingsStore
|
|
10
10
|
from simple_module_core.environments import NON_PROD_ENVIRONMENTS
|
|
11
11
|
from simple_module_core.health import HealthCheckResult, HealthStatus
|
|
12
|
-
from simple_module_core.mail import
|
|
12
|
+
from simple_module_core.mail import (
|
|
13
|
+
MailMessage,
|
|
14
|
+
MailSender,
|
|
15
|
+
current_mail_sender,
|
|
16
|
+
install_default_mail_sender,
|
|
17
|
+
)
|
|
13
18
|
from simple_module_core.settings_hydrate import hydrate_settings
|
|
14
19
|
|
|
15
20
|
from mail.core import constants as c
|
|
16
21
|
from mail.core.settings import MailSettings
|
|
22
|
+
from mail.core.transports import get_mail_transport
|
|
17
23
|
from mail.delivery.sender import build_sender
|
|
18
24
|
|
|
19
25
|
|
|
@@ -24,7 +30,16 @@ async def resolve_sender_from_db(db: Any) -> MailSender:
|
|
|
24
30
|
"""
|
|
25
31
|
store = SettingsStore(SettingService(db))
|
|
26
32
|
settings = await hydrate_settings(MailSettings, store, c.MODULE_PACKAGE, lenient=True)
|
|
27
|
-
|
|
33
|
+
development = os.environ.get("SM_ENVIRONMENT", "development") == "development"
|
|
34
|
+
transport = get_mail_transport(settings.backend, development=development)
|
|
35
|
+
options = None
|
|
36
|
+
if transport.settings_model is not None and transport.package is not None:
|
|
37
|
+
options = await hydrate_settings(
|
|
38
|
+
transport.settings_model, store, transport.package, lenient=True
|
|
39
|
+
)
|
|
40
|
+
return build_sender(
|
|
41
|
+
settings, options=options, log_bodies=_worker_is_non_prod(), development=development
|
|
42
|
+
)
|
|
28
43
|
|
|
29
44
|
|
|
30
45
|
def _worker_is_non_prod() -> bool:
|
|
@@ -33,13 +48,39 @@ def _worker_is_non_prod() -> bool:
|
|
|
33
48
|
return os.environ.get("SM_ENVIRONMENT", "development") in NON_PROD_ENVIRONMENTS
|
|
34
49
|
|
|
35
50
|
|
|
51
|
+
class _UnavailableMailSender:
|
|
52
|
+
# Keep callers on the send path so durable delivery fails and retries.
|
|
53
|
+
delivers_email = True
|
|
54
|
+
|
|
55
|
+
async def send(self, message: MailMessage) -> None:
|
|
56
|
+
await self.verify_connection()
|
|
57
|
+
|
|
58
|
+
async def verify_connection(self) -> None:
|
|
59
|
+
raise RuntimeError("Mail transport is unavailable: configured sender construction failed")
|
|
60
|
+
|
|
61
|
+
|
|
36
62
|
def install_app_sender(app: Any) -> None:
|
|
37
63
|
"""Install a sender built from *app*'s current mail settings.
|
|
38
64
|
|
|
39
65
|
Bodies are logged only in development or testing (host ``environment``).
|
|
40
66
|
"""
|
|
41
67
|
log_bodies = app.state.sm.settings.environment in NON_PROD_ENVIRONMENTS
|
|
42
|
-
|
|
68
|
+
development = app.state.sm.settings.environment == "development"
|
|
69
|
+
settings = app.state.mail.settings
|
|
70
|
+
try:
|
|
71
|
+
transport = get_mail_transport(settings.backend, development=development)
|
|
72
|
+
options = None
|
|
73
|
+
if transport.package is not None:
|
|
74
|
+
options = getattr(app.state, transport.package).settings
|
|
75
|
+
sender = build_sender(
|
|
76
|
+
settings, options=options, log_bodies=log_bodies, development=development
|
|
77
|
+
)
|
|
78
|
+
except Exception:
|
|
79
|
+
app.state.mail.sender_failed = True
|
|
80
|
+
install_default_mail_sender(_UnavailableMailSender())
|
|
81
|
+
raise
|
|
82
|
+
app.state.mail.sender_failed = False
|
|
83
|
+
install_default_mail_sender(sender)
|
|
43
84
|
|
|
44
85
|
|
|
45
86
|
async def check_smtp() -> HealthCheckResult:
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Mail senders and the settings -> sender mapping."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
from email import policy
|
|
7
|
+
from email.message import EmailMessage
|
|
8
|
+
from email.utils import formatdate, make_msgid
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import aiosmtplib
|
|
12
|
+
from simple_module_core.mail import (
|
|
13
|
+
MailMessage,
|
|
14
|
+
MailSender,
|
|
15
|
+
smtp_address_header,
|
|
16
|
+
validate_mail_headers,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from mail.core import constants as c
|
|
20
|
+
from mail.core.settings import MailSettings
|
|
21
|
+
from mail.core.transports import get_mail_transport
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class _SmtpPolicy(policy.EmailPolicy):
|
|
25
|
+
"""Keep UTF-8 header lines within SMTP's byte limit."""
|
|
26
|
+
|
|
27
|
+
def fold_binary(self, name: str, value: Any) -> bytes:
|
|
28
|
+
folded = super().fold_binary(name, value)
|
|
29
|
+
if self.utf8 and any(len(line) > 998 for line in folded.split(b"\r\n")):
|
|
30
|
+
# The stdlib counts characters; UTF-8 needs up to four bytes each.
|
|
31
|
+
return policy.EmailPolicy.fold_binary(self.clone(max_line_length=998 // 4), name, value)
|
|
32
|
+
return folded
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class SmtpMailSender:
|
|
36
|
+
"""Delivers through an SMTP server with aiosmtplib."""
|
|
37
|
+
|
|
38
|
+
delivers_email = True
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
host: str,
|
|
43
|
+
port: int,
|
|
44
|
+
username: str,
|
|
45
|
+
password: str,
|
|
46
|
+
from_address: str,
|
|
47
|
+
use_tls: bool,
|
|
48
|
+
) -> None:
|
|
49
|
+
self._host = host
|
|
50
|
+
self._port = port
|
|
51
|
+
self._username = username
|
|
52
|
+
self._password = password
|
|
53
|
+
self._from = from_address
|
|
54
|
+
self._use_tls = use_tls
|
|
55
|
+
|
|
56
|
+
async def send(self, message: MailMessage) -> None:
|
|
57
|
+
email = EmailMessage()
|
|
58
|
+
email["From"] = smtp_address_header(self._from)
|
|
59
|
+
email["To"] = smtp_address_header(message.to)
|
|
60
|
+
if message.reply_to is not None:
|
|
61
|
+
email["Reply-To"] = smtp_address_header(message.reply_to)
|
|
62
|
+
email["Subject"] = message.subject
|
|
63
|
+
email["Date"] = formatdate(localtime=False, usegmt=True)
|
|
64
|
+
from_header = email["From"]
|
|
65
|
+
domain = None
|
|
66
|
+
if not from_header.defects and len(from_header.addresses) == 1:
|
|
67
|
+
domain = from_header.addresses[0].domain or None
|
|
68
|
+
email["Message-ID"] = make_msgid(domain=domain)
|
|
69
|
+
# Revalidate because a frozen dataclass can still contain a mutable dictionary.
|
|
70
|
+
for name, value in validate_mail_headers(message.headers).items():
|
|
71
|
+
email[name] = value
|
|
72
|
+
email.set_content(message.text)
|
|
73
|
+
if message.html:
|
|
74
|
+
email.add_alternative(message.html, subtype="html")
|
|
75
|
+
for attachment in message.attachments:
|
|
76
|
+
maintype, subtype = attachment.content_type.split("/")
|
|
77
|
+
email.add_attachment(
|
|
78
|
+
attachment.content,
|
|
79
|
+
maintype=maintype,
|
|
80
|
+
subtype=subtype,
|
|
81
|
+
filename=attachment.filename,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
# Never infer the SMTP envelope from custom or trace headers.
|
|
85
|
+
sender = from_header.addresses[0].addr_spec
|
|
86
|
+
recipients = [address.addr_spec for address in email["To"].addresses]
|
|
87
|
+
utf8_required = not (sender.isascii() and all(address.isascii() for address in recipients))
|
|
88
|
+
# Typeshed's EmailPolicy constructor self type excludes subclasses.
|
|
89
|
+
wire_policy = _SmtpPolicy( # ty: ignore[invalid-argument-type]
|
|
90
|
+
utf8=utf8_required, linesep="\r\n"
|
|
91
|
+
)
|
|
92
|
+
# Avoid encoded words in long RFC 2369 URLs; bytes bypass aiosmtplib's refolding.
|
|
93
|
+
wire = email.as_bytes(policy=wire_policy.clone(max_line_length=998, cte_type="7bit"))
|
|
94
|
+
await aiosmtplib.send(
|
|
95
|
+
wire,
|
|
96
|
+
sender=sender,
|
|
97
|
+
recipients=recipients,
|
|
98
|
+
mail_options=["SMTPUTF8"] if utf8_required else [],
|
|
99
|
+
hostname=self._host,
|
|
100
|
+
port=self._port,
|
|
101
|
+
username=self._username or None,
|
|
102
|
+
password=self._password or None,
|
|
103
|
+
use_tls=self._use_tls,
|
|
104
|
+
timeout=c.SMTP_TIMEOUT_SECONDS,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
async def verify_connection(self) -> None:
|
|
108
|
+
"""Open an SMTP session and authenticate, then hang up.
|
|
109
|
+
|
|
110
|
+
Deliberately stops short of sending anything: an admin checking their
|
|
111
|
+
config should not put a stray message in someone's inbox. Raises
|
|
112
|
+
whatever aiosmtplib raises so the caller can show the real reason.
|
|
113
|
+
"""
|
|
114
|
+
client = aiosmtplib.SMTP(
|
|
115
|
+
hostname=self._host,
|
|
116
|
+
port=self._port,
|
|
117
|
+
use_tls=self._use_tls,
|
|
118
|
+
timeout=c.SMTP_TIMEOUT_SECONDS,
|
|
119
|
+
)
|
|
120
|
+
await client.connect()
|
|
121
|
+
try:
|
|
122
|
+
if self._username:
|
|
123
|
+
await client.login(self._username, self._password or "")
|
|
124
|
+
finally:
|
|
125
|
+
# A failure hanging up must not mask the login error being unwound.
|
|
126
|
+
with contextlib.suppress(Exception):
|
|
127
|
+
await client.quit()
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def build_sender(
|
|
131
|
+
settings: MailSettings,
|
|
132
|
+
*,
|
|
133
|
+
log_bodies: bool = True,
|
|
134
|
+
development: bool = True,
|
|
135
|
+
options: Any = None,
|
|
136
|
+
) -> MailSender:
|
|
137
|
+
"""Build the selected registered transport with its module-owned options.
|
|
138
|
+
|
|
139
|
+
*log_bodies* is false outside development and testing: a console backend
|
|
140
|
+
left in place in production must not write reset and invite tokens to the
|
|
141
|
+
log, so there it logs only recipient, subject and attachment metadata.
|
|
142
|
+
"""
|
|
143
|
+
transport = get_mail_transport(settings.backend, development=development)
|
|
144
|
+
return transport.factory(settings if options is None else options, log_bodies)
|
|
@@ -14,6 +14,7 @@ if TYPE_CHECKING:
|
|
|
14
14
|
from fastapi import FastAPI
|
|
15
15
|
from simple_module_core.data_compatibility import DataCompatibilityIssue
|
|
16
16
|
from simple_module_core.events import EventBus
|
|
17
|
+
from simple_module_core.invalidation import InvalidationBus
|
|
17
18
|
|
|
18
19
|
|
|
19
20
|
class MailModule(ModuleBase):
|
|
@@ -46,7 +47,7 @@ class MailModule(ModuleBase):
|
|
|
46
47
|
)
|
|
47
48
|
)
|
|
48
49
|
|
|
49
|
-
def register_event_handlers(self, bus: EventBus, app: FastAPI | None
|
|
50
|
+
def register_event_handlers(self, bus: EventBus, app: FastAPI | None) -> None:
|
|
50
51
|
# Before the ``app is None`` return: the outbox worker builds modules
|
|
51
52
|
# without an app and still has to send durable mail.
|
|
52
53
|
from mail.delivery.runtime import resolve_sender_from_db
|
|
@@ -60,12 +61,32 @@ class MailModule(ModuleBase):
|
|
|
60
61
|
from mail.delivery.runtime import install_app_sender
|
|
61
62
|
|
|
62
63
|
async def _reinstall(event: SettingsReloaded) -> None:
|
|
64
|
+
from mail.core.transports import get_mail_transport
|
|
65
|
+
|
|
63
66
|
if event.package != c.MODULE_PACKAGE:
|
|
64
|
-
|
|
67
|
+
transport = get_mail_transport(
|
|
68
|
+
app.state.mail.settings.backend,
|
|
69
|
+
development=app.state.sm.settings.environment == "development",
|
|
70
|
+
)
|
|
71
|
+
if event.package != transport.package:
|
|
72
|
+
return
|
|
65
73
|
install_app_sender(app)
|
|
66
74
|
|
|
67
75
|
bus.subscribe(SettingsReloaded, _reinstall)
|
|
68
76
|
|
|
77
|
+
def register_invalidations(self, bus: InvalidationBus, app: FastAPI) -> None:
|
|
78
|
+
from settings.core.invalidation import CHANNEL
|
|
79
|
+
from simple_module_core.invalidation_refresh import InvalidationRefresh
|
|
80
|
+
|
|
81
|
+
from mail.delivery.runtime import install_app_sender
|
|
82
|
+
|
|
83
|
+
async def retry_failed_sender(key: str | None) -> None:
|
|
84
|
+
# Hydration can succeed while construction fails, leaving no later change event.
|
|
85
|
+
if app.state.mail.sender_failed:
|
|
86
|
+
install_app_sender(app)
|
|
87
|
+
|
|
88
|
+
self._refresh = InvalidationRefresh(bus, CHANNEL, retry_failed_sender)
|
|
89
|
+
|
|
69
90
|
async def check_data_compatibility(self, db: Any) -> list[DataCompatibilityIssue]:
|
|
70
91
|
from mail.core.data_compatibility import check_data_compatibility
|
|
71
92
|
|
|
@@ -75,7 +96,11 @@ class MailModule(ModuleBase):
|
|
|
75
96
|
from mail.delivery.runtime import install_app_sender
|
|
76
97
|
|
|
77
98
|
install_app_sender(app)
|
|
99
|
+
if hasattr(self, "_refresh"):
|
|
100
|
+
self._refresh.start()
|
|
78
101
|
|
|
79
102
|
async def on_shutdown(self, app: FastAPI) -> None:
|
|
103
|
+
if hasattr(self, "_refresh"):
|
|
104
|
+
await self._refresh.stop()
|
|
80
105
|
install_mail_sender(None)
|
|
81
106
|
install_mail_resolver(None)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "simple_module_mail"
|
|
3
|
-
version = "0.0.
|
|
3
|
+
version = "0.0.49"
|
|
4
4
|
description = "Outgoing mail (SMTP or console) for simple_module apps, configured from the DB-backed settings"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
@@ -9,8 +9,8 @@ requires-python = ">=3.12"
|
|
|
9
9
|
authors = [{ name = "Anto Subash", email = "antosubash@live.com" }]
|
|
10
10
|
keywords = ["simple-module", "mail", "smtp", "email"]
|
|
11
11
|
dependencies = [
|
|
12
|
-
"simple_module_core==0.0.
|
|
13
|
-
"simple_module_settings==0.0.
|
|
12
|
+
"simple_module_core==0.0.49",
|
|
13
|
+
"simple_module_settings==0.0.49",
|
|
14
14
|
"aiosmtplib>=3.0,<6",
|
|
15
15
|
]
|
|
16
16
|
|
|
@@ -34,5 +34,8 @@ async def test_mail_obsolete_system_keys(scope, scope_id, key, expected):
|
|
|
34
34
|
if expected:
|
|
35
35
|
assert issues[0].upgrade_id == "mail.settings_namespace_v1"
|
|
36
36
|
assert issues[0].severity == "warning"
|
|
37
|
+
assert "uv run smpy migrations prepare mail.settings_namespace_v1 --head" in (
|
|
38
|
+
issues[0].remediation_text or ""
|
|
39
|
+
)
|
|
37
40
|
finally:
|
|
38
41
|
await engine.dispose()
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Failed transport construction blocks delivery until an unchanged refresh recovers."""
|
|
2
|
+
|
|
3
|
+
from types import SimpleNamespace
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from mail.contracts import register_mail_transport
|
|
7
|
+
from mail.core import transports
|
|
8
|
+
from mail.core.settings import MailSettings
|
|
9
|
+
from mail.core.state import MailState
|
|
10
|
+
from mail.module import MailModule
|
|
11
|
+
from settings.contracts.events import SettingsReloaded
|
|
12
|
+
from settings.core.invalidation import reload_package
|
|
13
|
+
from simple_module_core import mail as core_mail
|
|
14
|
+
from simple_module_core.events import EventBus
|
|
15
|
+
from simple_module_core.health import HealthStatus
|
|
16
|
+
from simple_module_core.invalidation import InvalidationBus
|
|
17
|
+
from simple_module_core.module_settings import register_module_settings
|
|
18
|
+
from simple_module_core.settings_base import DbBackedSettings
|
|
19
|
+
from simple_module_test.mail import CapturedMail
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ProviderSettings(DbBackedSettings):
|
|
23
|
+
from_address: str = "old@test"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@pytest.mark.parametrize("refresh_key", [None, "mail"])
|
|
27
|
+
@pytest.mark.parametrize("package", ["mail", "provider"])
|
|
28
|
+
async def test_failed_reload_blocks_delivery_and_unchanged_refresh_recovers(
|
|
29
|
+
monkeypatch, refresh_key, package
|
|
30
|
+
):
|
|
31
|
+
from mail.delivery.runtime import check_smtp
|
|
32
|
+
|
|
33
|
+
monkeypatch.setattr(transports, "_transports", dict(transports._transports))
|
|
34
|
+
monkeypatch.setattr(transports, "TRANSPORT_NAMES", list(transports.TRANSPORT_NAMES))
|
|
35
|
+
available = True
|
|
36
|
+
recovered = CapturedMail()
|
|
37
|
+
|
|
38
|
+
def factory(options, log_bodies):
|
|
39
|
+
if not available:
|
|
40
|
+
raise RuntimeError("provider unavailable")
|
|
41
|
+
return recovered
|
|
42
|
+
|
|
43
|
+
register_mail_transport(
|
|
44
|
+
"recovering", factory, settings_model=ProviderSettings, package="provider"
|
|
45
|
+
)
|
|
46
|
+
app = SimpleNamespace(
|
|
47
|
+
state=SimpleNamespace(
|
|
48
|
+
sm=SimpleNamespace(settings=SimpleNamespace(environment="testing")),
|
|
49
|
+
mail=MailState(settings=MailSettings()),
|
|
50
|
+
)
|
|
51
|
+
)
|
|
52
|
+
register_module_settings(app, "mail", MailSettings, lambda s: MailState(settings=s))
|
|
53
|
+
register_module_settings(
|
|
54
|
+
app, "provider", ProviderSettings, lambda s: SimpleNamespace(settings=s)
|
|
55
|
+
)
|
|
56
|
+
if package == "provider":
|
|
57
|
+
app.state.mail.settings = MailSettings(backend="recovering")
|
|
58
|
+
module = MailModule()
|
|
59
|
+
events = EventBus()
|
|
60
|
+
module.register_event_handlers(events, app)
|
|
61
|
+
module.register_invalidations(InvalidationBus(), app)
|
|
62
|
+
await module.on_startup(app)
|
|
63
|
+
available = False
|
|
64
|
+
|
|
65
|
+
class Overrides:
|
|
66
|
+
async def get_overrides(self, package):
|
|
67
|
+
if package == "mail":
|
|
68
|
+
return {"backend": ("recovering", "string")}
|
|
69
|
+
return {"from_address": ("new@test", "string")}
|
|
70
|
+
|
|
71
|
+
changed = []
|
|
72
|
+
|
|
73
|
+
async def record(event):
|
|
74
|
+
changed.append(event)
|
|
75
|
+
|
|
76
|
+
events.subscribe(SettingsReloaded, record)
|
|
77
|
+
message = core_mail.MailMessage("to@test", "Subject", "Body")
|
|
78
|
+
try:
|
|
79
|
+
await reload_package(app, events, Overrides(), package)
|
|
80
|
+
assert app.state.mail.settings.backend == "recovering"
|
|
81
|
+
for sender in (
|
|
82
|
+
core_mail.current_mail_sender(),
|
|
83
|
+
await core_mail.resolve_mail_sender(object()),
|
|
84
|
+
):
|
|
85
|
+
with pytest.raises(RuntimeError, match=r"Mail transport.*unavailable"):
|
|
86
|
+
await sender.send(message)
|
|
87
|
+
assert (await check_smtp()).status is HealthStatus.UNHEALTHY
|
|
88
|
+
with pytest.raises(RuntimeError, match="provider unavailable"):
|
|
89
|
+
await module._refresh.refresh(refresh_key)
|
|
90
|
+
with pytest.raises(RuntimeError, match=r"Mail transport.*unavailable"):
|
|
91
|
+
await core_mail.current_mail_sender().send(message)
|
|
92
|
+
|
|
93
|
+
# No new SettingsReloaded event: the settings already contain this backend.
|
|
94
|
+
available = True
|
|
95
|
+
await reload_package(app, events, Overrides(), package)
|
|
96
|
+
assert len(changed) == 1
|
|
97
|
+
await module._refresh.refresh(refresh_key)
|
|
98
|
+
await core_mail.current_mail_sender().send(message)
|
|
99
|
+
assert recovered.messages == [message]
|
|
100
|
+
assert (await check_smtp()).status is HealthStatus.HEALTHY
|
|
101
|
+
finally:
|
|
102
|
+
await module.on_shutdown(app)
|