Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Correct response handling for checking dead links (#4748)
sarayourfriend6cfca4900623
diff --git a/api/api/utils/aiohttp.py b/api/api/utils/aiohttp.pyindex bebe39c07..2724953c4 100644--- a/api/api/utils/aiohttp.py+++ b/api/api/utils/aiohttp.py@@ -1,4 +1,5 @@import asyncio+import timeimport weakrefimport aiohttp@@ -73,7 +74,64 @@ async def get_aiohttp_session() -> aiohttp.ClientSession:logger.info(msg)if create_session:- session = aiohttp.ClientSession()+ session = aiohttp.ClientSession(trace_configs=[LogTiming()])_SESSIONS[loop] = sessionreturn _SESSIONS[loop]+++class LogTiming(aiohttp.TraceConfig):+ TIMEOUT_STATUS = -2+ ERROR_STATUS = -1++ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)++ self.on_request_start.append(self._start_timing)+ self.on_request_end.append(self._log_timing)+ self.on_request_exception.append(self._log_timing)++ async def _start_timing(+ self,+ session: aiohttp.ClientSession,+ trace_config_ctx,+ params: aiohttp.TraceRequestStartParams,+ ):+ trace_config_ctx.start_time = time.perf_counter()++ async def _log_timing(+ self,+ session: aiohttp.ClientSession,+ trace_config_ctx,+ params: aiohttp.TraceRequestEndParams | aiohttp.TraceRequestExceptionParams,+ ):+ """Log timing at end of request or when request results in an exception."""++ if not (+ trace_config_ctx.trace_request_ctx+ and "timing_event_name" in trace_config_ctx.trace_request_ctx+ ):+ return++ end_time = time.perf_counter()+ start_time = trace_config_ctx.start_time++ request_ctx = trace_config_ctx.trace_request_ctx++ if hasattr(params, "response"):+ # request end+ status = params.response.status+ elif isinstance(params.exception, aiohttp.ClientResponseError):+ status = params.exception.status+ elif isinstance(params.exception, asyncio.TimeoutError):+ status = self.TIMEOUT_STATUS+ else:+ status = self.ERROR_STATUS++ logger.info(+ request_ctx["timing_event_name"],+ status=status,+ time=end_time - start_time,+ url=str(params.url),+ **request_ctx.get("timing_event_ctx", {}),+ )diff --git a/api/api/utils/check_dead_links/__init__.py b/api/api/utils/check_dead_links/__init__.pyindex ef602d5b6..f54486f99 100644--- a/api/api/utils/check_dead_links/__init__.py+++ b/api/api/utils/check_dead_links/__init__.py@@ -17,7 +17,6 @@ from api.utils.dead_link_mask import get_query_mask, save_query_masklogger = structlog.get_logger(__name__)-head_logger = structlog.get_logger(f"{__name__}._head")CACHE_PREFIX = "valid:"HEADERS = {@@ -41,35 +40,39 @@ def _get_expiry(status, default):_timeout = aiohttp.ClientTimeout(total=settings.LINK_VALIDATION_TIMEOUT_SECONDS)-_TIMEOUT_STATUS = -2+_ERROR_STATUS = -1async def _head(url: str, session: aiohttp.ClientSession, provider: str) -> tuple[str, int]:- start_time = time.perf_counter()-try:response = await session.head(- url, allow_redirects=False, headers=HEADERS, timeout=_timeout+ url,+ allow_redirects=False,+ headers=HEADERS,+ timeout=_timeout,+ # do not raise_for_status=True; we want "bad" status codes+ # so we can cache on them and interpret them per provider+ # the except block should only handle errors in making or+ # receiving the response, but not the content of the response+ # e.g., a 500 from upstream is good information for dead link+ # validation. An issue with timeouts or being able to actually+ # access the upstream over the wire are problems we want in+ # the log and for which we need to fall back to the _ERROR_STATUS+ # because we won't have a true status from upstream.+ trace_request_ctx={+ "timing_event_name": "dead_link_validation_timing",+ "timing_event_ctx": {+ "provider": provider,+ },+ },)status = response.statusexcept (aiohttp.ClientError, asyncio.TimeoutError) as exception:- if not isinstance(exception, asyncio.TimeoutError):- head_logger.error("dead_link_validation_error", e=exception)- status = _ERROR_STATUS- else:- status = _TIMEOUT_STATUS-- end_time = time.perf_counter()- logger.info(- "dead_link_validation_timing",- url=url,- status=status,- time=end_time - start_time,- provider=provider,- )+ logger.error("dead_link_validation_error", exc_info=True, e=exception)+ status = _ERROR_STATUSreturn url, status@@ -140,7 +143,7 @@ def check_dead_links(query_hash: str, start_slice: int, results: list[Hit]) -> Nfor key, status in to_cache.items():if status == 200:logger.debug(f"healthy link key={key}")- elif status == _TIMEOUT_STATUS or status == _ERROR_STATUS:+ elif status == _ERROR_STATUS:logger.debug(f"no response from provider key={key}")else:logger.debug(f"broken link key={key}")diff --git a/api/api/utils/image_proxy/__init__.py b/api/api/utils/image_proxy/__init__.pyindex 8cac9613a..1061cd2a9 100644--- a/api/api/utils/image_proxy/__init__.py+++ b/api/api/utils/image_proxy/__init__.py@@ -1,9 +1,7 @@-from dataclasses import dataclassfrom datetime import timedeltafrom functools import wrapsfrom typing import Literal, Typefrom urllib.parse import urlparse-from uuid import UUIDfrom django.conf import settingsfrom django.http import HttpResponse@@ -18,6 +16,7 @@ from redis.client import Redisfrom redis.exceptions import ConnectionErrorfrom api.utils.aiohttp import get_aiohttp_session+from api.utils.image_proxy.dataclasses import MediaInfo, RequestConfigfrom api.utils.image_proxy.exception import UpstreamThumbnailExceptionfrom api.utils.image_proxy.extension import get_image_extensionfrom api.utils.image_proxy.photon import get_photon_request_params@@ -40,20 +39,6 @@ ORIGINAL = "original"THUMBNAIL_STRATEGY = Literal["photon_proxy", "original"]-@dataclass-class MediaInfo:- media_provider: str- media_identifier: UUID- image_url: str---@dataclass-class RequestConfig:- accept_header: str = "image/*"- is_full_size: bool = False- is_compressed: bool = True--def get_request_params_for_extension(ext: str,headers: dict[str, str],@@ -90,7 +75,7 @@ def _tally_response(response: aiohttp.ClientResponse,):"""- Tally image proxy response without waiting for Redis to respond.+ Tally image proxy response.Pulled into a separate function to help reduce overload when skimmingthe `get` function, which is complex enough as is.@@ -200,7 +185,7 @@ def _cache_repeated_failures(_get):return do_cache-_UPSTREAM_TIMEOUT = aiohttp.ClientTimeout(15)+_UPSTREAM_TIMEOUT = aiohttp.ClientTimeout(settings.THUMBNAIL_UPSTREAM_TIMEOUT)@_cache_repeated_failures@@ -215,13 +200,12 @@ async def get(original image if the file type is SVG. Otherwise, raise an exception."""image_url = media_info.image_url- media_identifier = media_info.media_identifiertallies = django_redis.get_redis_connection("tallies")tallies_incr = sync_to_async(tallies.incr)month = get_monthly_timestamp()- image_extension = await get_image_extension(image_url, media_identifier)+ image_extension = await get_image_extension(media_info)headers = {"Accept": request_config.accept_header} | HEADERS@@ -244,17 +228,25 @@ async def get(timeout=_UPSTREAM_TIMEOUT,params=params,headers=headers,+ trace_request_ctx={+ "timing_event_name": "thumbnail_upstream_timing",+ "timing_event_ctx": {+ "provider": media_info.media_provider,+ "image_url": media_info.image_url,+ "image_extension": image_extension,+ },+ },)+await _tally_response(tallies, media_info, month, domain, upstream_response)+upstream_response.raise_for_status()+status_code = upstream_response.statuscontent_type = upstream_response.headers.get("Content-Type")- logger.debug(- "Image proxy response status: %s, content-type: %s",- status_code,- content_type,- )+content = await upstream_response.content.read()+return HttpResponse(content,status=status_code,@@ -263,6 +255,7 @@ async def get(except Exception as exc:exception_name = f"{exc.__class__.__module__}.{exc.__class__.__name__}"key = f"thumbnail_error:{exception_name}:{domain}:{month}"+try:await tallies_incr(key)except ConnectionError:@@ -272,9 +265,11 @@ async def get(status = exc.statusawait _tally_client_response_errors(tallies, month, domain, status)logger.warning(- f"Failed to render thumbnail "- f"{upstream_url=} {status=} "- f"{media_info.media_provider=} "- f"{exc.message=}"+ "thumbnail_upstream_failure",+ url=upstream_url,+ status=status,+ provider=media_info.media_provider,+ exc=exc.message,)+raise UpstreamThumbnailException(f"Failed to render thumbnail. {exc}")diff --git a/api/api/utils/image_proxy/dataclasses.py b/api/api/utils/image_proxy/dataclasses.pynew file mode 100644index 000000000..f15fb1f85--- /dev/null+++ b/api/api/utils/image_proxy/dataclasses.py@@ -0,0 +1,16 @@+from dataclasses import dataclass+from uuid import UUID+++@dataclass+class MediaInfo:+ media_provider: str+ media_identifier: UUID+ image_url: str+++@dataclass+class RequestConfig:+ accept_header: str = "image/*"+ is_full_size: bool = False+ is_compressed: bool = Truediff --git a/api/api/utils/image_proxy/extension.py b/api/api/utils/image_proxy/extension.pyindex 5519dea42..07d4ffe59 100644--- a/api/api/utils/image_proxy/extension.py+++ b/api/api/utils/image_proxy/extension.py@@ -2,6 +2,8 @@ import mimetypesfrom os.path import splitextfrom urllib.parse import urlparse+from django.conf import settings+import aiohttpimport django_redisimport sentry_sdk@@ -10,18 +12,21 @@ from asgiref.sync import sync_to_asyncfrom redis.exceptions import ConnectionErrorfrom api.utils.aiohttp import get_aiohttp_session+from api.utils.image_proxy.dataclasses import MediaInfofrom api.utils.image_proxy.exception import UpstreamThumbnailExceptionlogger = structlog.get_logger(__name__)-_HEAD_TIMEOUT = aiohttp.ClientTimeout(10)+_HEAD_TIMEOUT = aiohttp.ClientTimeout(settings.THUMBNAIL_EXTENSION_REQUEST_TIMEOUT)++async def get_image_extension(media_info: MediaInfo) -> str | None:+ image_url = media_info.image_url-async def get_image_extension(image_url: str, media_identifier) -> str | None:cache = django_redis.get_redis_connection("default")- key = f"media:{media_identifier}:thumb_type"+ key = f"media:{media_info.media_identifier}:thumb_type"ext = _get_file_extension_from_url(image_url)@@ -37,8 +42,16 @@ async def get_image_extension(image_url: str, media_identifier) -> str | None:# If the extension is still not present, try getting it from the content typetry:session = await get_aiohttp_session()- response = await session.head(image_url, timeout=_HEAD_TIMEOUT)- response.raise_for_status()+ response = await session.head(+ image_url,+ raise_for_status=True,+ timeout=_HEAD_TIMEOUT,+ trace_request_ctx={+ "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)diff --git a/api/compose.yml b/api/compose.ymlindex 3fa993453..b02dbccec 100644--- a/api/compose.yml+++ b/api/compose.yml@@ -53,3 +53,13 @@ services:DJANGO_NGINX_UPSTREAM_URL: web:50280depends_on:- web++ # Used in API unit tests+ httpbin:+ profiles:+ - api+ # Use go-httpbin because it's only 15 MB compared to upstream HTTPBin's 204 MB+ # That helps reduce the network burden of spinning up a development environment+ image: docker.io/mccutchen/go-httpbin:v2.14.0+ expose:+ - "8080"diff --git a/api/conf/settings/thumbnails.py b/api/conf/settings/thumbnails.pyindex d538871c0..31d5f4ed8 100644--- a/api/conf/settings/thumbnails.py+++ b/api/conf/settings/thumbnails.py@@ -29,3 +29,11 @@ THUMBNAIL_FAILURE_CACHE_WINDOW_SECONDS = config(THUMBNAIL_FAILURE_CACHE_TOLERANCE = config("THUMBNAIL_FAILURE_CACHE_TOLERANCE", default=2, cast=int)++# Timeout when requesting the thumbnail from the upstream image proxy+THUMBNAIL_UPSTREAM_TIMEOUT = config("THUMBNAIL_UPSTREAM_TIMEOUT", default=4, cast=int)++# Timeout when trying to determine the filetype based on a HEAD request to the upstream image provider+THUMBNAIL_EXTENSION_REQUEST_TIMEOUT = config(+ "THUMBNAIL_EXTENSION_REQUEST_TIMEOUT", default=4, cast=int+)diff --git a/api/test/unit/utils/test_aiohttp.py b/api/test/unit/utils/test_aiohttp.pyindex ec3cbdc15..470c5de2c 100644--- a/api/test/unit/utils/test_aiohttp.py+++ b/api/test/unit/utils/test_aiohttp.py@@ -1,3 +1,9 @@+import asyncio++import aiohttp+import pytest+from structlog.testing import capture_logs+from api.utils.aiohttp import get_aiohttp_session@@ -31,3 +37,165 @@ def test_multiple_loops_reuse_separate_sessions(get_new_loop):assert loop_1_session_1 is loop_1_session_2assert loop_2_session_1 is loop_2_session_2+++def test_log_timing_trace_config_ignored_if_event_name_undefined(session_loop):+ aiohttp_session = session_loop.run_until_complete(get_aiohttp_session())++ with capture_logs() as logs:+ session_loop.run_until_complete(+ aiohttp_session.get("http://httpbin:8080/status/202")+ )++ assert len(logs) == 0+++_EXPECTED_BASE_CTX = {"url", "status", "time"}+++def test_log_timing_trace_config_no_request_ctx(session_loop):+ aiohttp_session = session_loop.run_until_complete(get_aiohttp_session())++ event_name = "no_request_ctx_timing_event_test"+ with capture_logs() as logs:+ session_loop.run_until_complete(+ aiohttp_session.get(+ "http://httpbin:8080/status/202",+ trace_request_ctx={+ "timing_event_name": event_name,+ },+ )+ )++ log_event = next(log for log in logs if log["event"] == event_name)+ assert _EXPECTED_BASE_CTX & log_event.keys() == _EXPECTED_BASE_CTX+ assert log_event["status"] == 202+ assert log_event["url"] == "http://httpbin:8080/status/202"+++def test_log_timing_trace_config_empty_request_ctx(session_loop):+ aiohttp_session = session_loop.run_until_complete(get_aiohttp_session())++ event_name = "empty_request_ctx_timing_event_test"+ with capture_logs() as logs:+ session_loop.run_until_complete(+ aiohttp_session.get(+ "http://httpbin:8080/status/202",+ trace_request_ctx={+ "timing_event_name": event_name,+ "timing_event_ctx": {},+ },+ )+ )++ log_event = next(log for log in logs if log["event"] == event_name)+ assert _EXPECTED_BASE_CTX & log_event.keys() == _EXPECTED_BASE_CTX+ assert log_event["status"] == 202+ assert log_event["url"] == "http://httpbin:8080/status/202"+++def test_log_timing_trace_config_with_request_ctx(session_loop):+ aiohttp_session = session_loop.run_until_complete(get_aiohttp_session())++ event_name = "empty_request_ctx_timing_event_test"+ event_ctx = {+ "amazing_info": "hello_test",+ "helpful_info": "so cool",+ }++ with capture_logs() as logs:+ session_loop.run_until_complete(+ aiohttp_session.get(+ "http://httpbin:8080/status/202",+ trace_request_ctx={+ "timing_event_name": event_name,+ "timing_event_ctx": event_ctx,+ },+ )+ )++ log_event = next(log for log in logs if log["event"] == event_name)++ assert _EXPECTED_BASE_CTX & log_event.keys() == _EXPECTED_BASE_CTX+ assert log_event["status"] == 202+ assert log_event["url"] == "http://httpbin:8080/status/202"++ log_event_items = log_event.items()+ for event_ctx_item in event_ctx.items():+ assert event_ctx_item in log_event_items+++def test_log_timing_trace_config_response_exception(session_loop, monkeypatch):+ aiohttp_session = session_loop.run_until_complete(get_aiohttp_session())++ event_name = "response_exception_timing_event_test"++ with capture_logs() as logs:+ with pytest.raises(aiohttp.ClientResponseError):+ session_loop.run_until_complete(+ aiohttp_session.get(+ "http://httpbin:8080/status/400",+ # raise for status coerces a client response error within the tracing context+ raise_for_status=True,+ trace_request_ctx={+ "timing_event_name": event_name,+ },+ )+ )++ log_event = next(log for log in logs if log["event"] == event_name)++ assert _EXPECTED_BASE_CTX & log_event.keys() == _EXPECTED_BASE_CTX+ assert log_event["status"] == 400+ assert log_event["url"] == "http://httpbin:8080/status/400"+++def test_log_timing_trace_config_runtime_exception(session_loop, monkeypatch):+ aiohttp_session = session_loop.run_until_complete(get_aiohttp_session())++ event_name = "runtime_exception_timing_event_test"++ with capture_logs() as logs:+ with pytest.raises(aiohttp.InvalidURL):+ session_loop.run_until_complete(+ aiohttp_session.get(+ # The malformed URL will raise an error when the client tries to parse+ # the URL to redirect to+ "http://httpbin:8080/redirect-to",+ params={"url": "//:@/"},+ allow_redirects=True,+ trace_request_ctx={+ "timing_event_name": event_name,+ },+ )+ )++ log_event = next(log for log in logs if log["event"] == event_name)++ assert _EXPECTED_BASE_CTX & log_event.keys() == _EXPECTED_BASE_CTX+ assert log_event["status"] == -1+ assert log_event["url"] == "http://httpbin:8080/redirect-to?url=//:@/"+++def test_log_timing_trace_config_timeout(session_loop):+ aiohttp_session = session_loop.run_until_complete(get_aiohttp_session())++ event_name = "empty_request_ctx_timing_event_test"++ with capture_logs() as logs:+ with pytest.raises(asyncio.TimeoutError):+ session_loop.run_until_complete(+ aiohttp_session.get(+ "http://httpbin:8080/delay/4",+ timeout=aiohttp.ClientTimeout(1),+ trace_request_ctx={+ "timing_event_name": event_name,+ },+ )+ )++ log_event = next(log for log in logs if log["event"] == event_name)++ assert _EXPECTED_BASE_CTX & log_event.keys() == _EXPECTED_BASE_CTX+ assert log_event["status"] == -2+ assert log_event["url"] == "http://httpbin:8080/delay/4"