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

Commit

Permalink
Merge pull request #8593 from matrix-org/rav/cache_hacking/3
Browse files Browse the repository at this point in the history
Optimisation in DeferredCache.set
  • Loading branch information
richvdh authored Oct 21, 2020
2 parents 9146a8a + c13820b commit 15d5553
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
1 change: 1 addition & 0 deletions changelog.d/8593.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Minor optimisations in caching code.
18 changes: 15 additions & 3 deletions synapse/util/caches/deferred_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
from prometheus_client import Gauge

from twisted.internet import defer
from twisted.python import failure

from synapse.util.async_helpers import ObservableDeferred
from synapse.util.caches.lrucache import LruCache
Expand Down Expand Up @@ -214,16 +215,27 @@ def set(

callbacks = [callback] if callback else []
self.check_thread()
observable = ObservableDeferred(value, consumeErrors=True)
observer = observable.observe()
entry = CacheEntry(deferred=observable, callbacks=callbacks)

existing_entry = self._pending_deferred_cache.pop(key, None)
if existing_entry:
existing_entry.invalidate()

# XXX: why don't we invalidate the entry in `self.cache` yet?

# we can save a whole load of effort if the deferred is ready.
if value.called:
result = value.result
if not isinstance(result, failure.Failure):
self.cache.set(key, result, callbacks)
return value

# otherwise, we'll add an entry to the _pending_deferred_cache for now,
# and add callbacks to add it to the cache properly later.

observable = ObservableDeferred(value, consumeErrors=True)
observer = observable.observe()
entry = CacheEntry(deferred=observable, callbacks=callbacks)

self._pending_deferred_cache[key] = entry

def compare_and_pop():
Expand Down

0 comments on commit 15d5553

Please sign in to comment.