Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Don't cache or serve source counts that some shards failed to answer (#5857)
Olga Bulat9ef1c2ab27a7
diff --git a/api/api/controllers/search_controller.py b/api/api/controllers/search_controller.pyindex f49247efc..406d8cd36 100644--- a/api/api/controllers/search_controller.py+++ b/api/api/controllers/search_controller.py@@ -28,6 +28,7 @@ from api.controllers.elasticsearch.helpers import (from api.utils import talliesfrom api.utils.check_dead_links import check_dead_linksfrom api.utils.dead_link_mask import get_query_hash+from api.utils.exceptions import IncompleteSourceCountsfrom api.utils.search_context import SearchContext@@ -529,19 +530,36 @@ def execute_search(return page_count, result_count, results+def _cache_get(key: str, description: str):+ try:+ return cache.get(key=key)+ except ConnectionError:+ logger.warning(f"Redis connect failed, cannot get cached {description}.")+ return None+++def _cache_set(key: str, value, timeout: int | None, description: str):+ try:+ cache.set(key=key, timeout=timeout, value=value)+ except ConnectionError:+ logger.warning(f"Redis connect failed, cannot cache {description}.")++def get_sources(index):"""Given an index, find all available data sources and return their counts.+ Counts from an aggregation that some shards failed to answer are too low by+ the share of documents on those shards, so they are neither cached nor+ returned. The last complete counts are returned instead, and if there are+ none, ``IncompleteSourceCounts`` is raised.+:param index: An Elasticsearch index, such as `'image'`.:return: A dictionary mapping sources to the count of their images.`"""source_cache_name = "sources-" + index- try:- sources = cache.get(key=source_cache_name)- except ConnectionError:- logger.warning("Redis connect failed, cannot get cached sources.")- sources = None+ complete_cache_name = f"{source_cache_name}-last-complete"+ sources = _cache_get(source_cache_name, "sources")if not sources:# Don't increase `size` without reading this issue first:@@ -566,19 +584,35 @@ def get_sources(index):request_cache=True,es_query="sources",)- buckets = results["aggregations"]["unique_sources"]["buckets"]except NotFoundError:- buckets = [{"key": "none_found", "doc_count": 0}]- sources = {bucket["key"]: bucket["doc_count"] for bucket in buckets}+ results = {+ "aggregations": {+ "unique_sources": {+ "buckets": [{"key": "none_found", "doc_count": 0}]+ }+ }+ }- try:- cache.set(- key=source_cache_name,- timeout=SOURCE_CACHE_TIMEOUT,- value=sources,+ # The client's response object supports `in` and `[]` but not `.get`.+ shards = results["_shards"] if "_shards" in results else {}+ failed_shards = shards.get("failed", 0)+ if failed_shards:+ logger.warning(+ "Some shards failed to count the sources.",+ index=index,+ shards=shards,)- except ConnectionError:- logger.warning("Redis connect failed, cannot cache sources.")+ sources = _cache_get(complete_cache_name, "complete sources")+ if not sources:+ raise IncompleteSourceCounts(+ f"{failed_shards} shards of `{index}` failed to count the sources."+ )+ else:+ buckets = results["aggregations"]["unique_sources"]["buckets"]+ sources = {bucket["key"]: bucket["doc_count"] for bucket in buckets}+ _cache_set(source_cache_name, sources, SOURCE_CACHE_TIMEOUT, "sources")+ # Kept with no expiry, to answer while the shards keep failing.+ _cache_set(complete_cache_name, sources, None, "complete sources")sources = {source: int(count) for source, count in sources.items()}return sourcesdiff --git a/api/api/utils/exceptions.py b/api/api/utils/exceptions.pyindex 39f9607cb..27070c56d 100644--- a/api/api/utils/exceptions.py+++ b/api/api/utils/exceptions.py@@ -12,6 +12,14 @@ from api.utils.es_transport import SearchCapacityExceededlogger = structlog.get_logger(__name__)++class IncompleteSourceCounts(RuntimeError):+ """+ Some shards failed to answer the source count aggregation, and no complete+ counts are cached to fall back on.+ """++# Elasticsearch failing to answer is a backend outage the client can only wait# out, so it is reported as one. Answering here also keeps these out of the# error logs, which otherwise receive one 500 per timed-out search.@@ -28,6 +36,10 @@ SEARCH_BACKEND_FAILURES = {status.HTTP_503_SERVICE_UNAVAILABLE,"Search is temporarily unavailable, please retry shortly.",),+ IncompleteSourceCounts: (+ status.HTTP_503_SERVICE_UNAVAILABLE,+ "Source counts are temporarily unavailable, please retry shortly.",+ ),}diff --git a/api/test/unit/controllers/test_search_controller.py b/api/test/unit/controllers/test_search_controller.pyindex 54f2569a5..337d11ceb 100644--- a/api/test/unit/controllers/test_search_controller.py+++ b/api/test/unit/controllers/test_search_controller.py@@ -10,6 +10,7 @@ from uuid import uuid4import pookimport pytestfrom django_redis import get_redis_connection+from elastic_transport import ObjectApiResponsefrom elasticsearch_dsl import Searchfrom elasticsearch_dsl.query import Termsfrom structlog.testing import capture_logs@@ -22,6 +23,7 @@ from api.controllers.search_controller import ()from api.utils import talliesfrom api.utils.dead_link_mask import get_query_hash, save_query_mask+from api.utils.exceptions import IncompleteSourceCountsfrom api.utils.search_context import SearchContextfrom test.factory.es_http import (MOCK_DEAD_RESULT_URL_PREFIX,@@ -916,3 +918,72 @@ def test_get_sources_returns_stats(is_cache_reachable, cache_name, request, capl"Redis connect failed, cannot cache sources.",])+++def _source_counts_response(failed_shards: int) -> ObjectApiResponse:+ body = {+ "_shards": {+ "total": 18,+ "successful": 18 - failed_shards,+ "skipped": 0,+ "failed": failed_shards,+ },+ "aggregations": {+ "unique_sources": {+ "buckets": [+ {"key": "source_1", "doc_count": 1000 - 300 * bool(failed_shards)},+ {"key": "source_2", "doc_count": 500 - 150 * bool(failed_shards)},+ ]+ }+ },+ }+ return ObjectApiResponse(body=body, meta=mock.Mock())+++def test_get_sources_caches_complete_counts(search_con_cache):+ with patch(+ "api.controllers.search_controller.get_raw_es_response",+ return_value=_source_counts_response(failed_shards=0),+ ):+ search_controller.get_sources("image")++ expected = {"source_1": 1000, "source_2": 500}+ assert search_con_cache.get("sources-image") == expected+ assert search_con_cache.get("sources-image-last-complete") == expected+++def test_get_sources_returns_last_complete_counts_when_shards_fail(search_con_cache):+ search_con_cache.set(+ "sources-image-last-complete", {"source_1": 900, "source_2": 400}+ )++ with patch(+ "api.controllers.search_controller.get_raw_es_response",+ return_value=_source_counts_response(failed_shards=3),+ ):+ assert search_controller.get_sources("image") == {+ "source_1": 900,+ "source_2": 400,+ }++ assert search_con_cache.get("sources-image") is None+ assert search_con_cache.get("sources-image-last-complete") == {+ "source_1": 900,+ "source_2": 400,+ }+++@cache_availability_params+def test_get_sources_raises_when_shards_fail_without_complete_counts(+ is_cache_reachable, cache_name, request+):+ request.getfixturevalue(cache_name)++ with (+ patch(+ "api.controllers.search_controller.get_raw_es_response",+ return_value=_source_counts_response(failed_shards=3),+ ),+ pytest.raises(IncompleteSourceCounts),+ ):+ search_controller.get_sources("image")diff --git a/api/test/unit/utils/test_exceptions.py b/api/test/unit/utils/test_exceptions.pyindex 03eaad2af..280fa034f 100644--- a/api/test/unit/utils/test_exceptions.py+++ b/api/test/unit/utils/test_exceptions.py@@ -5,7 +5,7 @@ from elastic_transport import ConnectionError as ESConnectionErrorfrom elastic_transport import ConnectionTimeoutfrom api.utils.es_transport import SearchCapacityExceeded-from api.utils.exceptions import exception_handler+from api.utils.exceptions import IncompleteSourceCounts, exception_handler@pytest.mark.parametrize(@@ -14,6 +14,7 @@ from api.utils.exceptions import exception_handler(SearchCapacityExceeded("no socket free"), 503),(ConnectionTimeout("Connection timed out"), 504),(ESConnectionError("connection refused"), 503),+ (IncompleteSourceCounts("3 shards failed"), 503),],)def test_search_backend_failures_are_not_server_errors(ex, status_code):