send_queue.py 18 KB

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