notifier.py 21 KB

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