test_sharded_event_persister.py 12 KB

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