Skip to content

Commit a70d153

Browse files
authored
Merge pull request #203 from tina4stack/fix/issue-278-smtp-timeout
fix(messenger): configurable SMTP timeout (#278)
2 parents 1e91e5c + f349829 commit a70d153

2 files changed

Lines changed: 157 additions & 2 deletions

File tree

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
# Copyright (c) 2026 Code Infinity
2+
# SPDX-License-Identifier: MPL-2.0
3+
# This Source Code Form is subject to the terms of the Mozilla Public
4+
# License, v. 2.0. If a copy of the MPL was not distributed with this
5+
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
6+
7+
"""Regression for tina4-python#278: the SMTP send timeout is configurable.
8+
9+
No mocks. A REAL TCP server accepts the connection and then says nothing, so
10+
send() blocks waiting for the SMTP greeting. With the timeout left at its 30 s
11+
default that is a 30 s hold; with a 1 s timeout the send must fail in about a
12+
second. The wall-clock is the instrument: a configured 1 s timeout that is
13+
honoured finishes well under the default, a hardcoded 30 s does not.
14+
"""
15+
16+
import os
17+
import socket
18+
import threading
19+
import time
20+
21+
import pytest
22+
23+
from tina4_python.messenger import Messenger
24+
25+
26+
@pytest.fixture
27+
def silent_smtp():
28+
"""A server that accepts TCP connections and never sends a byte."""
29+
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
30+
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
31+
server.bind(("127.0.0.1", 0))
32+
server.listen(8)
33+
port = server.getsockname()[1]
34+
held = []
35+
stop = threading.Event()
36+
37+
def accept_loop():
38+
server.settimeout(0.5)
39+
while not stop.is_set():
40+
try:
41+
conn, _ = server.accept()
42+
held.append(conn) # keep it open, never reply
43+
except OSError:
44+
pass
45+
46+
thread = threading.Thread(target=accept_loop, daemon=True)
47+
thread.start()
48+
try:
49+
yield port
50+
finally:
51+
stop.set()
52+
thread.join(timeout=2)
53+
for conn in held:
54+
conn.close()
55+
server.close()
56+
57+
58+
def _send(**kwargs):
59+
messenger = Messenger(host="127.0.0.1", encryption="none",
60+
from_address="app@localhost", **kwargs)
61+
start = time.monotonic()
62+
result = messenger.send("someone@localhost", "test", "hello")
63+
elapsed = time.monotonic() - start
64+
# The host never speaks SMTP, so the send always fails - what matters is HOW
65+
# LONG it waited, and that the failure is reported AS a timeout.
66+
assert result["success"] is False
67+
return elapsed, result
68+
69+
70+
def test_constructor_timeout_bounds_the_send_and_reports_a_timeout(silent_smtp):
71+
elapsed, result = _send(port=silent_smtp, timeout=1)
72+
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}"
75+
76+
77+
def test_env_timeout_bounds_the_send(silent_smtp, monkeypatch):
78+
monkeypatch.setenv("TINA4_MAIL_TIMEOUT", "1")
79+
elapsed, _ = _send(port=silent_smtp)
80+
assert elapsed < 8, f"TINA4_MAIL_TIMEOUT=1 should fail fast (took {elapsed:.1f} s)"
81+
82+
83+
def test_default_timeout_is_thirty_seconds():
84+
# The default is unchanged (no behaviour change for apps that set nothing).
85+
assert Messenger(host="127.0.0.1", encryption="none").timeout == 30
86+
87+
88+
def test_a_bad_env_value_warns_once_and_falls_back_to_the_default(monkeypatch):
89+
monkeypatch.setenv("TINA4_MAIL_TIMEOUT", "not-a-number")
90+
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: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,13 +130,53 @@ 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,
136176
encryption: str = None, use_tls: bool = None,
137177
imap_host: str = None, imap_port: int = None,
138178
imap_username: str = None, imap_password: str = None,
139-
imap_encryption: str = None):
179+
imap_encryption: str = None, timeout: int = None):
140180
# SMTP (send) — priority: constructor > .env > sensible default
141181
# Whether a host was actually CONFIGURED, which is not the same as
142182
# self.host being set: self.host falls back to "localhost", so it is never
@@ -151,6 +191,11 @@ 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

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"))
198+
154199
# Encryption: constructor > .env > backward-compat use_tls > default "tls".
155200
# Validated here (ADR-0071 section 2): an unknown value raises now, it
156201
# never reaches a socket as "plaintext".
@@ -421,7 +466,7 @@ def _smtp_open(self, timeout: int) -> smtplib.SMTP:
421466

422467
def _smtp_send(self, msg: MIMEText | MIMEMultipart, recipients: list[str]) -> str:
423468
"""Connect to SMTP and send."""
424-
server = self._smtp_open(timeout=30)
469+
server = self._smtp_open(timeout=self.timeout)
425470

426471
try:
427472
if self.username and self.password:

0 commit comments

Comments
 (0)