notifier.py 19 KB

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