Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
email_backends: Don't retry SMTP protocol errors in connection backoff.
Alex Vandiver8d99e506bb80
diff --git a/zerver/tests/test_send_email.py b/zerver/tests/test_send_email.pyindex b9831451eda..1fcb663cd48 100644--- a/zerver/tests/test_send_email.py+++ b/zerver/tests/test_send_email.py@@ -1,5 +1,11 @@from datetime import timedelta-from smtplib import SMTP, SMTPDataError, SMTPException, SMTPRecipientsRefused+from smtplib import (+ SMTP,+ SMTPDataError,+ SMTPException,+ SMTPRecipientsRefused,+ SMTPServerDisconnected,+)from unittest import mockimport time_machine@@ -11,6 +17,7 @@ from django.utils.timezone import now as timezone_nowfrom zerver.lib.send_email import (EmailNotDeliveredError,FromAddress,+ _send_messages,build_email,logger,send_email,@@ -132,6 +139,40 @@ class TestSendEmail(ZulipTestCase):# 3 calls to open as we try 3 times before giving upself.assertEqual(open_call.call_count, 3)+ def test_send_messages_backoff(self) -> None:+ """_send_messages retries on connection-level errors but not+ on SMTP protocol errors."""+ connection = mock.MagicMock()++ # ConnectionError: retries 3 times then raises+ connection.send_messages.side_effect = ConnectionError+ with self.assertRaises(ConnectionError):+ _send_messages(connection, [])+ self.assertEqual(connection.send_messages.call_count, 3)+ connection.reset_mock()++ # SMTPServerDisconnected: retries (it's a dropped connection)+ connection.send_messages.side_effect = SMTPServerDisconnected+ with self.assertRaises(SMTPServerDisconnected):+ _send_messages(connection, [])+ self.assertEqual(connection.send_messages.call_count, 3)+ connection.reset_mock()++ # SMTPRecipientsRefused: no retry (protocol error)+ connection.send_messages.side_effect = SMTPRecipientsRefused(+ recipients={"[email protected]": (550, b"Unknown")}+ )+ with self.assertRaises(SMTPRecipientsRefused):+ _send_messages(connection, [])+ self.assertEqual(connection.send_messages.call_count, 1)+ connection.reset_mock()++ # SMTPDataError: no retry (protocol error)+ connection.send_messages.side_effect = SMTPDataError(550, b"Rejected")+ with self.assertRaises(SMTPDataError):+ _send_messages(connection, [])+ self.assertEqual(connection.send_messages.call_count, 1)+def test_send_immediate_email_backoff_only_without_connection(self) -> None:"""send_immediate_email uses backoff when it creates theconnection (no caller-provided one), but sends directly@@ -343,19 +384,15 @@ class TestSendEmail(ZulipTestCase):)self.assertEqual(mail.extra_headers["From"], f"{from_name} <{FromAddress.NOREPLY}>")- # We test the cases that should raise an EmailNotDeliveredError.- # Exception side_effects need 3 entries because- # smtp_connection_backoff retries OSError (which SMTPException- # is a subclass of) up to 3 times before giving up.+ # We test the cases that should raise an EmailNotDeliveredErrorerrors = {f"Unknown error sending password_reset email to {mail.to}": [0],- f"Error sending password_reset email to {mail.to}": [SMTPException() for _ in range(3)],+ f"Error sending password_reset email to {mail.to}": [SMTPException()],f"Error sending password_reset email to {mail.to}: {{'{address}': (550, b'User unknown')}}": [SMTPRecipientsRefused(recipients={address: (550, b"User unknown")})- for _ in range(3)],f"Error sending password_reset email to {mail.to} with error code 242: From field too long": [- SMTPDataError(242, "From field too long.") for _ in range(3)+ SMTPDataError(242, "From field too long.")],}diff --git a/zproject/email_backends.py b/zproject/email_backends.pyindex 55fbe58f2a2..66393b2a5d5 100644--- a/zproject/email_backends.py+++ b/zproject/email_backends.py@@ -1,6 +1,7 @@# https://zulip.readthedocs.io/en/latest/subsystems/email.html#testing-in-a-real-email-clientimport configparserimport logging+import smtplibfrom collections.abc import Sequencefrom email.message import Messagefrom typing import Any@@ -16,11 +17,18 @@ from typing_extensions import overrideMAX_CONNECTION_TRIES = 3+# SMTPException is a subclass of OSError, so retry on connection-level+# errors (ConnectionError, TimeoutError) and SMTPServerDisconnected+# (dropped connection), but not on SMTP protocol errors like+# SMTPAuthenticationError, SMTPRecipientsRefused, or SMTPDataError.smtp_connection_backoff = backoff.on_exception(backoff.expo,OSError,max_tries=MAX_CONNECTION_TRIES,logger=None,+ giveup=lambda e: (+ isinstance(e, smtplib.SMTPException) and not isinstance(e, smtplib.SMTPServerDisconnected)+ ),)