Skip to content

Commit 3754e20

Browse files
authored
Prevent duplicate entries in uri_keys lists (#63)
This prevents duplicate entries in the `uri_keys` lists for the items in the keyring.
1 parent 79638e9 commit 3754e20

File tree

3 files changed

+27
-3
lines changed

3 files changed

+27
-3
lines changed

testproject/home/tests.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import time
2+
13
from django.contrib.auth.models import User
24
from django.contrib.contenttypes.models import ContentType
35
from django.core.cache import caches
@@ -490,6 +492,23 @@ def test_cache_keyring(self):
490492
# Compare Keys
491493
self.assertEqual(key, url)
492494

495+
@override_settings(WAGTAIL_CACHE_BACKEND="one_second")
496+
def test_cache_keyring_no_uri_key_duplication(self):
497+
# First get to populate keyring
498+
self.get_miss(self.page_cachedpage.get_url())
499+
# Wait a short time
500+
time.sleep(0.5)
501+
# Fetch a different page
502+
self.get_miss(self.page_wagtailpage.get_url())
503+
# Wait until the first page is expired, but not the keyring
504+
time.sleep(0.6)
505+
# Fetch the first page again
506+
self.get_miss(self.page_cachedpage.get_url())
507+
# Check the keyring does not contain duplicate uri_keys
508+
url = "http://%s%s" % ("testserver", self.page_cachedpage.get_url())
509+
keyring = self.cache.get("keyring")
510+
self.assertEqual(len(keyring.get(url, [])), 1)
511+
493512
def test_clear_cache(self):
494513
# First get should miss cache.
495514
self.get_miss(self.page_cachedpage.get_url())

testproject/testproject/settings.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,10 @@
133133
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
134134
"TIMEOUT": 90061, # 1 day, 1 hour, 1 minute, 1 second.
135135
},
136+
"one_second": {
137+
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
138+
"TIMEOUT": 1,
139+
},
136140
"zero": {
137141
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
138142
"TIMEOUT": 0,

wagtailcache/cache.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -308,9 +308,10 @@ def process_response(
308308
# Get current cache keys belonging to this URI.
309309
# This should be a list of keys.
310310
uri_keys: List[str] = keyring.get(uri, [])
311-
# Append the key to this list and save.
312-
uri_keys.append(cache_key)
313-
keyring[uri] = uri_keys
311+
# Append the key to this list if not already present and save.
312+
if cache_key not in uri_keys:
313+
uri_keys.append(cache_key)
314+
keyring[uri] = uri_keys
314315
self._wagcache.set("keyring", keyring)
315316

316317
if isinstance(response, SimpleTemplateResponse):

0 commit comments

Comments
 (0)