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

Commit d6196ef

Browse files
Add ResponseCache tests. (#9458)
1 parent b2c4d3d commit d6196ef

File tree

10 files changed

+156
-20
lines changed

10 files changed

+156
-20
lines changed

changelog.d/9458.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add tests to ResponseCache.

synapse/appservice/api.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def __init__(self, hs):
9090
self.clock = hs.get_clock()
9191

9292
self.protocol_meta_cache = ResponseCache(
93-
hs, "as_protocol_meta", timeout_ms=HOUR_IN_MS
93+
hs.get_clock(), "as_protocol_meta", timeout_ms=HOUR_IN_MS
9494
) # type: ResponseCache[Tuple[str, str]]
9595

9696
async def query_user(self, service, user_id):

synapse/federation/federation_server.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
Awaitable,
2323
Callable,
2424
Dict,
25+
Iterable,
2526
List,
2627
Optional,
2728
Tuple,
@@ -98,7 +99,7 @@
9899

99100

100101
class FederationServer(FederationBase):
101-
def __init__(self, hs):
102+
def __init__(self, hs: "HomeServer"):
102103
super().__init__(hs)
103104

104105
self.auth = hs.get_auth()
@@ -118,7 +119,7 @@ def __init__(self, hs):
118119

119120
# We cache results for transaction with the same ID
120121
self._transaction_resp_cache = ResponseCache(
121-
hs, "fed_txn_handler", timeout_ms=30000
122+
hs.get_clock(), "fed_txn_handler", timeout_ms=30000
122123
) # type: ResponseCache[Tuple[str, str]]
123124

124125
self.transaction_actions = TransactionActions(self.store)
@@ -128,10 +129,10 @@ def __init__(self, hs):
128129
# We cache responses to state queries, as they take a while and often
129130
# come in waves.
130131
self._state_resp_cache = ResponseCache(
131-
hs, "state_resp", timeout_ms=30000
132+
hs.get_clock(), "state_resp", timeout_ms=30000
132133
) # type: ResponseCache[Tuple[str, str]]
133134
self._state_ids_resp_cache = ResponseCache(
134-
hs, "state_ids_resp", timeout_ms=30000
135+
hs.get_clock(), "state_ids_resp", timeout_ms=30000
135136
) # type: ResponseCache[Tuple[str, str]]
136137

137138
self._federation_metrics_domains = (
@@ -453,7 +454,9 @@ async def _on_context_state_request_compute(
453454
self, room_id: str, event_id: str
454455
) -> Dict[str, list]:
455456
if event_id:
456-
pdus = await self.handler.get_state_for_pdu(room_id, event_id)
457+
pdus = await self.handler.get_state_for_pdu(
458+
room_id, event_id
459+
) # type: Iterable[EventBase]
457460
else:
458461
pdus = (await self.state.get_current_state(room_id)).values()
459462

synapse/handlers/initial_sync.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def __init__(self, hs: "HomeServer"):
4848
self.clock = hs.get_clock()
4949
self.validator = EventValidator()
5050
self.snapshot_cache = ResponseCache(
51-
hs, "initial_sync_cache"
51+
hs.get_clock(), "initial_sync_cache"
5252
) # type: ResponseCache[Tuple[str, Optional[StreamToken], Optional[StreamToken], str, Optional[int], bool, bool]]
5353
self._event_serializer = hs.get_event_client_serializer()
5454
self.storage = hs.get_storage()

synapse/handlers/room.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ def __init__(self, hs: "HomeServer"):
121121
# succession, only process the first attempt and return its result to
122122
# subsequent requests
123123
self._upgrade_response_cache = ResponseCache(
124-
hs, "room_upgrade", timeout_ms=FIVE_MINUTES_IN_MS
124+
hs.get_clock(), "room_upgrade", timeout_ms=FIVE_MINUTES_IN_MS
125125
) # type: ResponseCache[Tuple[str, str]]
126126
self._server_notices_mxid = hs.config.server_notices_mxid
127127

synapse/handlers/room_list.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,10 @@ def __init__(self, hs: "HomeServer"):
4444
super().__init__(hs)
4545
self.enable_room_list_search = hs.config.enable_room_list_search
4646
self.response_cache = ResponseCache(
47-
hs, "room_list"
47+
hs.get_clock(), "room_list"
4848
) # type: ResponseCache[Tuple[Optional[int], Optional[str], ThirdPartyInstanceID]]
4949
self.remote_response_cache = ResponseCache(
50-
hs, "remote_room_list", timeout_ms=30 * 1000
50+
hs.get_clock(), "remote_room_list", timeout_ms=30 * 1000
5151
) # type: ResponseCache[Tuple[str, Optional[int], Optional[str], bool, Optional[str]]]
5252

5353
async def get_local_public_room_list(

synapse/handlers/sync.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ def __init__(self, hs: "HomeServer"):
244244
self.event_sources = hs.get_event_sources()
245245
self.clock = hs.get_clock()
246246
self.response_cache = ResponseCache(
247-
hs, "sync"
247+
hs.get_clock(), "sync"
248248
) # type: ResponseCache[Tuple[Any, ...]]
249249
self.state = hs.get_state_handler()
250250
self.auth = hs.get_auth()

synapse/replication/http/_base.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
import re
1919
import urllib
2020
from inspect import signature
21-
from typing import Dict, List, Tuple
21+
from typing import TYPE_CHECKING, Dict, List, Tuple
2222

2323
from prometheus_client import Counter, Gauge
2424

@@ -28,6 +28,9 @@
2828
from synapse.util.caches.response_cache import ResponseCache
2929
from synapse.util.stringutils import random_string
3030

31+
if TYPE_CHECKING:
32+
from synapse.server import HomeServer
33+
3134
logger = logging.getLogger(__name__)
3235

3336
_pending_outgoing_requests = Gauge(
@@ -88,10 +91,10 @@ class ReplicationEndpoint(metaclass=abc.ABCMeta):
8891
CACHE = True
8992
RETRY_ON_TIMEOUT = True
9093

91-
def __init__(self, hs):
94+
def __init__(self, hs: "HomeServer"):
9295
if self.CACHE:
9396
self.response_cache = ResponseCache(
94-
hs, "repl." + self.NAME, timeout_ms=30 * 60 * 1000
97+
hs.get_clock(), "repl." + self.NAME, timeout_ms=30 * 60 * 1000
9598
) # type: ResponseCache[str]
9699

97100
# We reserve `instance_name` as a parameter to sending requests, so we

synapse/util/caches/response_cache.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,15 @@
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
1515
import logging
16-
from typing import TYPE_CHECKING, Any, Callable, Dict, Generic, Optional, TypeVar
16+
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
1717

1818
from twisted.internet import defer
1919

2020
from synapse.logging.context import make_deferred_yieldable, run_in_background
21+
from synapse.util import Clock
2122
from synapse.util.async_helpers import ObservableDeferred
2223
from synapse.util.caches import register_cache
2324

24-
if TYPE_CHECKING:
25-
from synapse.app.homeserver import HomeServer
26-
2725
logger = logging.getLogger(__name__)
2826

2927
T = TypeVar("T")
@@ -37,11 +35,11 @@ class ResponseCache(Generic[T]):
3735
used rather than trying to compute a new response.
3836
"""
3937

40-
def __init__(self, hs: "HomeServer", name: str, timeout_ms: float = 0):
38+
def __init__(self, clock: Clock, name: str, timeout_ms: float = 0):
4139
# Requests that haven't finished yet.
4240
self.pending_result_cache = {} # type: Dict[T, ObservableDeferred]
4341

44-
self.clock = hs.get_clock()
42+
self.clock = clock
4543
self.timeout_sec = timeout_ms / 1000.0
4644

4745
self._name = name
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
# Copyright 2021 The Matrix.org Foundation C.I.C.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from synapse.util.caches.response_cache import ResponseCache
16+
17+
from tests.server import get_clock
18+
from tests.unittest import TestCase
19+
20+
21+
class DeferredCacheTestCase(TestCase):
22+
"""
23+
A TestCase class for ResponseCache.
24+
25+
The test-case function naming has some logic to it in it's parts, here's some notes about it:
26+
wait: Denotes tests that have an element of "waiting" before its wrapped result becomes available
27+
(Generally these just use .delayed_return instead of .instant_return in it's wrapped call.)
28+
expire: Denotes tests that test expiry after assured existence.
29+
(These have cache with a short timeout_ms=, shorter than will be tested through advancing the clock)
30+
"""
31+
32+
def setUp(self):
33+
self.reactor, self.clock = get_clock()
34+
35+
def with_cache(self, name: str, ms: int = 0) -> ResponseCache:
36+
return ResponseCache(self.clock, name, timeout_ms=ms)
37+
38+
@staticmethod
39+
async def instant_return(o: str) -> str:
40+
return o
41+
42+
async def delayed_return(self, o: str) -> str:
43+
await self.clock.sleep(1)
44+
return o
45+
46+
def test_cache_hit(self):
47+
cache = self.with_cache("keeping_cache", ms=9001)
48+
49+
expected_result = "howdy"
50+
51+
wrap_d = cache.wrap(0, self.instant_return, expected_result)
52+
53+
self.assertEqual(
54+
expected_result,
55+
self.successResultOf(wrap_d),
56+
"initial wrap result should be the same",
57+
)
58+
self.assertEqual(
59+
expected_result,
60+
self.successResultOf(cache.get(0)),
61+
"cache should have the result",
62+
)
63+
64+
def test_cache_miss(self):
65+
cache = self.with_cache("trashing_cache", ms=0)
66+
67+
expected_result = "howdy"
68+
69+
wrap_d = cache.wrap(0, self.instant_return, expected_result)
70+
71+
self.assertEqual(
72+
expected_result,
73+
self.successResultOf(wrap_d),
74+
"initial wrap result should be the same",
75+
)
76+
self.assertIsNone(cache.get(0), "cache should not have the result now")
77+
78+
def test_cache_expire(self):
79+
cache = self.with_cache("short_cache", ms=1000)
80+
81+
expected_result = "howdy"
82+
83+
wrap_d = cache.wrap(0, self.instant_return, expected_result)
84+
85+
self.assertEqual(expected_result, self.successResultOf(wrap_d))
86+
self.assertEqual(
87+
expected_result,
88+
self.successResultOf(cache.get(0)),
89+
"cache should still have the result",
90+
)
91+
92+
# cache eviction timer is handled
93+
self.reactor.pump((2,))
94+
95+
self.assertIsNone(cache.get(0), "cache should not have the result now")
96+
97+
def test_cache_wait_hit(self):
98+
cache = self.with_cache("neutral_cache")
99+
100+
expected_result = "howdy"
101+
102+
wrap_d = cache.wrap(0, self.delayed_return, expected_result)
103+
self.assertNoResult(wrap_d)
104+
105+
# function wakes up, returns result
106+
self.reactor.pump((2,))
107+
108+
self.assertEqual(expected_result, self.successResultOf(wrap_d))
109+
110+
def test_cache_wait_expire(self):
111+
cache = self.with_cache("medium_cache", ms=3000)
112+
113+
expected_result = "howdy"
114+
115+
wrap_d = cache.wrap(0, self.delayed_return, expected_result)
116+
self.assertNoResult(wrap_d)
117+
118+
# stop at 1 second to callback cache eviction callLater at that time, then another to set time at 2
119+
self.reactor.pump((1, 1))
120+
121+
self.assertEqual(expected_result, self.successResultOf(wrap_d))
122+
self.assertEqual(
123+
expected_result,
124+
self.successResultOf(cache.get(0)),
125+
"cache should still have the result",
126+
)
127+
128+
# (1 + 1 + 2) > 3.0, cache eviction timer is handled
129+
self.reactor.pump((2,))
130+
131+
self.assertIsNone(cache.get(0), "cache should not have the result now")

0 commit comments

Comments
 (0)