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

Commit 8d6dde7

Browse files
committed
Merge pull request #457 from matrix-org/markjh/cached_sync
Add a cache for initialSync responses that expires after 5 minutes
2 parents ba39d3d + d12c00b commit 8d6dde7

File tree

3 files changed

+177
-1
lines changed

3 files changed

+177
-1
lines changed

synapse/handlers/message.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from synapse.events.validator import EventValidator
2323
from synapse.util import unwrapFirstError
2424
from synapse.util.logcontext import PreserveLoggingContext
25+
from synapse.util.caches.snapshot_cache import SnapshotCache
2526
from synapse.types import UserID, RoomStreamToken, StreamToken
2627

2728
from ._base import BaseHandler
@@ -45,6 +46,7 @@ def __init__(self, hs):
4546
self.state = hs.get_state_handler()
4647
self.clock = hs.get_clock()
4748
self.validator = EventValidator()
49+
self.snapshot_cache = SnapshotCache()
4850

4951
@defer.inlineCallbacks
5052
def get_message(self, msg_id=None, room_id=None, sender_id=None,
@@ -326,7 +328,6 @@ def get_state_events(self, user_id, room_id, is_guest=False):
326328
[serialize_event(c, now) for c in room_state.values()]
327329
)
328330

329-
@defer.inlineCallbacks
330331
def snapshot_all_rooms(self, user_id=None, pagin_config=None,
331332
as_client_event=True, include_archived=False):
332333
"""Retrieve a snapshot of all rooms the user is invited or has joined.
@@ -346,6 +347,28 @@ def snapshot_all_rooms(self, user_id=None, pagin_config=None,
346347
is joined on, may return a "messages" key with messages, depending
347348
on the specified PaginationConfig.
348349
"""
350+
key = (
351+
user_id,
352+
pagin_config.from_token,
353+
pagin_config.to_token,
354+
pagin_config.direction,
355+
pagin_config.limit,
356+
as_client_event,
357+
include_archived,
358+
)
359+
now_ms = self.clock.time_msec()
360+
result = self.snapshot_cache.get(now_ms, key)
361+
if result is not None:
362+
return result
363+
364+
return self.snapshot_cache.set(now_ms, key, self._snapshot_all_rooms(
365+
user_id, pagin_config, as_client_event, include_archived
366+
))
367+
368+
@defer.inlineCallbacks
369+
def _snapshot_all_rooms(self, user_id=None, pagin_config=None,
370+
as_client_event=True, include_archived=False):
371+
349372
memberships = [Membership.INVITE, Membership.JOIN]
350373
if include_archived:
351374
memberships.append(Membership.LEAVE)
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# -*- coding: utf-8 -*-
2+
# Copyright 2015 OpenMarket Ltd
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
16+
from synapse.util.async import ObservableDeferred
17+
18+
19+
class SnapshotCache(object):
20+
"""Cache for snapshots like the response of /initialSync.
21+
The response of initialSync only has to be a recent snapshot of the
22+
server state. It shouldn't matter to clients if it is a few minutes out
23+
of date.
24+
25+
This caches a deferred response. Until the deferred completes it will be
26+
returned from the cache. This means that if the client retries the request
27+
while the response is still being computed, that original response will be
28+
used rather than trying to compute a new response.
29+
30+
Once the deferred completes it will removed from the cache after 5 minutes.
31+
We delay removing it from the cache because a client retrying its request
32+
could race with us finishing computing the response.
33+
34+
Rather than tracking precisely how long something has been in the cache we
35+
keep two generations of completed responses. Every 5 minutes discard the
36+
old generation, move the new generation to the old generation, and set the
37+
new generation to be empty. This means that a result will be in the cache
38+
somewhere between 5 and 10 minutes.
39+
"""
40+
41+
DURATION_MS = 5 * 60 * 1000 # Cache results for 5 minutes.
42+
43+
def __init__(self):
44+
self.pending_result_cache = {} # Request that haven't finished yet.
45+
self.prev_result_cache = {} # The older requests that have finished.
46+
self.next_result_cache = {} # The newer requests that have finished.
47+
self.time_last_rotated_ms = 0
48+
49+
def rotate(self, time_now_ms):
50+
# Rotate once if the cache duration has passed since the last rotation.
51+
if time_now_ms - self.time_last_rotated_ms >= self.DURATION_MS:
52+
self.prev_result_cache = self.next_result_cache
53+
self.next_result_cache = {}
54+
self.time_last_rotated_ms += self.DURATION_MS
55+
56+
# Rotate again if the cache duration has passed twice since the last
57+
# rotation.
58+
if time_now_ms - self.time_last_rotated_ms >= self.DURATION_MS:
59+
self.prev_result_cache = self.next_result_cache
60+
self.next_result_cache = {}
61+
self.time_last_rotated_ms = time_now_ms
62+
63+
def get(self, time_now_ms, key):
64+
self.rotate(time_now_ms)
65+
# This cache is intended to deduplicate requests, so we expect it to be
66+
# missed most of the time. So we just lookup the key in all of the
67+
# dictionaries rather than trying to short circuit the lookup if the
68+
# key is found.
69+
result = self.prev_result_cache.get(key)
70+
result = self.next_result_cache.get(key, result)
71+
result = self.pending_result_cache.get(key, result)
72+
if result is not None:
73+
return result.observe()
74+
else:
75+
return None
76+
77+
def set(self, time_now_ms, key, deferred):
78+
self.rotate(time_now_ms)
79+
80+
result = ObservableDeferred(deferred)
81+
82+
self.pending_result_cache[key] = result
83+
84+
def shuffle_along(r):
85+
# When the deferred completes we shuffle it along to the first
86+
# generation of the result cache. So that it will eventually
87+
# expire from the rotation of that cache.
88+
self.next_result_cache[key] = result
89+
self.pending_result_cache.pop(key, None)
90+
91+
result.observe().addBoth(shuffle_along)
92+
93+
return result.observe()

tests/util/test_snapshot_cache.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# -*- coding: utf-8 -*-
2+
# Copyright 2015 OpenMarket Ltd
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
16+
17+
from .. import unittest
18+
19+
from synapse.util.caches.snapshot_cache import SnapshotCache
20+
from twisted.internet.defer import Deferred
21+
22+
class SnapshotCacheTestCase(unittest.TestCase):
23+
24+
def setUp(self):
25+
self.cache = SnapshotCache()
26+
self.cache.DURATION_MS = 1
27+
28+
def test_get_set(self):
29+
# Check that getting a missing key returns None
30+
self.assertEquals(self.cache.get(0, "key"), None)
31+
32+
# Check that setting a key with a deferred returns
33+
# a deferred that resolves when the initial deferred does
34+
d = Deferred()
35+
set_result = self.cache.set(0, "key", d)
36+
self.assertIsNotNone(set_result)
37+
self.assertFalse(set_result.called)
38+
39+
# Check that getting the key before the deferred has resolved
40+
# returns a deferred that resolves when the initial deferred does.
41+
get_result_at_10 = self.cache.get(10, "key")
42+
self.assertIsNotNone(get_result_at_10)
43+
self.assertFalse(get_result_at_10.called)
44+
45+
# Check that the returned deferreds resolve when the initial deferred
46+
# does.
47+
d.callback("v")
48+
self.assertTrue(set_result.called)
49+
self.assertTrue(get_result_at_10.called)
50+
51+
# Check that getting the key after the deferred has resolved
52+
# before the cache expires returns a resolved deferred.
53+
get_result_at_11 = self.cache.get(11, "key")
54+
self.assertIsNotNone(get_result_at_11)
55+
self.assertTrue(get_result_at_11.called)
56+
57+
# Check that getting the key after the deferred has resolved
58+
# after the cache expires returns None
59+
get_result_at_12 = self.cache.get(12, "key")
60+
self.assertIsNone(get_result_at_12)

0 commit comments

Comments
 (0)