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.
 
 
 
 
 
 

509 lines
17 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2021 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """A federation sender that forwards things to be sent across replication to
  16. a worker process.
  17. It assumes there is a single worker process feeding off of it.
  18. Each row in the replication stream consists of a type and some json, where the
  19. types indicate whether they are presence, or edus, etc.
  20. Ephemeral or non-event data are queued up in-memory. When the worker requests
  21. updates since a particular point, all in-memory data since before that point is
  22. dropped. We also expire things in the queue after 5 minutes, to ensure that a
  23. dead worker doesn't cause the queues to grow limitlessly.
  24. Events are replicated via a separate events stream.
  25. """
  26. import logging
  27. from typing import (
  28. TYPE_CHECKING,
  29. Dict,
  30. Hashable,
  31. Iterable,
  32. List,
  33. Optional,
  34. Sized,
  35. Tuple,
  36. Type,
  37. )
  38. import attr
  39. from sortedcontainers import SortedDict
  40. from synapse.api.presence import UserPresenceState
  41. from synapse.federation.sender import AbstractFederationSender, FederationSender
  42. from synapse.metrics import LaterGauge
  43. from synapse.replication.tcp.streams.federation import FederationStream
  44. from synapse.types import JsonDict, ReadReceipt, RoomStreamToken
  45. from synapse.util.metrics import Measure
  46. from .units import Edu
  47. if TYPE_CHECKING:
  48. from synapse.server import HomeServer
  49. logger = logging.getLogger(__name__)
  50. class FederationRemoteSendQueue(AbstractFederationSender):
  51. """A drop in replacement for FederationSender"""
  52. def __init__(self, hs: "HomeServer"):
  53. self.server_name = hs.hostname
  54. self.clock = hs.get_clock()
  55. self.notifier = hs.get_notifier()
  56. self.is_mine_id = hs.is_mine_id
  57. # We may have multiple federation sender instances, so we need to track
  58. # their positions separately.
  59. self._sender_instances = hs.config.worker.federation_shard_config.instances
  60. self._sender_positions: Dict[str, int] = {}
  61. # Pending presence map user_id -> UserPresenceState
  62. self.presence_map: Dict[str, UserPresenceState] = {}
  63. # Stores the destinations we need to explicitly send presence to about a
  64. # given user.
  65. # Stream position -> (user_id, destinations)
  66. self.presence_destinations: SortedDict[
  67. int, Tuple[str, Iterable[str]]
  68. ] = SortedDict()
  69. # (destination, key) -> EDU
  70. self.keyed_edu: Dict[Tuple[str, tuple], Edu] = {}
  71. # stream position -> (destination, key)
  72. self.keyed_edu_changed: SortedDict[int, Tuple[str, tuple]] = SortedDict()
  73. self.edus: SortedDict[int, Edu] = SortedDict()
  74. # stream ID for the next entry into keyed_edu_changed/edus.
  75. self.pos = 1
  76. # map from stream ID to the time that stream entry was generated, so that we
  77. # can clear out entries after a while
  78. self.pos_time: SortedDict[int, int] = SortedDict()
  79. # EVERYTHING IS SAD. In particular, python only makes new scopes when
  80. # we make a new function, so we need to make a new function so the inner
  81. # lambda binds to the queue rather than to the name of the queue which
  82. # changes. ARGH.
  83. def register(name: str, queue: Sized) -> None:
  84. LaterGauge(
  85. "synapse_federation_send_queue_%s_size" % (queue_name,),
  86. "",
  87. [],
  88. lambda: len(queue),
  89. )
  90. for queue_name in [
  91. "presence_map",
  92. "keyed_edu",
  93. "keyed_edu_changed",
  94. "edus",
  95. "pos_time",
  96. "presence_destinations",
  97. ]:
  98. register(queue_name, getattr(self, queue_name))
  99. self.clock.looping_call(self._clear_queue, 30 * 1000)
  100. def _next_pos(self) -> int:
  101. pos = self.pos
  102. self.pos += 1
  103. self.pos_time[self.clock.time_msec()] = pos
  104. return pos
  105. def _clear_queue(self) -> None:
  106. """Clear the queues for anything older than N minutes"""
  107. FIVE_MINUTES_AGO = 5 * 60 * 1000
  108. now = self.clock.time_msec()
  109. keys = self.pos_time.keys()
  110. time = self.pos_time.bisect_left(now - FIVE_MINUTES_AGO)
  111. if not keys[:time]:
  112. return
  113. position_to_delete = max(keys[:time])
  114. for key in keys[:time]:
  115. del self.pos_time[key]
  116. self._clear_queue_before_pos(position_to_delete)
  117. def _clear_queue_before_pos(self, position_to_delete: int) -> None:
  118. """Clear all the queues from before a given position"""
  119. with Measure(self.clock, "send_queue._clear"):
  120. # Delete things out of presence maps
  121. keys = self.presence_destinations.keys()
  122. i = self.presence_destinations.bisect_left(position_to_delete)
  123. for key in keys[:i]:
  124. del self.presence_destinations[key]
  125. user_ids = {user_id for user_id, _ in self.presence_destinations.values()}
  126. to_del = [
  127. user_id for user_id in self.presence_map if user_id not in user_ids
  128. ]
  129. for user_id in to_del:
  130. del self.presence_map[user_id]
  131. # Delete things out of keyed edus
  132. keys = self.keyed_edu_changed.keys()
  133. i = self.keyed_edu_changed.bisect_left(position_to_delete)
  134. for key in keys[:i]:
  135. del self.keyed_edu_changed[key]
  136. live_keys = set()
  137. for edu_key in self.keyed_edu_changed.values():
  138. live_keys.add(edu_key)
  139. keys_to_del = [
  140. edu_key for edu_key in self.keyed_edu if edu_key not in live_keys
  141. ]
  142. for edu_key in keys_to_del:
  143. del self.keyed_edu[edu_key]
  144. # Delete things out of edu map
  145. keys = self.edus.keys()
  146. i = self.edus.bisect_left(position_to_delete)
  147. for key in keys[:i]:
  148. del self.edus[key]
  149. def notify_new_events(self, max_token: RoomStreamToken) -> None:
  150. """As per FederationSender"""
  151. # This should never get called.
  152. raise NotImplementedError()
  153. def build_and_send_edu(
  154. self,
  155. destination: str,
  156. edu_type: str,
  157. content: JsonDict,
  158. key: Optional[Hashable] = None,
  159. ) -> None:
  160. """As per FederationSender"""
  161. if destination == self.server_name:
  162. logger.info("Not sending EDU to ourselves")
  163. return
  164. pos = self._next_pos()
  165. edu = Edu(
  166. origin=self.server_name,
  167. destination=destination,
  168. edu_type=edu_type,
  169. content=content,
  170. )
  171. if key:
  172. assert isinstance(key, tuple)
  173. self.keyed_edu[(destination, key)] = edu
  174. self.keyed_edu_changed[pos] = (destination, key)
  175. else:
  176. self.edus[pos] = edu
  177. self.notifier.on_new_replication_data()
  178. async def send_read_receipt(self, receipt: ReadReceipt) -> None:
  179. """As per FederationSender
  180. Args:
  181. receipt:
  182. """
  183. # nothing to do here: the replication listener will handle it.
  184. def send_presence_to_destinations(
  185. self, states: Iterable[UserPresenceState], destinations: Iterable[str]
  186. ) -> None:
  187. """As per FederationSender
  188. Args:
  189. states
  190. destinations
  191. """
  192. for state in states:
  193. pos = self._next_pos()
  194. self.presence_map.update({state.user_id: state for state in states})
  195. self.presence_destinations[pos] = (state.user_id, destinations)
  196. self.notifier.on_new_replication_data()
  197. def send_device_messages(self, destination: str, immediate: bool = False) -> None:
  198. """As per FederationSender"""
  199. # We don't need to replicate this as it gets sent down a different
  200. # stream.
  201. def wake_destination(self, server: str) -> None:
  202. pass
  203. def get_current_token(self) -> int:
  204. return self.pos - 1
  205. def federation_ack(self, instance_name: str, token: int) -> None:
  206. if self._sender_instances:
  207. # If we have configured multiple federation sender instances we need
  208. # to track their positions separately, and only clear the queue up
  209. # to the token all instances have acked.
  210. self._sender_positions[instance_name] = token
  211. token = min(self._sender_positions.values())
  212. self._clear_queue_before_pos(token)
  213. async def get_replication_rows(
  214. self, instance_name: str, from_token: int, to_token: int, target_row_count: int
  215. ) -> Tuple[List[Tuple[int, Tuple]], int, bool]:
  216. """Get rows to be sent over federation between the two tokens
  217. Args:
  218. instance_name: the name of the current process
  219. from_token: the previous stream token: the starting point for fetching the
  220. updates
  221. to_token: the new stream token: the point to get updates up to
  222. target_row_count: a target for the number of rows to be returned.
  223. Returns: a triplet `(updates, new_last_token, limited)`, where:
  224. * `updates` is a list of `(token, row)` entries.
  225. * `new_last_token` is the new position in stream.
  226. * `limited` is whether there are more updates to fetch.
  227. """
  228. # TODO: Handle target_row_count.
  229. # To handle restarts where we wrap around
  230. if from_token > self.pos:
  231. from_token = -1
  232. # list of tuple(int, BaseFederationRow), where the first is the position
  233. # of the federation stream.
  234. rows: List[Tuple[int, BaseFederationRow]] = []
  235. # Fetch presence to send to destinations
  236. i = self.presence_destinations.bisect_right(from_token)
  237. j = self.presence_destinations.bisect_right(to_token) + 1
  238. for pos, (user_id, dests) in self.presence_destinations.items()[i:j]:
  239. rows.append(
  240. (
  241. pos,
  242. PresenceDestinationsRow(
  243. state=self.presence_map[user_id], destinations=list(dests)
  244. ),
  245. )
  246. )
  247. # Fetch changes keyed edus
  248. i = self.keyed_edu_changed.bisect_right(from_token)
  249. j = self.keyed_edu_changed.bisect_right(to_token) + 1
  250. # We purposefully clobber based on the key here, python dict comprehensions
  251. # always use the last value, so this will correctly point to the last
  252. # stream position.
  253. keyed_edus = {v: k for k, v in self.keyed_edu_changed.items()[i:j]}
  254. for (destination, edu_key), pos in keyed_edus.items():
  255. rows.append(
  256. (
  257. pos,
  258. KeyedEduRow(
  259. key=edu_key, edu=self.keyed_edu[(destination, edu_key)]
  260. ),
  261. )
  262. )
  263. # Fetch changed edus
  264. i = self.edus.bisect_right(from_token)
  265. j = self.edus.bisect_right(to_token) + 1
  266. edus = self.edus.items()[i:j]
  267. for pos, edu in edus:
  268. rows.append((pos, EduRow(edu)))
  269. # Sort rows based on pos
  270. rows.sort()
  271. return (
  272. [(pos, (row.TypeId, row.to_data())) for pos, row in rows],
  273. to_token,
  274. False,
  275. )
  276. class BaseFederationRow:
  277. """Base class for rows to be sent in the federation stream.
  278. Specifies how to identify, serialize and deserialize the different types.
  279. """
  280. TypeId = "" # Unique string that ids the type. Must be overridden in sub classes.
  281. @staticmethod
  282. def from_data(data: JsonDict) -> "BaseFederationRow":
  283. """Parse the data from the federation stream into a row.
  284. Args:
  285. data: The value of ``data`` from FederationStreamRow.data, type
  286. depends on the type of stream
  287. """
  288. raise NotImplementedError()
  289. def to_data(self) -> JsonDict:
  290. """Serialize this row to be sent over the federation stream.
  291. Returns:
  292. The value to be sent in FederationStreamRow.data. The type depends
  293. on the type of stream.
  294. """
  295. raise NotImplementedError()
  296. def add_to_buffer(self, buff: "ParsedFederationStreamData") -> None:
  297. """Add this row to the appropriate field in the buffer ready for this
  298. to be sent over federation.
  299. We use a buffer so that we can batch up events that have come in at
  300. the same time and send them all at once.
  301. Args:
  302. buff (BufferedToSend)
  303. """
  304. raise NotImplementedError()
  305. @attr.s(slots=True, frozen=True, auto_attribs=True)
  306. class PresenceDestinationsRow(BaseFederationRow):
  307. state: UserPresenceState
  308. destinations: List[str]
  309. TypeId = "pd"
  310. @staticmethod
  311. def from_data(data: JsonDict) -> "PresenceDestinationsRow":
  312. return PresenceDestinationsRow(
  313. state=UserPresenceState.from_dict(data["state"]), destinations=data["dests"]
  314. )
  315. def to_data(self) -> JsonDict:
  316. return {"state": self.state.as_dict(), "dests": self.destinations}
  317. def add_to_buffer(self, buff: "ParsedFederationStreamData") -> None:
  318. buff.presence_destinations.append((self.state, self.destinations))
  319. @attr.s(slots=True, frozen=True, auto_attribs=True)
  320. class KeyedEduRow(BaseFederationRow):
  321. """Streams EDUs that have an associated key that is ued to clobber. For example,
  322. typing EDUs clobber based on room_id.
  323. """
  324. key: Tuple[str, ...] # the edu key passed to send_edu
  325. edu: Edu
  326. TypeId = "k"
  327. @staticmethod
  328. def from_data(data: JsonDict) -> "KeyedEduRow":
  329. return KeyedEduRow(key=tuple(data["key"]), edu=Edu(**data["edu"]))
  330. def to_data(self) -> JsonDict:
  331. return {"key": self.key, "edu": self.edu.get_internal_dict()}
  332. def add_to_buffer(self, buff: "ParsedFederationStreamData") -> None:
  333. buff.keyed_edus.setdefault(self.edu.destination, {})[self.key] = self.edu
  334. @attr.s(slots=True, frozen=True, auto_attribs=True)
  335. class EduRow(BaseFederationRow):
  336. """Streams EDUs that don't have keys. See KeyedEduRow"""
  337. edu: Edu
  338. TypeId = "e"
  339. @staticmethod
  340. def from_data(data: JsonDict) -> "EduRow":
  341. return EduRow(Edu(**data))
  342. def to_data(self) -> JsonDict:
  343. return self.edu.get_internal_dict()
  344. def add_to_buffer(self, buff: "ParsedFederationStreamData") -> None:
  345. buff.edus.setdefault(self.edu.destination, []).append(self.edu)
  346. _rowtypes: Tuple[Type[BaseFederationRow], ...] = (
  347. PresenceDestinationsRow,
  348. KeyedEduRow,
  349. EduRow,
  350. )
  351. TypeToRow = {Row.TypeId: Row for Row in _rowtypes}
  352. @attr.s(slots=True, frozen=True, auto_attribs=True)
  353. class ParsedFederationStreamData:
  354. # list of tuples of UserPresenceState and destinations
  355. presence_destinations: List[Tuple[UserPresenceState, List[str]]]
  356. # dict of destination -> { key -> Edu }
  357. keyed_edus: Dict[str, Dict[Tuple[str, ...], Edu]]
  358. # dict of destination -> [Edu]
  359. edus: Dict[str, List[Edu]]
  360. def process_rows_for_federation(
  361. transaction_queue: FederationSender,
  362. rows: List[FederationStream.FederationStreamRow],
  363. ) -> None:
  364. """Parse a list of rows from the federation stream and put them in the
  365. transaction queue ready for sending to the relevant homeservers.
  366. Args:
  367. transaction_queue
  368. rows
  369. """
  370. # The federation stream contains a bunch of different types of
  371. # rows that need to be handled differently. We parse the rows, put
  372. # them into the appropriate collection and then send them off.
  373. buff = ParsedFederationStreamData(
  374. presence_destinations=[],
  375. keyed_edus={},
  376. edus={},
  377. )
  378. # Parse the rows in the stream and add to the buffer
  379. for row in rows:
  380. if row.type not in TypeToRow:
  381. logger.error("Unrecognized federation row type %r", row.type)
  382. continue
  383. RowType = TypeToRow[row.type]
  384. parsed_row = RowType.from_data(row.data)
  385. parsed_row.add_to_buffer(buff)
  386. for state, destinations in buff.presence_destinations:
  387. transaction_queue.send_presence_to_destinations(
  388. states=[state], destinations=destinations
  389. )
  390. for edu_map in buff.keyed_edus.values():
  391. for key, edu in edu_map.items():
  392. transaction_queue.send_edu(edu, key)
  393. for edu_list in buff.edus.values():
  394. for edu in edu_list:
  395. transaction_queue.send_edu(edu, None)