send_queue.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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 six import iteritems
  29. from sortedcontainers import SortedDict
  30. from synapse.metrics import LaterGauge
  31. from synapse.storage.presence import UserPresenceState
  32. from synapse.util.metrics import Measure
  33. from .units import Edu
  34. logger = logging.getLogger(__name__)
  35. class FederationRemoteSendQueue(object):
  36. """A drop in replacement for FederationSender"""
  37. def __init__(self, hs):
  38. self.server_name = hs.hostname
  39. self.clock = hs.get_clock()
  40. self.notifier = hs.get_notifier()
  41. self.is_mine_id = hs.is_mine_id
  42. self.presence_map = {} # Pending presence map user_id -> UserPresenceState
  43. self.presence_changed = SortedDict() # Stream position -> list[user_id]
  44. # Stores the destinations we need to explicitly send presence to about a
  45. # given user.
  46. # Stream position -> (user_id, destinations)
  47. self.presence_destinations = SortedDict()
  48. self.keyed_edu = {} # (destination, key) -> EDU
  49. self.keyed_edu_changed = SortedDict() # stream position -> (destination, key)
  50. self.edus = SortedDict() # stream position -> Edu
  51. self.device_messages = SortedDict() # stream position -> destination
  52. self.pos = 1
  53. self.pos_time = SortedDict()
  54. # EVERYTHING IS SAD. In particular, python only makes new scopes when
  55. # we make a new function, so we need to make a new function so the inner
  56. # lambda binds to the queue rather than to the name of the queue which
  57. # changes. ARGH.
  58. def register(name, queue):
  59. LaterGauge(
  60. "synapse_federation_send_queue_%s_size" % (queue_name,),
  61. "",
  62. [],
  63. lambda: len(queue),
  64. )
  65. for queue_name in [
  66. "presence_map",
  67. "presence_changed",
  68. "keyed_edu",
  69. "keyed_edu_changed",
  70. "edus",
  71. "device_messages",
  72. "pos_time",
  73. "presence_destinations",
  74. ]:
  75. register(queue_name, getattr(self, queue_name))
  76. self.clock.looping_call(self._clear_queue, 30 * 1000)
  77. def _next_pos(self):
  78. pos = self.pos
  79. self.pos += 1
  80. self.pos_time[self.clock.time_msec()] = pos
  81. return pos
  82. def _clear_queue(self):
  83. """Clear the queues for anything older than N minutes"""
  84. FIVE_MINUTES_AGO = 5 * 60 * 1000
  85. now = self.clock.time_msec()
  86. keys = self.pos_time.keys()
  87. time = self.pos_time.bisect_left(now - FIVE_MINUTES_AGO)
  88. if not keys[:time]:
  89. return
  90. position_to_delete = max(keys[:time])
  91. for key in keys[:time]:
  92. del self.pos_time[key]
  93. self._clear_queue_before_pos(position_to_delete)
  94. def _clear_queue_before_pos(self, position_to_delete):
  95. """Clear all the queues from before a given position"""
  96. with Measure(self.clock, "send_queue._clear"):
  97. # Delete things out of presence maps
  98. keys = self.presence_changed.keys()
  99. i = self.presence_changed.bisect_left(position_to_delete)
  100. for key in keys[:i]:
  101. del self.presence_changed[key]
  102. user_ids = set(
  103. user_id for uids in self.presence_changed.values() for user_id in uids
  104. )
  105. keys = self.presence_destinations.keys()
  106. i = self.presence_destinations.bisect_left(position_to_delete)
  107. for key in keys[:i]:
  108. del self.presence_destinations[key]
  109. user_ids.update(
  110. user_id for user_id, _ in self.presence_destinations.values()
  111. )
  112. to_del = [
  113. user_id for user_id in self.presence_map if user_id not in user_ids
  114. ]
  115. for user_id in to_del:
  116. del self.presence_map[user_id]
  117. # Delete things out of keyed edus
  118. keys = self.keyed_edu_changed.keys()
  119. i = self.keyed_edu_changed.bisect_left(position_to_delete)
  120. for key in keys[:i]:
  121. del self.keyed_edu_changed[key]
  122. live_keys = set()
  123. for edu_key in self.keyed_edu_changed.values():
  124. live_keys.add(edu_key)
  125. to_del = [edu_key for edu_key in self.keyed_edu if edu_key not in live_keys]
  126. for edu_key in to_del:
  127. del self.keyed_edu[edu_key]
  128. # Delete things out of edu map
  129. keys = self.edus.keys()
  130. i = self.edus.bisect_left(position_to_delete)
  131. for key in keys[:i]:
  132. del self.edus[key]
  133. # Delete things out of device map
  134. keys = self.device_messages.keys()
  135. i = self.device_messages.bisect_left(position_to_delete)
  136. for key in keys[:i]:
  137. del self.device_messages[key]
  138. def notify_new_events(self, current_id):
  139. """As per FederationSender"""
  140. # We don't need to replicate this as it gets sent down a different
  141. # stream.
  142. pass
  143. def build_and_send_edu(self, destination, edu_type, content, key=None):
  144. """As per FederationSender"""
  145. if destination == self.server_name:
  146. logger.info("Not sending EDU to ourselves")
  147. return
  148. pos = self._next_pos()
  149. edu = Edu(
  150. origin=self.server_name,
  151. destination=destination,
  152. edu_type=edu_type,
  153. content=content,
  154. )
  155. if key:
  156. assert isinstance(key, tuple)
  157. self.keyed_edu[(destination, key)] = edu
  158. self.keyed_edu_changed[pos] = (destination, key)
  159. else:
  160. self.edus[pos] = edu
  161. self.notifier.on_new_replication_data()
  162. def send_read_receipt(self, receipt):
  163. """As per FederationSender
  164. Args:
  165. receipt (synapse.types.ReadReceipt):
  166. """
  167. # nothing to do here: the replication listener will handle it.
  168. pass
  169. def send_presence(self, states):
  170. """As per FederationSender
  171. Args:
  172. states (list(UserPresenceState))
  173. """
  174. pos = self._next_pos()
  175. # We only want to send presence for our own users, so lets always just
  176. # filter here just in case.
  177. local_states = list(filter(lambda s: self.is_mine_id(s.user_id), states))
  178. self.presence_map.update({state.user_id: state for state in local_states})
  179. self.presence_changed[pos] = [state.user_id for state in local_states]
  180. self.notifier.on_new_replication_data()
  181. def send_presence_to_destinations(self, states, destinations):
  182. """As per FederationSender
  183. Args:
  184. states (list[UserPresenceState])
  185. destinations (list[str])
  186. """
  187. for state in states:
  188. pos = self._next_pos()
  189. self.presence_map.update({state.user_id: state for state in states})
  190. self.presence_destinations[pos] = (state.user_id, destinations)
  191. self.notifier.on_new_replication_data()
  192. def send_device_messages(self, destination):
  193. """As per FederationSender"""
  194. pos = self._next_pos()
  195. self.device_messages[pos] = destination
  196. self.notifier.on_new_replication_data()
  197. def get_current_token(self):
  198. return self.pos - 1
  199. def federation_ack(self, token):
  200. self._clear_queue_before_pos(token)
  201. def get_replication_rows(self, from_token, to_token, limit, federation_ack=None):
  202. """Get rows to be sent over federation between the two tokens
  203. Args:
  204. from_token (int)
  205. to_token(int)
  206. limit (int)
  207. federation_ack (int): Optional. The position where the worker is
  208. explicitly acknowledged it has handled. Allows us to drop
  209. data from before that point
  210. """
  211. # TODO: Handle limit.
  212. # To handle restarts where we wrap around
  213. if from_token > self.pos:
  214. from_token = -1
  215. # list of tuple(int, BaseFederationRow), where the first is the position
  216. # of the federation stream.
  217. rows = []
  218. # There should be only one reader, so lets delete everything its
  219. # acknowledged its seen.
  220. if federation_ack:
  221. self._clear_queue_before_pos(federation_ack)
  222. # Fetch changed presence
  223. i = self.presence_changed.bisect_right(from_token)
  224. j = self.presence_changed.bisect_right(to_token) + 1
  225. dest_user_ids = [
  226. (pos, user_id)
  227. for pos, user_id_list in self.presence_changed.items()[i:j]
  228. for user_id in user_id_list
  229. ]
  230. for (key, user_id) in dest_user_ids:
  231. rows.append((key, PresenceRow(state=self.presence_map[user_id])))
  232. # Fetch presence to send to destinations
  233. i = self.presence_destinations.bisect_right(from_token)
  234. j = self.presence_destinations.bisect_right(to_token) + 1
  235. for pos, (user_id, dests) in self.presence_destinations.items()[i:j]:
  236. rows.append(
  237. (
  238. pos,
  239. PresenceDestinationsRow(
  240. state=self.presence_map[user_id], destinations=list(dests)
  241. ),
  242. )
  243. )
  244. # Fetch changes keyed edus
  245. i = self.keyed_edu_changed.bisect_right(from_token)
  246. j = self.keyed_edu_changed.bisect_right(to_token) + 1
  247. # We purposefully clobber based on the key here, python dict comprehensions
  248. # always use the last value, so this will correctly point to the last
  249. # stream position.
  250. keyed_edus = {v: k for k, v in self.keyed_edu_changed.items()[i:j]}
  251. for ((destination, edu_key), pos) in iteritems(keyed_edus):
  252. rows.append(
  253. (
  254. pos,
  255. KeyedEduRow(
  256. key=edu_key, edu=self.keyed_edu[(destination, edu_key)]
  257. ),
  258. )
  259. )
  260. # Fetch changed edus
  261. i = self.edus.bisect_right(from_token)
  262. j = self.edus.bisect_right(to_token) + 1
  263. edus = self.edus.items()[i:j]
  264. for (pos, edu) in edus:
  265. rows.append((pos, EduRow(edu)))
  266. # Fetch changed device messages
  267. i = self.device_messages.bisect_right(from_token)
  268. j = self.device_messages.bisect_right(to_token) + 1
  269. device_messages = {v: k for k, v in self.device_messages.items()[i:j]}
  270. for (destination, pos) in iteritems(device_messages):
  271. rows.append((pos, DeviceRow(destination=destination)))
  272. # Sort rows based on pos
  273. rows.sort()
  274. return [(pos, row.TypeId, row.to_data()) for pos, row in rows]
  275. class BaseFederationRow(object):
  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 = None # Unique string that ids the type. Must be overriden 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 PresenceRow(
  305. BaseFederationRow, namedtuple("PresenceRow", ("state",)) # UserPresenceState
  306. ):
  307. TypeId = "p"
  308. @staticmethod
  309. def from_data(data):
  310. return PresenceRow(state=UserPresenceState.from_dict(data))
  311. def to_data(self):
  312. return self.state.as_dict()
  313. def add_to_buffer(self, buff):
  314. buff.presence.append(self.state)
  315. class PresenceDestinationsRow(
  316. BaseFederationRow,
  317. namedtuple(
  318. "PresenceDestinationsRow",
  319. ("state", "destinations"), # UserPresenceState # list[str]
  320. ),
  321. ):
  322. TypeId = "pd"
  323. @staticmethod
  324. def from_data(data):
  325. return PresenceDestinationsRow(
  326. state=UserPresenceState.from_dict(data["state"]), destinations=data["dests"]
  327. )
  328. def to_data(self):
  329. return {"state": self.state.as_dict(), "dests": self.destinations}
  330. def add_to_buffer(self, buff):
  331. buff.presence_destinations.append((self.state, self.destinations))
  332. class KeyedEduRow(
  333. BaseFederationRow,
  334. namedtuple(
  335. "KeyedEduRow",
  336. ("key", "edu"), # tuple(str) - the edu key passed to send_edu # Edu
  337. ),
  338. ):
  339. """Streams EDUs that have an associated key that is ued to clobber. For example,
  340. typing EDUs clobber based on room_id.
  341. """
  342. TypeId = "k"
  343. @staticmethod
  344. def from_data(data):
  345. return KeyedEduRow(key=tuple(data["key"]), edu=Edu(**data["edu"]))
  346. def to_data(self):
  347. return {"key": self.key, "edu": self.edu.get_internal_dict()}
  348. def add_to_buffer(self, buff):
  349. buff.keyed_edus.setdefault(self.edu.destination, {})[self.key] = self.edu
  350. class EduRow(BaseFederationRow, namedtuple("EduRow", ("edu",))): # Edu
  351. """Streams EDUs that don't have keys. See KeyedEduRow
  352. """
  353. TypeId = "e"
  354. @staticmethod
  355. def from_data(data):
  356. return EduRow(Edu(**data))
  357. def to_data(self):
  358. return self.edu.get_internal_dict()
  359. def add_to_buffer(self, buff):
  360. buff.edus.setdefault(self.edu.destination, []).append(self.edu)
  361. class DeviceRow(BaseFederationRow, namedtuple("DeviceRow", ("destination",))): # str
  362. """Streams the fact that either a) there is pending to device messages for
  363. users on the remote, or b) a local users device has changed and needs to
  364. be sent to the remote.
  365. """
  366. TypeId = "d"
  367. @staticmethod
  368. def from_data(data):
  369. return DeviceRow(destination=data["destination"])
  370. def to_data(self):
  371. return {"destination": self.destination}
  372. def add_to_buffer(self, buff):
  373. buff.device_destinations.add(self.destination)
  374. TypeToRow = {
  375. Row.TypeId: Row
  376. for Row in (PresenceRow, PresenceDestinationsRow, KeyedEduRow, EduRow, DeviceRow)
  377. }
  378. ParsedFederationStreamData = namedtuple(
  379. "ParsedFederationStreamData",
  380. (
  381. "presence", # list(UserPresenceState)
  382. "presence_destinations", # list of tuples of UserPresenceState and destinations
  383. "keyed_edus", # dict of destination -> { key -> Edu }
  384. "edus", # dict of destination -> [Edu]
  385. "device_destinations", # set of destinations
  386. ),
  387. )
  388. def process_rows_for_federation(transaction_queue, rows):
  389. """Parse a list of rows from the federation stream and put them in the
  390. transaction queue ready for sending to the relevant homeservers.
  391. Args:
  392. transaction_queue (FederationSender)
  393. rows (list(synapse.replication.tcp.streams.FederationStreamRow))
  394. """
  395. # The federation stream contains a bunch of different types of
  396. # rows that need to be handled differently. We parse the rows, put
  397. # them into the appropriate collection and then send them off.
  398. buff = ParsedFederationStreamData(
  399. presence=[],
  400. presence_destinations=[],
  401. keyed_edus={},
  402. edus={},
  403. device_destinations=set(),
  404. )
  405. # Parse the rows in the stream and add to the buffer
  406. for row in rows:
  407. if row.type not in TypeToRow:
  408. logger.error("Unrecognized federation row type %r", row.type)
  409. continue
  410. RowType = TypeToRow[row.type]
  411. parsed_row = RowType.from_data(row.data)
  412. parsed_row.add_to_buffer(buff)
  413. if buff.presence:
  414. transaction_queue.send_presence(buff.presence)
  415. for state, destinations in buff.presence_destinations:
  416. transaction_queue.send_presence_to_destinations(
  417. states=[state], destinations=destinations
  418. )
  419. for destination, edu_map in iteritems(buff.keyed_edus):
  420. for key, edu in edu_map.items():
  421. transaction_queue.send_edu(edu, key)
  422. for destination, edu_list in iteritems(buff.edus):
  423. for edu in edu_list:
  424. transaction_queue.send_edu(edu, None)
  425. for destination in buff.device_destinations:
  426. transaction_queue.send_device_messages(destination)