Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
send_email: Move noop validation into validate_or_reconnect().
Alex Vandiver2c3b5404544b
diff --git a/zerver/lib/send_email.py b/zerver/lib/send_email.pyindex fd34bc8db40..db154618941 100644--- a/zerver/lib/send_email.py+++ b/zerver/lib/send_email.py@@ -321,8 +321,6 @@ def send_immediate_email(logger.info("Sending %s email to %s%s", template, logging_recipient, cause)try:- # This will call .open() for us, which is a no-op if it's already open;- # it will only call .close() if it was not open to begin withif connection.send_messages([mail]) == 0:logger.error("Unknown error sending %s email to %s", template, mail.to)connection.close()@@ -403,11 +401,15 @@ def send_email(@backoff.on_exception(backoff.expo, OSError, max_tries=MAX_CONNECTION_TRIES, logger=None)def initialize_connection(connection: BaseEmailBackend | None = None) -> BaseEmailBackend:+ from zproject.email_backends import PersistentSMTPEmailBackend+if not connection:connection = get_connection()assert connection is not Noneconnection.open()+ if isinstance(connection, PersistentSMTPEmailBackend):+ connection.validate_or_reconnect()return connectiondiff --git a/zerver/tests/test_send_email.py b/zerver/tests/test_send_email.pyindex de3ecde4a7a..ab683988dd0 100644--- a/zerver/tests/test_send_email.py+++ b/zerver/tests/test_send_email.py@@ -86,53 +86,51 @@ class TestSendEmail(ZulipTestCase):self.assertEqual(backend.opened_at, timezone_now())with (- mock.patch.object(backend, "_open", wraps=backend._open) as _open_call,+ mock.patch.object(backend, "open", wraps=backend.open) as open_call,mock.patch.object(backend, "close", wraps=backend.close) as close_call,):- # In case of an exception when trying to do the noop- # operation, the connection will open and close.- # 1 call to _open is to check whether the connection is- # open and second is to actually open the connection.+ # Noop raises an exception — validate_or_reconnect closes+ # and reopens. open() is called twice: once from+ # initialize_connection, once from the reconnect path.backend.connection = mock.MagicMock(spec=SMTP)backend.connection.noop.side_effect = AssertionErrorwith mock.patch("django.core.mail.backends.smtp.EmailBackend.open", side_effect=[False, True]):initialize_connection(backend)- self.assertEqual(_open_call.call_count, 2)+ self.assertEqual(open_call.call_count, 2)self.assertEqual(close_call.call_count, 0)close_call.reset_mock()- _open_call.reset_mock()+ open_call.reset_mock()- # Test case: The connection already exists and noop() succeeds, so we do not reopen it.+ # Noop succeeds — no reconnect needed.backend.connection = mock.MagicMock(spec=SMTP)backend.connection.noop.return_value = [250]initialize_connection(backend)- self.assertEqual(_open_call.call_count, 1)+ self.assertEqual(open_call.call_count, 1)self.assertEqual(backend.connection.noop.call_count, 1)close_call.reset_mock()- _open_call.reset_mock()+ open_call.reset_mock()- # Test the old connection case when it was closed by the server+ # Noop returns 404 — validate_or_reconnect closes and reopens.backend.connection.noop.return_value = [404]with mock.patch("django.core.mail.backends.smtp.EmailBackend.open", side_effect=[False, True]):initialize_connection(backend)- # 2 calls to open and 1 call to close- self.assertEqual(_open_call.call_count, 2)+ self.assertEqual(open_call.call_count, 2)self.assertEqual(close_call.call_count, 0)close_call.reset_mock()- _open_call.reset_mock()+ open_call.reset_mock()# Test backoff procedure- _open_call.side_effect = OSError+ open_call.side_effect = OSErrorwith self.assertRaises(OSError):initialize_connection(backend)# 3 calls to open as we try 3 times before giving up- self.assertEqual(_open_call.call_count, 3)+ self.assertEqual(open_call.call_count, 3)@time_machine.travel(timezone_now(), tick=False)@override_settings(EMAIL_MAX_CONNECTION_LIFETIME_IN_MINUTES=None)@@ -140,7 +138,7 @@ class TestSendEmail(ZulipTestCase):backend = PersistentSMTPEmailBackend()with (- mock.patch.object(backend, "_open", wraps=backend._open) as _open_call,+ mock.patch.object(backend, "open", wraps=backend.open) as open_call,mock.patch.object(backend, "close", wraps=backend.close) as close_call,):backend.open()@@ -148,11 +146,11 @@ class TestSendEmail(ZulipTestCase):backend.connection.noop.return_value = [250]self.assertEqual(close_call.call_count, 0)- self.assertEqual(_open_call.call_count, 1)+ self.assertEqual(open_call.call_count, 1)self.assertEqual(backend.connection.noop.call_count, 0)self.assertEqual(backend.opened_at, timezone_now())close_call.reset_mock()- _open_call.reset_mock()+ open_call.reset_mock()# Old connection is open, we will not open a new connection because max connection lifetime is None.with time_machine.travel(@@ -161,13 +159,11 @@ class TestSendEmail(ZulipTestCase):):initialize_connection(backend)self.assertEqual(close_call.call_count, 0)- # open.call_count is 1 because we are calling connection.open()- # to check whether an open connection already exists. In case of actually opening- # a new connection, the call count will be 2.- self.assertEqual(_open_call.call_count, 1)+ # open is called once from initialize_connection; no reconnect.+ self.assertEqual(open_call.call_count, 1)self.assertEqual(backend.connection.noop.call_count, 1)close_call.reset_mock()- _open_call.reset_mock()+ open_call.reset_mock()backend.connection.noop.reset_mock()@time_machine.travel(timezone_now(), tick=False)@@ -176,19 +172,19 @@ class TestSendEmail(ZulipTestCase):backend = PersistentSMTPEmailBackend()with (- mock.patch.object(backend, "_open", wraps=backend._open) as _open_call,+ mock.patch.object(backend, "open", wraps=backend.open) as open_call,mock.patch.object(backend, "close", wraps=backend.close) as close_call,):backend.open()self.assertEqual(close_call.call_count, 0)- self.assertEqual(_open_call.call_count, 1)+ self.assertEqual(open_call.call_count, 1)self.assertEqual(backend.opened_at, timezone_now())close_call.reset_mock()- _open_call.reset_mock()+ open_call.reset_mock()backend.connection = mock.MagicMock(spec=SMTP)backend.connection.noop.return_value = [250]- # Old connection is open, we will not open a new connection because not enough time has elapsed.+ # Within lifetime — noop check, no reconnect.with time_machine.travel(timezone_now() + timedelta(minutes=3),tick=False,@@ -196,16 +192,14 @@ class TestSendEmail(ZulipTestCase):initialize_connection(backend)self.assertEqual(close_call.call_count, 0)- # open.call_count is 1 because we are calling connection.open()- # to check whether an open connection already exists. In case of actually opening- # a new connection, the call count will be 2.- self.assertEqual(_open_call.call_count, 1)+ # open is called once from initialize_connection; no reconnect.+ self.assertEqual(open_call.call_count, 1)self.assertEqual(backend.connection.noop.call_count, 1)close_call.reset_mock()- _open_call.reset_mock()+ open_call.reset_mock()backend.connection.noop.reset_mock()- # Old connection is open, we will open a new connection because max time has elapsed.+ # Past lifetime — reconnects without noop.with time_machine.travel(timezone_now() + timedelta(minutes=6),tick=False,@@ -220,10 +214,10 @@ class TestSendEmail(ZulipTestCase):self.assertEqual(backend.opened_at, timezone_now())self.assertEqual(close_call.call_count, 0)- self.assertEqual(_open_call.call_count, 2)+ self.assertEqual(open_call.call_count, 2)self.assertEqual(old_connection_mock.noop.call_count, 0)close_call.reset_mock()- _open_call.reset_mock()+ open_call.reset_mock()# Connections older than 24 hours are properly# recycled: timedelta.seconds wraps at 24 hours, but@@ -242,7 +236,7 @@ class TestSendEmail(ZulipTestCase):# Noop should not have been attempted on the old connection.self.assertEqual(old_connection_mock.noop.call_count, 0)- self.assertEqual(_open_call.call_count, 2)+ self.assertEqual(open_call.call_count, 2)def test_open_returns_false_for_new_connection(self) -> None:"""open() returns False even for new connections, whichdiff --git a/zproject/email_backends.py b/zproject/email_backends.pyindex 91d55f8a3c9..6ce3aac98ef 100644--- a/zproject/email_backends.py+++ b/zproject/email_backends.py@@ -115,22 +115,18 @@ class EmailLogBackEnd(EmailBackend):class PersistentSMTPEmailBackend(EmailBackend):- def _open(self, **kwargs: Any) -> bool | None:- is_opened = super().open(**kwargs)- if is_opened:- self.opened_at = timezone_now()- return True-- return is_opened-@overridedef open(self, **kwargs: Any) -> bool:- is_opened = self._open(**kwargs)- if is_opened:- # Return False (not True) so that Django's send_messages- # does not auto-close the connection after sending.- return False+ if super().open(**kwargs):+ self.opened_at = timezone_now()+ # Always return False so that Django's send_messages does not+ # auto-close the connection after sending.+ return False+ def validate_or_reconnect(self) -> None:+ """Validate that the existing SMTP connection is still alive,+ reconnecting if necessary. Called from initialize_connection+ with backoff protection, not from open()."""status = Nonetime_elapsed = (timezone_now() - self.opened_at).total_seconds() / 60if (@@ -147,6 +143,4 @@ class PersistentSMTPEmailBackend(EmailBackend):if status is None or status != 250:# Close and connect again.super().close()- self._open()-- return False+ self.open()