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.
 
 
 
 
 
 

577 lines
18 KiB

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