test_federation_catch_up.py 22 KB

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