Skip to content

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

Fix handful of networking issues including silence errors (#4875)

sarayourfriend18d8416ede2d
diff --git a/api/api/utils/check_dead_links/__init__.py b/api/api/utils/check_dead_links/__init__.py
index 9b8d56dd3..ab66ea0cd 100644
--- a/api/api/utils/check_dead_links/__init__.py
+++ b/api/api/utils/check_dead_links/__init__.py
@@ -44,11 +44,28 @@ _timeout = aiohttp.ClientTimeout(total=settings.LINK_VALIDATION_TIMEOUT_SECONDS)
_ERROR_STATUS = -1
+# Used to filter network errors during liveness checks that we believe
+# we should get errors (rather than warnings) for, e.g., a Sentry issue.
+# As such, this should exclude errors where we don't think we have the
+# ability to control the outcome, whether now or in the future.
+# Some things, like SSL errors and timeouts, may be used for detecting
+# more confident liveness checks or useful catalog information in the future.
+# However, for now, we just need to avoid filling up our error backlog
+# with things we aren't able to actually do anything about right now.
+_NON_ACTIONABLE_NETWORK_EXCEPTIONS = (
+ aiohttp.ClientConnectorCertificateError,
+ aiohttp.ClientConnectorSSLError,
+ aiohttp.ClientConnectorError,
+ aiohttp.ServerDisconnectedError,
+ aiohttp.ClientOSError,
+)
+
+
async def _head(
url: str, session: aiohttp.ClientSession, provider: str
) -> tuple[str, int]:
try:
- response = await session.head(
+ async with session.head(
url,
allow_redirects=False,
headers=HEADERS,
@@ -68,18 +85,25 @@ async def _head(
"provider": provider,
},
},
- )
- status = response.status
+ ) as response:
+ status = response.status
+
except (aiohttp.ClientError, asyncio.TimeoutError) as exception:
+ # only log non-timeout exceptions. Timeouts are more or less expected
+ # and we have means of visibility into them (e.g., querying for timings
+ # that exceed the timeout); they do _not_ need to be in the error log or go to Sentry
+ # The timeout exception class aiohttp uses is a subclass of `ClientError` and `asyncio.TimeoutError`,
+ # so we have to explicitly check that the error is _not_ an asyncio timeout error, not that it
+ # _is_ an aiohttp error. When it is a timeout error, it will be both `asyncio.TimeoutError` and
+ # `aiohttp.ClientError` because it's a subclass of both
if not isinstance(exception, asyncio.TimeoutError):
- # only log non-timeout exceptions. Timeouts are more or less expected
- # and we have means of visibility into them (e.g., querying for timings
- # that exceed the timeout); they do _not_ need to be in the error log or go to Sentry
- # The timeout exception class aiohttp uses is a subclass of `ClientError` and `asyncio.TimeoutError`,
- # so we have to explicitly check that the error is _not_ an asyncio timeout error, not that it
- # _is_ an aiohttp error. When it is a timeout error, it will be both `asyncio.TimeoutError` and
- # `aiohttp.ClientError` because it's a subclass of both
- logger.error("dead_link_validation_error", exc_info=True, exc=exception)
+ if isinstance(exception, _NON_ACTIONABLE_NETWORK_EXCEPTIONS):
+ log = logger.warning
+ else:
+ # Only error log actionable exceptions
+ log = logger.error
+
+ log("dead_link_validation_error", exc_info=True, exc=exception)
status = _ERROR_STATUS
diff --git a/api/api/utils/image_proxy/__init__.py b/api/api/utils/image_proxy/__init__.py
index a8b47ea41..69535bf14 100644
--- a/api/api/utils/image_proxy/__init__.py
+++ b/api/api/utils/image_proxy/__init__.py
@@ -10,7 +10,7 @@ from rest_framework.exceptions import UnsupportedMediaType
import aiohttp
import django_redis
import structlog
-from aiohttp.client_exceptions import ClientResponseError
+from aiohttp import client_exceptions
from asgiref.sync import sync_to_async
from redis.client import Redis
from redis.exceptions import ConnectionError
@@ -96,7 +96,7 @@ def _tally_response(
media_info: MediaInfo,
month: str,
domain: str,
- response: aiohttp.ClientResponse,
+ status_code: int,
):
"""
Tally image proxy response.
@@ -106,13 +106,13 @@ def _tally_response(
"""
with tallies_conn.pipeline() as tallies:
- tallies.incr(f"thumbnail_response_code:{month}:{response.status}")
+ tallies.incr(f"thumbnail_response_code:{month}:{status_code}")
tallies.incr(
- f"thumbnail_response_code_by_domain:{domain}:" f"{month}:{response.status}"
+ f"thumbnail_response_code_by_domain:{domain}:" f"{month}:{status_code}"
)
tallies.incr(
f"thumbnail_response_code_by_provider:{media_info.media_provider}:"
- f"{month}:{response.status}"
+ f"{month}:{status_code}"
)
try:
tallies.execute()
@@ -247,7 +247,7 @@ async def get(
try:
session = await get_aiohttp_session()
- upstream_response = await session.get(
+ async with session.get(
upstream_url,
timeout=_UPSTREAM_TIMEOUT,
params=params,
@@ -260,16 +260,17 @@ async def get(
"image_extension": image_extension,
},
},
- )
-
- await _tally_response(tallies, media_info, month, domain, upstream_response)
+ ) as upstream_response:
+ await _tally_response(
+ tallies, media_info, month, domain, upstream_response.status
+ )
- upstream_response.raise_for_status()
+ upstream_response.raise_for_status()
- status_code = upstream_response.status
- content_type = upstream_response.headers.get("Content-Type")
+ status_code = upstream_response.status
+ content_type = upstream_response.headers.get("Content-Type")
- content = await upstream_response.content.read()
+ content = await upstream_response.content.read()
return HttpResponse(
content,
@@ -285,7 +286,7 @@ async def get(
except ConnectionError:
logger.warning("Redis connect failed, thumbnail errors not tallied.")
- if isinstance(exc, ClientResponseError):
+ if isinstance(exc, aiohttp.ClientResponseError):
status = exc.status
await _tally_client_response_errors(tallies, month, domain, status)
logger.warning(
diff --git a/api/api/utils/image_proxy/extension.py b/api/api/utils/image_proxy/extension.py
index 876922a2f..3c2e24569 100644
--- a/api/api/utils/image_proxy/extension.py
+++ b/api/api/utils/image_proxy/extension.py
@@ -1,3 +1,4 @@
+import asyncio
import mimetypes
from os.path import splitext
from urllib.parse import urlparse
@@ -21,6 +22,25 @@ logger = structlog.get_logger(__name__)
_HEAD_TIMEOUT = aiohttp.ClientTimeout(settings.THUMBNAIL_EXTENSION_REQUEST_TIMEOUT)
+# Used to filter network errors during extension checks that we believe
+# we should get errors (rather than warnings) for, e.g., a Sentry issue.
+# As such, this should exclude errors where we don't think we have the
+# ability to control the outcome, whether now or in the future.
+# Some things, like SSL errors and timeouts, may be used to inform liveness
+# checks or otherwise useful catalog information in the future.
+# However, for now, we just need to avoid filling up our error backlog
+# with things we aren't able to actually do anything about right now.
+_NON_ACTIONABLE_NETWORK_EXCEPTIONS = (
+ aiohttp.ClientConnectorCertificateError,
+ aiohttp.ClientConnectorSSLError,
+ aiohttp.ClientConnectorError,
+ aiohttp.ServerDisconnectedError,
+ aiohttp.ServerTimeoutError,
+ aiohttp.ClientOSError,
+ asyncio.TimeoutError,
+)
+
+
async def get_image_extension(media_info: MediaInfo) -> str | None:
image_url = media_info.image_url
@@ -41,7 +61,8 @@ async def get_image_extension(media_info: MediaInfo) -> str | None:
# If the extension is still not present, try getting it from the content type
try:
session = await get_aiohttp_session()
- response = await session.head(
+
+ async with session.head(
image_url,
raise_for_status=True,
timeout=_HEAD_TIMEOUT,
@@ -49,17 +70,29 @@ async def get_image_extension(media_info: MediaInfo) -> str | None:
"timing_event_name": "thumbnail_extension_request_timing",
"timing_event_ctx": {"provider": media_info.media_provider},
},
- )
-
- if response.headers and "Content-Type" in response.headers:
- content_type = response.headers["Content-Type"]
- ext = _get_file_extension_from_content_type(content_type)
- else:
- ext = None
+ ) as response:
+ if response.headers and "Content-Type" in response.headers:
+ content_type = response.headers["Content-Type"]
+ ext = _get_file_extension_from_content_type(content_type)
+ else:
+ ext = None
await _cache_extension(cache, key, ext)
except Exception as exc:
- logger.error("upstream_thumbnail_exception", exc=exc, exc_info=True)
+ # Aside from client errors, the timeout defined for `get_image_extension`
+ # is generous, and if the head request exceeds it, we're comfortable saying
+ # we'll skip generating this thumbnail. In the future, we might adjust
+ # timeouts with per-provider granularity, but for now, we just have to
+ # accept they will happen and are part of the set of non-actionable
+ # networking errors that we don't need to report as errors to Sentry.
+ if not isinstance(exc, asyncio.TimeoutError):
+ if isinstance(exc, _NON_ACTIONABLE_NETWORK_EXCEPTIONS):
+ log = logger.warning
+ else:
+ log = logger.error
+
+ log("upstream_thumbnail_exception", exc=exc, exc_info=True)
+
raise UpstreamThumbnailException(
"Failed to render thumbnail due to inability to check media "
f"type. {exc}"
diff --git a/api/api/views/image_views.py b/api/api/views/image_views.py
index 974a4292b..4c8ad6bc4 100644
--- a/api/api/views/image_views.py
+++ b/api/api/views/image_views.py
@@ -87,9 +87,15 @@ class ImageViewSet(MediaViewSet):
if not (image.height and image.width):
session = await get_aiohttp_session()
- image_file = await session.get(image.url, headers=self.OEMBED_HEADERS)
- image_content = await image_file.content.read()
- width, height = PILImage.open(io.BytesIO(image_content)).size
+
+ async with session.get(
+ image.url, headers=self.OEMBED_HEADERS
+ ) as image_file:
+ image_content = await image_file.content.read()
+
+ with PILImage.open(io.BytesIO(image_content)) as image_file:
+ width, height = image_file.size
+
context |= {
"width": width,
"height": height,
@@ -209,3 +215,5 @@ class ImageViewSet(MediaViewSet):
pil_img.save(destination, "jpeg", exif=exif_bytes)
else:
pil_img.save(destination, "jpeg")
+
+ pil_img.close()
diff --git a/api/test/unit/utils/test_check_dead_links.py b/api/test/unit/utils/test_check_dead_links.py
index d89b6e7e6..827abe98b 100644
--- a/api/test/unit/utils/test_check_dead_links.py
+++ b/api/test/unit/utils/test_check_dead_links.py
@@ -1,4 +1,3 @@
-import asyncio
from collections.abc import Callable
from typing import Any
@@ -49,7 +48,7 @@ def test_handles_timeout(monkeypatch):
start_slice = 0
async def raise_timeout_error(*args, **kwargs):
- raise asyncio.TimeoutError()
+ raise aiohttp.ServerTimeoutError()
monkeypatch.setattr(aiohttp.ClientSession, "_request", raise_timeout_error)
with capture_logs() as logs:
diff --git a/api/test/unit/utils/test_image_proxy.py b/api/test/unit/utils/test_image_proxy.py
index 1020796c9..044b4b395 100644
--- a/api/test/unit/utils/test_image_proxy.py
+++ b/api/test/unit/utils/test_image_proxy.py
@@ -1,3 +1,4 @@
+import contextlib
from dataclasses import replace
from urllib.parse import urlencode
from uuid import uuid4
@@ -263,8 +264,11 @@ def test_get_successful_forward_query_params(mock_image_data):
@pytest.fixture
def setup_request_exception(monkeypatch):
def do(exc):
+ # ClientSession.get returns a context manager
+ @contextlib.asynccontextmanager
async def raise_exc(*args, **kwargs):
raise exc
+ yield
monkeypatch.setattr(aiohttp.ClientSession, "get", raise_exc)