send_queue.py 16 KB

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