Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

512 řádky
21 KiB

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