notifier.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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.federation_sender = hs.get_federation_sender()
  113. self.state_handler = hs.get_state_handler()
  114. self.clock.looping_call(
  115. self.remove_expired_streams, self.UNUSED_STREAM_EXPIRY_MS
  116. )
  117. self.replication_deferred = ObservableDeferred(defer.Deferred())
  118. # This is not a very cheap test to perform, but it's only executed
  119. # when rendering the metrics page, which is likely once per minute at
  120. # most when scraping it.
  121. def count_listeners():
  122. all_user_streams = set()
  123. for x in self.room_to_user_streams.values():
  124. all_user_streams |= x
  125. for x in self.user_to_user_stream.values():
  126. all_user_streams.add(x)
  127. return sum(stream.count_listeners() for stream in all_user_streams)
  128. metrics.register_callback("listeners", count_listeners)
  129. metrics.register_callback(
  130. "rooms",
  131. lambda: count(bool, self.room_to_user_streams.values()),
  132. )
  133. metrics.register_callback(
  134. "users",
  135. lambda: len(self.user_to_user_stream),
  136. )
  137. @preserve_fn
  138. def on_new_room_event(self, event, room_stream_id, max_room_stream_id,
  139. extra_users=[]):
  140. """ Used by handlers to inform the notifier something has happened
  141. in the room, room event wise.
  142. This triggers the notifier to wake up any listeners that are
  143. listening to the room, and any listeners for the users in the
  144. `extra_users` param.
  145. The events can be peristed out of order. The notifier will wait
  146. until all previous events have been persisted before notifying
  147. the client streams.
  148. """
  149. with PreserveLoggingContext():
  150. self.pending_new_room_events.append((
  151. room_stream_id, event, extra_users
  152. ))
  153. self._notify_pending_new_room_events(max_room_stream_id)
  154. self.notify_replication()
  155. @preserve_fn
  156. def _notify_pending_new_room_events(self, max_room_stream_id):
  157. """Notify for the room events that were queued waiting for a previous
  158. event to be persisted.
  159. Args:
  160. max_room_stream_id(int): The highest stream_id below which all
  161. events have been persisted.
  162. """
  163. pending = self.pending_new_room_events
  164. self.pending_new_room_events = []
  165. for room_stream_id, event, extra_users in pending:
  166. if room_stream_id > max_room_stream_id:
  167. self.pending_new_room_events.append((
  168. room_stream_id, event, extra_users
  169. ))
  170. else:
  171. self._on_new_room_event(event, room_stream_id, extra_users)
  172. @preserve_fn
  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.appservice_handler.notify_interested_services(room_stream_id)
  177. self.federation_sender.notify_new_events(room_stream_id)
  178. if event.type == EventTypes.Member and event.membership == Membership.JOIN:
  179. self._user_joined_room(event.state_key, event.room_id)
  180. self.on_new_event(
  181. "room_key", room_stream_id,
  182. users=extra_users,
  183. rooms=[event.room_id],
  184. )
  185. @preserve_fn
  186. def on_new_event(self, stream_key, new_token, users=[], rooms=[]):
  187. """ Used to inform listeners that something has happend event wise.
  188. Will wake up all listeners for the given users and rooms.
  189. """
  190. with PreserveLoggingContext():
  191. with Measure(self.clock, "on_new_event"):
  192. user_streams = set()
  193. for user in users:
  194. user_stream = self.user_to_user_stream.get(str(user))
  195. if user_stream is not None:
  196. user_streams.add(user_stream)
  197. for room in rooms:
  198. user_streams |= self.room_to_user_streams.get(room, set())
  199. time_now_ms = self.clock.time_msec()
  200. for user_stream in user_streams:
  201. try:
  202. user_stream.notify(stream_key, new_token, time_now_ms)
  203. except:
  204. logger.exception("Failed to notify listener")
  205. self.notify_replication()
  206. @preserve_fn
  207. def on_new_replication_data(self):
  208. """Used to inform replication listeners that something has happend
  209. without waking up any of the normal user event streams"""
  210. with PreserveLoggingContext():
  211. self.notify_replication()
  212. @defer.inlineCallbacks
  213. def wait_for_events(self, user_id, timeout, callback, room_ids=None,
  214. from_token=StreamToken.START):
  215. """Wait until the callback returns a non empty response or the
  216. timeout fires.
  217. """
  218. user_stream = self.user_to_user_stream.get(user_id)
  219. if user_stream is None:
  220. current_token = yield self.event_sources.get_current_token()
  221. if room_ids is None:
  222. rooms = yield self.store.get_rooms_for_user(user_id)
  223. room_ids = [room.room_id for room in rooms]
  224. user_stream = _NotifierUserStream(
  225. user_id=user_id,
  226. rooms=room_ids,
  227. current_token=current_token,
  228. time_now_ms=self.clock.time_msec(),
  229. )
  230. self._register_with_keys(user_stream)
  231. result = None
  232. if timeout:
  233. # Will be set to a _NotificationListener that we'll be waiting on.
  234. # Allows us to cancel it.
  235. listener = None
  236. def timed_out():
  237. if listener:
  238. listener.deferred.cancel()
  239. timer = self.clock.call_later(timeout / 1000., timed_out)
  240. prev_token = from_token
  241. while not result:
  242. try:
  243. current_token = user_stream.current_token
  244. result = yield callback(prev_token, current_token)
  245. if result:
  246. break
  247. # Now we wait for the _NotifierUserStream to be told there
  248. # is a new token.
  249. # We need to supply the token we supplied to callback so
  250. # that we don't miss any current_token updates.
  251. prev_token = current_token
  252. listener = user_stream.new_listener(prev_token)
  253. with PreserveLoggingContext():
  254. yield listener.deferred
  255. except defer.CancelledError:
  256. break
  257. self.clock.cancel_call_later(timer, ignore_errs=True)
  258. else:
  259. current_token = user_stream.current_token
  260. result = yield callback(from_token, current_token)
  261. defer.returnValue(result)
  262. @defer.inlineCallbacks
  263. def get_events_for(self, user, pagination_config, timeout,
  264. only_keys=None,
  265. is_guest=False, explicit_room_id=None):
  266. """ For the given user and rooms, return any new events for them. If
  267. there are no new events wait for up to `timeout` milliseconds for any
  268. new events to happen before returning.
  269. If `only_keys` is not None, events from keys will be sent down.
  270. If explicit_room_id is not set, the user's joined rooms will be polled
  271. for events.
  272. If explicit_room_id is set, that room will be polled for events only if
  273. it is world readable or the user has joined the room.
  274. """
  275. from_token = pagination_config.from_token
  276. if not from_token:
  277. from_token = yield self.event_sources.get_current_token()
  278. limit = pagination_config.limit
  279. room_ids, is_joined = yield self._get_room_ids(user, explicit_room_id)
  280. is_peeking = not is_joined
  281. @defer.inlineCallbacks
  282. def check_for_updates(before_token, after_token):
  283. if not after_token.is_after(before_token):
  284. defer.returnValue(EventStreamResult([], (from_token, from_token)))
  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_keys and name not in only_keys:
  294. continue
  295. new_events, new_key = yield source.get_new_events(
  296. user=user,
  297. from_key=getattr(from_token, keyname),
  298. limit=limit,
  299. is_guest=is_peeking,
  300. room_ids=room_ids,
  301. )
  302. if name == "room":
  303. new_events = yield filter_events_for_client(
  304. self.store,
  305. user.to_string(),
  306. new_events,
  307. is_peeking=is_peeking,
  308. )
  309. events.extend(new_events)
  310. end_token = end_token.copy_and_replace(keyname, new_key)
  311. defer.returnValue(EventStreamResult(events, (from_token, end_token)))
  312. user_id_for_stream = user.to_string()
  313. if is_peeking:
  314. # Internally, the notifier keeps an event stream per user_id.
  315. # This is used by both /sync and /events.
  316. # We want /events to be used for peeking independently of /sync,
  317. # without polluting its contents. So we invent an illegal user ID
  318. # (which thus cannot clash with any real users) for keying peeking
  319. # over /events.
  320. #
  321. # I am sorry for what I have done.
  322. user_id_for_stream = "_PEEKING_%s_%s" % (
  323. explicit_room_id, user_id_for_stream
  324. )
  325. result = yield self.wait_for_events(
  326. user_id_for_stream,
  327. timeout,
  328. check_for_updates,
  329. room_ids=room_ids,
  330. from_token=from_token,
  331. )
  332. defer.returnValue(result)
  333. @defer.inlineCallbacks
  334. def _get_room_ids(self, user, explicit_room_id):
  335. joined_rooms = yield self.store.get_rooms_for_user(user.to_string())
  336. joined_room_ids = map(lambda r: r.room_id, joined_rooms)
  337. if explicit_room_id:
  338. if explicit_room_id in joined_room_ids:
  339. defer.returnValue(([explicit_room_id], True))
  340. if (yield self._is_world_readable(explicit_room_id)):
  341. defer.returnValue(([explicit_room_id], False))
  342. raise AuthError(403, "Non-joined access not allowed")
  343. defer.returnValue((joined_room_ids, True))
  344. @defer.inlineCallbacks
  345. def _is_world_readable(self, room_id):
  346. state = yield self.state_handler.get_current_state(
  347. room_id,
  348. EventTypes.RoomHistoryVisibility,
  349. "",
  350. )
  351. if state and "history_visibility" in state.content:
  352. defer.returnValue(state.content["history_visibility"] == "world_readable")
  353. else:
  354. defer.returnValue(False)
  355. @log_function
  356. def remove_expired_streams(self):
  357. time_now_ms = self.clock.time_msec()
  358. expired_streams = []
  359. expire_before_ts = time_now_ms - self.UNUSED_STREAM_EXPIRY_MS
  360. for stream in self.user_to_user_stream.values():
  361. if stream.count_listeners():
  362. continue
  363. if stream.last_notified_ms < expire_before_ts:
  364. expired_streams.append(stream)
  365. for expired_stream in expired_streams:
  366. expired_stream.remove(self)
  367. @log_function
  368. def _register_with_keys(self, user_stream):
  369. self.user_to_user_stream[user_stream.user_id] = user_stream
  370. for room in user_stream.rooms:
  371. s = self.room_to_user_streams.setdefault(room, set())
  372. s.add(user_stream)
  373. def _user_joined_room(self, user_id, room_id):
  374. new_user_stream = self.user_to_user_stream.get(user_id)
  375. if new_user_stream is not None:
  376. room_streams = self.room_to_user_streams.setdefault(room_id, set())
  377. room_streams.add(new_user_stream)
  378. new_user_stream.rooms.add(room_id)
  379. def notify_replication(self):
  380. """Notify the any replication listeners that there's a new event"""
  381. with PreserveLoggingContext():
  382. deferred = self.replication_deferred
  383. self.replication_deferred = ObservableDeferred(defer.Deferred())
  384. deferred.callback(None)
  385. @defer.inlineCallbacks
  386. def wait_for_replication(self, callback, timeout):
  387. """Wait for an event to happen.
  388. Args:
  389. callback: Gets called whenever an event happens. If this returns a
  390. truthy value then ``wait_for_replication`` returns, otherwise
  391. it waits for another event.
  392. timeout: How many milliseconds to wait for callback return a truthy
  393. value.
  394. Returns:
  395. A deferred that resolves with the value returned by the callback.
  396. """
  397. listener = _NotificationListener(None)
  398. def timed_out():
  399. listener.deferred.cancel()
  400. timer = self.clock.call_later(timeout / 1000., timed_out)
  401. while True:
  402. listener.deferred = self.replication_deferred.observe()
  403. result = yield callback()
  404. if result:
  405. break
  406. try:
  407. with PreserveLoggingContext():
  408. yield listener.deferred
  409. except defer.CancelledError:
  410. break
  411. self.clock.cancel_call_later(timer, ignore_errs=True)
  412. defer.returnValue(result)