-
Notifications
You must be signed in to change notification settings - Fork 85
[PULP-2012] Cache Simple API responses #1271
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jobselko
wants to merge
1
commit into
pulp:main
Choose a base branch
from
jobselko:1254
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+188
−5
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Added server-side caching and HTTP cache headers (`Cache-Control`, `ETag`) to Simple API responses. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| from django.core.exceptions import ObjectDoesNotExist | ||
| from django.http import Http404, HttpResponseNotModified | ||
|
|
||
| from pulpcore.plugin.cache import CacheKeys, SyncContentCache | ||
| from pulpcore.plugin.util import cache_key, get_domain | ||
|
|
||
| from pulp_python.app.models import PythonDistribution | ||
|
|
||
| ACCEPT_HEADER_KEY = "accept_header" | ||
|
|
||
|
|
||
| class PythonApiCache(SyncContentCache): | ||
| """ | ||
| Cache for the Simple API. | ||
|
|
||
| Adds Accept header to the cache key so HTML and JSON responses are cached separately. | ||
| Also handles ETag-based conditional requests (304 Not Modified). | ||
| """ | ||
|
|
||
| def __init__(self, base_key=None): | ||
| keys = (CacheKeys.path, CacheKeys.method, ACCEPT_HEADER_KEY) | ||
| super().__init__(base_key=base_key, keys=keys) | ||
|
|
||
| def __call__(self, func): | ||
| original = super().__call__(func) | ||
|
|
||
| def with_conditional_get(*args, **kwargs): | ||
| response = original(*args, **kwargs) | ||
| etag = response.get("ETag") | ||
| if etag: | ||
| request = self.get_request_from_args(args) | ||
| if request and request.META.get("HTTP_IF_NONE_MATCH") == etag: | ||
| not_modified = HttpResponseNotModified() | ||
| not_modified["ETag"] = etag | ||
| if cache_control := response.get("Cache-Control"): | ||
| not_modified["Cache-Control"] = cache_control | ||
| if x_pulp_cache := response.get("X-PULP-CACHE"): | ||
| not_modified["X-PULP-CACHE"] = x_pulp_cache | ||
| return not_modified | ||
| return response | ||
|
|
||
| return with_conditional_get | ||
|
|
||
| def make_key(self, request): | ||
| all_keys = { | ||
| CacheKeys.path: request.path, | ||
| CacheKeys.method: request.method, | ||
| ACCEPT_HEADER_KEY: request.headers.get("accept", ""), | ||
| } | ||
| return ":".join(all_keys[k] for k in self.keys) | ||
|
|
||
|
|
||
| def find_base_path_cached(request, cached): | ||
| """ | ||
| Resolve the distribution base_path for use as the Redis cache base_key. | ||
| """ | ||
| path = request.resolver_match.kwargs["path"] | ||
| base_key = cache_key(path) | ||
| if cached.exists(base_key=base_key): | ||
| return base_key | ||
| try: | ||
| distro = PythonDistribution.objects.get(base_path=path, pulp_domain=get_domain()) | ||
| except ObjectDoesNotExist: | ||
| raise Http404(f"No PythonDistribution found for base_path {path}") | ||
| return cache_key(distro.base_path) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| from urllib.parse import urljoin | ||
|
|
||
| import pytest | ||
| import requests | ||
|
|
||
| from pulp_python.tests.functional.constants import ( | ||
| PYPI_SIMPLE_V1_HTML, | ||
| PYPI_SIMPLE_V1_JSON, | ||
| PYTHON_SM_PROJECT_SPECIFIER, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def skip_without_cache(pulp_settings): | ||
| """ | ||
| Skip test if server-side caching is not enabled. | ||
| """ | ||
| if not pulp_settings.CACHE_ENABLED: | ||
| pytest.skip("CACHE_ENABLED is not set") | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def synced_distro( | ||
| skip_without_cache, | ||
| python_remote_factory, | ||
| python_repo_with_sync, | ||
| python_distribution_factory, | ||
| ): | ||
| """ | ||
| Sync a repo and create a distribution for cache tests. | ||
| """ | ||
| remote = python_remote_factory(includes=PYTHON_SM_PROJECT_SPECIFIER) | ||
| repo = python_repo_with_sync(remote) | ||
| return python_distribution_factory(repository=repo) | ||
|
|
||
|
|
||
| @pytest.mark.parallel | ||
| def test_simple_cache_hit_miss_and_headers(synced_distro): | ||
| """ | ||
| First request is a MISS, second is a HIT. Cache headers are present and stable. | ||
| """ | ||
| index_url = urljoin(synced_distro.base_url, "simple/") | ||
| detail_url = f"{index_url}aiohttp" | ||
|
|
||
| for url in [index_url, detail_url]: | ||
| r1 = requests.get(url) | ||
| assert r1.status_code == 200 | ||
| assert r1.headers["X-PULP-CACHE"] == "MISS" | ||
| assert r1.headers["Cache-Control"] == "max-age=600, public" | ||
| assert r1.headers["ETag"].startswith('"') and r1.headers["ETag"].endswith('"') | ||
|
|
||
| r2 = requests.get(url) | ||
| assert r2.status_code == 200 | ||
| assert r2.headers["X-PULP-CACHE"] == "HIT" | ||
| assert r2.headers["Cache-Control"] == r1.headers["Cache-Control"] | ||
| assert r2.headers["ETag"] == r1.headers["ETag"] | ||
|
|
||
|
|
||
| @pytest.mark.parallel | ||
| def test_simple_cache_separate_accept_headers(synced_distro): | ||
| """ | ||
| HTML and JSON responses are cached separately. | ||
| """ | ||
| url = urljoin(synced_distro.base_url, "simple/") | ||
|
|
||
| for header in [PYPI_SIMPLE_V1_HTML, PYPI_SIMPLE_V1_JSON]: | ||
| r = requests.get(url, headers={"Accept": header}) | ||
| assert r.status_code == 200 | ||
| assert r.headers["X-PULP-CACHE"] == "MISS" | ||
|
|
||
| for header in [PYPI_SIMPLE_V1_HTML, PYPI_SIMPLE_V1_JSON]: | ||
| r = requests.get(url, headers={"Accept": header}) | ||
| assert r.status_code == 200 | ||
| assert r.headers["X-PULP-CACHE"] == "HIT" | ||
|
|
||
|
|
||
| @pytest.mark.parallel | ||
| def test_simple_cache_etag_conditional_request(synced_distro): | ||
| """ | ||
| Matching If-None-Match returns 304, non-matching returns 200. | ||
| """ | ||
| url = urljoin(synced_distro.base_url, "simple/") | ||
|
|
||
| r1 = requests.get(url) | ||
| assert r1.status_code == 200 | ||
| etag = r1.headers["ETag"] | ||
|
|
||
| r2 = requests.get(url, headers={"If-None-Match": etag}) | ||
| assert r2.status_code == 304 | ||
| assert r2.headers["ETag"] == etag | ||
| assert len(r2.content) == 0 | ||
|
|
||
| r3 = requests.get(url, headers={"If-None-Match": '"old"'}) | ||
| assert r3.status_code == 200 | ||
| assert r3.headers["ETag"] == etag | ||
| assert len(r3.content) > 0 |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I did not include tests for invalidation as this is functionality of pulpcore.