notifier.py 21 KB

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