notifier.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014, 2015 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. from twisted.internet import defer
  16. from synapse.util.logutils import log_function
  17. from synapse.util.async import run_on_reactor, ObservableDeferred
  18. from synapse.types import StreamToken
  19. import synapse.metrics
  20. import logging
  21. logger = logging.getLogger(__name__)
  22. metrics = synapse.metrics.get_metrics_for(__name__)
  23. notified_events_counter = metrics.register_counter("notified_events")
  24. # TODO(paul): Should be shared somewhere
  25. def count(func, l):
  26. """Return the number of items in l for which func returns true."""
  27. n = 0
  28. for x in l:
  29. if func(x):
  30. n += 1
  31. return n
  32. class _NotificationListener(object):
  33. """ This represents a single client connection to the events stream.
  34. The events stream handler will have yielded to the deferred, so to
  35. notify the handler it is sufficient to resolve the deferred.
  36. """
  37. __slots__ = ["deferred"]
  38. def __init__(self, deferred):
  39. self.deferred = deferred
  40. class _NotifierUserStream(object):
  41. """This represents a user connected to the event stream.
  42. It tracks the most recent stream token for that user.
  43. At a given point a user may have a number of streams listening for
  44. events.
  45. This listener will also keep track of which rooms it is listening in
  46. so that it can remove itself from the indexes in the Notifier class.
  47. """
  48. def __init__(self, user, rooms, current_token, time_now_ms,
  49. appservice=None):
  50. self.user = str(user)
  51. self.appservice = appservice
  52. self.rooms = set(rooms)
  53. self.current_token = current_token
  54. self.last_notified_ms = time_now_ms
  55. self.notify_deferred = ObservableDeferred(defer.Deferred())
  56. def notify(self, stream_key, stream_id, time_now_ms):
  57. """Notify any listeners for this user of a new event from an
  58. event source.
  59. Args:
  60. stream_key(str): The stream the event came from.
  61. stream_id(str): The new id for the stream the event came from.
  62. time_now_ms(int): The current time in milliseconds.
  63. """
  64. self.current_token = self.current_token.copy_and_advance(
  65. stream_key, stream_id
  66. )
  67. self.last_notified_ms = time_now_ms
  68. noify_deferred = self.notify_deferred
  69. self.notify_deferred = ObservableDeferred(defer.Deferred())
  70. noify_deferred.callback(self.current_token)
  71. def remove(self, notifier):
  72. """ Remove this listener from all the indexes in the Notifier
  73. it knows about.
  74. """
  75. for room in self.rooms:
  76. lst = notifier.room_to_user_streams.get(room, set())
  77. lst.discard(self)
  78. notifier.user_to_user_stream.pop(self.user)
  79. if self.appservice:
  80. notifier.appservice_to_user_streams.get(
  81. self.appservice, set()
  82. ).discard(self)
  83. def count_listeners(self):
  84. return len(self.notify_deferred.observers())
  85. def new_listener(self, token):
  86. """Returns a deferred that is resolved when there is a new token
  87. greater than the given token.
  88. """
  89. if self.current_token.is_after(token):
  90. return _NotificationListener(defer.succeed(self.current_token))
  91. else:
  92. return _NotificationListener(self.notify_deferred.observe())
  93. class Notifier(object):
  94. """ This class is responsible for notifying any listeners when there are
  95. new events available for it.
  96. Primarily used from the /events stream.
  97. """
  98. UNUSED_STREAM_EXPIRY_MS = 10 * 60 * 1000
  99. def __init__(self, hs):
  100. self.hs = hs
  101. self.user_to_user_stream = {}
  102. self.room_to_user_streams = {}
  103. self.appservice_to_user_streams = {}
  104. self.event_sources = hs.get_event_sources()
  105. self.store = hs.get_datastore()
  106. self.pending_new_room_events = []
  107. self.clock = hs.get_clock()
  108. hs.get_distributor().observe(
  109. "user_joined_room", self._user_joined_room
  110. )
  111. self.clock.looping_call(
  112. self.remove_expired_streams, self.UNUSED_STREAM_EXPIRY_MS
  113. )
  114. # This is not a very cheap test to perform, but it's only executed
  115. # when rendering the metrics page, which is likely once per minute at
  116. # most when scraping it.
  117. def count_listeners():
  118. all_user_streams = set()
  119. for x in self.room_to_user_streams.values():
  120. all_user_streams |= x
  121. for x in self.user_to_user_stream.values():
  122. all_user_streams.add(x)
  123. for x in self.appservice_to_user_streams.values():
  124. all_user_streams |= x
  125. return sum(stream.count_listeners() for stream in all_user_streams)
  126. metrics.register_callback("listeners", count_listeners)
  127. metrics.register_callback(
  128. "rooms",
  129. lambda: count(bool, self.room_to_user_streams.values()),
  130. )
  131. metrics.register_callback(
  132. "users",
  133. lambda: len(self.user_to_user_stream),
  134. )
  135. metrics.register_callback(
  136. "appservices",
  137. lambda: count(bool, self.appservice_to_user_streams.values()),
  138. )
  139. @log_function
  140. @defer.inlineCallbacks
  141. def on_new_room_event(self, event, room_stream_id, max_room_stream_id,
  142. extra_users=[]):
  143. """ Used by handlers to inform the notifier something has happened
  144. in the room, room event wise.
  145. This triggers the notifier to wake up any listeners that are
  146. listening to the room, and any listeners for the users in the
  147. `extra_users` param.
  148. The events can be peristed out of order. The notifier will wait
  149. until all previous events have been persisted before notifying
  150. the client streams.
  151. """
  152. yield run_on_reactor()
  153. self.pending_new_room_events.append((
  154. room_stream_id, event, extra_users
  155. ))
  156. self._notify_pending_new_room_events(max_room_stream_id)
  157. def _notify_pending_new_room_events(self, max_room_stream_id):
  158. """Notify for the room events that were queued waiting for a previous
  159. event to be persisted.
  160. Args:
  161. max_room_stream_id(int): The highest stream_id below which all
  162. events have been persisted.
  163. """
  164. pending = self.pending_new_room_events
  165. self.pending_new_room_events = []
  166. for room_stream_id, event, extra_users in pending:
  167. if room_stream_id > max_room_stream_id:
  168. self.pending_new_room_events.append((
  169. room_stream_id, event, extra_users
  170. ))
  171. else:
  172. self._on_new_room_event(event, room_stream_id, extra_users)
  173. def _on_new_room_event(self, event, room_stream_id, extra_users=[]):
  174. """Notify any user streams that are interested in this room event"""
  175. # poke any interested application service.
  176. self.hs.get_handlers().appservice_handler.notify_interested_services(
  177. event
  178. )
  179. app_streams = set()
  180. for appservice in self.appservice_to_user_streams:
  181. # TODO (kegan): Redundant appservice listener checks?
  182. # App services will already be in the room_to_user_streams set, but
  183. # that isn't enough. They need to be checked here in order to
  184. # receive *invites* for users they are interested in. Does this
  185. # make the room_to_user_streams check somewhat obselete?
  186. if appservice.is_interested(event):
  187. app_user_streams = self.appservice_to_user_streams.get(
  188. appservice, set()
  189. )
  190. app_streams |= app_user_streams
  191. self.on_new_event(
  192. "room_key", room_stream_id,
  193. users=extra_users,
  194. rooms=[event.room_id],
  195. extra_streams=app_streams,
  196. )
  197. @defer.inlineCallbacks
  198. @log_function
  199. def on_new_event(self, stream_key, new_token, users=[], rooms=[],
  200. extra_streams=set()):
  201. """ Used to inform listeners that something has happend event wise.
  202. Will wake up all listeners for the given users and rooms.
  203. """
  204. yield run_on_reactor()
  205. user_streams = set()
  206. for user in users:
  207. user_stream = self.user_to_user_stream.get(str(user))
  208. if user_stream is not None:
  209. user_streams.add(user_stream)
  210. for room in rooms:
  211. user_streams |= self.room_to_user_streams.get(room, set())
  212. time_now_ms = self.clock.time_msec()
  213. for user_stream in user_streams:
  214. try:
  215. user_stream.notify(stream_key, new_token, time_now_ms)
  216. except:
  217. logger.exception("Failed to notify listener")
  218. @defer.inlineCallbacks
  219. def wait_for_events(self, user, rooms, timeout, callback,
  220. from_token=StreamToken("s0", "0", "0", "0")):
  221. """Wait until the callback returns a non empty response or the
  222. timeout fires.
  223. """
  224. user = str(user)
  225. user_stream = self.user_to_user_stream.get(user)
  226. if user_stream is None:
  227. appservice = yield self.store.get_app_service_by_user_id(user)
  228. current_token = yield self.event_sources.get_current_token()
  229. rooms = yield self.store.get_rooms_for_user(user)
  230. rooms = [room.room_id for room in rooms]
  231. user_stream = _NotifierUserStream(
  232. user=user,
  233. rooms=rooms,
  234. appservice=appservice,
  235. current_token=current_token,
  236. time_now_ms=self.clock.time_msec(),
  237. )
  238. self._register_with_keys(user_stream)
  239. result = None
  240. if timeout:
  241. # Will be set to a _NotificationListener that we'll be waiting on.
  242. # Allows us to cancel it.
  243. listener = None
  244. def timed_out():
  245. if listener:
  246. listener.deferred.cancel()
  247. timer = self.clock.call_later(timeout/1000., timed_out)
  248. prev_token = from_token
  249. while not result:
  250. try:
  251. current_token = user_stream.current_token
  252. result = yield callback(prev_token, current_token)
  253. if result:
  254. break
  255. # Now we wait for the _NotifierUserStream to be told there
  256. # is a new token.
  257. # We need to supply the token we supplied to callback so
  258. # that we don't miss any current_token updates.
  259. prev_token = current_token
  260. listener = user_stream.new_listener(prev_token)
  261. yield listener.deferred
  262. except defer.CancelledError:
  263. break
  264. self.clock.cancel_call_later(timer, ignore_errs=True)
  265. else:
  266. current_token = user_stream.current_token
  267. result = yield callback(from_token, current_token)
  268. defer.returnValue(result)
  269. @defer.inlineCallbacks
  270. def get_events_for(self, user, rooms, pagination_config, timeout,
  271. only_room_events=False):
  272. """ For the given user and rooms, return any new events for them. If
  273. there are no new events wait for up to `timeout` milliseconds for any
  274. new events to happen before returning.
  275. If `only_room_events` is `True` only room events will be returned.
  276. """
  277. from_token = pagination_config.from_token
  278. if not from_token:
  279. from_token = yield self.event_sources.get_current_token()
  280. limit = pagination_config.limit
  281. @defer.inlineCallbacks
  282. def check_for_updates(before_token, after_token):
  283. if not after_token.is_after(before_token):
  284. defer.returnValue(None)
  285. events = []
  286. end_token = from_token
  287. for name, source in self.event_sources.sources.items():
  288. keyname = "%s_key" % name
  289. before_id = getattr(before_token, keyname)
  290. after_id = getattr(after_token, keyname)
  291. if before_id == after_id:
  292. continue
  293. if only_room_events and name != "room":
  294. continue
  295. new_events, new_key = yield source.get_new_events_for_user(
  296. user, getattr(from_token, keyname), limit,
  297. )
  298. events.extend(new_events)
  299. end_token = end_token.copy_and_replace(keyname, new_key)
  300. if events:
  301. defer.returnValue((events, (from_token, end_token)))
  302. else:
  303. defer.returnValue(None)
  304. result = yield self.wait_for_events(
  305. user, rooms, timeout, check_for_updates, from_token=from_token
  306. )
  307. if result is None:
  308. result = ([], (from_token, from_token))
  309. defer.returnValue(result)
  310. @log_function
  311. def remove_expired_streams(self):
  312. time_now_ms = self.clock.time_msec()
  313. expired_streams = []
  314. expire_before_ts = time_now_ms - self.UNUSED_STREAM_EXPIRY_MS
  315. for stream in self.user_to_user_stream.values():
  316. if stream.count_listeners():
  317. continue
  318. if stream.last_notified_ms < expire_before_ts:
  319. expired_streams.append(stream)
  320. for expired_stream in expired_streams:
  321. expired_stream.remove(self)
  322. @log_function
  323. def _register_with_keys(self, user_stream):
  324. self.user_to_user_stream[user_stream.user] = user_stream
  325. for room in user_stream.rooms:
  326. s = self.room_to_user_streams.setdefault(room, set())
  327. s.add(user_stream)
  328. if user_stream.appservice:
  329. self.appservice_to_user_stream.setdefault(
  330. user_stream.appservice, set()
  331. ).add(user_stream)
  332. def _user_joined_room(self, user, room_id):
  333. user = str(user)
  334. new_user_stream = self.user_to_user_stream.get(user)
  335. if new_user_stream is not None:
  336. room_streams = self.room_to_user_streams.setdefault(room_id, set())
  337. room_streams.add(new_user_stream)
  338. new_user_stream.rooms.add(room_id)