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

Fix LruCache callback deduplication #6213

Merged
merged 8 commits into from
Nov 7, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/6213.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix LruCache callback deduplication.
48 changes: 37 additions & 11 deletions synapse/util/caches/descriptors.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
import inspect
import logging
import threading
from collections import namedtuple
from typing import Any, cast
from typing import Any, Tuple, Union, cast
from weakref import WeakValueDictionary

from six import itervalues

Expand All @@ -38,6 +38,8 @@

logger = logging.getLogger(__name__)

CacheKey = Union[Tuple, Any]
V02460 marked this conversation as resolved.
Show resolved Hide resolved


class _CachedFunction(Protocol):
invalidate = None # type: Any
Expand Down Expand Up @@ -430,7 +432,7 @@ def _wrapped(*args, **kwargs):
# Add our own `cache_context` to argument list if the wrapped function
# has asked for one
if self.add_cache_context:
kwargs["cache_context"] = _CacheContext(cache, cache_key)
kwargs["cache_context"] = _CacheContext.get_instance(cache, cache_key)

try:
cached_result_d = cache.get(cache_key, callback=invalidate_callback)
Expand Down Expand Up @@ -624,14 +626,38 @@ def errback(f):
return wrapped


class _CacheContext(namedtuple("_CacheContext", ("cache", "key"))):
# We rely on _CacheContext implementing __eq__ and __hash__ sensibly,
# which namedtuple does for us (i.e. two _CacheContext are the same if
# their caches and keys match). This is important in particular to
# dedupe when we add callbacks to lru cache nodes, otherwise the number
# of callbacks would grow.
def invalidate(self):
self.cache.invalidate(self.key)
class _CacheContext:
"""Holds cache information from the cached function higher in the calling order.

Can be used to invalidate the higher level cache entry if something changes
on a lower level.
"""

_cache_context_objects = (
WeakValueDictionary()
) # type: WeakValueDictionary[Tuple[Cache, CacheKey], _CacheContext]

def __init__(self, cache, cache_key): # type: (Cache, CacheKey) -> None
self._cache = cache
self._cache_key = cache_key

def invalidate(self): # type: () -> None
"""Invalidates the cache entry referred to by the context."""
self._cache.invalidate(self._cache_key)

@classmethod
def get_instance(cls, cache, cache_key): # type: (Cache, CacheKey) -> _CacheContext
"""Returns an instance constructed with the given arguments.

A new instance is only created if none already exists.
"""

# We make sure there are no identical _CacheContext instances. This is
# important in particular to dedupe when we add callbacks to lru cache
# nodes, otherwise the number of callbacks would grow.
return cls._cache_context_objects.setdefault(
(cache, cache_key), cls(cache, cache_key)
)


def cached(
Expand Down