Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Commit

Permalink
Fix 'LruCache' object has no attribute '_on_resize' (#8591)
Browse files Browse the repository at this point in the history
We need to make sure we are readu for the `set_cache_factor` callback.
  • Loading branch information
richvdh authored Oct 19, 2020
1 parent 34c2049 commit 96e7d3c
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
1 change: 1 addition & 0 deletions changelog.d/8591.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Move metric registration code down into `LruCache`.
10 changes: 9 additions & 1 deletion synapse/util/caches/lrucache.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,10 @@ def __init__(
else:
self.max_size = int(max_size)

# register_cache might call our "set_cache_factor" callback; there's nothing to
# do yet when we get resized.
self._on_resize = None # type: Optional[Callable[[],None]]

if cache_name is not None:
metrics = register_cache(
"lru_cache",
Expand Down Expand Up @@ -332,7 +336,10 @@ def cache_contains(key: KT) -> bool:
return key in cache

self.sentinel = object()

# make sure that we clear out any excess entries after we get resized.
self._on_resize = evict

self.get = cache_get
self.set = cache_set
self.setdefault = cache_set_default
Expand Down Expand Up @@ -383,6 +390,7 @@ def set_cache_factor(self, factor: float) -> bool:
new_size = int(self._original_max_size * factor)
if new_size != self.max_size:
self.max_size = new_size
self._on_resize()
if self._on_resize:
self._on_resize()
return True
return False
8 changes: 7 additions & 1 deletion tests/util/test_lrucache.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
from synapse.util.caches.lrucache import LruCache
from synapse.util.caches.treecache import TreeCache

from .. import unittest
from tests import unittest
from tests.unittest import override_config


class LruCacheTestCase(unittest.HomeserverTestCase):
Expand Down Expand Up @@ -83,6 +84,11 @@ def test_clear(self):
cache.clear()
self.assertEquals(len(cache), 0)

@override_config({"caches": {"per_cache_factors": {"mycache": 10}}})
def test_special_size(self):
cache = LruCache(10, "mycache")
self.assertEqual(cache.max_size, 100)


class LruCacheCallbacksTestCase(unittest.HomeserverTestCase):
def test_get(self):
Expand Down

0 comments on commit 96e7d3c

Please sign in to comment.