test_sharded_event_persister.py 12 KB

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