Skip to content

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

Simplify and consolidate photon log handling, improve tallying (#2243)

Madison Swain-Bowdenf54c71c4b7d4
diff --git a/api/api/utils/photon.py b/api/api/utils/photon.py
index 23c9a7c80..0857ee43f 100644
--- a/api/api/utils/photon.py
+++ b/api/api/utils/photon.py
@@ -11,6 +11,8 @@ import django_redis
import requests
import sentry_sdk
+from api.utils.tallies import get_monthly_timestamp
+
parent_logger = logging.getLogger(__name__)
@@ -120,6 +122,7 @@ def get(
) -> HttpResponse:
logger = parent_logger.getChild("get")
cache = django_redis.get_redis_connection("default")
+ month = get_monthly_timestamp()
params, parsed_image_url = _get_photon_params(
image_url, is_full_size, is_compressed
@@ -142,53 +145,34 @@ def get(
params=params,
headers=headers,
)
- upstream_response.raise_for_status()
- except requests.ReadTimeout as exc:
- # Count the incident so that we can identify providers with most timeouts.
- key = f"{settings.THUMBNAIL_TIMEOUT_PREFIX}{domain}"
- try:
- cache.incr(key)
- except ValueError: # Key does not exist.
- cache.set(key, 1)
-
- sentry_sdk.capture_exception(exc)
- raise UpstreamThumbnailException(
- f"Failed to render thumbnail due to timeout: {exc}"
+ cache.incr(f"thumbnail_response_code:{month}:{upstream_response.status_code}")
+ cache.incr(
+ f"thumbnail_response_code_by_domain:{domain}:"
+ f"{month}:{upstream_response.status_code}"
)
- except requests.HTTPError as exc:
- # Save number of occurrences to redis. Only raise a Sentry error when
- # the number of occurrences reaches the configured threshold, to
- # prevent provider API downtime from causing excessive Sentry events.
- key = f"{settings.THUMBNAIL_HTTP_ERROR_PREFIX}{domain}"
- errors = 1
- try:
- errors = cache.incr(key)
- except ValueError: # Key does not exist.
- cache.set(key, 1)
- if errors >= settings.THUMBNAIL_HTTP_ERROR_THRESHOLD_TO_NOTIFY and (
- errors % settings.THUMBNAIL_HTTP_ERROR_THRESHOLD_FOR_REPEATED_NOTIFICATIONS
- == 0
+ upstream_response.raise_for_status()
+ except Exception as exc:
+ exception_name = f"{exc.__class__.__module__}.{exc.__class__.__name__}"
+ key = f"thumbnail_error:{exception_name}:{domain}:{month}"
+ count = cache.incr(key)
+ if count <= settings.THUMBNAIL_ERROR_INITIAL_ALERT_THRESHOLD or (
+ count % settings.THUMBNAIL_ERROR_REPEATED_ALERT_FREQUENCY == 0
):
sentry_sdk.capture_exception(exc)
+ if isinstance(exc, requests.exceptions.HTTPError):
+ cache.incr(
+ f"thumbnail_http_error:{domain}:{month}:{exc.response.status_code}:{exc.response.text}"
+ )
raise UpstreamThumbnailException(f"Failed to render thumbnail. {exc}")
- except requests.RequestException as exc:
- sentry_sdk.capture_exception(exc)
- raise UpstreamThumbnailException(f"Failed to render thumbnail. {exc}")
- except Exception as exc:
- sentry_sdk.capture_exception(exc)
- raise UpstreamThumbnailException(
- f"Failed to render thumbnail due to unidentified exception. {exc}"
- )
- else:
- res_status = upstream_response.status_code
- content_type = upstream_response.headers.get("Content-Type")
- logger.debug(
- "Image proxy response "
- f"status: {res_status}, content-type: {content_type}"
- )
- return HttpResponse(
- upstream_response.content,
- status=res_status,
- content_type=content_type,
- )
+ res_status = upstream_response.status_code
+ content_type = upstream_response.headers.get("Content-Type")
+ logger.debug(
+ f"Image proxy response status: {res_status}, content-type: {content_type}"
+ )
+
+ return HttpResponse(
+ upstream_response.content,
+ status=res_status,
+ content_type=content_type,
+ )
diff --git a/api/api/utils/tallies.py b/api/api/utils/tallies.py
index b683d473e..6dd352a43 100644
--- a/api/api/utils/tallies.py
+++ b/api/api/utils/tallies.py
@@ -5,13 +5,19 @@ import django_redis
from django_redis.client.default import Redis
-def _get_weekly_timestamp() -> str:
+def get_weekly_timestamp() -> str:
"""Get a timestamp for the Monday of any given week."""
now = datetime.now()
monday = now - timedelta(days=now.weekday())
return monday.strftime("%Y-%m-%d")
+def get_monthly_timestamp() -> str:
+ """Get a timestamp for the month."""
+ now = datetime.now()
+ return now.strftime("%Y-%m")
+
+
def count_provider_occurrences(results: list[dict], index: str) -> None:
# Use ``get_redis_connection`` rather than Django's caches
# so that we can open a pipeline rather than sending off ``n``
@@ -26,7 +32,7 @@ def count_provider_occurrences(results: list[dict], index: str) -> None:
for result in results:
provider_occurrences[result["provider"]] += 1
- week = _get_weekly_timestamp()
+ week = get_weekly_timestamp()
with tallies.pipeline() as pipe:
for provider, occurrences in provider_occurrences.items():
pipe.incr(f"provider_occurrences:{index}:{week}:{provider}", occurrences)
diff --git a/api/conf/settings/thumbnails.py b/api/conf/settings/thumbnails.py
index e4818033d..329bc2222 100644
--- a/api/conf/settings/thumbnails.py
+++ b/api/conf/settings/thumbnails.py
@@ -16,18 +16,10 @@ PHOTON_ENDPOINT = config("PHOTON_ENDPOINT", default="https://i0.wp.com/")
THUMBNAIL_WIDTH_PX = config("THUMBNAIL_WIDTH_PX", default="600")
THUMBNAIL_QUALITY = config("THUMBNAIL_JPG_QUALITY", default="80")
-THUMBNAIL_TIMEOUT_PREFIX = config(
- "THUMBNAIL_TIMEOUT_PREFIX", default="thumbnail_timeout:"
+THUMBNAIL_ERROR_INITIAL_ALERT_THRESHOLD = config(
+ "THUMBNAIL_ERROR_INITIAL_ALERT_THRESHOLD", default=100, cast=int
)
-THUMBNAIL_HTTP_ERROR_PREFIX = config(
- "THUMBNAIL_HTTP_ERROR_PREFIX", default="thumbnail_http_error:"
-)
-
-THUMBNAIL_HTTP_ERROR_THRESHOLD_TO_NOTIFY = config(
- "THUMBNAIL_HTTP_ERROR_THRESHOLD_TO_NOTIFY", default=1000, cast=int
-)
-
-THUMBNAIL_HTTP_ERROR_THRESHOLD_FOR_REPEATED_NOTIFICATIONS = config(
- "THUMBNAIL_HTTP_ERROR_THRESHOLD_FOR_REPEATED_NOTIFICATIONS", default=1000, cast=int
+THUMBNAIL_ERROR_REPEATED_ALERT_FREQUENCY = config(
+ "THUMBNAIL_ERROR_REPEATED_ALERT_FREQUENCY", default=1000, cast=int
)
diff --git a/api/test/unit/utils/test_photon.py b/api/test/unit/utils/test_photon.py
index 5754669af..7ea41252b 100644
--- a/api/test/unit/utils/test_photon.py
+++ b/api/test/unit/utils/test_photon.py
@@ -1,5 +1,6 @@
from test.factory.models.image import ImageFactory
from unittest import mock
+from unittest.mock import MagicMock
from urllib.parse import urlencode
from django.conf import settings
@@ -16,6 +17,7 @@ from api.utils.photon import (
check_image_type,
)
from api.utils.photon import get as photon_get
+from api.utils.tallies import get_monthly_timestamp
PHOTON_URL_FOR_TEST_IMAGE = f"{settings.PHOTON_ENDPOINT}subdomain.example.com/path_part1/part2/image_dot_jpg.jpg"
@@ -216,76 +218,136 @@ def setup_requests_get_exception(monkeypatch):
yield do
-def test_get_timeout_no_existing_cache_key(
- capture_exception, setup_requests_get_exception, redis
-):
- exc = requests.ReadTimeout()
- setup_requests_get_exception(exc)
+def test_get_successful_records_response_code(mock_image_data, redis):
+ (
+ pook.get(PHOTON_URL_FOR_TEST_IMAGE)
+ .params(
+ {
+ "w": settings.THUMBNAIL_WIDTH_PX,
+ "quality": settings.THUMBNAIL_QUALITY,
+ }
+ )
+ .header("User-Agent", UA_HEADER)
+ .header("Accept", "image/*")
+ .reply(200)
+ .body(MOCK_BODY)
+ .mock
+ )
- with pytest.raises(UpstreamThumbnailException):
- photon_get(TEST_IMAGE_URL)
+ photon_get(TEST_IMAGE_URL)
+ month = get_monthly_timestamp()
+ assert redis.get(f"thumbnail_response_code:{month}:200") == b"1"
+ assert (
+ redis.get(
+ f"thumbnail_response_code_by_domain:subdomain.example.com:{month}:200"
+ )
+ == b"1"
+ )
- capture_exception.assert_called_once_with(exc)
- key = f"{settings.THUMBNAIL_TIMEOUT_PREFIX}subdomain.example.com"
- assert redis.get(key) == b"1"
+alert_count_params = pytest.mark.parametrize(
+ "count_start, should_alert",
+ [
+ (0, True),
+ (1, True),
+ (50, True),
+ (99, True),
+ (100, False),
+ (999, True),
+ (1000, False),
+ (1500, False),
+ (1999, True),
+ ],
+)
-def test_get_timeout_existing_cache_key(
- capture_exception, setup_requests_get_exception, redis
+ "exc, exc_name",
+ [
+ (ValueError("whoops"), "builtins.ValueError"),
+ (requests.ConnectionError("whoops"), "requests.exceptions.ConnectionError"),
+ (requests.ConnectTimeout("whoops"), "requests.exceptions.ConnectTimeout"),
+ (requests.ReadTimeout("whoops"), "requests.exceptions.ReadTimeout"),
+ (requests.Timeout("whoops"), "requests.exceptions.Timeout"),
+ (requests.exceptions.SSLError("whoops"), "requests.exceptions.SSLError"),
+ (OSError("whoops"), "builtins.OSError"),
+ ],
+)
+@alert_count_params
+def test_get_exception_handles_error(
+ exc,
+ exc_name,
+ count_start,
+ should_alert,
+ capture_exception,
+ setup_requests_get_exception,
+ redis,
):
- exc = requests.ReadTimeout()
setup_requests_get_exception(exc)
- key = f"{settings.THUMBNAIL_TIMEOUT_PREFIX}subdomain.example.com"
- redis.set(key, 5)
+ month = get_monthly_timestamp()
+ key = f"thumbnail_error:{exc_name}:subdomain.example.com:{month}"
+ redis.set(key, count_start)
- with pytest.raises(UpstreamThumbnailException, match=r"due to timeout"):
+ with pytest.raises(UpstreamThumbnailException):
photon_get(TEST_IMAGE_URL)
- capture_exception.assert_called_once_with(exc)
-
- assert redis.get(key) == b"6"
-
-
-def test_get_http_error_pass_threshold(
- capture_exception, setup_requests_get_exception, redis
-):
- exc = requests.HTTPError()
- setup_requests_get_exception(exc)
- key = f"{settings.THUMBNAIL_HTTP_ERROR_PREFIX}subdomain.example.com"
- redis.set(key, settings.THUMBNAIL_HTTP_ERROR_THRESHOLD_TO_NOTIFY - 1)
-
- # Call several times
- for _ in range(3):
- with pytest.raises(
- UpstreamThumbnailException, match=r"Failed to render thumbnail."
- ):
- photon_get(TEST_IMAGE_URL)
-
- capture_exception.assert_called_once_with(exc)
-
- assert redis.get(key) == b"1002"
+ assert_func = (
+ capture_exception.assert_called_once
+ if should_alert
+ else capture_exception.assert_not_called
+ )
+ assert_func()
+ assert redis.get(key) == str(count_start + 1).encode()
+@alert_count_params
@pytest.mark.parametrize(
- "exception, expected_message",
+ "status_code, text",
[
- ( # Includes HTTP response errors
- requests.RequestException(),
- r"Failed to render thumbnail.",
- ),
- (ValueError(), r"due to unidentified exception."),
+ (400, "Bad Request"),
+ (401, "Unauthorized"),
+ (403, "Forbidden"),
+ (500, "Internal Server Error"),
],
)
-def test_get_raise_exception_msg(
- capture_exception, setup_requests_get_exception, exception, expected_message
+def test_get_http_exception_handles_error(
+ status_code,
+ text,
+ count_start,
+ should_alert,
+ capture_exception,
+ setup_requests_get_exception,
+ redis,
):
- setup_requests_get_exception(exception)
+ mock_response = MagicMock(spec=requests.Response)
+ mock_response.status_code = status_code
+ mock_response.text = text
+ exc = requests.HTTPError(response=mock_response)
+ setup_requests_get_exception(exc)
+
+ month = get_monthly_timestamp()
+ key = f"thumbnail_error:requests.exceptions.HTTPError:subdomain.example.com:{month}"
+ redis.set(key, count_start)
- with pytest.raises(UpstreamThumbnailException, match=expected_message):
+ with pytest.raises(UpstreamThumbnailException):
photon_get(TEST_IMAGE_URL)
- capture_exception.assert_called_once_with(exception)
+ assert_func = (
+ capture_exception.assert_called_once
+ if should_alert
+ else capture_exception.assert_not_called
+ )
+ assert_func()
+ assert redis.get(key) == str(count_start + 1).encode()
+
+ # Assertions about the HTTP error specific message
+ assert (
+ redis.get(
+ f"thumbnail_http_error:subdomain.example.com:{month}:{status_code}:{text}"
+ )
+ == b"1"
+ )
@pook.on