Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
More precisely handle waveform generation failures (#4444)
sarayourfriend5b563b1b529b
diff --git a/api/api/utils/waveform.py b/api/api/utils/waveform.pyindex 44c90237e..07b91429e 100644--- a/api/api/utils/waveform.py+++ b/api/api/utils/waveform.py@@ -7,8 +7,11 @@ import shutilimport subprocessfrom django.conf import settings+from rest_framework import status+from rest_framework.exceptions import APIExceptionimport requests+import sentry_sdkimport structlog@@ -18,6 +21,20 @@ TMP_DIR = pathlib.Path("/tmp").resolve()UA_STRING = settings.OUTBOUND_USER_AGENT_TEMPLATE.format(purpose="Waveform")+class WaveformGenerationFailure(APIException):+ status_code = status.HTTP_424_FAILED_DEPENDENCY+ default_detail = "Could not generate the waveform."+ default_code = "waveform_generation_failure"+++class UpstreamWaveformException(APIException):+ status_code = status.HTTP_424_FAILED_DEPENDENCY+ default_detail = (+ "Could not generate the waveform due to a problem connecting to the provider."+ )+ default_code = "upstream_waveform_exception"++def ext_from_url(url):"""Get the file extension from the given URL.@@ -45,20 +62,30 @@ def download_audio(url, identifier)::returns: the name of the file on the disk"""- logger.info(f"downloading file url={url}")+ logger.debug("waveform_audio_download_start", url=url, identifier=identifier)headers = {"User-Agent": UA_STRING}- with requests.get(url, stream=True, headers=headers) as res:- logger.debug(f"res.status_code={res.status_code}")- mimetype = res.headers["content-type"]- logger.debug(f"mimetype={mimetype}")- ext = ext_from_url(url) or mimetypes.guess_extension(mimetype)- if ext is None:- raise ValueError("Could not identify media extension")- file_name = f"audio-{identifier}{ext}"- logger.debug(f"file name={file_name}")- with open(TMP_DIR.joinpath(file_name), "wb") as file:- shutil.copyfileobj(res.raw, file)+ try:+ with requests.get(url, stream=True, headers=headers) as res:+ logger.debug(f"res.status_code={res.status_code}")+ res.raise_for_status()+ mimetype = res.headers["content-type"]+ logger.debug(f"mimetype={mimetype}")+ ext = ext_from_url(url) or mimetypes.guess_extension(mimetype)+ if ext is None:+ raise ValueError("Could not identify media extension")+ file_name = f"audio-{identifier}{ext}"+ logger.debug(f"file name={file_name}")+ with open(TMP_DIR.joinpath(file_name), "wb") as file:+ shutil.copyfileobj(res.raw, file)+ except (requests.RequestException, ValueError) as e:+ logger.error("waveform_audio_download_failed", e=e)+ if isinstance(e, requests.RequestException):+ raise UpstreamWaveformException()+ else:+ sentry_sdk.capture_exception(e)+ raise WaveformGenerationFailure("Unknown file extension")+return file_name@@ -73,7 +100,7 @@ def generate_waveform(file_name, duration)::param duration: the duration of the audio to determine pixels per second"""- logger.info("Invoking audiowaveform")+ logger.debug("waveform_generation_started")pps = math.ceil(1e6 / duration) # approx 1000 points in totalargs = [@@ -85,9 +112,18 @@ def generate_waveform(file_name, duration):"--pixels-per-second",str(pps),]- logger.debug(f'executing subprocess command={" ".join(args)}')- proc = subprocess.run(args, cwd=TMP_DIR, check=True, capture_output=True)- logger.debug(f"finished subprocess proc.returncode={proc.returncode}")+ logger.debug("waveform_generation_subprocess", args=args)++ try:+ proc = subprocess.run(args, cwd=TMP_DIR, check=True, capture_output=True)+ except subprocess.CalledProcessError as e:+ logger.error("waveform_generation_failed", file_name=file_name, e=e)+ sentry_sdk.capture_exception(e)+ # Do not return details of the exception; we're calling directly to a system binary, and+ # the command output could be sensitive. Folks debugging can find details in the logs+ raise WaveformGenerationFailure()++ logger.debug("waveform_generation_finished", returncode=proc.returncode)return proc.stdout@@ -137,7 +173,14 @@ def cleanup(file_name):logger.debug(f"file_path={file_path}")if file_path.exists():logger.debug("deleting file")- os.remove(file_path)+ try:+ os.remove(file_path)+ except (OSError, FileNotFoundError) as e:+ # Do not raise a further exception, because this actually doesn't necessarily mean the request needs to fail+ sentry_sdk.capture_exception(e)+ logger.error("waveform_cleanup_failed", e=e, file_name=file_name)+ return+logger.debug("file deleted")else:logger.debug("file not found, nothing deleted")diff --git a/api/api/views/audio_views.py b/api/api/views/audio_views.pyindex c87162611..6336217af 100644--- a/api/api/views/audio_views.py+++ b/api/api/views/audio_views.py@@ -1,6 +1,6 @@from django.conf import settingsfrom rest_framework.decorators import action-from rest_framework.exceptions import APIException, NotFound+from rest_framework.exceptions import NotFoundfrom rest_framework.response import Responsefrom drf_spectacular.utils import extend_schema, extend_schema_view@@ -92,13 +92,10 @@ class AudioViewSet(MediaViewSet):audio = self.get_object()- try:- obj = {"points": audio.get_or_create_waveform()}- serializer = self.get_serializer(obj)+ obj = {"points": audio.get_or_create_waveform()}+ serializer = self.get_serializer(obj)- return Response(status=200, data=serializer.data)- except Exception as e:- raise APIException(getattr(e, "message", str(e)))+ return Response(status=200, data=serializer.data)@report@action(diff --git a/api/test/integration/test_audio_integration.py b/api/test/integration/test_audio_integration.pyindex 32e4bfb1e..8bb33090b 100644--- a/api/test/integration/test_audio_integration.py+++ b/api/test/integration/test_audio_integration.py@@ -1,13 +1,14 @@"""End-to-end API tests for audio.-Can be used to verify a live deployment is functioning as designed.-Run with the `pytest -s` command from this directory, inside the Docker-container.-Tests common to all media types are in ``test_media_integration.py``."""+import os+import subprocess+from unittest import mock++import pookimport pytest@@ -27,3 +28,42 @@ def test_audio_search_without_thumb(api_client):assert resp.status_code == 200parsed = resp.json()assert parsed["results"][0]["thumbnail"] is None+++def test_audio_waveform(api_client):+ resp = api_client.get("/v1/audio/44540200-91eb-483d-9e99-38ce86a52fb6/waveform/")+ assert resp.status_code == 200+ parsed = resp.json()+ assert parsed["len"] == len(parsed["points"])+++def test_audio_generation_failure(monkeypatch, api_client):+ mock_subprocess_run = mock.Mock()+ mock_subprocess_run.side_effect = subprocess.CalledProcessError(1, "", "", "")+ monkeypatch.setattr(subprocess, "run", mock_subprocess_run)+ resp = api_client.get("/v1/audio/44540200-91eb-483d-9e99-38ce86a52fb6/waveform/")+ assert resp.status_code == 424+ mock_subprocess_run.assert_called_once()+ assert "Could not generate the waveform." == resp.json()["detail"]+++def test_audio_waveform_cleanup_failure_does_not_fail_request(monkeypatch, api_client):+ mock_os_remove = mock.Mock()+ mock_os_remove.side_effect = OSError("beep boop")+ monkeypatch.setattr(os, "remove", mock_os_remove)+ resp = api_client.get("/v1/audio/44540200-91eb-483d-9e99-38ce86a52fb6/waveform/")+ assert resp.status_code == 200+ mock_os_remove.assert_called_once()++[email protected](start_active=False)+def test_audio_waveform_upstream_failure(api_client):+ audio_res = api_client.get("/v1/audio/44540200-91eb-483d-9e99-38ce86a52fb6/")+ audio = audio_res.json()++ pook.on()+ pook.get(audio["url"]).reply(500)++ resp = api_client.get("/v1/audio/44540200-91eb-483d-9e99-38ce86a52fb6/waveform/")+ assert resp.status_code == 424+ assert "problem connecting to the provider" in resp.json()["detail"]diff --git a/api/test/integration/test_image_integration.py b/api/test/integration/test_image_integration.pyindex 7ee3ac03c..3ac5986e1 100644--- a/api/test/integration/test_image_integration.py+++ b/api/test/integration/test_image_integration.py@@ -1,10 +1,6 @@"""End-to-end API tests for images.-Can be used to verify a live deployment is functioning as designed.-Run with the `pytest -s` command from this directory, inside the Docker-container.-Tests common to all media types are in ``test_media_integration.py``."""