client.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. # Copyright 2017 Vector Creations Ltd
  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. """A replication client for use by synapse workers.
  15. """
  16. import logging
  17. from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Set, Tuple
  18. from twisted.internet import defer
  19. from twisted.internet.defer import Deferred
  20. from twisted.internet.interfaces import IAddress, IConnector
  21. from twisted.internet.protocol import ReconnectingClientFactory
  22. from twisted.python.failure import Failure
  23. from synapse.api.constants import EventTypes, Membership, ReceiptTypes
  24. from synapse.federation import send_queue
  25. from synapse.federation.sender import FederationSender
  26. from synapse.logging.context import PreserveLoggingContext, make_deferred_yieldable
  27. from synapse.metrics.background_process_metrics import run_as_background_process
  28. from synapse.replication.tcp.protocol import ClientReplicationStreamProtocol
  29. from synapse.replication.tcp.streams import (
  30. AccountDataStream,
  31. DeviceListsStream,
  32. PushersStream,
  33. PushRulesStream,
  34. ReceiptsStream,
  35. ToDeviceStream,
  36. TypingStream,
  37. UnPartialStatedEventStream,
  38. UnPartialStatedRoomStream,
  39. )
  40. from synapse.replication.tcp.streams.events import (
  41. EventsStream,
  42. EventsStreamEventRow,
  43. EventsStreamRow,
  44. )
  45. from synapse.replication.tcp.streams.partial_state import (
  46. UnPartialStatedEventStreamRow,
  47. UnPartialStatedRoomStreamRow,
  48. )
  49. from synapse.types import PersistedEventPosition, ReadReceipt, StreamKeyType, UserID
  50. from synapse.util.async_helpers import Linearizer, timeout_deferred
  51. from synapse.util.metrics import Measure
  52. if TYPE_CHECKING:
  53. from synapse.replication.tcp.handler import ReplicationCommandHandler
  54. from synapse.server import HomeServer
  55. logger = logging.getLogger(__name__)
  56. # How long we allow callers to wait for replication updates before timing out.
  57. _WAIT_FOR_REPLICATION_TIMEOUT_SECONDS = 30
  58. class DirectTcpReplicationClientFactory(ReconnectingClientFactory):
  59. """Factory for building connections to the master. Will reconnect if the
  60. connection is lost.
  61. Accepts a handler that is passed to `ClientReplicationStreamProtocol`.
  62. """
  63. initialDelay = 0.1
  64. maxDelay = 1 # Try at least once every N seconds
  65. def __init__(
  66. self,
  67. hs: "HomeServer",
  68. client_name: str,
  69. command_handler: "ReplicationCommandHandler",
  70. ):
  71. self.client_name = client_name
  72. self.command_handler = command_handler
  73. self.server_name = hs.config.server.server_name
  74. self.hs = hs
  75. self._clock = hs.get_clock() # As self.clock is defined in super class
  76. hs.get_reactor().addSystemEventTrigger("before", "shutdown", self.stopTrying)
  77. def startedConnecting(self, connector: IConnector) -> None:
  78. logger.info("Connecting to replication: %r", connector.getDestination())
  79. def buildProtocol(self, addr: IAddress) -> ClientReplicationStreamProtocol:
  80. logger.info("Connected to replication: %r", addr)
  81. return ClientReplicationStreamProtocol(
  82. self.hs,
  83. self.client_name,
  84. self.server_name,
  85. self._clock,
  86. self.command_handler,
  87. )
  88. def clientConnectionLost(self, connector: IConnector, reason: Failure) -> None:
  89. logger.error("Lost replication conn: %r", reason)
  90. ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
  91. def clientConnectionFailed(self, connector: IConnector, reason: Failure) -> None:
  92. logger.error("Failed to connect to replication: %r", reason)
  93. ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
  94. class ReplicationDataHandler:
  95. """Handles incoming stream updates from replication.
  96. This instance notifies the slave data store about updates. Can be subclassed
  97. to handle updates in additional ways.
  98. """
  99. def __init__(self, hs: "HomeServer"):
  100. self.store = hs.get_datastores().main
  101. self.notifier = hs.get_notifier()
  102. self._reactor = hs.get_reactor()
  103. self._clock = hs.get_clock()
  104. self._streams = hs.get_replication_streams()
  105. self._instance_name = hs.get_instance_name()
  106. self._typing_handler = hs.get_typing_handler()
  107. self._state_storage_controller = hs.get_storage_controllers().state
  108. self._notify_pushers = hs.config.worker.start_pushers
  109. self._pusher_pool = hs.get_pusherpool()
  110. self._presence_handler = hs.get_presence_handler()
  111. self.send_handler: Optional[FederationSenderHandler] = None
  112. if hs.should_send_federation():
  113. self.send_handler = FederationSenderHandler(hs)
  114. # Map from stream to list of deferreds waiting for the stream to
  115. # arrive at a particular position. The lists are sorted by stream position.
  116. self._streams_to_waiters: Dict[str, List[Tuple[int, Deferred]]] = {}
  117. async def on_rdata(
  118. self, stream_name: str, instance_name: str, token: int, rows: list
  119. ) -> None:
  120. """Called to handle a batch of replication data with a given stream token.
  121. By default this just pokes the slave store. Can be overridden in subclasses to
  122. handle more.
  123. Args:
  124. stream_name: name of the replication stream for this batch of rows
  125. instance_name: the instance that wrote the rows.
  126. token: stream token for this batch of rows
  127. rows: a list of Stream.ROW_TYPE objects as returned by Stream.parse_row.
  128. """
  129. self.store.process_replication_rows(stream_name, instance_name, token, rows)
  130. # NOTE: this must be called after process_replication_rows to ensure any
  131. # cache invalidations are first handled before any stream ID advances.
  132. self.store.process_replication_position(stream_name, instance_name, token)
  133. if self.send_handler:
  134. await self.send_handler.process_replication_rows(stream_name, token, rows)
  135. if stream_name == TypingStream.NAME:
  136. self._typing_handler.process_replication_rows(token, rows)
  137. self.notifier.on_new_event(
  138. StreamKeyType.TYPING, token, rooms=[row.room_id for row in rows]
  139. )
  140. elif stream_name == PushRulesStream.NAME:
  141. self.notifier.on_new_event(
  142. StreamKeyType.PUSH_RULES, token, users=[row.user_id for row in rows]
  143. )
  144. elif stream_name in AccountDataStream.NAME:
  145. self.notifier.on_new_event(
  146. StreamKeyType.ACCOUNT_DATA, token, users=[row.user_id for row in rows]
  147. )
  148. elif stream_name == ReceiptsStream.NAME:
  149. self.notifier.on_new_event(
  150. StreamKeyType.RECEIPT, token, rooms=[row.room_id for row in rows]
  151. )
  152. await self._pusher_pool.on_new_receipts(
  153. token, token, {row.room_id for row in rows}
  154. )
  155. elif stream_name == ToDeviceStream.NAME:
  156. entities = [row.entity for row in rows if row.entity.startswith("@")]
  157. if entities:
  158. self.notifier.on_new_event(
  159. StreamKeyType.TO_DEVICE, token, users=entities
  160. )
  161. elif stream_name == DeviceListsStream.NAME:
  162. all_room_ids: Set[str] = set()
  163. for row in rows:
  164. if row.entity.startswith("@") and not row.is_signature:
  165. room_ids = await self.store.get_rooms_for_user(row.entity)
  166. all_room_ids.update(room_ids)
  167. self.notifier.on_new_event(
  168. StreamKeyType.DEVICE_LIST, token, rooms=all_room_ids
  169. )
  170. elif stream_name == PushersStream.NAME:
  171. for row in rows:
  172. if row.deleted:
  173. self.stop_pusher(row.user_id, row.app_id, row.pushkey)
  174. else:
  175. await self.process_pusher_change(
  176. row.user_id, row.app_id, row.pushkey
  177. )
  178. elif stream_name == EventsStream.NAME:
  179. # We shouldn't get multiple rows per token for events stream, so
  180. # we don't need to optimise this for multiple rows.
  181. for row in rows:
  182. if row.type != EventsStreamEventRow.TypeId:
  183. continue
  184. assert isinstance(row, EventsStreamRow)
  185. assert isinstance(row.data, EventsStreamEventRow)
  186. if row.data.rejected:
  187. continue
  188. extra_users: Tuple[UserID, ...] = ()
  189. if row.data.type == EventTypes.Member and row.data.state_key:
  190. extra_users = (UserID.from_string(row.data.state_key),)
  191. max_token = self.store.get_room_max_token()
  192. event_pos = PersistedEventPosition(instance_name, token)
  193. event_entry = self.notifier.create_pending_room_event_entry(
  194. event_pos,
  195. extra_users,
  196. row.data.room_id,
  197. row.data.type,
  198. row.data.state_key,
  199. row.data.membership,
  200. )
  201. await self.notifier.notify_new_room_events(
  202. [(event_entry, row.data.event_id)], max_token
  203. )
  204. # If this event is a join, make a note of it so we have an accurate
  205. # cross-worker room rate limit.
  206. # TODO: Erik said we should exclude rows that came from ex_outliers
  207. # here, but I don't see how we can determine that. I guess we could
  208. # add a flag to row.data?
  209. if (
  210. row.data.type == EventTypes.Member
  211. and row.data.membership == Membership.JOIN
  212. and not row.data.outlier
  213. ):
  214. # TODO retrieve the previous state, and exclude join -> join transitions
  215. self.notifier.notify_user_joined_room(
  216. row.data.event_id, row.data.room_id
  217. )
  218. elif stream_name == UnPartialStatedRoomStream.NAME:
  219. for row in rows:
  220. assert isinstance(row, UnPartialStatedRoomStreamRow)
  221. # Wake up any tasks waiting for the room to be un-partial-stated.
  222. self._state_storage_controller.notify_room_un_partial_stated(
  223. row.room_id
  224. )
  225. elif stream_name == UnPartialStatedEventStream.NAME:
  226. for row in rows:
  227. assert isinstance(row, UnPartialStatedEventStreamRow)
  228. # Wake up any tasks waiting for the event to be un-partial-stated.
  229. self._state_storage_controller.notify_event_un_partial_stated(
  230. row.event_id
  231. )
  232. await self._presence_handler.process_replication_rows(
  233. stream_name, instance_name, token, rows
  234. )
  235. # Notify any waiting deferreds. The list is ordered by position so we
  236. # just iterate through the list until we reach a position that is
  237. # greater than the received row position.
  238. waiting_list = self._streams_to_waiters.get(stream_name, [])
  239. # Index of first item with a position after the current token, i.e we
  240. # have called all deferreds before this index. If not overwritten by
  241. # loop below means either a) no items in list so no-op or b) all items
  242. # in list were called and so the list should be cleared. Setting it to
  243. # `len(list)` works for both cases.
  244. index_of_first_deferred_not_called = len(waiting_list)
  245. for idx, (position, deferred) in enumerate(waiting_list):
  246. if position <= token:
  247. try:
  248. with PreserveLoggingContext():
  249. deferred.callback(None)
  250. except Exception:
  251. # The deferred has been cancelled or timed out.
  252. pass
  253. else:
  254. # The list is sorted by position so we don't need to continue
  255. # checking any further entries in the list.
  256. index_of_first_deferred_not_called = idx
  257. break
  258. # Drop all entries in the waiting list that were called in the above
  259. # loop. (This maintains the order so no need to resort)
  260. waiting_list[:] = waiting_list[index_of_first_deferred_not_called:]
  261. async def on_position(
  262. self, stream_name: str, instance_name: str, token: int
  263. ) -> None:
  264. await self.on_rdata(stream_name, instance_name, token, [])
  265. # We poke the generic "replication" notifier to wake anything up that
  266. # may be streaming.
  267. self.notifier.notify_replication()
  268. def on_remote_server_up(self, server: str) -> None:
  269. """Called when get a new REMOTE_SERVER_UP command."""
  270. # Let's wake up the transaction queue for the server in case we have
  271. # pending stuff to send to it.
  272. if self.send_handler:
  273. self.send_handler.wake_destination(server)
  274. async def wait_for_stream_position(
  275. self,
  276. instance_name: str,
  277. stream_name: str,
  278. position: int,
  279. raise_on_timeout: bool = True,
  280. ) -> None:
  281. """Wait until this instance has received updates up to and including
  282. the given stream position.
  283. Args:
  284. instance_name
  285. stream_name
  286. position
  287. raise_on_timeout: Whether to raise an exception if we time out
  288. waiting for the updates, or if we log an error and return.
  289. """
  290. if instance_name == self._instance_name:
  291. # We don't get told about updates written by this process, and
  292. # anyway in that case we don't need to wait.
  293. return
  294. current_position = self._streams[stream_name].current_token(instance_name)
  295. if position <= current_position:
  296. # We're already past the position
  297. return
  298. # Create a new deferred that times out after N seconds, as we don't want
  299. # to wedge here forever.
  300. deferred: "Deferred[None]" = Deferred()
  301. deferred = timeout_deferred(
  302. deferred, _WAIT_FOR_REPLICATION_TIMEOUT_SECONDS, self._reactor
  303. )
  304. waiting_list = self._streams_to_waiters.setdefault(stream_name, [])
  305. waiting_list.append((position, deferred))
  306. waiting_list.sort(key=lambda t: t[0])
  307. # We measure here to get in flight counts and average waiting time.
  308. with Measure(self._clock, "repl.wait_for_stream_position"):
  309. logger.info("Waiting for repl stream %r to reach %s", stream_name, position)
  310. try:
  311. await make_deferred_yieldable(deferred)
  312. except defer.TimeoutError:
  313. logger.error("Timed out waiting for stream %s", stream_name)
  314. if raise_on_timeout:
  315. raise
  316. return
  317. logger.info(
  318. "Finished waiting for repl stream %r to reach %s", stream_name, position
  319. )
  320. def stop_pusher(self, user_id: str, app_id: str, pushkey: str) -> None:
  321. if not self._notify_pushers:
  322. return
  323. key = "%s:%s" % (app_id, pushkey)
  324. pushers_for_user = self._pusher_pool.pushers.get(user_id, {})
  325. pusher = pushers_for_user.pop(key, None)
  326. if pusher is None:
  327. return
  328. logger.info("Stopping pusher %r / %r", user_id, key)
  329. pusher.on_stop()
  330. async def process_pusher_change(
  331. self, user_id: str, app_id: str, pushkey: str
  332. ) -> None:
  333. if not self._notify_pushers:
  334. return
  335. key = "%s:%s" % (app_id, pushkey)
  336. logger.info("Starting pusher %r / %r", user_id, key)
  337. await self._pusher_pool.process_pusher_change_by_id(app_id, pushkey, user_id)
  338. class FederationSenderHandler:
  339. """Processes the fedration replication stream
  340. This class is only instantiate on the worker responsible for sending outbound
  341. federation transactions. It receives rows from the replication stream and forwards
  342. the appropriate entries to the FederationSender class.
  343. """
  344. def __init__(self, hs: "HomeServer"):
  345. assert hs.should_send_federation()
  346. self.store = hs.get_datastores().main
  347. self._is_mine_id = hs.is_mine_id
  348. self._hs = hs
  349. # We need to make a temporary value to ensure that mypy picks up the
  350. # right type. We know we should have a federation sender instance since
  351. # `should_send_federation` is True.
  352. sender = hs.get_federation_sender()
  353. assert isinstance(sender, FederationSender)
  354. self.federation_sender = sender
  355. # Stores the latest position in the federation stream we've gotten up
  356. # to. This is always set before we use it.
  357. self.federation_position: Optional[int] = None
  358. self._fed_position_linearizer = Linearizer(name="_fed_position_linearizer")
  359. def wake_destination(self, server: str) -> None:
  360. self.federation_sender.wake_destination(server)
  361. async def process_replication_rows(
  362. self, stream_name: str, token: int, rows: list
  363. ) -> None:
  364. # The federation stream contains things that we want to send out, e.g.
  365. # presence, typing, etc.
  366. if stream_name == "federation":
  367. send_queue.process_rows_for_federation(self.federation_sender, rows)
  368. await self.update_token(token)
  369. # ... and when new receipts happen
  370. elif stream_name == ReceiptsStream.NAME:
  371. await self._on_new_receipts(rows)
  372. # ... as well as device updates and messages
  373. elif stream_name == DeviceListsStream.NAME:
  374. # The entities are either user IDs (starting with '@') whose devices
  375. # have changed, or remote servers that we need to tell about
  376. # changes.
  377. hosts = {
  378. row.entity
  379. for row in rows
  380. if not row.entity.startswith("@") and not row.is_signature
  381. }
  382. for host in hosts:
  383. self.federation_sender.send_device_messages(host, immediate=False)
  384. elif stream_name == ToDeviceStream.NAME:
  385. # The to_device stream includes stuff to be pushed to both local
  386. # clients and remote servers, so we ignore entities that start with
  387. # '@' (since they'll be local users rather than destinations).
  388. hosts = {row.entity for row in rows if not row.entity.startswith("@")}
  389. for host in hosts:
  390. self.federation_sender.send_device_messages(host)
  391. async def _on_new_receipts(
  392. self, rows: Iterable[ReceiptsStream.ReceiptsStreamRow]
  393. ) -> None:
  394. """
  395. Args:
  396. rows: new receipts to be processed
  397. """
  398. for receipt in rows:
  399. # we only want to send on receipts for our own users
  400. if not self._is_mine_id(receipt.user_id):
  401. continue
  402. # Private read receipts never get sent over federation.
  403. if receipt.receipt_type == ReceiptTypes.READ_PRIVATE:
  404. continue
  405. receipt_info = ReadReceipt(
  406. receipt.room_id,
  407. receipt.receipt_type,
  408. receipt.user_id,
  409. [receipt.event_id],
  410. thread_id=receipt.thread_id,
  411. data=receipt.data,
  412. )
  413. await self.federation_sender.send_read_receipt(receipt_info)
  414. async def update_token(self, token: int) -> None:
  415. """Update the record of where we have processed to in the federation stream.
  416. Called after we have processed a an update received over replication. Sends
  417. a FEDERATION_ACK back to the master, and stores the token that we have processed
  418. in `federation_stream_position` so that we can restart where we left off.
  419. """
  420. self.federation_position = token
  421. # We save and send the ACK to master asynchronously, so we don't block
  422. # processing on persistence. We don't need to do this operation for
  423. # every single RDATA we receive, we just need to do it periodically.
  424. if self._fed_position_linearizer.is_queued(None):
  425. # There is already a task queued up to save and send the token, so
  426. # no need to queue up another task.
  427. return
  428. run_as_background_process("_save_and_send_ack", self._save_and_send_ack)
  429. async def _save_and_send_ack(self) -> None:
  430. """Save the current federation position in the database and send an ACK
  431. to master with where we're up to.
  432. """
  433. # We should only be calling this once we've got a token.
  434. assert self.federation_position is not None
  435. try:
  436. # We linearize here to ensure we don't have races updating the token
  437. #
  438. # XXX this appears to be redundant, since the ReplicationCommandHandler
  439. # has a linearizer which ensures that we only process one line of
  440. # replication data at a time. Should we remove it, or is it doing useful
  441. # service for robustness? Or could we replace it with an assertion that
  442. # we're not being re-entered?
  443. async with self._fed_position_linearizer.queue(None):
  444. # We persist and ack the same position, so we take a copy of it
  445. # here as otherwise it can get modified from underneath us.
  446. current_position = self.federation_position
  447. await self.store.update_federation_out_pos(
  448. "federation", current_position
  449. )
  450. # We ACK this token over replication so that the master can drop
  451. # its in memory queues
  452. self._hs.get_replication_command_handler().send_federation_ack(
  453. current_position
  454. )
  455. except Exception:
  456. logger.exception("Error updating federation stream position")