test_sharded_event_persister.py 12 KB

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