1
0

test_sharded_event_persister.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. # Copyright 2020 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. import logging
  15. from unittest.mock import patch
  16. from twisted.test.proto_helpers import MemoryReactor
  17. from synapse.rest import admin
  18. from synapse.rest.client import login, room, sync
  19. from synapse.server import HomeServer
  20. from synapse.storage.util.id_generators import MultiWriterIdGenerator
  21. from synapse.util import Clock
  22. from tests.replication._base import BaseMultiWorkerStreamTestCase
  23. from tests.server import make_request
  24. logger = logging.getLogger(__name__)
  25. class EventPersisterShardTestCase(BaseMultiWorkerStreamTestCase):
  26. """Checks event persisting sharding works"""
  27. servlets = [
  28. admin.register_servlets_for_client_rest_resource,
  29. room.register_servlets,
  30. login.register_servlets,
  31. sync.register_servlets,
  32. ]
  33. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  34. # Register a user who sends a message that we'll get notified about
  35. self.other_user_id = self.register_user("otheruser", "pass")
  36. self.other_access_token = self.login("otheruser", "pass")
  37. self.room_creator = self.hs.get_room_creation_handler()
  38. self.store = hs.get_datastores().main
  39. def default_config(self) -> dict:
  40. conf = super().default_config()
  41. conf["stream_writers"] = {"events": ["worker1", "worker2"]}
  42. conf["instance_map"] = {
  43. "worker1": {"host": "testserv", "port": 1001},
  44. "worker2": {"host": "testserv", "port": 1002},
  45. }
  46. return conf
  47. def _create_room(self, room_id: str, user_id: str, tok: str) -> None:
  48. """Create a room with given room_id"""
  49. # We control the room ID generation by patching out the
  50. # `_generate_room_id` method
  51. with patch(
  52. "synapse.handlers.room.RoomCreationHandler._generate_room_id"
  53. ) as mock:
  54. mock.side_effect = lambda: room_id
  55. self.helper.create_room_as(user_id, tok=tok)
  56. def test_basic(self) -> None:
  57. """Simple test to ensure that multiple rooms can be created and joined,
  58. and that different rooms get handled by different instances.
  59. """
  60. self.make_worker_hs(
  61. "synapse.app.generic_worker",
  62. {"worker_name": "worker1"},
  63. )
  64. self.make_worker_hs(
  65. "synapse.app.generic_worker",
  66. {"worker_name": "worker2"},
  67. )
  68. persisted_on_1 = False
  69. persisted_on_2 = False
  70. store = self.hs.get_datastores().main
  71. user_id = self.register_user("user", "pass")
  72. access_token = self.login("user", "pass")
  73. # Keep making new rooms until we see rooms being persisted on both
  74. # workers.
  75. for _ in range(10):
  76. # Create a room
  77. room = self.helper.create_room_as(user_id, tok=access_token)
  78. # The other user joins
  79. self.helper.join(
  80. room=room, user=self.other_user_id, tok=self.other_access_token
  81. )
  82. # The other user sends some messages
  83. rseponse = self.helper.send(room, body="Hi!", tok=self.other_access_token)
  84. event_id = rseponse["event_id"]
  85. # The event position includes which instance persisted the event.
  86. pos = self.get_success(store.get_position_for_event(event_id))
  87. persisted_on_1 |= pos.instance_name == "worker1"
  88. persisted_on_2 |= pos.instance_name == "worker2"
  89. if persisted_on_1 and persisted_on_2:
  90. break
  91. self.assertTrue(persisted_on_1)
  92. self.assertTrue(persisted_on_2)
  93. def test_vector_clock_token(self) -> None:
  94. """Tests that using a stream token with a vector clock component works
  95. correctly with basic /sync and /messages usage.
  96. """
  97. self.make_worker_hs(
  98. "synapse.app.generic_worker",
  99. {"worker_name": "worker1"},
  100. )
  101. worker_hs2 = self.make_worker_hs(
  102. "synapse.app.generic_worker",
  103. {"worker_name": "worker2"},
  104. )
  105. sync_hs = self.make_worker_hs(
  106. "synapse.app.generic_worker",
  107. {"worker_name": "sync"},
  108. )
  109. sync_hs_site = self._hs_to_site[sync_hs]
  110. # Specially selected room IDs that get persisted on different workers.
  111. room_id1 = "!foo:test"
  112. room_id2 = "!baz:test"
  113. self.assertEqual(
  114. self.hs.config.worker.events_shard_config.get_instance(room_id1), "worker1"
  115. )
  116. self.assertEqual(
  117. self.hs.config.worker.events_shard_config.get_instance(room_id2), "worker2"
  118. )
  119. user_id = self.register_user("user", "pass")
  120. access_token = self.login("user", "pass")
  121. store = self.hs.get_datastores().main
  122. # Create two room on the different workers.
  123. self._create_room(room_id1, user_id, access_token)
  124. self._create_room(room_id2, user_id, access_token)
  125. # The other user joins
  126. self.helper.join(
  127. room=room_id1, user=self.other_user_id, tok=self.other_access_token
  128. )
  129. self.helper.join(
  130. room=room_id2, user=self.other_user_id, tok=self.other_access_token
  131. )
  132. # Do an initial sync so that we're up to date.
  133. channel = make_request(
  134. self.reactor, sync_hs_site, "GET", "/sync", access_token=access_token
  135. )
  136. next_batch = channel.json_body["next_batch"]
  137. # We now gut wrench into the events stream MultiWriterIdGenerator on
  138. # worker2 to mimic it getting stuck persisting an event. This ensures
  139. # that when we send an event on worker1 we end up in a state where
  140. # worker2 events stream position lags that on worker1, resulting in a
  141. # RoomStreamToken with a non-empty instance map component.
  142. #
  143. # Worker2's event stream position will not advance until we call
  144. # __aexit__ again.
  145. worker_store2 = worker_hs2.get_datastores().main
  146. assert isinstance(worker_store2._stream_id_gen, MultiWriterIdGenerator)
  147. actx = worker_store2._stream_id_gen.get_next()
  148. self.get_success(actx.__aenter__())
  149. response = self.helper.send(room_id1, body="Hi!", tok=self.other_access_token)
  150. first_event_in_room1 = response["event_id"]
  151. # Assert that the current stream token has an instance map component, as
  152. # we are trying to test vector clock tokens.
  153. room_stream_token = store.get_room_max_token()
  154. self.assertNotEqual(len(room_stream_token.instance_map), 0)
  155. # Check that syncing still gets the new event, despite the gap in the
  156. # stream IDs.
  157. channel = make_request(
  158. self.reactor,
  159. sync_hs_site,
  160. "GET",
  161. f"/sync?since={next_batch}",
  162. access_token=access_token,
  163. )
  164. # We should only see the new event and nothing else
  165. self.assertIn(room_id1, channel.json_body["rooms"]["join"])
  166. self.assertNotIn(room_id2, channel.json_body["rooms"]["join"])
  167. events = channel.json_body["rooms"]["join"][room_id1]["timeline"]["events"]
  168. self.assertListEqual(
  169. [first_event_in_room1], [event["event_id"] for event in events]
  170. )
  171. # Get the next batch and makes sure its a vector clock style token.
  172. vector_clock_token = channel.json_body["next_batch"]
  173. self.assertTrue(vector_clock_token.startswith("m"))
  174. # Now that we've got a vector clock token we finish the fake persisting
  175. # an event we started above.
  176. self.get_success(actx.__aexit__(None, None, None))
  177. # Now try and send an event to the other rooom so that we can test that
  178. # the vector clock style token works as a `since` token.
  179. response = self.helper.send(room_id2, body="Hi!", tok=self.other_access_token)
  180. first_event_in_room2 = response["event_id"]
  181. channel = make_request(
  182. self.reactor,
  183. sync_hs_site,
  184. "GET",
  185. f"/sync?since={vector_clock_token}",
  186. access_token=access_token,
  187. )
  188. self.assertNotIn(room_id1, channel.json_body["rooms"]["join"])
  189. self.assertIn(room_id2, channel.json_body["rooms"]["join"])
  190. events = channel.json_body["rooms"]["join"][room_id2]["timeline"]["events"]
  191. self.assertListEqual(
  192. [first_event_in_room2], [event["event_id"] for event in events]
  193. )
  194. next_batch = channel.json_body["next_batch"]
  195. # We also want to test that the vector clock style token works with
  196. # pagination. We do this by sending a couple of new events into the room
  197. # and syncing again to get a prev_batch token for each room, then
  198. # paginating from there back to the vector clock token.
  199. self.helper.send(room_id1, body="Hi again!", tok=self.other_access_token)
  200. self.helper.send(room_id2, body="Hi again!", tok=self.other_access_token)
  201. channel = make_request(
  202. self.reactor,
  203. sync_hs_site,
  204. "GET",
  205. f"/sync?since={next_batch}",
  206. access_token=access_token,
  207. )
  208. prev_batch1 = channel.json_body["rooms"]["join"][room_id1]["timeline"][
  209. "prev_batch"
  210. ]
  211. prev_batch2 = channel.json_body["rooms"]["join"][room_id2]["timeline"][
  212. "prev_batch"
  213. ]
  214. # Paginating back in the first room should not produce any results, as
  215. # no events have happened in it. This tests that we are correctly
  216. # filtering results based on the vector clock portion.
  217. channel = make_request(
  218. self.reactor,
  219. sync_hs_site,
  220. "GET",
  221. "/rooms/{}/messages?from={}&to={}&dir=b".format(
  222. room_id1, prev_batch1, vector_clock_token
  223. ),
  224. access_token=access_token,
  225. )
  226. self.assertListEqual([], channel.json_body["chunk"])
  227. # Paginating back on the second room should produce the first event
  228. # again. This tests that pagination isn't completely broken.
  229. channel = make_request(
  230. self.reactor,
  231. sync_hs_site,
  232. "GET",
  233. "/rooms/{}/messages?from={}&to={}&dir=b".format(
  234. room_id2, prev_batch2, vector_clock_token
  235. ),
  236. access_token=access_token,
  237. )
  238. self.assertEqual(len(channel.json_body["chunk"]), 1)
  239. self.assertEqual(
  240. channel.json_body["chunk"][0]["event_id"], first_event_in_room2
  241. )
  242. # Paginating forwards should give the same results
  243. channel = make_request(
  244. self.reactor,
  245. sync_hs_site,
  246. "GET",
  247. "/rooms/{}/messages?from={}&to={}&dir=f".format(
  248. room_id1, vector_clock_token, prev_batch1
  249. ),
  250. access_token=access_token,
  251. )
  252. self.assertListEqual([], channel.json_body["chunk"])
  253. channel = make_request(
  254. self.reactor,
  255. sync_hs_site,
  256. "GET",
  257. "/rooms/{}/messages?from={}&to={}&dir=f".format(
  258. room_id2,
  259. vector_clock_token,
  260. prev_batch2,
  261. ),
  262. access_token=access_token,
  263. )
  264. self.assertEqual(len(channel.json_body["chunk"]), 1)
  265. self.assertEqual(
  266. channel.json_body["chunk"][0]["event_id"], first_event_in_room2
  267. )