Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

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