notifier.py 21 KB

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