You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

503 lines
19 KiB

  1. from typing import Callable, List, Optional, Tuple
  2. from unittest.mock import Mock
  3. from twisted.test.proto_helpers import MemoryReactor
  4. from synapse.api.constants import EventTypes
  5. from synapse.events import EventBase
  6. from synapse.federation.sender import (
  7. FederationSender,
  8. PerDestinationQueue,
  9. TransactionManager,
  10. )
  11. from synapse.federation.units import Edu, Transaction
  12. from synapse.rest import admin
  13. from synapse.rest.client import login, room
  14. from synapse.server import HomeServer
  15. from synapse.types import JsonDict
  16. from synapse.util import Clock
  17. from synapse.util.retryutils import NotRetryingDestination
  18. from tests.test_utils import event_injection, make_awaitable
  19. from tests.unittest import FederatingHomeserverTestCase
  20. class FederationCatchUpTestCases(FederatingHomeserverTestCase):
  21. """
  22. Tests cases of catching up over federation.
  23. By default for test cases federation sending is disabled. This Test class has it
  24. re-enabled for the main process.
  25. """
  26. servlets = [
  27. admin.register_servlets,
  28. room.register_servlets,
  29. login.register_servlets,
  30. ]
  31. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  32. self.federation_transport_client = Mock(spec=["send_transaction"])
  33. return self.setup_test_homeserver(
  34. federation_transport_client=self.federation_transport_client,
  35. )
  36. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  37. # stub out get_current_hosts_in_room
  38. state_storage_controller = hs.get_storage_controllers().state
  39. # This mock is crucial for destination_rooms to be populated.
  40. # TODO: this seems to no longer be the case---tests pass with this mock
  41. # commented out.
  42. state_storage_controller.get_current_hosts_in_room = Mock( # type: ignore[assignment]
  43. return_value=make_awaitable({"test", "host2"})
  44. )
  45. # whenever send_transaction is called, record the pdu data
  46. self.pdus: List[JsonDict] = []
  47. self.failed_pdus: List[JsonDict] = []
  48. self.is_online = True
  49. self.federation_transport_client.send_transaction.side_effect = (
  50. self.record_transaction
  51. )
  52. federation_sender = hs.get_federation_sender()
  53. assert isinstance(federation_sender, FederationSender)
  54. self.federation_sender = federation_sender
  55. def default_config(self) -> JsonDict:
  56. config = super().default_config()
  57. config["federation_sender_instances"] = None
  58. return config
  59. async def record_transaction(
  60. self, txn: Transaction, json_cb: Optional[Callable[[], JsonDict]]
  61. ) -> JsonDict:
  62. if json_cb is None:
  63. # The tests seem to expect that this method raises in this situation.
  64. raise Exception("Blank json_cb")
  65. elif self.is_online:
  66. data = json_cb()
  67. self.pdus.extend(data["pdus"])
  68. return {}
  69. else:
  70. data = json_cb()
  71. self.failed_pdus.extend(data["pdus"])
  72. raise NotRetryingDestination(0, 24 * 60 * 60 * 1000, txn.destination)
  73. def get_destination_room(self, room: str, destination: str = "host2") -> dict:
  74. """
  75. Gets the destination_rooms entry for a (destination, room_id) pair.
  76. Args:
  77. room: room ID
  78. destination: what destination, default is "host2"
  79. Returns:
  80. Dictionary of { event_id: str, stream_ordering: int }
  81. """
  82. event_id, stream_ordering = self.get_success(
  83. self.hs.get_datastores().main.db_pool.execute(
  84. "test:get_destination_rooms",
  85. None,
  86. """
  87. SELECT event_id, stream_ordering
  88. FROM destination_rooms dr
  89. JOIN events USING (stream_ordering)
  90. WHERE dr.destination = ? AND dr.room_id = ?
  91. """,
  92. destination,
  93. room,
  94. )
  95. )[0]
  96. return {"event_id": event_id, "stream_ordering": stream_ordering}
  97. def test_catch_up_destination_rooms_tracking(self) -> None:
  98. """
  99. Tests that we populate the `destination_rooms` table as needed.
  100. """
  101. self.register_user("u1", "you the one")
  102. u1_token = self.login("u1", "you the one")
  103. room = self.helper.create_room_as("u1", tok=u1_token)
  104. self.get_success(
  105. event_injection.inject_member_event(self.hs, room, "@user:host2", "join")
  106. )
  107. event_id_1 = self.helper.send(room, "wombats!", tok=u1_token)["event_id"]
  108. row_1 = self.get_destination_room(room)
  109. event_id_2 = self.helper.send(room, "rabbits!", tok=u1_token)["event_id"]
  110. row_2 = self.get_destination_room(room)
  111. # check: events correctly registered in order
  112. self.assertEqual(row_1["event_id"], event_id_1)
  113. self.assertEqual(row_2["event_id"], event_id_2)
  114. self.assertEqual(row_1["stream_ordering"], row_2["stream_ordering"] - 1)
  115. def test_catch_up_last_successful_stream_ordering_tracking(self) -> None:
  116. """
  117. Tests that we populate the `destination_rooms` table as needed.
  118. """
  119. self.register_user("u1", "you the one")
  120. u1_token = self.login("u1", "you the one")
  121. room = self.helper.create_room_as("u1", tok=u1_token)
  122. # take the remote offline
  123. self.is_online = False
  124. self.get_success(
  125. event_injection.inject_member_event(self.hs, room, "@user:host2", "join")
  126. )
  127. self.helper.send(room, "wombats!", tok=u1_token)
  128. self.pump()
  129. lsso_1 = self.get_success(
  130. self.hs.get_datastores().main.get_destination_last_successful_stream_ordering(
  131. "host2"
  132. )
  133. )
  134. self.assertIsNone(
  135. lsso_1,
  136. "There should be no last successful stream ordering for an always-offline destination",
  137. )
  138. # bring the remote online
  139. self.is_online = True
  140. event_id_2 = self.helper.send(room, "rabbits!", tok=u1_token)["event_id"]
  141. lsso_2 = self.get_success(
  142. self.hs.get_datastores().main.get_destination_last_successful_stream_ordering(
  143. "host2"
  144. )
  145. )
  146. row_2 = self.get_destination_room(room)
  147. self.assertEqual(
  148. self.pdus[0]["content"]["body"],
  149. "rabbits!",
  150. "Test fault: didn't receive the right PDU",
  151. )
  152. self.assertEqual(
  153. row_2["event_id"],
  154. event_id_2,
  155. "Test fault: destination_rooms not updated correctly",
  156. )
  157. self.assertEqual(
  158. lsso_2,
  159. row_2["stream_ordering"],
  160. "Send succeeded but not marked as last_successful_stream_ordering",
  161. )
  162. def test_catch_up_from_blank_state(self) -> None:
  163. """
  164. Runs an overall test of federation catch-up from scratch.
  165. Further tests will focus on more narrow aspects and edge-cases, but I
  166. hope to provide an overall view with this test.
  167. """
  168. # bring the other server online
  169. self.is_online = True
  170. # let's make some events for the other server to receive
  171. self.register_user("u1", "you the one")
  172. u1_token = self.login("u1", "you the one")
  173. room_1 = self.helper.create_room_as("u1", tok=u1_token)
  174. room_2 = self.helper.create_room_as("u1", tok=u1_token)
  175. # also critical to federate
  176. self.get_success(
  177. event_injection.inject_member_event(self.hs, room_1, "@user:host2", "join")
  178. )
  179. self.get_success(
  180. event_injection.inject_member_event(self.hs, room_2, "@user:host2", "join")
  181. )
  182. self.helper.send_state(
  183. room_1, event_type="m.room.topic", body={"topic": "wombat"}, tok=u1_token
  184. )
  185. # check: PDU received for topic event
  186. self.assertEqual(len(self.pdus), 1)
  187. self.assertEqual(self.pdus[0]["type"], "m.room.topic")
  188. # take the remote offline
  189. self.is_online = False
  190. # send another event
  191. self.helper.send(room_1, "hi user!", tok=u1_token)
  192. # check: things didn't go well since the remote is down
  193. self.assertEqual(len(self.failed_pdus), 1)
  194. self.assertEqual(self.failed_pdus[0]["content"]["body"], "hi user!")
  195. # let's delete the federation transmission queue
  196. # (this pretends we are starting up fresh.)
  197. self.assertFalse(
  198. self.federation_sender._per_destination_queues[
  199. "host2"
  200. ].transmission_loop_running
  201. )
  202. del self.federation_sender._per_destination_queues["host2"]
  203. # let's also clear any backoffs
  204. self.get_success(
  205. self.hs.get_datastores().main.set_destination_retry_timings(
  206. "host2", None, 0, 0
  207. )
  208. )
  209. # bring the remote online and clear the received pdu list
  210. self.is_online = True
  211. self.pdus = []
  212. # now we need to initiate a federation transaction somehow…
  213. # to do that, let's send another event (because it's simple to do)
  214. # (do it to another room otherwise the catch-up logic decides it doesn't
  215. # need to catch up room_1 — something I overlooked when first writing
  216. # this test)
  217. self.helper.send(room_2, "wombats!", tok=u1_token)
  218. # we should now have received both PDUs
  219. self.assertEqual(len(self.pdus), 2)
  220. self.assertEqual(self.pdus[0]["content"]["body"], "hi user!")
  221. self.assertEqual(self.pdus[1]["content"]["body"], "wombats!")
  222. def make_fake_destination_queue(
  223. self, destination: str = "host2"
  224. ) -> Tuple[PerDestinationQueue, List[EventBase]]:
  225. """
  226. Makes a fake per-destination queue.
  227. """
  228. transaction_manager = TransactionManager(self.hs)
  229. per_dest_queue = PerDestinationQueue(self.hs, transaction_manager, destination)
  230. results_list = []
  231. async def fake_send(
  232. destination_tm: str,
  233. pending_pdus: List[EventBase],
  234. _pending_edus: List[Edu],
  235. ) -> None:
  236. assert destination == destination_tm
  237. results_list.extend(pending_pdus)
  238. transaction_manager.send_new_transaction = fake_send # type: ignore[assignment]
  239. return per_dest_queue, results_list
  240. def test_catch_up_loop(self) -> None:
  241. """
  242. Tests the behaviour of _catch_up_transmission_loop.
  243. """
  244. # ARRANGE:
  245. # - a local user (u1)
  246. # - 3 rooms which u1 is joined to (and remote user @user:host2 is
  247. # joined to)
  248. # - some events (1 to 5) in those rooms
  249. # we have 'already sent' events 1 and 2 to host2
  250. per_dest_queue, sent_pdus = self.make_fake_destination_queue()
  251. self.register_user("u1", "you the one")
  252. u1_token = self.login("u1", "you the one")
  253. room_1 = self.helper.create_room_as("u1", tok=u1_token)
  254. room_2 = self.helper.create_room_as("u1", tok=u1_token)
  255. room_3 = self.helper.create_room_as("u1", tok=u1_token)
  256. self.get_success(
  257. event_injection.inject_member_event(self.hs, room_1, "@user:host2", "join")
  258. )
  259. self.get_success(
  260. event_injection.inject_member_event(self.hs, room_2, "@user:host2", "join")
  261. )
  262. self.get_success(
  263. event_injection.inject_member_event(self.hs, room_3, "@user:host2", "join")
  264. )
  265. # create some events
  266. self.helper.send(room_1, "you hear me!!", tok=u1_token)
  267. event_id_2 = self.helper.send(room_2, "wombats!", tok=u1_token)["event_id"]
  268. self.helper.send(room_3, "Matrix!", tok=u1_token)
  269. event_id_4 = self.helper.send(room_2, "rabbits!", tok=u1_token)["event_id"]
  270. event_id_5 = self.helper.send(room_3, "Synapse!", tok=u1_token)["event_id"]
  271. # destination_rooms should already be populated, but let us pretend that we already
  272. # sent (successfully) up to and including event id 2
  273. event_2 = self.get_success(self.hs.get_datastores().main.get_event(event_id_2))
  274. # also fetch event 5 so we know its last_successful_stream_ordering later
  275. event_5 = self.get_success(self.hs.get_datastores().main.get_event(event_id_5))
  276. assert event_2.internal_metadata.stream_ordering is not None
  277. self.get_success(
  278. self.hs.get_datastores().main.set_destination_last_successful_stream_ordering(
  279. "host2", event_2.internal_metadata.stream_ordering
  280. )
  281. )
  282. # ACT
  283. self.get_success(per_dest_queue._catch_up_transmission_loop())
  284. # ASSERT, noticing in particular:
  285. # - event 3 not sent out, because event 5 replaces it
  286. # - order is least recent first, so event 5 comes after event 4
  287. # - catch-up is completed
  288. self.assertEqual(len(sent_pdus), 2)
  289. self.assertEqual(sent_pdus[0].event_id, event_id_4)
  290. self.assertEqual(sent_pdus[1].event_id, event_id_5)
  291. self.assertFalse(per_dest_queue._catching_up)
  292. self.assertEqual(
  293. per_dest_queue._last_successful_stream_ordering,
  294. event_5.internal_metadata.stream_ordering,
  295. )
  296. def test_catch_up_on_synapse_startup(self) -> None:
  297. """
  298. Tests the behaviour of get_catch_up_outstanding_destinations and
  299. _wake_destinations_needing_catchup.
  300. """
  301. # list of sorted server names (note that there are more servers than the batch
  302. # size used in get_catch_up_outstanding_destinations).
  303. server_names = ["server%02d" % number for number in range(42)] + ["zzzerver"]
  304. # ARRANGE:
  305. # - a local user (u1)
  306. # - a room which u1 is joined to (and remote users @user:serverXX are
  307. # joined to)
  308. # mark the remotes as online
  309. self.is_online = True
  310. self.register_user("u1", "you the one")
  311. u1_token = self.login("u1", "you the one")
  312. room_id = self.helper.create_room_as("u1", tok=u1_token)
  313. for server_name in server_names:
  314. self.get_success(
  315. event_injection.inject_member_event(
  316. self.hs, room_id, "@user:%s" % server_name, "join"
  317. )
  318. )
  319. # create an event
  320. self.helper.send(room_id, "deary me!", tok=u1_token)
  321. # ASSERT:
  322. # - All servers are up to date so none should have outstanding catch-up
  323. outstanding_when_successful = self.get_success(
  324. self.hs.get_datastores().main.get_catch_up_outstanding_destinations(None)
  325. )
  326. self.assertEqual(outstanding_when_successful, [])
  327. # ACT:
  328. # - Make the remote servers unreachable
  329. self.is_online = False
  330. # - Mark zzzerver as being backed-off from
  331. now = self.clock.time_msec()
  332. self.get_success(
  333. self.hs.get_datastores().main.set_destination_retry_timings(
  334. "zzzerver", now, now, 24 * 60 * 60 * 1000 # retry in 1 day
  335. )
  336. )
  337. # - Send an event
  338. self.helper.send(room_id, "can anyone hear me?", tok=u1_token)
  339. # ASSERT (get_catch_up_outstanding_destinations):
  340. # - all remotes are outstanding
  341. # - they are returned in batches of 25, in order
  342. outstanding_1 = self.get_success(
  343. self.hs.get_datastores().main.get_catch_up_outstanding_destinations(None)
  344. )
  345. self.assertEqual(len(outstanding_1), 25)
  346. self.assertEqual(outstanding_1, server_names[0:25])
  347. outstanding_2 = self.get_success(
  348. self.hs.get_datastores().main.get_catch_up_outstanding_destinations(
  349. outstanding_1[-1]
  350. )
  351. )
  352. self.assertNotIn("zzzerver", outstanding_2)
  353. self.assertEqual(len(outstanding_2), 17)
  354. self.assertEqual(outstanding_2, server_names[25:-1])
  355. # ACT: call _wake_destinations_needing_catchup
  356. # patch wake_destination to just count the destinations instead
  357. woken = []
  358. def wake_destination_track(destination: str) -> None:
  359. woken.append(destination)
  360. self.federation_sender.wake_destination = wake_destination_track # type: ignore[assignment]
  361. # cancel the pre-existing timer for _wake_destinations_needing_catchup
  362. # this is because we are calling it manually rather than waiting for it
  363. # to be called automatically
  364. assert self.federation_sender._catchup_after_startup_timer is not None
  365. self.federation_sender._catchup_after_startup_timer.cancel()
  366. self.get_success(
  367. self.federation_sender._wake_destinations_needing_catchup(), by=5.0
  368. )
  369. # ASSERT (_wake_destinations_needing_catchup):
  370. # - all remotes are woken up, save for zzzerver
  371. self.assertNotIn("zzzerver", woken)
  372. # - all destinations are woken exactly once; they appear once in woken.
  373. self.assertCountEqual(woken, server_names[:-1])
  374. def test_not_latest_event(self) -> None:
  375. """Test that we send the latest event in the room even if its not ours."""
  376. per_dest_queue, sent_pdus = self.make_fake_destination_queue()
  377. # Make a room with a local user, and two servers. One will go offline
  378. # and one will send some events.
  379. self.register_user("u1", "you the one")
  380. u1_token = self.login("u1", "you the one")
  381. room_1 = self.helper.create_room_as("u1", tok=u1_token)
  382. self.get_success(
  383. event_injection.inject_member_event(self.hs, room_1, "@user:host2", "join")
  384. )
  385. event_1 = self.get_success(
  386. event_injection.inject_member_event(self.hs, room_1, "@user:host3", "join")
  387. )
  388. # First we send something from the local server, so that we notice the
  389. # remote is down and go into catchup mode.
  390. self.helper.send(room_1, "you hear me!!", tok=u1_token)
  391. # Now simulate us receiving an event from the still online remote.
  392. event_2 = self.get_success(
  393. event_injection.inject_event(
  394. self.hs,
  395. type=EventTypes.Message,
  396. sender="@user:host3",
  397. room_id=room_1,
  398. content={"msgtype": "m.text", "body": "Hello"},
  399. )
  400. )
  401. assert event_1.internal_metadata.stream_ordering is not None
  402. self.get_success(
  403. self.hs.get_datastores().main.set_destination_last_successful_stream_ordering(
  404. "host2", event_1.internal_metadata.stream_ordering
  405. )
  406. )
  407. self.get_success(per_dest_queue._catch_up_transmission_loop())
  408. # We expect only the last message from the remote, event_2, to have been
  409. # sent, rather than the last *local* event that was sent.
  410. self.assertEqual(len(sent_pdus), 1)
  411. self.assertEqual(sent_pdus[0].event_id, event_2.event_id)
  412. self.assertFalse(per_dest_queue._catching_up)