1
0

send_queue.py 18 KB

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