Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Stop sending DB pool timeouts and uvloop SSL close logs to Sentry (#5783)

Olga Bulat00535a3f0452
diff --git a/api/conf/settings/sentry.py b/api/conf/settings/sentry.py
index ae6d2452e..39c61c256 100644
--- a/api/conf/settings/sentry.py
+++ b/api/conf/settings/sentry.py
@@ -1,5 +1,6 @@
import sentry_sdk
from decouple import config
+from psycopg_pool import PoolTimeout
from sentry_sdk.integrations.django import DjangoIntegration
from sentry_sdk.integrations.logging import LoggingIntegration, ignore_logger
@@ -33,6 +34,41 @@ def profiles_sampler(sampling_context) -> float:
return SENTRY_PROFILES_SAMPLE_RATE
+def _is_pool_timeout(exc: BaseException | None) -> bool:
+ # Django wraps the pool's ``PoolTimeout`` in its own ``OperationalError``,
+ # so the type to match is somewhere down the exception chain.
+ seen = set()
+ while exc is not None and id(exc) not in seen:
+ if isinstance(exc, PoolTimeout):
+ return True
+ seen.add(id(exc))
+ exc = exc.__cause__ or exc.__context__
+ return False
+
+
+def before_send(event, hint):
+ """
+ Drop events that only report infrastructure noise.
+
+ - DB connection pool timeouts: the pool is saturated and the request can
+ only be retried; there is nothing to fix at the call site.
+ - uvloop's "Fatal error on SSL protocol" log: the remote end of an outbound
+ HTTPS request closed the connection. The request itself succeeds, but
+ asyncio logs this at ERROR, which ``SentryProcessor`` turns into an event.
+ """
+ exc_info = hint.get("exc_info")
+ if exc_info and _is_pool_timeout(exc_info[1]):
+ return None
+
+ message = event.get("message") or ""
+ if event.get("logger") == "asyncio" and message.startswith(
+ "Fatal error on SSL protocol"
+ ):
+ return None
+
+ return event
+
+
INTEGRATIONS = [
# See https://docs.sentry.io/platforms/python/integrations/django/
DjangoIntegration(),
@@ -49,6 +85,7 @@ if not DEBUG and SENTRY_DSN:
integrations=INTEGRATIONS,
traces_sample_rate=SENTRY_TRACES_SAMPLE_RATE,
profiles_sampler=profiles_sampler,
+ before_send=before_send,
send_default_pii=False,
environment=ENVIRONMENT,
)
diff --git a/api/test/unit/configuration/test_sentry.py b/api/test/unit/configuration/test_sentry.py
new file mode 100644
index 000000000..78cd84c48
--- /dev/null
+++ b/api/test/unit/configuration/test_sentry.py
@@ -0,0 +1,74 @@
+import sys
+
+from django.db.utils import OperationalError
+
+import pytest
+from psycopg_pool import PoolTimeout
+
+from conf.settings.sentry import before_send
+
+
+SSL_LOG_MESSAGE = (
+ "Fatal error on SSL protocol\n"
+ "protocol: <uvloop.loop.SSLProtocol object at 0x7fc2e0f5e820>\n"
+ "transport: <TCPTransport closed=True reading=False 0x558f2baa0e70>"
+)
+
+
+def _exc_info(raise_exc):
+ try:
+ raise_exc()
+ except Exception:
+ return sys.exc_info()
+
+
+def _raise_wrapped_pool_timeout():
+ # Mirrors ``django.db.utils.DatabaseErrorWrapper``.
+ try:
+ raise PoolTimeout("couldn't get a connection after 10.00 sec")
+ except PoolTimeout as exc:
+ raise OperationalError(str(exc)) from exc
+
+
+def _raise_operational_error():
+ raise OperationalError("server closed the connection unexpectedly")
+
+
+ "event, raise_exc",
+ [
+ pytest.param({}, _raise_wrapped_pool_timeout, id="pool_timeout"),
+ pytest.param(
+ {"logger": "asyncio", "message": SSL_LOG_MESSAGE},
+ None,
+ id="asyncio_ssl_log",
+ ),
+ ],
+)
+def test_drops_noise(event, raise_exc):
+ hint = {"exc_info": _exc_info(raise_exc)} if raise_exc else {}
+
+ assert before_send(event, hint) is None
+
+
+ "event, raise_exc",
+ [
+ pytest.param({}, _raise_operational_error, id="other_db_error"),
+ pytest.param(
+ {"logger": "asyncio", "message": "Task exception was never retrieved"},
+ None,
+ id="other_asyncio_log",
+ ),
+ pytest.param(
+ {"logger": "api.views", "message": SSL_LOG_MESSAGE},
+ None,
+ id="ssl_message_from_other_logger",
+ ),
+ pytest.param({"logger": "asyncio"}, None, id="asyncio_without_message"),
+ ],
+)
+def test_keeps_other_events(event, raise_exc):
+ hint = {"exc_info": _exc_info(raise_exc)} if raise_exc else {}
+
+ assert before_send(event, hint) is event