Skip to content

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

Make link validation expiry maximally configurable (#879)

sarayourfriend9f8b15773df5
diff --git a/api/catalog/api/utils/validate_images.py b/api/catalog/api/utils/validate_images.py
index 123627d78..b888fa286 100644
--- a/api/catalog/api/utils/validate_images.py
+++ b/api/catalog/api/utils/validate_images.py
@@ -77,26 +77,20 @@ def validate_images(query_hash, start_slice, results, image_urls):
status = -1
to_cache[cache_key] = status
- thirty_minutes = 60 * 30
- twenty_four_hours_seconds = 60 * 60 * 24
-
pipe = redis.pipeline()
if len(to_cache) > 0:
pipe.mset(to_cache)
for key, status in to_cache.items():
- # Cache successful links for a day, and broken links for 120 days.
if status == 200:
- logger.debug("healthy link " f"key={key} ")
- expiry = _get_expiry(200, twenty_four_hours_seconds * 30)
+ logger.debug(f"healthy link key={key}")
elif status == -1:
- logger.debug("no response from provider " f"key={key}")
- # Content provider failed to respond; try again in a short interval
- expiry = _get_expiry("_1", thirty_minutes)
+ logger.debug(f"no response from provider key={key}")
else:
- logger.debug("broken link " f"key={key} ")
- expiry = _get_expiry("DEFAULT", twenty_four_hours_seconds * 120)
+ logger.debug(f"broken link key={key}")
+ expiry = settings.LINK_VALIDATION_CACHE_EXPIRY_CONFIGURATION[status]
+ logger.debug(f"caching status={status} expiry={expiry}")
pipe.expire(key, expiry)
pipe.execute()
diff --git a/api/catalog/configuration/link_validation_cache.py b/api/catalog/configuration/link_validation_cache.py
new file mode 100644
index 000000000..582f0d8d9
--- /dev/null
+++ b/api/catalog/configuration/link_validation_cache.py
@@ -0,0 +1,68 @@
+import json
+import logging
+import os
+from collections import defaultdict
+from datetime import timedelta
+from typing import Optional
+
+from django.core.exceptions import ImproperlyConfigured
+
+from decouple import config
+
+
+logger = logging.getLogger(__name__)
+
+
+class LinkValidationCacheExpiryConfiguration(defaultdict):
+ """
+ Link validation cache expiry configuration.
+ """
+
+ SETTING_PREFIX = "LINK_VALIDATION_CACHE_EXPIRY__"
+
+ # Cache successful links for a month, and broken links for 120 days.
+ OVERALL_DEFAULT = {"days": 120}
+ STATUS_DEFAULTS = {
+ 200: {"days": 30},
+ -1: {"minutes": 30},
+ }
+
+ def __init__(self):
+ default = self._config("default", default=self.OVERALL_DEFAULT)
+ super().__init__(lambda: default)
+
+ self.update(
+ {k: self._config(k, default=v) for k, v in self.STATUS_DEFAULTS.items()}
+ )
+
+ for k, v in os.environ.items():
+ if not k.startswith(self.SETTING_PREFIX) or k.lower().endswith("default"):
+ continue
+
+ try:
+ status = int(k.replace(self.SETTING_PREFIX, ""))
+ except ValueError:
+ raise ImproperlyConfigured(
+ "Invalid link validation cache setting name: "
+ f"{self.SETTING_PREFIX}. Please ensure settings "
+ "are named in the format of "
+ f"'{self.SETTING_PREFIX}<http integer status code>'."
+ )
+
+ value = self._config(status)
+
+ self[status] = value
+
+ def _config(self, key: str | int, default: Optional[dict] = None) -> Optional[int]:
+ try:
+ v = config(
+ f"{self.SETTING_PREFIX}{str(key)}",
+ default=default,
+ # Value should either be a str or dict here
+ cast=lambda x: json.loads(x) if isinstance(x, str) else x,
+ )
+ return int(timedelta(**v).total_seconds())
+ except (json.JSONDecodeError, TypeError):
+ raise ImproperlyConfigured(
+ f"Invalid link validation cache setting. Impossible to parse {key}."
+ )
diff --git a/api/catalog/settings.py b/api/catalog/settings.py
index 53a91dfd6..47e52b384 100644
--- a/api/catalog/settings.py
+++ b/api/catalog/settings.py
@@ -10,6 +10,7 @@ For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
+from datetime import timedelta
from pathlib import Path
from socket import gethostbyname, gethostname
@@ -20,6 +21,9 @@ from sentry_sdk.integrations.logging import ignore_logger
from catalog.configuration.aws import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
from catalog.configuration.elasticsearch import ES, MEDIA_INDEX_MAPPING
+from catalog.configuration.link_validation_cache import (
+ LinkValidationCacheExpiryConfiguration,
+)
from catalog.configuration.logging import LOGGING
@@ -361,3 +365,10 @@ if not DEBUG and SENTRY_DSN:
# from pushing un-actionable alerts to Sentry like
# https://sentry.io/share/issue/9af3cdf8ef74420aa7bbb6697760a82c/
ignore_logger("django.security.DisallowedHost")
+
+# Custom link validation expiration times
+# Overrides can be set via LINK_VALIDATION_CACHE_EXPIRY__<http integer status code>
+# and should be set as kwarg dicts for datetime.timedelta
+# E.g. LINK_VALIDATION_CACHE_EXPIRY__200='{"days": 1}' will set the expiration time
+# for links with HTTP status 200 to 1 day
+LINK_VALIDATION_CACHE_EXPIRY_CONFIGURATION = LinkValidationCacheExpiryConfiguration()
diff --git a/api/test/unit/configuration/link_validation_cache_test.py b/api/test/unit/configuration/link_validation_cache_test.py
new file mode 100644
index 000000000..0ca972f7b
--- /dev/null
+++ b/api/test/unit/configuration/link_validation_cache_test.py
@@ -0,0 +1,82 @@
+from datetime import timedelta
+
+from django.core.exceptions import ImproperlyConfigured
+
+import pytest
+
+from catalog.configuration.link_validation_cache import (
+ LinkValidationCacheExpiryConfiguration,
+)
+
+
+ ("status", "td"),
+ (
+ (200, timedelta(days=30)),
+ (-1, timedelta(minutes=30)),
+ # subsequent entries all use default
+ (400, timedelta(days=120)),
+ (500, timedelta(days=120)),
+ (503, timedelta(days=120)),
+ (401, timedelta(days=120)),
+ (301, timedelta(days=120)),
+ ),
+)
+def test_all_default_values(status, td):
+ config = LinkValidationCacheExpiryConfiguration()
+
+ assert config[status] == int(td.total_seconds())
+
+
+ ("overrides", "expecteds"),
+ (
+ ({"default": '{"days": 1}'}, ((400, timedelta(days=1)),)),
+ ({"200": '{"days": 3}'}, ((200, timedelta(days=3)),)),
+ ({"200": '{"days": 3}'}, ((300, timedelta(days=120)),)),
+ ({"-1": '{"seconds": 120}'}, ((-1, timedelta(seconds=120)),)),
+ # invalid value
+ pytest.param(
+ {"default": "not parseable"},
+ ((400, None),),
+ marks=pytest.mark.raises(exception=ImproperlyConfigured),
+ ),
+ # invalid key
+ pytest.param(
+ {"3a312": '{"hours": 12}'},
+ ((200, None),),
+ marks=pytest.mark.raises(exception=ImproperlyConfigured),
+ ),
+ # invalid arguments for timedelta
+ pytest.param(
+ {"500": '{"not_a_valid_keyword": 12}'},
+ ((200, None),),
+ marks=pytest.mark.raises(exception=ImproperlyConfigured),
+ ),
+ # multiple configurations
+ (
+ {
+ "default": '{"minutes": 25}',
+ "500": '{"days": 20}',
+ "200": '{"days": 1}',
+ },
+ (
+ (324, timedelta(minutes=25)),
+ (500, timedelta(days=20)),
+ (200, timedelta(days=1)),
+ (400, timedelta(minutes=25)),
+ # -1 still retains default value, doesn't use the `default` override
+ (-1, timedelta(minutes=30)),
+ ),
+ ),
+ ),
+)
+def test_environment_overrides(overrides, expecteds, monkeypatch):
+ for k, v in overrides.items():
+ env_key = f"{LinkValidationCacheExpiryConfiguration.SETTING_PREFIX}{k}"
+ monkeypatch.setenv(env_key, v)
+
+ config = LinkValidationCacheExpiryConfiguration()
+
+ for status, td in expecteds:
+ assert config[status] == td.total_seconds()