summary refs log tree commit diff
path: root/synapse/util/caches/deferred_cache.py
diff options
context:
space:
mode:
authorRichard van der Hoff <richard@matrix.org>2020-10-16 13:16:02 +0100
committerRichard van der Hoff <richard@matrix.org>2020-10-21 17:55:53 +0100
commit2b3af01791120de5d0b829395109b42870d9e465 (patch)
tree74b5939d87715eeac0e79932b360088e3a70a30d /synapse/util/caches/deferred_cache.py
parentMerge pull request #8572 from matrix-org/rav/cache_hacking/2 (diff)
downloadsynapse-2b3af01791120de5d0b829395109b42870d9e465.tar.xz
optimise DeferredCache.set
Diffstat (limited to 'synapse/util/caches/deferred_cache.py')
-rw-r--r--synapse/util/caches/deferred_cache.py15
1 files changed, 12 insertions, 3 deletions
diff --git a/synapse/util/caches/deferred_cache.py b/synapse/util/caches/deferred_cache.py
index 6c162e9f34..fc01026285 100644
--- a/synapse/util/caches/deferred_cache.py
+++ b/synapse/util/caches/deferred_cache.py
@@ -214,9 +214,6 @@ class DeferredCache(Generic[KT, VT]):
 
         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:
@@ -224,6 +221,18 @@ class DeferredCache(Generic[KT, VT]):
 
         # 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:
+            self.cache.set(key, value.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():