Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Switch to Photon for thumbnail generation (#1056)
sarayourfriendd78abb98cb7b
diff --git a/.github/actions/staging-thumbnails-deploy/action.yml b/.github/actions/staging-thumbnails-deploy/action.ymldeleted file mode 100644index 88e21cc6f..000000000--- a/.github/actions/staging-thumbnails-deploy/action.yml+++ /dev/null@@ -1,136 +0,0 @@-### !!!-# This file is automatically generated using Terraform.-# Do not update it manually. If changes need to be made,-# please request help from a maintainer to generate the-# updated version.-### !!!--name: openverse/staging-thumbnails-imaginary-deploy-description: Update the task definition for a staging-thumbnails-imaginary deployment--inputs:- tag:- required: true- description: Image tag to deploy.- aws-access-key-id:- required: true- aws-secret-access-key:- required: true- slack-webhook:- required: true--runs:- using: "composite"-- steps:- - name: Notify deployment start- uses: slackapi/[email protected]- with:- payload: |- {- "text": "Starting deployment of staging-thumbnails",- "blocks": [- {- "type": "section",- "text": {- "type": "mrkdwn",- "text": ":spinning-cd: A deployment of staging-thumbnails is starting using the `${{ inputs.tag }}` tag."- }- },- {- "type": "section",- "text": {- "type": "mrkdwn",- "text": "<${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|Click here to monitor the deployment>."- }- }- ]- }- env:- SLACK_WEBHOOK_URL: ${{ inputs.slack-webhook }}- SLACK_WEBHOOK_TYPE: INCOMING_WEBHOOK-- - name: Configure AWS credentials- uses: aws-actions/configure-aws-credentials@v1- with:- aws-access-key-id: ${{ inputs.aws-access-key-id }}- aws-secret-access-key: ${{ inputs.aws-secret-access-key }}- aws-region: us-east-1-- - name: Download task definition template- shell: bash- run: |- aws ecs describe-task-definition \- --task-definition staging-thumbnails-template \- --query taskDefinition > task-definition.json-- - name: Fill in the new image ID in the Amazon ECS task definition- id: task-def- uses: aws-actions/amazon-ecs-render-task-definition@v1- with:- task-definition: task-definition.json- container-name: imaginary- image: ghcr.io/wordpress/openverse-imaginary:${{ inputs.tag }}-- - name: Deploy Amazon ECS task definition- uses: aws-actions/amazon-ecs-deploy-task-definition@v1- with:- task-definition: ${{ steps.task-def.outputs.task-definition }}- service: staging-thumbnails- cluster: staging-default- wait-for-service-stability: true-- - name: Notify deployment finished- uses: slackapi/[email protected]- with:- payload: |- {- "text": "Deployment of staging-thumbnails successful",- "blocks": [- {- "type": "section",- "text": {- "type": "mrkdwn",- "text": ":tadaco: The deployment of staging-thumbnails using the `${{ inputs.tag }}` tag *succeeded*."- }- },- {- "type": "section",- "text": {- "type": "mrkdwn",- "text": "<${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|Click here to review the completed deployment workflow>."- }- }- ]- }- env:- SLACK_WEBHOOK_URL: ${{ inputs.slack-webhook }}- SLACK_WEBHOOK_TYPE: INCOMING_WEBHOOK-- - name: Notify deployment failure- if: failure()- uses: slackapi/[email protected]- with:- payload: |- {- "text": "Deployment of staging-thumbnails failed!",- "blocks": [- {- "type": "section",- "text": {- "type": "mrkdwn",- "text": ":alert: The deployment of staging-thumbnails using the `${{ inputs.tag }}` tag *failed* :alert:"- }- },- {- "type": "section",- "text": {- "type": "mrkdwn",- "text": "<${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|Click here to review the failed deployment workflow>."- }- }- ]- }- env:- SLACK_WEBHOOK_URL: ${{ inputs.slack-webhook }}- SLACK_WEBHOOK_TYPE: INCOMING_WEBHOOKdiff --git a/.github/workflows/build_imaginary.yml b/.github/workflows/build_imaginary.ymldeleted file mode 100644index 0ce93fd63..000000000--- a/.github/workflows/build_imaginary.yml+++ /dev/null@@ -1,106 +0,0 @@-name: Build imaginary-on:- workflow_dispatch:- inputs:- deploy-to:- type: string- default: null- description: The environment to deploy to, if a deploy is desired. Currently only `staging` is available.-- build:- type: boolean- default: true- description: Set to `false` to trigger _just_ a redeployment--concurrency: ${{ github.workflow }}-${{ inputs.deploy-to }}--jobs:- build:- name: Build- if: github.event.inputs.build- runs-on: ubuntu-latest- steps:- - name: Checkout h2non/imaginary repository- uses: actions/checkout@v3- with:- repository: h2non/imaginary- path: imaginary-- - name: Set up QEMU- uses: docker/setup-qemu-action@v1-- - name: Set up Docker Buildx- uses: docker/setup-buildx-action@v1- with:- install: true-- - name: Log in to GitHub Docker Registry- uses: docker/login-action@v1- with:- registry: https://ghcr.io- username: ${{ github.actor }}- password: ${{ secrets.GITHUB_TOKEN }}-- - name: Setup Go- uses: actions/setup-go@v3- with:- go-version: "1.17"-- - name: Update modules # https://github.com/h2non/imaginary/issues/387- working-directory: imaginary- run: |- sed -i 's/bimg v1.1.4/bimg v1.1.9/' go.mod- go mod tidy-- - name: Skip tests # https://github.com/golang/go/issues/29948- working-directory: imaginary- run: |- sed -i 's/RUN go test/# RUN go test/' Dockerfile- sed -i 's/RUN golangci/# RUN golangci/' Dockerfile-- - name: Build image 'imaginary'- uses: docker/build-push-action@v2- with:- context: imaginary- platforms: linux/arm64,linux/amd64- cache-from: type=gha,scope=imaginary- cache-to: type=gha,scope=imaginary- push: true- tags: |- ghcr.io/wordpress/openverse-imaginary:latest-- deploy:- name: Deploy Imaginary- runs-on: ubuntu-latest- if: github.event.inputs.deploy-to != null- needs: [build]-- steps:- - uses: actions/github-script@v6- with:- github-token: ${{ secrets.ACCESS_TOKEN }}- script: |- const { data: members } = await github.rest.teams.listMembersInOrg({- org: 'WordPress',- team_slug: 'openverse-maintainers',- });-- const isAllowed = members.some(m => m.login === "${{ github.actor }}")-- if (!isAllowed) {- throw new Error(- "Only GitHub users in the @WordPress/openverse-maintainers "- + "team are allowed to run this workflow. If you need to run "- + "this workflow, please reach out to that group for help."- )- }-- - uses: actions/checkout@v3-- - uses: ./.github/actions/staging-thumbnails-deploy- if: github.event.inputs.deploy-to == 'staging'- with:- tag: latest- aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}- aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}- slack-webhook: ${{ secrets.SLACK_WEBHOOK_URL }}diff --git a/api/catalog/api/models/mixins.py b/api/catalog/api/models/mixins.pyindex 61b736356..69782a075 100644--- a/api/catalog/api/models/mixins.py+++ b/api/catalog/api/models/mixins.py@@ -87,7 +87,7 @@ class MediaMixin(models.Model):)# Because all forms of media have a thumbnail for visual representation- # For images, this field is not used as images are generated using ``imaginary``.+ # For images, this field is not used as images are generated using Photon.# For audio, this field points to the artwork, or is ``null``.thumbnail = models.URLField(max_length=1000,diff --git a/api/catalog/api/utils/photon.py b/api/catalog/api/utils/photon.pynew file mode 100644index 000000000..2a1056174--- /dev/null+++ b/api/catalog/api/utils/photon.py@@ -0,0 +1,104 @@+import logging+from urllib.parse import urlparse++from django.conf import settings+from django.http import HttpResponse+from rest_framework import status+from rest_framework.exceptions import APIException++import django_redis+import requests+import sentry_sdk+++parent_logger = logging.getLogger(__name__)+++class UpstreamThumbnailException(APIException):+ status_code = status.HTTP_424_FAILED_DEPENDENCY+ default_detail = "Could not render thumbnail due to upstream provider error."+ default_code = "upstream_photon_failure"+++HEADERS = {+ "User-Agent": settings.OUTBOUND_USER_AGENT_TEMPLATE.format(+ purpose="ThumbnailGeneration"+ )+}+++def get(+ image_url: str,+ accept_header: str = "image/*",+ is_full_size: bool = False,+ is_compressed: bool = True,+) -> HttpResponse:+ logger = parent_logger.getChild("get")+ # Photon options documented here:+ # https://developer.wordpress.com/docs/photon/api/+ params = {}++ if not is_full_size:+ params["w"] = settings.THUMBNAIL_WIDTH_PX++ if is_compressed:+ params["quality"] = settings.THUMBNAIL_QUALITY++ parsed_image_url = urlparse(image_url)++ if parsed_image_url.query:+ # No need to URL encode this string because requests will already+ # pass the `params` object to `urlencode` before it appends it to the+ # request URL.+ params["q"] = parsed_image_url.query++ # Photon excludes the protocol so we need to reconstruct the url + port + path+ # to send as the "path" of the Photon request+ domain = parsed_image_url.netloc+ path = parsed_image_url.path+ upstream_url = f"{settings.PHOTON_ENDPOINT}{domain}{path}"++ try:+ headers = {"Accept": accept_header} | HEADERS+ if settings.PHOTON_AUTH_KEY:+ headers["X-Photon-Authentication"] = settings.PHOTON_AUTH_KEY++ upstream_response = requests.get(+ upstream_url,+ timeout=10,+ params=params,+ headers=headers,+ )+ 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,+ )+ except requests.ReadTimeout as exc:+ # Count the incident so that we can identify providers with most timeouts.+ key = f"{settings.THUMBNAIL_TIMEOUT_PREFIX}{domain}"+ cache = django_redis.get_redis_connection("default")+ 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}"+ )+ 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}"+ )diff --git a/api/catalog/api/views/media_views.py b/api/catalog/api/views/media_views.pyindex 48405abe5..9f49259e2 100644--- a/api/catalog/api/views/media_views.py+++ b/api/catalog/api/views/media_views.py@@ -1,30 +1,19 @@import logging-from urllib.parse import urlencode, urlparse-from django.conf import settings-from django.core.cache import cache-from django.http.response import HttpResponsefrom rest_framework import statusfrom rest_framework.decorators import actionfrom rest_framework.exceptions import APIExceptionfrom rest_framework.response import Responsefrom rest_framework.viewsets import ReadOnlyModelViewSet-import requests-from sentry_sdk import capture_exception-from catalog.api.controllers import search_controllerfrom catalog.api.models import ContentProviderfrom catalog.api.serializers.provider_serializers import ProviderSerializer+from catalog.api.utils import photonfrom catalog.api.utils.pagination import StandardPaginationfrom catalog.custom_auto_schema import CustomAutoSchema-class UpstreamThumbnailException(APIException):- status_code = status.HTTP_424_FAILED_DEPENDENCY- default_detail = "Could not render thumbnail due to upstream provider error."--parent_logger = logging.getLogger(__name__)@@ -167,7 +156,7 @@ class MediaViewSet(ReadOnlyModelViewSet):def thumbnail(self, image_url, request, *_, **__):serializer = self.get_serializer(data=request.query_params)serializer.is_valid(raise_exception=True)- return self._get_proxied_image(+ return photon.get(image_url,accept_header=request.headers.get("Accept", "image/*"),**serializer.validated_data,@@ -190,101 +179,3 @@ class MediaViewSet(ReadOnlyModelViewSet):else:ip = request.META.get("REMOTE_ADDR")return ip-- THUMBNAIL_PROXY_COMM_HEADERS = {- "User-Agent": settings.OUTBOUND_USER_AGENT_TEMPLATE.format(- purpose="ThumbnailGeneration"- )- }-- @staticmethod- def _thumbnail_proxy_comm(- path: str,- params: dict,- headers: tuple[tuple[str, str]] = (),- ) -> tuple[requests.Response, int, str]:- logger = parent_logger.getChild("_thumbnail_proxy_comm")- proxy_url = settings.THUMBNAIL_PROXY_URL- query_string = urlencode(params)- upstream_url = f"{proxy_url}/{path}?{query_string}"- logger.debug(f"Image proxy upstream URL: {upstream_url}")-- try:- compiled_headers = MediaViewSet.THUMBNAIL_PROXY_COMM_HEADERS | {- k: v for k, v in headers- }- upstream_response = requests.get(- upstream_url, timeout=10, headers=compiled_headers- )-- 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 upstream_response, res_status, content_type- except requests.ReadTimeout as exc:- # Count the incident so that we can identify providers with most timeouts.- domain = urlparse(params["url"]).netloc- key = f"{settings.THUMBNAIL_TIMEOUT_PREFIX}{domain}"- try:- cache.incr(key)- except ValueError: # Key does not exist.- cache.set(key, 1)-- capture_exception(exc)- raise UpstreamThumbnailException(- f"Failed to render thumbnail due to timeout: {exc}"- )- except requests.RequestException as exc:- capture_exception(exc)- raise UpstreamThumbnailException(f"Failed to render thumbnail: {exc}")- except Exception as exc:- capture_exception(exc)- raise UpstreamThumbnailException(- f"Failed to render thumbnail due to unidentified exception: {exc}"- )-- @staticmethod- def _get_proxied_image(- image_url: str,- accept_header: str = "image/*",- is_full_size: bool = False,- is_compressed: bool = True,- ):- width = settings.THUMBNAIL_WIDTH_PX- if is_full_size:- info_res, *_ = MediaViewSet._thumbnail_proxy_comm(- "info", {"url": image_url}- )- info = info_res.json()- width = info["width"]-- params = {- "url": image_url,- "width": width,- }-- if is_compressed:- params |= {- "quality": settings.THUMBNAIL_JPG_QUALITY,- "compression": settings.THUMBNAIL_PNG_COMPRESSION,- }- else:- params |= {- "quality": 100,- "compression": 0,- }-- if "webp" in accept_header:- params["type"] = "auto" # Use ``Accept`` header to determine output type.-- img_res, res_status, content_type = MediaViewSet._thumbnail_proxy_comm(- "resize", params, (("Accept", accept_header),)- )- response = HttpResponse(- img_res.content, status=res_status, content_type=content_type- )- return responsediff --git a/api/catalog/settings.py b/api/catalog/settings.pyindex 17541c54e..dedc7c4cb 100644--- a/api/catalog/settings.py+++ b/api/catalog/settings.py@@ -206,12 +206,20 @@ CACHES = {},}-# Produce CC-hosted thumbnails dynamically through a proxy.-THUMBNAIL_PROXY_URL = config("THUMBNAIL_PROXY_URL", default="http://localhost:8222")+# If key is not present then the authentication header won't be sent+# and query forwarding will not work as expected. Lack of query forwarding+# is not an issue for local development so this compromise is okay.+PHOTON_AUTH_KEY = config("PHOTON_AUTH_KEY", default=None)-THUMBNAIL_WIDTH_PX = config("THUMBNAIL_WIDTH_PX", cast=int, default=600)-THUMBNAIL_JPG_QUALITY = config("THUMBNAIL_JPG_QUALITY", cast=int, default=80)-THUMBNAIL_PNG_COMPRESSION = config("THUMBNAIL_PNG_COMPRESSION", cast=int, default=6)+# Produce CC-hosted thumbnails dynamically through a proxy.+PHOTON_ENDPOINT = config("PHOTON_ENDPOINT", default="https://i0.wp.com/")++# These do not need to be cast to int because we don't use them directly,+# they're just passed through to Photon's API+# Keeping them as strings makes the tests slightly less verbose (for not needing+# to cast them in assertions to match the parsed param types)+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:"diff --git a/api/docs/guides/quickstart.md b/api/docs/guides/quickstart.mdindex 7c55829c1..0bd318748 100644--- a/api/docs/guides/quickstart.md+++ b/api/docs/guides/quickstart.md@@ -102,7 +102,6 @@ The command `just up` spawns the following services:- API application database- [Elasticsearch](https://www.elastic.co/elasticsearch/)- [Redis](https://redis.io/)-- [imaginary](https://github.com/h2non/imaginary)- [NGINX](http://nginx.org)- **web** (`api/`)- **ingestion_server** and **indexer_worker** (`ingestion_server/`)diff --git a/api/env.docker b/api/env.dockerindex f5e422747..ad081d60e 100644--- a/api/env.docker+++ b/api/env.docker@@ -10,8 +10,6 @@ ALLOWED_HOSTS=api.openverse.engineering,api-dev.openverse.engineering,host.dockeREDIS_HOST=cache-THUMBNAIL_PROXY_URL=http://thumbnails:8222-DJANGO_DATABASE_HOST=dbDJANGO_MIGRATE_DB_ON_STARTUP=Falsediff --git a/api/env.template b/api/env.templateindex 1fadb26b3..d9a043c0e 100644--- a/api/env.template+++ b/api/env.template@@ -1,7 +1,7 @@PYTHONUNBUFFERED=0DJANGO_SETTINGS_MODULE=catalog.settings-DJANGO_SECRET_KEY=+DJANGO_SECRET_KEY="ny#b__$$f6ry4wy8oxre97&-68u_0lk3gw(z=d40_dxey3zw0v1"DJANGO_DEBUG_ENABLED=TrueBASE_URL=http://localhost:50280/@@ -20,8 +20,6 @@ ALLOWED_HOSTS=172.17.0.1,host.docker.internal#REDIS_PORT=6379#REDIS_PASSWORD=-#THUMBNAIL_PROXY_URL=http://thumbnails:8222-#THUMBNAIL_WIDTH_PX=600#THUMBNAIL_JPG_QUALITY=80#THUMBNAIL_PNG_COMPRESSION=6diff --git a/api/test/unit/conftest.py b/api/test/unit/conftest.pyindex fbadf3d12..fef125464 100644--- a/api/test/unit/conftest.py+++ b/api/test/unit/conftest.py@@ -1,3 +1,5 @@+from unittest.mock import MagicMock+from rest_framework.test import APIClientimport pytest@@ -6,3 +8,11 @@ import pytest@pytest.fixturedef api_client():return APIClient()++[email protected](autouse=True)+def capture_exception(monkeypatch):+ mock = MagicMock()+ monkeypatch.setattr("sentry_sdk.capture_exception", mock)++ yield mockdiff --git a/api/test/unit/utils/conftest.py b/api/test/unit/utils/conftest.pynew file mode 100644index 000000000..4c726c29f--- /dev/null+++ b/api/test/unit/utils/conftest.py@@ -0,0 +1,33 @@+import json+from pathlib import Path++import pytest+from fakeredis import FakeRedis++[email protected](autouse=True)+def redis(monkeypatch) -> FakeRedis:+ fake_redis = FakeRedis()++ def get_redis_connection(*args, **kwargs):+ return fake_redis++ monkeypatch.setattr("django_redis.get_redis_connection", get_redis_connection)++ yield fake_redis+ fake_redis.client().close()++[email protected](scope="session")+def mock_image_data():+ mock_image_path = Path(__file__).parent / ".." / ".." / "factory"+ mock_image_file = mock_image_path / "sample-image.jpg"+ mock_image_info = json.loads(+ (mock_image_path / "sample-image-info.json").read_text()+ )++ yield {+ "file": mock_image_file,+ "byes": mock_image_file.read_bytes(),+ "info": mock_image_info,+ }diff --git a/api/test/unit/utils/photon_test.py b/api/test/unit/utils/photon_test.pynew file mode 100644index 000000000..0531646fe--- /dev/null+++ b/api/test/unit/utils/photon_test.py@@ -0,0 +1,263 @@+from urllib.parse import urlencode++from django.conf import settings++import pook+import pytest+import requests++from catalog.api.utils.photon import HEADERS, UpstreamThumbnailException+from catalog.api.utils.photon import get as photon_get+++PHOTON_URL_FOR_TEST_IMAGE = f"{settings.PHOTON_ENDPOINT}subdomain.example.com/path_part1/part2/image_dot_jpg.jpg"+TEST_IMAGE_URL = PHOTON_URL_FOR_TEST_IMAGE.replace(settings.PHOTON_ENDPOINT, "https://")++UA_HEADER = HEADERS["User-Agent"]++# cannot use actual image response because I kept running into some issue with+# requests not being able to decode the content+# I will come back to try to sort it out later but for now+# this will get the tests working.+MOCK_BODY = "mock response body"+++def auth_key():+ test_key = "this is a test Photon Key boop boop, let me in"+ settings.PHOTON_AUTH_KEY = test_key++ yield test_key++ settings.PHOTON_AUTH_KEY = None+++def test_get_successful_no_auth_key_default_args(mock_image_data):+ mock_get: pook.Mock = (+ 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+ )++ res = photon_get(TEST_IMAGE_URL)++ assert res.content == MOCK_BODY.encode()+ assert res.status_code == 200+ assert mock_get.matched+++def test_get_successful_with_auth_key_default_args(mock_image_data, auth_key):+ mock_get: pook.Mock = (+ 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/*")+ .header("X-Photon-Authentication", auth_key)+ .reply(200)+ .body(MOCK_BODY)+ .mock+ )++ res = photon_get(TEST_IMAGE_URL)++ assert res.content == MOCK_BODY.encode()+ assert res.status_code == 200+ assert mock_get.matched+++def test_get_successful_no_auth_key_not_compressed(mock_image_data):+ mock_get: pook.Mock = (+ pook.get(PHOTON_URL_FOR_TEST_IMAGE)+ .params(+ {+ "w": settings.THUMBNAIL_WIDTH_PX,+ }+ )+ .header("User-Agent", UA_HEADER)+ .header("Accept", "image/*")+ .reply(200)+ .body(MOCK_BODY)+ .mock+ )++ res = photon_get(TEST_IMAGE_URL, is_compressed=False)++ assert res.content == MOCK_BODY.encode()+ assert res.status_code == 200+ assert mock_get.matched+++def test_get_successful_no_auth_key_full_size(mock_image_data):+ mock_get: pook.Mock = (+ pook.get(PHOTON_URL_FOR_TEST_IMAGE)+ .params(+ {+ "quality": settings.THUMBNAIL_QUALITY,+ }+ )+ .header("User-Agent", UA_HEADER)+ .header("Accept", "image/*")+ .reply(200)+ .body(MOCK_BODY)+ .mock+ )++ res = photon_get(TEST_IMAGE_URL, is_full_size=True)++ assert res.content == MOCK_BODY.encode()+ assert res.status_code == 200+ assert mock_get.matched+++def test_get_successful_no_auth_key_full_size_not_compressed(mock_image_data):+ mock_get: pook.Mock = (+ pook.get(PHOTON_URL_FOR_TEST_IMAGE)+ .header("User-Agent", UA_HEADER)+ .header("Accept", "image/*")+ .reply(200)+ .body(MOCK_BODY)+ .mock+ )++ res = photon_get(TEST_IMAGE_URL, is_full_size=True, is_compressed=False)++ assert res.content == MOCK_BODY.encode()+ assert res.status_code == 200+ assert mock_get.matched+++def test_get_successful_no_auth_key_png_only(mock_image_data):+ mock_get: pook.Mock = (+ 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/png")+ .reply(200)+ .body(MOCK_BODY)+ .mock+ )++ res = photon_get(TEST_IMAGE_URL, accept_header="image/png")++ assert res.content == MOCK_BODY.encode()+ assert res.status_code == 200+ assert mock_get.matched+++def test_get_successful_forward_query_params(mock_image_data):+ params = urlencode({"hello": "world", 1: 2, "beep": "boop"})+ mock_get: pook.Mock = (+ pook.get(PHOTON_URL_FOR_TEST_IMAGE)+ .params(+ {+ "w": settings.THUMBNAIL_WIDTH_PX,+ "quality": settings.THUMBNAIL_QUALITY,+ "q": params,+ }+ )+ .header("User-Agent", UA_HEADER)+ .header("Accept", "image/*")+ .reply(200)+ .body(MOCK_BODY)+ .mock+ )++ url_with_params = f"{TEST_IMAGE_URL}?{params}"++ res = photon_get(url_with_params)++ assert res.content == MOCK_BODY.encode()+ assert res.status_code == 200+ assert mock_get.matched+++def setup_requests_get_exception(monkeypatch):+ def do(exc):+ def raise_exc(*args, **kwargs):+ raise exc++ monkeypatch.setattr("requests.get", raise_exc)++ 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)++ with pytest.raises(UpstreamThumbnailException):+ photon_get(TEST_IMAGE_URL)++ capture_exception.assert_called_once_with(exc)++ key = f"{settings.THUMBNAIL_TIMEOUT_PREFIX}subdomain.example.com"+ assert redis.get(key) == b"1"+++def test_get_timeout_existing_cache_key(+ 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)++ with pytest.raises(UpstreamThumbnailException, match=r"due to timeout"):+ photon_get(TEST_IMAGE_URL)++ capture_exception.assert_called_once_with(exc)++ assert redis.get(key) == b"6"+++def test_get_request_exception(capture_exception, setup_requests_get_exception):+ exc = requests.RequestException()+ setup_requests_get_exception(exc)++ with pytest.raises(+ UpstreamThumbnailException, match=r"Failed to render thumbnail:"+ ):+ photon_get(TEST_IMAGE_URL)++ capture_exception.assert_called_once_with(exc)+++def test_get_generic_exception(capture_exception, setup_requests_get_exception):+ exc = ValueError()+ setup_requests_get_exception(exc)++ with pytest.raises(+ UpstreamThumbnailException, match=r"due to unidentified exception"+ ):+ photon_get(TEST_IMAGE_URL)++ capture_exception.assert_called_once_with(exc)diff --git a/api/test/unit/utils/validate_images_test.py b/api/test/unit/utils/validate_images_test.pyindex e38e42284..de89cc45c 100644--- a/api/test/unit/utils/validate_images_test.py+++ b/api/test/unit/utils/validate_images_test.py@@ -3,25 +3,10 @@ from unittest import mockimport aiohttpimport pook-import pytest-from fakeredis import FakeRedisfrom catalog.api.utils.validate_images import HEADERS, validate_images[email protected](autouse=True)-def redis(monkeypatch) -> FakeRedis:- fake_redis = FakeRedis()-- def get_redis_connection(*args, **kwargs):- return fake_redis-- monkeypatch.setattr("django_redis.get_redis_connection", get_redis_connection)-- yield fake_redis- fake_redis.client().close()--@mock.patch.object(aiohttp, "ClientSession", wraps=aiohttp.ClientSession)@pook.ondef test_sends_user_agent(wrapped_client_session: mock.AsyncMock):diff --git a/api/test/unit/views/media_views_test.py b/api/test/unit/views/media_views_test.pyindex c297fda40..c22309f80 100644--- a/api/test/unit/views/media_views_test.py+++ b/api/test/unit/views/media_views_test.py@@ -1,64 +1,9 @@-import json-from collections.abc import Callable-from dataclasses import dataclass, field-from pathlib import Pathfrom test.factory.models.audio import AudioFactoryfrom test.factory.models.image import ImageFactory-from unittest import mockfrom unittest.mock import MagicMock, patchimport pytestimport pytest_django.asserts-import requests as requests_lib-from fakeredis import FakeRedis-from requests import PreparedRequest, ReadTimeout, Request, Response--from catalog.api.views.media_views import MediaViewSet, UpstreamThumbnailException---_MOCK_IMAGE_PATH = Path(__file__).parent / ".." / ".." / "factory"-_MOCK_IMAGE_BYTES = (_MOCK_IMAGE_PATH / "sample-image.jpg").read_bytes()-_MOCK_IMAGE_INFO = json.loads((_MOCK_IMAGE_PATH / "sample-image-info.json").read_text())---@dataclass-class SentRequest:- request: PreparedRequest- kwargs: dict---@dataclass-class RequestsFixture:- sent_requests: list[SentRequest]- send_handler: Callable[- [Request], Response- ] = lambda *args, **kwargs: RequestsFixture._default_send_handler(*args, **kwargs)- response_queue: list[Response] = field(default_factory=list)-- @staticmethod- def _default_send_handler(fixture, session, req, **kwargs) -> Response:- if fixture.response_queue:- return fixture.response_queue.pop()-- res = Response()- res.url = req.url- res.status_code = 200- res._content = _MOCK_IMAGE_BYTES- return res--[email protected](autouse=True)-def requests(monkeypatch) -> RequestsFixture:- fixture = RequestsFixture([])-- def send(session, req, **kwargs):- fixture.sent_requests.append(SentRequest(req, kwargs))- response = fixture.send_handler(fixture, session, req, **kwargs)- return response-- monkeypatch.setattr("requests.sessions.Session.send", send)-- return fixture@pytest.mark.django_db@@ -109,205 +54,3 @@ def test_retrieve_query_count(api_client, media_type, media_factory):res = api_client.get(f"/v1/{media_type}/{media.identifier}/")assert res.status_code == 200--- ("media_type", "media_factory"),- (- ("images", ImageFactory),- ("audio", AudioFactory),- ),-)-def test_thumb_error(api_client, media_type, media_factory, requests):- error = None-- def send_handler(fixture, session, req, **kwargs):- requests.sent_requests.append(SentRequest(req, kwargs))- nonlocal error- error = requests_lib.HTTPError(- req.url, 503, "Bad error upstream whoops", {}, None- )- raise error-- requests.send_handler = send_handler-- with mock.patch(- "catalog.api.views.media_views.capture_exception", autospec=True- ) as mock_capture_exception:- media = media_factory.create()- response = api_client.get(f"/v1/{media_type}/{media.identifier}/thumb/")-- assert response.status_code == 424- mock_capture_exception.assert_called_once_with(error)--- ("media_type", "media_factory"),- (- ("images", ImageFactory),- ("audio", AudioFactory),- ),-)-def test_thumb_sends_ua_header(api_client, media_type, media_factory, requests):- media = media_factory.create()- res = api_client.get(f"/v1/{media_type}/{media.identifier}/thumb/")-- assert res.status_code == 200-- assert len(requests.sent_requests) == 1- assert (- requests.sent_requests[0].request.headers["User-agent"]- == MediaViewSet.THUMBNAIL_PROXY_COMM_HEADERS["User-Agent"]- )--- ("media_type", "media_factory"),- (- ("images", ImageFactory),- ("audio", AudioFactory),- ),-)-def test_thumb(api_client, media_type, media_factory, requests):- media = media_factory.create()- res = api_client.get(f"/v1/{media_type}/{media.identifier}/thumb/")-- assert res.status_code == 200- assert res.content == _MOCK_IMAGE_BYTES- expected_upstream_params = {- "quality=",- "compression=",- "width=600",- }- for entry in expected_upstream_params:- assert (- entry in requests.sent_requests[0].request.url- ), f"{entry} not found in prepared request url: {requests.sent_requests[0].request.url}"--- ("media_type", "media_factory"),- (- ("images", ImageFactory),- ("audio", AudioFactory),- ),-)-def test_thumb_compression(api_client, media_type, media_factory, requests):- media = media_factory.create()- res = api_client.get(- f"/v1/{media_type}/{media.identifier}/thumb/", data={"compressed": "yes"}- )-- assert res.status_code == 200- expected_upstream_params = {- # Don't encode the defaults here, just assert that these params- # exist, but not with the uncompressed values in the rejected set below- "quality=",- "compression=",- }- rejected_params = {- "quality=100",- "compression=0",- }- for entry in expected_upstream_params:- assert (- entry in requests.sent_requests[0].request.url- ), f"{entry} not found in prepared request url: {requests.sent_requests[0].request.url}"-- for entry in rejected_params:- assert (- entry not in requests.sent_requests[0].request.url- ), f"Rejected {entry} found in prepared request url: {requests.sent_requests[0].request.url}"--- ("media_type", "media_factory"),- (- ("images", ImageFactory),- ("audio", AudioFactory),- ),-)-def test_thumb_webp(api_client, media_type, media_factory, requests):- media = media_factory.create()- accept_header = "image/webp,image/*,*/*"- res = api_client.get(- f"/v1/{media_type}/{media.identifier}/thumb/", HTTP_ACCEPT=accept_header- )-- assert res.status_code == 200- expected_upstream_params = {"type=auto"}- for entry in expected_upstream_params:- assert (- entry in requests.sent_requests[0].request.url- ), f"{entry} not found in prepared request url: {requests.sent_requests[0].request.url}"-- assert ("accept", accept_header) in requests.sent_requests[- 0- ].request.headers.lower_items()--- ("media_type", "media_factory"),- (- ("images", ImageFactory),- ("audio", AudioFactory),- ),-)-def test_thumb_full_size(api_client, media_type, media_factory, requests):- media = media_factory.create()-- upstream_width = 1200- info_response = Response()- info_response.status = 200- info_response._content = json.dumps({"width": upstream_width}).encode()- requests.response_queue = [info_response]-- res = api_client.get(- f"/v1/{media_type}/{media.identifier}/thumb/", data={"full_size": "yes"}- )-- assert res.status_code == 200- rejected_params = {- "width=600",- }-- for entry in rejected_params:- assert (- entry not in requests.sent_requests[1].request.url- ), f"Rejected {entry} found in prepared request url: {requests.sent_requests[0].request.url}"-- expected_params = {f"width={upstream_width}"}- for entry in expected_params:- assert (- entry in requests.sent_requests[1].request.url- ), f"{entry} not found in prepared request url: {requests.sent_requests[0].request.url}"---def redis(monkeypatch) -> FakeRedis:- fake_redis = FakeRedis()- monkeypatch.setattr("catalog.api.views.media_views.cache", fake_redis)-- yield fake_redis-- fake_redis.client().close()--[email protected]("count", [1, 3])-def test_thumb_timeout(redis, count: int):- with patch("requests.get", side_effect=ReadTimeout()):- for idx in range(count):- with pytest.raises(UpstreamThumbnailException):- MediaViewSet._thumbnail_proxy_comm(- "test", params={"url": f"https://example.com/image/{idx}"}- )-- # Conversion to ``int`` required because of bug:- # https://github.com/cunla/fakeredis-py/issues/58- assert count == int(redis.get("thumbnail_timeout:example.com"))diff --git a/docker-compose.yml b/docker-compose.ymlindex ae2065afd..5778c9db4 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -11,15 +11,6 @@ services:volumes:- api-postgres:/var/lib/postgresql/data- thumbnails:- image: ghcr.io/wordpress/openverse-imaginary:latest- expose:- - "8222"- environment:- PORT: 8222- MALLOC_ARENA_MAX: 2- command: ["-enable-url-source", "-forward-headers", "User-Agent"]-upstream_db:image: postgres:13.2-alpineexpose:@@ -82,6 +73,7 @@ services:- cacheenv_file:- api/env.docker+ - api/.envenvironment:STATIC_ROOT: ${STATIC_ROOT:-}MEDIA_ROOT: ${MEDIA_ROOT:-}diff --git a/justfile b/justfileindex 9f812c076..6e203f085 100644--- a/justfile+++ b/justfile@@ -35,6 +35,7 @@ DOCKER_FILE := "-f " + (# Run `docker-compose` configured with the correct files and environmentdc *args:+ @{{ if IS_CI != "" { "just env" } else { "true" } }}docker-compose {{ DOCKER_FILE }} {{ args }}# Build all (or specified) services