client.py 21 KB

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