1
0

test_sharded_event_persister.py 12 KB

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