Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

send_email: Add setting to control max connection lifetime.

Sairam Bisoyi33d8714017d5
diff --git a/zerver/lib/send_email.py b/zerver/lib/send_email.py
index 83d1bc6fe9d..4f63064f5a5 100644
--- a/zerver/lib/send_email.py
+++ b/zerver/lib/send_email.py
@@ -21,7 +21,6 @@ import orjson
from django.conf import settings
from django.core.mail import EmailMultiAlternatives, get_connection
from django.core.mail.backends.base import BaseEmailBackend
-from django.core.mail.backends.smtp import EmailBackend
from django.core.mail.message import sanitize_address
from django.core.management import CommandError
from django.db import transaction
@@ -40,7 +39,6 @@ from zerver.models import Realm, RealmAuditLog, ScheduledEmail, UserProfile
from zerver.models.realm_audit_logs import AuditLogEventType
from zerver.models.scheduled_jobs import EMAIL_TYPES
from zerver.models.users import get_user_profile_by_id
-from zproject.email_backends import EmailLogBackEnd, get_forward_address
if settings.ZILENCER_ENABLED:
from zilencer.models import RemoteZulipServer
@@ -406,32 +404,7 @@ def initialize_connection(connection: BaseEmailBackend | None = None) -> BaseEma
connection = get_connection()
assert connection is not None
- if connection.open():
- # If it's a new connection, no need to no-op to check connectivity
- return connection
-
- if isinstance(connection, EmailLogBackEnd) and not get_forward_address():
- # With the development environment backend and without a
- # configured forwarding address, we don't actually send emails.
- #
- # As a result, the connection cannot be closed by the server
- # (as there is none), and `connection.noop` is not
- # implemented, so we need to return the connection early.
- return connection
-
- # No-op to ensure that we don't return a connection that has been
- # closed by the mail server.
- if isinstance(connection, EmailBackend):
- try:
- assert connection.connection is not None
- status = connection.connection.noop()[0]
- except Exception:
- status = -1
- if status != 250:
- # Close and connect again.
- connection.close()
- connection.open()
-
+ connection.open()
return connection
diff --git a/zerver/tests/test_send_email.py b/zerver/tests/test_send_email.py
index dc0ac5b6e47..d317ca75f5a 100644
--- a/zerver/tests/test_send_email.py
+++ b/zerver/tests/test_send_email.py
@@ -1,9 +1,12 @@
+from datetime import timedelta
from smtplib import SMTP, SMTPDataError, SMTPException, SMTPRecipientsRefused
from unittest import mock
+import time_machine
from django.core.mail.backends.locmem import EmailBackend
-from django.core.mail.backends.smtp import EmailBackend as SMTPBackend
from django.core.mail.message import sanitize_address
+from django.test import override_settings
+from django.utils.timezone import now as timezone_now
from zerver.lib.send_email import (
EmailNotDeliveredError,
@@ -14,6 +17,7 @@ from zerver.lib.send_email import (
send_email,
)
from zerver.lib.test_classes import ZulipTestCase
+from zproject.email_backends import PersistentSMTPEmailBackend
class TestBuildEmail(ZulipTestCase):
@@ -70,39 +74,159 @@ class TestBuildEmail(ZulipTestCase):
class TestSendEmail(ZulipTestCase):
- def test_initialize_connection(self) -> None:
- # Test the new connection case
+ @override_settings(
+ EMAIL_BACKEND="zproject.email_backends.PersistentSMTPEmailBackend",
+ EMAIL_MAX_CONNECTION_LIFETIME_IN_MINUTES=5,
+ )
+ @time_machine.travel(timezone_now(), tick=False)
+ def test_connection_reuse_noop(self) -> None:
with mock.patch.object(EmailBackend, "open", return_value=True):
backend = initialize_connection(None)
- self.assertTrue(isinstance(backend, EmailBackend))
-
- backend = mock.MagicMock(spec=SMTPBackend)
- backend.connection = mock.MagicMock(spec=SMTP)
-
- self.assertTrue(isinstance(backend, SMTPBackend))
-
- # Test the old connection case when it is still open
- backend.open.return_value = False
- backend.connection.noop.return_value = [250]
- initialize_connection(backend)
- self.assertEqual(backend.open.call_count, 1)
- self.assertEqual(backend.connection.noop.call_count, 1)
-
- # Test the old connection case when it was closed by the server
- backend.connection.noop.return_value = [404]
- backend.close.return_value = False
- initialize_connection(backend)
- # 2 more calls to open, 1 more call to noop and 1 call to close
- self.assertEqual(backend.open.call_count, 3)
- self.assertEqual(backend.connection.noop.call_count, 2)
- self.assertEqual(backend.close.call_count, 1)
-
- # Test backoff procedure
- backend.open.side_effect = OSError
- with self.assertRaises(OSError):
+ assert isinstance(backend, PersistentSMTPEmailBackend)
+ self.assertEqual(backend.opened_at, timezone_now())
+
+ with (
+ 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.
+ backend.connection = mock.MagicMock(spec=SMTP)
+ backend.connection.noop.side_effect = AssertionError
+ with 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(close_call.call_count, 0)
+ close_call.reset_mock()
+ _open_call.reset_mock()
+
+ # Test case: The connection already exists and noop() succeeds, so we do not reopen it.
+ backend.connection = mock.MagicMock(spec=SMTP)
+ backend.connection.noop.return_value = [250]
initialize_connection(backend)
- # 3 more calls to open as we try 3 times before giving up
- self.assertEqual(backend.open.call_count, 6)
+
+ self.assertEqual(_open_call.call_count, 1)
+ self.assertEqual(backend.connection.noop.call_count, 1)
+ close_call.reset_mock()
+ _open_call.reset_mock()
+
+ # Test the old connection case when it was closed by the server
+ 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(close_call.call_count, 0)
+ close_call.reset_mock()
+ _open_call.reset_mock()
+
+ # Test backoff procedure
+ _open_call.side_effect = OSError
+ with 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)
+
+ @time_machine.travel(timezone_now(), tick=False)
+ @override_settings(EMAIL_MAX_CONNECTION_LIFETIME_IN_MINUTES=None)
+ def test_max_connection_lifetime_none(self) -> None:
+ backend = PersistentSMTPEmailBackend()
+
+ with (
+ mock.patch.object(backend, "_open", wraps=backend._open) as _open_call,
+ mock.patch.object(backend, "close", wraps=backend.close) as close_call,
+ ):
+ backend.open()
+ backend.connection = mock.MagicMock(spec=SMTP)
+ backend.connection.noop.return_value = [250]
+
+ self.assertEqual(close_call.call_count, 0)
+ self.assertEqual(_open_call.call_count, 1)
+ self.assertEqual(backend.connection.noop.call_count, 0)
+ self.assertEqual(backend.opened_at, timezone_now())
+ # Test that close() is a no-op and does not drop the connection.
+ connection_before = backend.connection
+ backend.close()
+ self.assertEqual(backend.connection, connection_before)
+ self.assertIsNotNone(backend.connection)
+ close_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(
+ timezone_now() + timedelta(minutes=10),
+ tick=False,
+ ):
+ 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)
+ self.assertEqual(backend.connection.noop.call_count, 1)
+ close_call.reset_mock()
+ _open_call.reset_mock()
+ backend.connection.noop.reset_mock()
+
+ @time_machine.travel(timezone_now(), tick=False)
+ @override_settings(EMAIL_MAX_CONNECTION_LIFETIME_IN_MINUTES=5)
+ def test_max_connection_lifetime_5_minutes(self) -> None:
+ backend = PersistentSMTPEmailBackend()
+
+ with (
+ 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(backend.opened_at, timezone_now())
+ close_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.
+ with time_machine.travel(
+ timezone_now() + timedelta(minutes=3),
+ tick=False,
+ ):
+ 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)
+ self.assertEqual(backend.connection.noop.call_count, 1)
+ close_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.
+ with time_machine.travel(
+ timezone_now() + timedelta(minutes=6),
+ tick=False,
+ ):
+ self.assertEqual(backend.opened_at, timezone_now() - timedelta(minutes=6))
+ old_connection_mock = mock.MagicMock(spec=SMTP)
+ backend.connection = old_connection_mock
+ with mock.patch(
+ "django.core.mail.backends.smtp.EmailBackend.open", side_effect=[False, True]
+ ):
+ initialize_connection(backend)
+ self.assertEqual(backend.opened_at, timezone_now())
+
+ self.assertEqual(close_call.call_count, 0)
+ self.assertEqual(_open_call.call_count, 2)
+ self.assertEqual(old_connection_mock.noop.call_count, 0)
def test_send_email_exceptions(self) -> None:
hamlet = self.example_user("hamlet")
diff --git a/zproject/computed_settings.py b/zproject/computed_settings.py
index 650a8843b7d..c9647207860 100644
--- a/zproject/computed_settings.py
+++ b/zproject/computed_settings.py
@@ -35,6 +35,7 @@ from .configured_settings import (
DEFAULT_RATE_LIMITING_RULES,
EMAIL_BACKEND,
EMAIL_HOST,
+ EMAIL_MAX_CONNECTION_LIFETIME_IN_MINUTES,
ERROR_REPORTING,
EXTERNAL_HOST,
EXTERNAL_HOST_WITHOUT_PORT,
@@ -1239,8 +1240,11 @@ elif not EMAIL_HOST:
WARN_NO_EMAIL = True
EMAIL_BACKEND = "django.core.mail.backends.dummy.EmailBackend"
else:
- EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
-
+ # Route '0' to Django's default, everything else to custom class
+ if EMAIL_MAX_CONNECTION_LIFETIME_IN_MINUTES == 0:
+ EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
+ else:
+ EMAIL_BACKEND = "zproject.email_backends.PersistentSMTPEmailBackend"
EMAIL_TIMEOUT = 15
if DEVELOPMENT:
diff --git a/zproject/default_settings.py b/zproject/default_settings.py
index ce97310596e..78200eba51e 100644
--- a/zproject/default_settings.py
+++ b/zproject/default_settings.py
@@ -39,6 +39,7 @@ TOKENIZED_NOREPLY_EMAIL_ADDRESS = Address(
).addr_spec
PHYSICAL_ADDRESS = ""
FAKE_EMAIL_DOMAIN = EXTERNAL_HOST_WITHOUT_PORT
+EMAIL_MAX_CONNECTION_LIFETIME_IN_MINUTES: int | None = 0
# SMTP settings
EMAIL_HOST: str | None = None
diff --git a/zproject/email_backends.py b/zproject/email_backends.py
index 626dfef2d3e..bba21fe8e64 100644
--- a/zproject/email_backends.py
+++ b/zproject/email_backends.py
@@ -3,12 +3,14 @@ import configparser
import logging
from collections.abc import Sequence
from email.message import Message
+from typing import Any
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.core.mail.backends.smtp import EmailBackend
from django.core.mail.message import EmailAlternative, EmailMessage
from django.template import loader
+from django.utils.timezone import now as timezone_now
from typing_extensions import override
@@ -110,3 +112,49 @@ class EmailLogBackEnd(EmailBackend):
email_log_url = settings.ROOT_DOMAIN_URI + "/emails"
logging.info("Emails sent in development are available at %s", email_log_url)
return num_sent
+
+
+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
+
+ @override
+ def open(self, **kwargs: Any) -> bool | None:
+ is_opened = self._open(**kwargs)
+ if is_opened:
+ return True
+
+ status = None
+ time_elapsed = (timezone_now() - self.opened_at).seconds / 60
+ if (
+ settings.EMAIL_MAX_CONNECTION_LIFETIME_IN_MINUTES is None
+ or time_elapsed <= settings.EMAIL_MAX_CONNECTION_LIFETIME_IN_MINUTES
+ ):
+ # No-op to ensure that we don't return a connection that has been
+ # closed by the mail server.
+ try:
+ assert self.connection is not None
+ status = self.connection.noop()[0]
+ except Exception:
+ pass
+ if status is None or status != 250:
+ # Close and connect again.
+ super().close()
+ self._open()
+ # We return false here as Django will then have
+ # to leave the connection alive for next entries.
+ return False
+
+ # The connection was already open, the noop succeeded.
+ return False
+
+ @override
+ def close(self) -> None:
+ # We override close to a no-op so that Django's send_messages
+ # does not close the connection after sending a batch of emails.
+ pass
diff --git a/zproject/prod_settings_template.py b/zproject/prod_settings_template.py
index 3cc3846d535..4fa5a427b15 100644
--- a/zproject/prod_settings_template.py
+++ b/zproject/prod_settings_template.py
@@ -86,6 +86,13 @@ EXTERNAL_HOST = "zulip.example.com"
# EMAIL_USE_TLS = True
# EMAIL_PORT = 587
+## By default, Zulip will open a new SMTP connection for each outgoing email.
+## This has a small overhead, though not one which is relevant in most installs,
+## which send very low volumes of email. You can set to a positive number to
+## reuse SMTP connections for that many minutes; set to None to leave connections
+## open indefinitely.
+# EMAIL_MAX_CONNECTION_LIFETIME_IN_MINUTES = 0
+
## The noreply address to be used as the sender for certain generated
## emails. Messages sent to this address could contain sensitive user
## data and should not be delivered anywhere. The default is