notifier.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. from twisted.internet import defer
  16. from synapse.api.constants import EventTypes, Membership
  17. from synapse.api.errors import AuthError
  18. from synapse.util.logutils import log_function
  19. from synapse.util.async import ObservableDeferred
  20. from synapse.util.logcontext import PreserveLoggingContext, preserve_fn
  21. from synapse.util.metrics import Measure
  22. from synapse.types import StreamToken
  23. from synapse.visibility import filter_events_for_client
  24. import synapse.metrics
  25. from collections import namedtuple
  26. import logging
  27. logger = logging.getLogger(__name__)
  28. metrics = synapse.metrics.get_metrics_for(__name__)
  29. notified_events_counter = metrics.register_counter("notified_events")
  30. # TODO(paul): Should be shared somewhere
  31. def count(func, l):
  32. """Return the number of items in l for which func returns true."""
  33. n = 0
  34. for x in l:
  35. if func(x):
  36. n += 1
  37. return n
  38. class _NotificationListener(object):
  39. """ This represents a single client connection to the events stream.
  40. The events stream handler will have yielded to the deferred, so to
  41. notify the handler it is sufficient to resolve the deferred.
  42. """
  43. __slots__ = ["deferred"]
  44. def __init__(self, deferred):
  45. self.deferred = deferred
  46. class _NotifierUserStream(object):
  47. """This represents a user connected to the event stream.
  48. It tracks the most recent stream token for that user.
  49. At a given point a user may have a number of streams listening for
  50. events.
  51. This listener will also keep track of which rooms it is listening in
  52. so that it can remove itself from the indexes in the Notifier class.
  53. """
  54. def __init__(self, user_id, rooms, current_token, time_now_ms):
  55. self.user_id = user_id
  56. self.rooms = set(rooms)
  57. self.current_token = current_token
  58. self.last_notified_ms = time_now_ms
  59. with PreserveLoggingContext():
  60. self.notify_deferred = ObservableDeferred(defer.Deferred())
  61. def notify(self, stream_key, stream_id, time_now_ms):
  62. """Notify any listeners for this user of a new event from an
  63. event source.
  64. Args:
  65. stream_key(str): The stream the event came from.
  66. stream_id(str): The new id for the stream the event came from.
  67. time_now_ms(int): The current time in milliseconds.
  68. """
  69. self.current_token = self.current_token.copy_and_advance(
  70. stream_key, stream_id
  71. )
  72. self.last_notified_ms = time_now_ms
  73. noify_deferred = self.notify_deferred
  74. with PreserveLoggingContext():
  75. self.notify_deferred = ObservableDeferred(defer.Deferred())
  76. noify_deferred.callback(self.current_token)
  77. def remove(self, notifier):
  78. """ Remove this listener from all the indexes in the Notifier
  79. it knows about.
  80. """
  81. for room in self.rooms:
  82. lst = notifier.room_to_user_streams.get(room, set())
  83. lst.discard(self)
  84. notifier.user_to_user_stream.pop(self.user_id)
  85. def count_listeners(self):
  86. return len(self.notify_deferred.observers())
  87. def new_listener(self, token):
  88. """Returns a deferred that is resolved when there is a new token
  89. greater than the given token.
  90. """
  91. if self.current_token.is_after(token):
  92. return _NotificationListener(defer.succeed(self.current_token))
  93. else:
  94. return _NotificationListener(self.notify_deferred.observe())
  95. class EventStreamResult(namedtuple("EventStreamResult", ("events", "tokens"))):
  96. def __nonzero__(self):
  97. return bool(self.events)
  98. class Notifier(object):
  99. """ This class is responsible for notifying any listeners when there are
  100. new events available for it.
  101. Primarily used from the /events stream.
  102. """
  103. UNUSED_STREAM_EXPIRY_MS = 10 * 60 * 1000
  104. def __init__(self, hs):
  105. self.user_to_user_stream = {}
  106. self.room_to_user_streams = {}
  107. self.event_sources = hs.get_event_sources()
  108. self.store = hs.get_datastore()
  109. self.pending_new_room_events = []
  110. self.clock = hs.get_clock()
  111. self.appservice_handler = hs.get_application_service_handler()
  112. self.state_handler = hs.get_state_handler()
  113. self.clock.looping_call(
  114. self.remove_expired_streams, self.UNUSED_STREAM_EXPIRY_MS
  115. )
  116. self.replication_deferred = ObservableDeferred(defer.Deferred())
  117. # This is not a very cheap test to perform, but it's only executed
  118. # when rendering the metrics page, which is likely once per minute at
  119. # most when scraping it.
  120. def count_listeners():
  121. all_user_streams = set()
  122. for x in self.room_to_user_streams.values():
  123. all_user_streams |= x
  124. for x in self.user_to_user_stream.values():
  125. all_user_streams.add(x)
  126. return sum(stream.count_listeners() for stream in all_user_streams)
  127. metrics.register_callback("listeners", count_listeners)
  128. metrics.register_callback(
  129. "rooms",
  130. lambda: count(bool, self.room_to_user_streams.values()),
  131. )
  132. metrics.register_callback(
  133. "users",
  134. lambda: len(self.user_to_user_stream),
  135. )
  136. @preserve_fn
  137. def on_new_room_event(self, event, room_stream_id, max_room_stream_id,
  138. extra_users=[]):
  139. """ Used by handlers to inform the notifier something has happened
  140. in the room, room event wise.
  141. This triggers the notifier to wake up any listeners that are
  142. listening to the room, and any listeners for the users in the
  143. `extra_users` param.
  144. The events can be peristed out of order. The notifier will wait
  145. until all previous events have been persisted before notifying
  146. the client streams.
  147. """
  148. with PreserveLoggingContext():
  149. self.pending_new_room_events.append((
  150. room_stream_id, event, extra_users
  151. ))
  152. self._notify_pending_new_room_events(max_room_stream_id)
  153. self.notify_replication()
  154. @preserve_fn
  155. def _notify_pending_new_room_events(self, max_room_stream_id):
  156. """Notify for the room events that were queued waiting for a previous
  157. event to be persisted.
  158. Args:
  159. max_room_stream_id(int): The highest stream_id below which all
  160. events have been persisted.
  161. """
  162. pending = self.pending_new_room_events
  163. self.pending_new_room_events = []
  164. for room_stream_id, event, extra_users in pending:
  165. if room_stream_id > max_room_stream_id:
  166. self.pending_new_room_events.append((
  167. room_stream_id, event, extra_users
  168. ))
  169. else:
  170. self._on_new_room_event(event, room_stream_id, extra_users)
  171. @preserve_fn
  172. def _on_new_room_event(self, event, room_stream_id, extra_users=[]):
  173. """Notify any user streams that are interested in this room event"""
  174. # poke any interested application service.
  175. self.appservice_handler.notify_interested_services(room_stream_id)
  176. if event.type == EventTypes.Member and event.membership == Membership.JOIN:
  177. self._user_joined_room(event.state_key, event.room_id)
  178. self.on_new_event(
  179. "room_key", room_stream_id,
  180. users=extra_users,
  181. rooms=[event.room_id],
  182. )
  183. @preserve_fn
  184. def on_new_event(self, stream_key, new_token, users=[], rooms=[]):
  185. """ Used to inform listeners that something has happend event wise.
  186. Will wake up all listeners for the given users and rooms.
  187. """
  188. with PreserveLoggingContext():
  189. with Measure(self.clock, "on_new_event"):
  190. user_streams = set()
  191. for user in users:
  192. user_stream = self.user_to_user_stream.get(str(user))
  193. if user_stream is not None:
  194. user_streams.add(user_stream)
  195. for room in rooms:
  196. user_streams |= self.room_to_user_streams.get(room, set())
  197. time_now_ms = self.clock.time_msec()
  198. for user_stream in user_streams:
  199. try:
  200. user_stream.notify(stream_key, new_token, time_now_ms)
  201. except:
  202. logger.exception("Failed to notify listener")
  203. self.notify_replication()
  204. @preserve_fn
  205. def on_new_replication_data(self):
  206. """Used to inform replication listeners that something has happend
  207. without waking up any of the normal user event streams"""
  208. with PreserveLoggingContext():
  209. self.notify_replication()
  210. @defer.inlineCallbacks
  211. def wait_for_events(self, user_id, timeout, callback, room_ids=None,
  212. from_token=StreamToken.START):
  213. """Wait until the callback returns a non empty response or the
  214. timeout fires.
  215. """
  216. user_stream = self.user_to_user_stream.get(user_id)
  217. if user_stream is None:
  218. current_token = yield self.event_sources.get_current_token()
  219. if room_ids is None:
  220. rooms = yield self.store.get_rooms_for_user(user_id)
  221. room_ids = [room.room_id for room in rooms]
  222. user_stream = _NotifierUserStream(
  223. user_id=user_id,
  224. rooms=room_ids,
  225. current_token=current_token,
  226. time_now_ms=self.clock.time_msec(),
  227. )
  228. self._register_with_keys(user_stream)
  229. result = None
  230. if timeout:
  231. # Will be set to a _NotificationListener that we'll be waiting on.
  232. # Allows us to cancel it.
  233. listener = None
  234. def timed_out():
  235. if listener:
  236. listener.deferred.cancel()
  237. timer = self.clock.call_later(timeout / 1000., timed_out)
  238. prev_token = from_token
  239. while not result:
  240. try:
  241. current_token = user_stream.current_token
  242. result = yield callback(prev_token, current_token)
  243. if result:
  244. break
  245. # Now we wait for the _NotifierUserStream to be told there
  246. # is a new token.
  247. # We need to supply the token we supplied to callback so
  248. # that we don't miss any current_token updates.
  249. prev_token = current_token
  250. listener = user_stream.new_listener(prev_token)
  251. with PreserveLoggingContext():
  252. yield listener.deferred
  253. except defer.CancelledError:
  254. break
  255. self.clock.cancel_call_later(timer, ignore_errs=True)
  256. else:
  257. current_token = user_stream.current_token
  258. result = yield callback(from_token, current_token)
  259. defer.returnValue(result)
  260. @defer.inlineCallbacks
  261. def get_events_for(self, user, pagination_config, timeout,
  262. only_keys=None,
  263. is_guest=False, explicit_room_id=None):
  264. """ For the given user and rooms, return any new events for them. If
  265. there are no new events wait for up to `timeout` milliseconds for any
  266. new events to happen before returning.
  267. If `only_keys` is not None, events from keys will be sent down.
  268. If explicit_room_id is not set, the user's joined rooms will be polled
  269. for events.
  270. If explicit_room_id is set, that room will be polled for events only if
  271. it is world readable or the user has joined the room.
  272. """
  273. from_token = pagination_config.from_token
  274. if not from_token:
  275. from_token = yield self.event_sources.get_current_token()
  276. limit = pagination_config.limit
  277. room_ids, is_joined = yield self._get_room_ids(user, explicit_room_id)
  278. is_peeking = not is_joined
  279. @defer.inlineCallbacks
  280. def check_for_updates(before_token, after_token):
  281. if not after_token.is_after(before_token):
  282. defer.returnValue(EventStreamResult([], (from_token, from_token)))
  283. events = []
  284. end_token = from_token
  285. for name, source in self.event_sources.sources.items():
  286. keyname = "%s_key" % name
  287. before_id = getattr(before_token, keyname)
  288. after_id = getattr(after_token, keyname)
  289. if before_id == after_id:
  290. continue
  291. if only_keys and name not in only_keys:
  292. continue
  293. new_events, new_key = yield source.get_new_events(
  294. user=user,
  295. from_key=getattr(from_token, keyname),
  296. limit=limit,
  297. is_guest=is_peeking,
  298. room_ids=room_ids,
  299. )
  300. if name == "room":
  301. new_events = yield filter_events_for_client(
  302. self.store,
  303. user.to_string(),
  304. new_events,
  305. is_peeking=is_peeking,
  306. )
  307. events.extend(new_events)
  308. end_token = end_token.copy_and_replace(keyname, new_key)
  309. defer.returnValue(EventStreamResult(events, (from_token, end_token)))
  310. user_id_for_stream = user.to_string()
  311. if is_peeking:
  312. # Internally, the notifier keeps an event stream per user_id.
  313. # This is used by both /sync and /events.
  314. # We want /events to be used for peeking independently of /sync,
  315. # without polluting its contents. So we invent an illegal user ID
  316. # (which thus cannot clash with any real users) for keying peeking
  317. # over /events.
  318. #
  319. # I am sorry for what I have done.
  320. user_id_for_stream = "_PEEKING_%s_%s" % (
  321. explicit_room_id, user_id_for_stream
  322. )
  323. result = yield self.wait_for_events(
  324. user_id_for_stream,
  325. timeout,
  326. check_for_updates,
  327. room_ids=room_ids,
  328. from_token=from_token,
  329. )
  330. defer.returnValue(result)
  331. @defer.inlineCallbacks
  332. def _get_room_ids(self, user, explicit_room_id):
  333. joined_rooms = yield self.store.get_rooms_for_user(user.to_string())
  334. joined_room_ids = map(lambda r: r.room_id, joined_rooms)
  335. if explicit_room_id:
  336. if explicit_room_id in joined_room_ids:
  337. defer.returnValue(([explicit_room_id], True))
  338. if (yield self._is_world_readable(explicit_room_id)):
  339. defer.returnValue(([explicit_room_id], False))
  340. raise AuthError(403, "Non-joined access not allowed")
  341. defer.returnValue((joined_room_ids, True))
  342. @defer.inlineCallbacks
  343. def _is_world_readable(self, room_id):
  344. state = yield self.state_handler.get_current_state(
  345. room_id,
  346. EventTypes.RoomHistoryVisibility,
  347. "",
  348. )
  349. if state and "history_visibility" in state.content:
  350. defer.returnValue(state.content["history_visibility"] == "world_readable")
  351. else:
  352. defer.returnValue(False)
  353. @log_function
  354. def remove_expired_streams(self):
  355. time_now_ms = self.clock.time_msec()
  356. expired_streams = []
  357. expire_before_ts = time_now_ms - self.UNUSED_STREAM_EXPIRY_MS
  358. for stream in self.user_to_user_stream.values():
  359. if stream.count_listeners():
  360. continue
  361. if stream.last_notified_ms < expire_before_ts:
  362. expired_streams.append(stream)
  363. for expired_stream in expired_streams:
  364. expired_stream.remove(self)
  365. @log_function
  366. def _register_with_keys(self, user_stream):
  367. self.user_to_user_stream[user_stream.user_id] = user_stream
  368. for room in user_stream.rooms:
  369. s = self.room_to_user_streams.setdefault(room, set())
  370. s.add(user_stream)
  371. def _user_joined_room(self, user_id, room_id):
  372. new_user_stream = self.user_to_user_stream.get(user_id)
  373. if new_user_stream is not None:
  374. room_streams = self.room_to_user_streams.setdefault(room_id, set())
  375. room_streams.add(new_user_stream)
  376. new_user_stream.rooms.add(room_id)
  377. def notify_replication(self):
  378. """Notify the any replication listeners that there's a new event"""
  379. with PreserveLoggingContext():
  380. deferred = self.replication_deferred
  381. self.replication_deferred = ObservableDeferred(defer.Deferred())
  382. deferred.callback(None)
  383. @defer.inlineCallbacks
  384. def wait_for_replication(self, callback, timeout):
  385. """Wait for an event to happen.
  386. Args:
  387. callback: Gets called whenever an event happens. If this returns a
  388. truthy value then ``wait_for_replication`` returns, otherwise
  389. it waits for another event.
  390. timeout: How many milliseconds to wait for callback return a truthy
  391. value.
  392. Returns:
  393. A deferred that resolves with the value returned by the callback.
  394. """
  395. listener = _NotificationListener(None)
  396. def timed_out():
  397. listener.deferred.cancel()
  398. timer = self.clock.call_later(timeout / 1000., timed_out)
  399. while True:
  400. listener.deferred = self.replication_deferred.observe()
  401. result = yield callback()
  402. if result:
  403. break
  404. try:
  405. with PreserveLoggingContext():
  406. yield listener.deferred
  407. except defer.CancelledError:
  408. break
  409. self.clock.cancel_call_later(timer, ignore_errs=True)
  410. defer.returnValue(result)