Skip to content

Commit f349829

Browse files
fix(messenger): align the SMTP timeout contract with the PHP master (#278)
Re-base the timeout resolution on MichaelC8E's PHP #286 (now the reference for this issue) so all four frameworks behave the same: - priority is constructor > TINA4_MAIL_TIMEOUT > 30; the SMTP_TIMEOUT fallback is dropped. - an explicit constructor value below 1 second RAISES (a programming error), rather than silently coercing to the default. - a garbage or < 1 env value warns ONCE and uses the default 30 (0 is garbage, not an opt-out: to the socket it means do-not-wait). - a silent server is already reported AS a timeout (smtplib surfaces socket.timeout -> 'timed out' in the result message); the test now asserts it. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Signed-off-by: Andre van Zuydam <andrevanzuydam@gmail.com>
1 parent 0751f7f commit f349829

2 files changed

Lines changed: 73 additions & 16 deletions

File tree

‎tests/test_messenger_timeout_278.py‎

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -55,26 +55,28 @@ def accept_loop():
5555
server.close()
5656

5757

58-
def _time_send(**kwargs) -> float:
58+
def _send(**kwargs):
5959
messenger = Messenger(host="127.0.0.1", encryption="none",
6060
from_address="app@localhost", **kwargs)
6161
start = time.monotonic()
6262
result = messenger.send("someone@localhost", "test", "hello")
6363
elapsed = time.monotonic() - start
6464
# The host never speaks SMTP, so the send always fails - what matters is HOW
65-
# LONG it waited.
65+
# LONG it waited, and that the failure is reported AS a timeout.
6666
assert result["success"] is False
67-
return elapsed
67+
return elapsed, result
6868

6969

70-
def test_constructor_timeout_bounds_the_send(silent_smtp):
71-
elapsed = _time_send(port=silent_smtp, timeout=1)
70+
def test_constructor_timeout_bounds_the_send_and_reports_a_timeout(silent_smtp):
71+
elapsed, result = _send(port=silent_smtp, timeout=1)
7272
assert elapsed < 8, f"a 1 s timeout should fail fast, not hold ~30 s (took {elapsed:.1f} s)"
73+
assert "tim" in str(result["message"]).lower(), \
74+
f"a silent server must be reported as a timeout, got {result['message']!r}"
7375

7476

7577
def test_env_timeout_bounds_the_send(silent_smtp, monkeypatch):
7678
monkeypatch.setenv("TINA4_MAIL_TIMEOUT", "1")
77-
elapsed = _time_send(port=silent_smtp)
79+
elapsed, _ = _send(port=silent_smtp)
7880
assert elapsed < 8, f"TINA4_MAIL_TIMEOUT=1 should fail fast (took {elapsed:.1f} s)"
7981

8082

@@ -83,6 +85,26 @@ def test_default_timeout_is_thirty_seconds():
8385
assert Messenger(host="127.0.0.1", encryption="none").timeout == 30
8486

8587

86-
def test_a_bad_timeout_value_falls_back_to_the_default(monkeypatch):
88+
def test_a_bad_env_value_warns_once_and_falls_back_to_the_default(monkeypatch):
8789
monkeypatch.setenv("TINA4_MAIL_TIMEOUT", "not-a-number")
8890
assert Messenger(host="127.0.0.1", encryption="none").timeout == 30
91+
92+
93+
def test_a_zero_env_value_falls_back_to_the_default(monkeypatch):
94+
# Zero is garbage, not an opt-out: to the socket it means "do not wait at all".
95+
monkeypatch.setenv("TINA4_MAIL_TIMEOUT", "0")
96+
assert Messenger(host="127.0.0.1", encryption="none").timeout == 30
97+
98+
99+
def test_an_explicit_sub_second_timeout_is_refused():
100+
# An explicit value is the caller's own instruction, so < 1 is a bug, not a default.
101+
with pytest.raises(ValueError):
102+
Messenger(host="127.0.0.1", encryption="none", timeout=0)
103+
104+
105+
def test_smtp_timeout_env_is_no_longer_honoured(monkeypatch):
106+
# The SMTP_TIMEOUT fallback was dropped for parity with the PHP master:
107+
# only TINA4_MAIL_TIMEOUT configures the timeout now.
108+
monkeypatch.delenv("TINA4_MAIL_TIMEOUT", raising=False)
109+
monkeypatch.setenv("SMTP_TIMEOUT", "1")
110+
assert Messenger(host="127.0.0.1", encryption="none").timeout == 30

‎tina4_python/messenger/__init__.py‎

Lines changed: 44 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,46 @@ def _parse_mail_redirect_list(raw: str) -> list[str]:
130130
class Messenger:
131131
"""SMTP email client using Python stdlib."""
132132

133+
#: Default socket timeout, in seconds - the value this class has always used.
134+
TIMEOUT_DEFAULT = 30
135+
#: Raw TINA4_MAIL_TIMEOUT values already warned about, so a bad one is said once.
136+
_timeout_warned: set = set()
137+
138+
@staticmethod
139+
def _resolve_timeout(explicit, raw):
140+
"""Resolve the SMTP socket timeout to whole seconds (issue #278).
141+
142+
Priority: an explicit constructor value, else TINA4_MAIL_TIMEOUT, else
143+
TIMEOUT_DEFAULT. An explicit value is the caller's own instruction, so one
144+
below a second is a programming error and raises. A bad env value is a
145+
misconfiguration: warn once and use the default rather than guess. Zero
146+
and negative are garbage, not an opt-out - to the socket 0 means "do not
147+
wait at all", so no send could succeed. Mirrors the PHP master
148+
(Messenger::resolveTimeout, tina4-php#286).
149+
"""
150+
if explicit is not None:
151+
explicit = int(explicit)
152+
if explicit < 1:
153+
raise ValueError(
154+
f"Messenger timeout must be at least 1 second, got {explicit}.")
155+
return explicit
156+
if raw is None or str(raw).strip() == "":
157+
return Messenger.TIMEOUT_DEFAULT
158+
try:
159+
seconds = int(str(raw).strip())
160+
except ValueError:
161+
seconds = None
162+
if seconds is None or seconds < 1:
163+
if raw not in Messenger._timeout_warned:
164+
Messenger._timeout_warned.add(raw)
165+
from tina4_python.debug import Log
166+
Log.warning(
167+
"TINA4_MAIL_TIMEOUT must be a whole number of seconds and at "
168+
f"least 1, got {raw!r} - using the default of "
169+
f"{Messenger.TIMEOUT_DEFAULT} seconds")
170+
return Messenger.TIMEOUT_DEFAULT
171+
return seconds
172+
133173
def __init__(self, host: str = None, port: int = None,
134174
username: str = None, password: str = None,
135175
from_address: str = None, from_name: str = None,
@@ -151,15 +191,10 @@ def __init__(self, host: str = None, port: int = None,
151191
"TINA4_MAIL_FROM", self.username or "noreply@localhost")
152192
self.from_name = from_name or os.environ.get("TINA4_MAIL_FROM_NAME", "")
153193

154-
# SMTP socket timeout (seconds): how long a connect, and each reply,
155-
# may block before the send fails. Configurable so a host that accepts
156-
# then goes silent cannot hold a worker for the full default. Priority:
157-
# constructor > TINA4_MAIL_TIMEOUT > SMTP_TIMEOUT > 30 (issue #278).
158-
try:
159-
self.timeout = int(timeout) if timeout is not None else int(
160-
os.environ.get("TINA4_MAIL_TIMEOUT") or os.environ.get("SMTP_TIMEOUT") or 30)
161-
except (TypeError, ValueError):
162-
self.timeout = 30
194+
# SMTP socket timeout (seconds): the connect, and each reply, may block
195+
# this long before the send fails. Priority: constructor >
196+
# TINA4_MAIL_TIMEOUT > 30 (issue #278). Whole seconds, at least 1.
197+
self.timeout = self._resolve_timeout(timeout, os.environ.get("TINA4_MAIL_TIMEOUT"))
163198

164199
# Encryption: constructor > .env > backward-compat use_tls > default "tls".
165200
# Validated here (ADR-0071 section 2): an unknown value raises now, it

0 commit comments

Comments
 (0)