Skip to content

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

Move the dev_env image to Fedora 45 and the catalog to Python 3.14 (#5866)

Olga Bulatc424578933cb
diff --git a/catalog/dags/common/extensions.py b/catalog/dags/common/extensions.py
index 0a1e74955..c6f60b3b8 100644
--- a/catalog/dags/common/extensions.py
+++ b/catalog/dags/common/extensions.py
@@ -32,8 +32,9 @@ MIME_TYPE_ALIASES = {
"audio/mpeg3": "audio/mpeg",
"audio/x-flac": "audio/flac",
"audio/mid": "audio/midi",
- "audio/wav": "audio/x-wav",
- "audio/wave": "audio/x-wav",
+ "audio/x-wav": "audio/wav",
+ "audio/wave": "audio/wav",
+ "audio/vnd.wave": "audio/wav",
}
@@ -42,6 +43,14 @@ mimetypes.add_type("audio/midi", ".midi")
mimetypes.add_type("audio/x-matroska", ".mka")
mimetypes.add_type("audio/wav", ".wav")
+# The default extension of some MIME types depends on the Python version and on
+# `/etc/mime.types`: `audio/ogg` was `.oga` before Python 3.14 and is `.ogg`
+# from 3.14 on. Pin the extensions that existing records use, so that new
+# records match them.
+PREFERRED_EXTENSIONS = {
+ "audio/ogg": "ogg",
+}
+
class InvalidFiletypeError(Exception):
def __init__(self, actual_filetype: str, expected_filetype: str, message: str = ""):
@@ -59,6 +68,8 @@ def get_extension_from_mimetype(mime_type: str | None) -> str | None:
if not mime_type:
return
mime_type = MIME_TYPE_ALIASES.get(mime_type, mime_type)
+ if mime_type in PREFERRED_EXTENSIONS:
+ return PREFERRED_EXTENSIONS[mime_type]
ext = mimetypes.guess_extension(mime_type)
# Removes the leading dot if there is an extension
return ext[1:] if ext else None
diff --git a/catalog/dags/common/retries.py b/catalog/dags/common/retries.py
new file mode 100644
index 000000000..4c3770e6c
--- /dev/null
+++ b/catalog/dags/common/retries.py
@@ -0,0 +1,58 @@
+"""
+Retry decorators for flaky provider APIs, built on tenacity.
+
+Both decorators wait with exponential backoff and full jitter, and re-raise the
+last exception once they stop retrying.
+"""
+
+from collections.abc import Collection
+
+from requests.exceptions import HTTPError
+from tenacity import (
+ retry,
+ retry_if_exception,
+ retry_if_exception_type,
+ stop_after_attempt,
+ stop_after_delay,
+ wait_random_exponential,
+)
+
+
+SERVER_ERROR_CODES = frozenset({502, 503, 504})
+
+
+def retry_on_http_status(
+ max_time: float, status_codes: Collection[int] = SERVER_ERROR_CODES
+):
+ """
+ Retry while the call raises an ``HTTPError`` whose status code is in
+ ``status_codes``, for up to ``max_time`` seconds. Other errors are raised
+ immediately.
+ """
+
+ def has_retryable_status(exc: BaseException) -> bool:
+ return (
+ isinstance(exc, HTTPError)
+ and exc.response is not None
+ and exc.response.status_code in status_codes
+ )
+
+ return retry(
+ retry=retry_if_exception(has_retryable_status),
+ wait=wait_random_exponential(multiplier=1),
+ stop=stop_after_delay(max_time),
+ reraise=True,
+ )
+
+
+def retry_on_exceptions(
+ exceptions: type[BaseException] | tuple[type[BaseException], ...],
+ max_tries: int,
+):
+ """Retry while the call raises one of ``exceptions``, up to ``max_tries`` calls."""
+ return retry(
+ retry=retry_if_exception_type(exceptions),
+ wait=wait_random_exponential(multiplier=1),
+ stop=stop_after_attempt(max_tries),
+ reraise=True,
+ )
diff --git a/catalog/dags/popularity/popularity_refresh_dag_factory.py b/catalog/dags/popularity/popularity_refresh_dag_factory.py
index ddf4cfad3..798f836a2 100644
--- a/catalog/dags/popularity/popularity_refresh_dag_factory.py
+++ b/catalog/dags/popularity/popularity_refresh_dag_factory.py
@@ -24,7 +24,7 @@ https://docs.openverse.org/projects/proposals/popularity_optimizations/20230420-
"""
import logging
-from datetime import datetime
+from datetime import UTC, datetime
from airflow.providers.standard.operators.trigger_dagrun import TriggerDagRunOperator
from airflow.sdk import DAG, task
@@ -54,7 +54,7 @@ def get_last_updated_time():
Getting this cutoff time is pulled out into a separate task to ensure that it
runs only when the `refresh_popularity_metrics_and_constants` task is complete.
"""
- return datetime.utcnow()
+ return datetime.now(UTC)
def create_popularity_refresh_dag(popularity_refresh: PopularityRefresh):
diff --git a/catalog/dags/providers/provider_api_scripts/brooklyn_museum.py b/catalog/dags/providers/provider_api_scripts/brooklyn_museum.py
index fa0d1a220..d04f05687 100644
--- a/catalog/dags/providers/provider_api_scripts/brooklyn_museum.py
+++ b/catalog/dags/providers/provider_api_scripts/brooklyn_museum.py
@@ -1,12 +1,11 @@
import logging
-import backoff
import lxml.html as html
from airflow.sdk import Variable
-from requests import HTTPError
from common.licenses import LicenseInfo, get_license_info
from common.loader import provider_details as prov
+from common.retries import retry_on_http_status
from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester
@@ -26,13 +25,9 @@ class BrooklynMuseumDataIngester(ProviderDataIngester):
# Brooklyn Museum's API tends to be flaky, so we add a backoff on every request
# for 5XX error codes.
# See: https://github.com/WordPress/openverse/issues/4712
- get_response_json = backoff.on_exception(
- backoff.expo,
- HTTPError,
- max_time=60 * 2,
- # Only retry on 5XX errors
- giveup=lambda e: e.response.status_code not in {502, 503, 504},
- )(ProviderDataIngester.get_response_json)
+ get_response_json = retry_on_http_status(max_time=60 * 2)(
+ ProviderDataIngester.get_response_json
+ )
def get_next_query_params(self, prev_query_params: dict | None) -> dict:
if not prev_query_params:
diff --git a/catalog/dags/providers/provider_api_scripts/freesound.py b/catalog/dags/providers/provider_api_scripts/freesound.py
index 5b815328f..1d19f53bd 100644
--- a/catalog/dags/providers/provider_api_scripts/freesound.py
+++ b/catalog/dags/providers/provider_api_scripts/freesound.py
@@ -17,12 +17,12 @@ import functools
import logging
from datetime import datetime
-import backoff
from airflow.sdk import Variable
from requests.exceptions import ConnectionError, HTTPError, SSLError
from common.licenses.licenses import get_license_info
from common.loader import provider_details as prov
+from common.retries import retry_on_exceptions, retry_on_http_status
from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester
@@ -66,14 +66,8 @@ class FreesoundDataIngester(ProviderDataIngester):
super().__init__(*args, **kwargs)
- get_response_json = backoff.on_exception(
- backoff.expo,
- HTTPError,
- max_time=60 * 2,
- # Raise all other errors
- giveup=lambda e: (
- e.response.status_code not in FreesoundDataIngester.flaky_error_codes
- ),
+ get_response_json = retry_on_http_status(
+ max_time=60 * 2, status_codes=flaky_error_codes
)(ProviderDataIngester.get_response_json)
def get_next_query_params(self, prev_query_params: dict | None) -> dict:
@@ -180,7 +174,7 @@ class FreesoundDataIngester(ProviderDataIngester):
else:
return None, None, None
- @backoff.on_exception(backoff.expo, flaky_exceptions, max_tries=3)
+ @retry_on_exceptions(flaky_exceptions, max_tries=3)
def _get_audio_file_size(self, url):
"""Get the content length of a provided URL."""
response = self.delayed_requester.head(url)
diff --git a/catalog/dags/providers/provider_api_scripts/science_museum.py b/catalog/dags/providers/provider_api_scripts/science_museum.py
index dd680a562..d364a7a67 100644
--- a/catalog/dags/providers/provider_api_scripts/science_museum.py
+++ b/catalog/dags/providers/provider_api_scripts/science_museum.py
@@ -14,12 +14,10 @@ import logging
import re
from datetime import date
-import backoff
-from requests import HTTPError
-
from common import slack
from common.licenses import LicenseInfo, get_license_info
from common.loader import provider_details as prov
+from common.retries import retry_on_http_status
from common.urls import rewrite_redirected_url
from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester
@@ -54,13 +52,9 @@ class ScienceMuseumDataIngester(ProviderDataIngester):
# Science Museum's API tends to be flaky, so we add a backoff on every request
# for 5XX error codes.
# See: https://github.com/WordPress/openverse/issues/4710
- get_response_json = backoff.on_exception(
- backoff.expo,
- HTTPError,
- max_time=60 * 30, # 30 minutes
- # Only retry on 5XX errors
- giveup=lambda e: e.response.status_code not in {502, 503, 504},
- )(ProviderDataIngester.get_response_json)
+ get_response_json = retry_on_http_status(max_time=60 * 30)(
+ ProviderDataIngester.get_response_json
+ )
@staticmethod
def _get_year_ranges(final_year: int) -> list[tuple[int, int]]:
diff --git a/catalog/dags/providers/provider_api_scripts/smithsonian.py b/catalog/dags/providers/provider_api_scripts/smithsonian.py
index 37e92bf84..4bee4f442 100644
--- a/catalog/dags/providers/provider_api_scripts/smithsonian.py
+++ b/catalog/dags/providers/provider_api_scripts/smithsonian.py
@@ -10,12 +10,12 @@ Notes: <https://api.si.edu/openaccess/api/v1.0/search>
import logging
-import backoff
from airflow.exceptions import AirflowException
from airflow.sdk import Variable
from common.licenses import LicenseInfo
from common.loader import provider_details as prov
+from common.retries import retry_on_exceptions
from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester
@@ -174,7 +174,7 @@ class SmithsonianDataIngester(ProviderDataIngester):
images += self._get_associated_images(image_list, shared_image_data)
return images
- @backoff.on_exception(backoff.expo, ValueError, max_tries=3)
+ @retry_on_exceptions(ValueError, max_tries=3)
def _get_unit_codes_from_api(self) -> set:
query_params = {"api_key": self.api_key, "q": "online_media_type:Images"}
response_json = self.get_response_json(
diff --git a/catalog/dags/providers/provider_api_scripts/stocksnap.py b/catalog/dags/providers/provider_api_scripts/stocksnap.py
index a7a1da399..a693c3dfd 100644
--- a/catalog/dags/providers/provider_api_scripts/stocksnap.py
+++ b/catalog/dags/providers/provider_api_scripts/stocksnap.py
@@ -15,11 +15,9 @@ Notes: <https://stocksnap.io/api/load-photos/date/desc/1>
import json
import logging
-import backoff
-from requests.exceptions import HTTPError
-
from common.licenses import get_license_info
from common.loader import provider_details as prov
+from common.retries import retry_on_http_status
from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester
@@ -163,14 +161,7 @@ class StockSnapDataIngester(ProviderDataIngester):
# Add a backoff on every request
# for 5XX error codes.
# See: https://github.com/WordPress/openverse/issues/4878
- @backoff.on_exception(
- backoff.expo,
- HTTPError,
- # 30 minutes
- max_time=60 * 30,
- # Only retry for 5xx errors
- giveup=lambda e: e.response.status_code not in {502, 503, 504},
- )
+ @retry_on_http_status(max_time=60 * 30)
def _get_filesize(self, image_url):
"""Get the size of the image in bytes."""
resp = self.delayed_requester.head(image_url)
diff --git a/catalog/requirements-prod.txt b/catalog/requirements-prod.txt
index f0085a001..fbfdfc71b 100644
--- a/catalog/requirements-prod.txt
+++ b/catalog/requirements-prod.txt
@@ -1,13 +1,13 @@
-# PYTHON=3.12
+# PYTHON=3.14
# Note: Unpinned packages have their versions determined by the Airflow constraints file
apache-airflow[amazon,postgres,http,elasticsearch,fab]==3.4.0
-backoff==2.2.1
lxml
psycopg2-binary
requests-file
requests-oauthlib
smart-open[s3]
tabulate==0.10.0
+tenacity
tldextract==5.4.0
diff --git a/catalog/tests/dags/common/test_extensions.py b/catalog/tests/dags/common/test_extensions.py
index f55a923fe..835ac04d3 100644
--- a/catalog/tests/dags/common/test_extensions.py
+++ b/catalog/tests/dags/common/test_extensions.py
@@ -30,8 +30,8 @@ from common import extensions
("https://example.com/audio.midi", "audio", "mid"),
("https://example.com/audio.mka", "audio", "mka"),
("https://example.com/audio.mp3", "audio", "mp3"),
- ("https://example.com/audio.ogg", "audio", "oga"),
- ("https://example.com/audio.opus", "audio", "oga"),
+ ("https://example.com/audio.ogg", "audio", "ogg"),
+ ("https://example.com/audio.opus", "audio", "ogg"),
("https://example.com/audio.wav", "audio", "wav"),
# Invalid cases
("https://example.com/test.jpg.image", None, None),
@@ -67,10 +67,12 @@ def test_extract_filetype_returns_for_supported_media_type(
("audio/midi", "mid"),
("audio/mp3", "mp3"),
("audio/mpeg3", "mp3"),
- ("audio/ogg", "oga"),
+ ("audio/ogg", "ogg"),
("audio/opus", "opus"),
("audio/wav", "wav"),
("audio/x-wav", "wav"),
+ ("audio/wave", "wav"),
+ ("audio/vnd.wave", "wav"),
("audio/x-matroska", "mka"),
],
)
diff --git a/catalog/tests/dags/common/test_retries.py b/catalog/tests/dags/common/test_retries.py
new file mode 100644
index 000000000..ff5f9be9b
--- /dev/null
+++ b/catalog/tests/dags/common/test_retries.py
@@ -0,0 +1,122 @@
+import pytest
+from requests import Response
+from requests.exceptions import ConnectionError, HTTPError, SSLError
+
+from common.retries import retry_on_exceptions, retry_on_http_status
+
+
[email protected](autouse=True)
+def skip_waits(monkeypatch):
+ # The decorators wait for up to several seconds between attempts.
+ monkeypatch.setattr("time.sleep", lambda seconds: None)
+
+
+def http_error(status_code: int | None = None) -> HTTPError:
+ if status_code is None:
+ return HTTPError()
+ response = Response()
+ response.status_code = status_code
+ return HTTPError(response=response)
+
+
+class Flaky:
+ """Raise each of ``errors`` on successive calls, then return ``"ok"``."""
+
+ def __init__(self, *errors: BaseException):
+ self.errors = list(errors)
+ self.calls = 0
+
+ def __call__(self):
+ self.calls += 1
+ if self.errors:
+ raise self.errors.pop(0)
+ return "ok"
+
+
+ "decorator, errors",
+ [
+ pytest.param(retry_on_http_status(max_time=60), [http_error(502)], id="502"),
+ pytest.param(retry_on_http_status(max_time=60), [http_error(503)], id="503"),
+ pytest.param(
+ retry_on_http_status(max_time=60),
+ [http_error(504), http_error(503), http_error(502)],
+ id="several-server-errors",
+ ),
+ pytest.param(
+ retry_on_http_status(max_time=60, status_codes={400}),
+ [http_error(400)],
+ id="custom-status-code",
+ ),
+ pytest.param(
+ retry_on_exceptions(ValueError, max_tries=3),
+ [ValueError(), ValueError()],
+ id="exception-within-max-tries",
+ ),
+ pytest.param(
+ retry_on_exceptions((SSLError, ConnectionError), max_tries=3),
+ [SSLError(), ConnectionError()],
+ id="any-of-several-exceptions",
+ ),
+ ],
+)
+def test_retries_until_the_call_succeeds(decorator, errors):
+ func = Flaky(*errors)
+
+ assert decorator(func)() == "ok"
+ assert func.calls == len(errors) + 1
+
+
+ "decorator, error",
+ [
+ pytest.param(retry_on_http_status(max_time=60), http_error(400), id="400"),
+ pytest.param(retry_on_http_status(max_time=60), http_error(404), id="404"),
+ pytest.param(retry_on_http_status(max_time=60), http_error(500), id="500"),
+ pytest.param(
+ retry_on_http_status(max_time=60, status_codes={400}),
+ http_error(503),
+ id="status-code-not-in-custom-codes",
+ ),
+ pytest.param(
+ retry_on_http_status(max_time=60), http_error(), id="http-error-no-response"
+ ),
+ pytest.param(retry_on_http_status(max_time=60), ValueError(), id="not-http"),
+ pytest.param(
+ retry_on_exceptions(ValueError, max_tries=3),
+ KeyError(),
+ id="exception-not-listed",
+ ),
+ ],
+)
+def test_raises_other_errors_without_retrying(decorator, error):
+ func = Flaky(error)
+
+ with pytest.raises(type(error)) as exc_info:
+ decorator(func)()
+
+ assert exc_info.value is error
+ assert func.calls == 1
+
+
[email protected]("max_tries", [1, 3])
+def test_retry_on_exceptions_raises_the_last_error_after_max_tries(max_tries):
+ errors = [ConnectionError(f"attempt {n}") for n in range(max_tries + 1)]
+ func = Flaky(*errors)
+
+ with pytest.raises(ConnectionError) as exc_info:
+ retry_on_exceptions(ConnectionError, max_tries=max_tries)(func)()
+
+ assert exc_info.value is errors[max_tries - 1]
+ assert func.calls == max_tries
+
+
+def test_retry_on_http_status_raises_the_error_once_max_time_has_passed():
+ error = http_error(503)
+ func = Flaky(error, http_error(503))
+
+ with pytest.raises(HTTPError) as exc_info:
+ retry_on_http_status(max_time=0)(func)()
+
+ assert exc_info.value is error
+ assert func.calls == 1
diff --git a/docker/dev_env/Dockerfile b/docker/dev_env/Dockerfile
index 8f4ca7b4d..6cbe46ef7 100644
--- a/docker/dev_env/Dockerfile
+++ b/docker/dev_env/Dockerfile
@@ -1,6 +1,6 @@
# syntax=docker/dockerfile:1
-FROM docker.io/library/fedora:41
+FROM docker.io/library/fedora:45
# We want to keep all important things in `/opt` as we will preserve the
# `/opt` directory as a volume.
@@ -36,7 +36,9 @@ ENV PATH="${PNPM_BIN}:${N_PREFIX}/bin:${HOME}/.local/bin:${PATH}"
# - tree: list files in a tree
# - xdg-utils: added because Storybook wants to open in a browser
# - nodejs, npm: language runtime (does not include Corepack)
-# - python*: required by some Python libraries for compilation during installation
+# - python*: required by some Python libraries for compilation during installation;
+# keep in sync with `# PYTHON=` in `catalog/requirements-prod.txt`, because
+# `just catalog/venv` runs `python<version>` from here
# - pipx: Python CLI app installer
# - libffi*: required for the Python package cffi
# - libatomic: required by the Node.js binaries that `n` installs
@@ -69,7 +71,7 @@ RUN mkdir -p $HOME/.local/bin \
tree \
xdg-utils \
nodejs npm \
- python3.12 python3.12-devel \
+ python3.14 python3.14-devel \
pipx \
libffi-devel \
libatomic \