notifier.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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.logging.context import PreserveLoggingContext
  23. from synapse.logging.utils import log_function
  24. from synapse.metrics import LaterGauge
  25. from synapse.metrics.background_process_metrics import run_as_background_process
  26. from synapse.types import StreamToken
  27. from synapse.util.async_helpers import ObservableDeferred, timeout_deferred
  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. )
  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(stream_key, stream_id)
  81. self.last_notified_token = self.current_token
  82. self.last_notified_ms = time_now_ms
  83. noify_deferred = self.notify_deferred
  84. users_woken_by_stream_counter.labels(stream_key).inc()
  85. with PreserveLoggingContext():
  86. self.notify_deferred = ObservableDeferred(defer.Deferred())
  87. noify_deferred.callback(self.current_token)
  88. def remove(self, notifier):
  89. """ Remove this listener from all the indexes in the Notifier
  90. it knows about.
  91. """
  92. for room in self.rooms:
  93. lst = notifier.room_to_user_streams.get(room, set())
  94. lst.discard(self)
  95. notifier.user_to_user_stream.pop(self.user_id)
  96. def count_listeners(self):
  97. return len(self.notify_deferred.observers())
  98. def new_listener(self, token):
  99. """Returns a deferred that is resolved when there is a new token
  100. greater than the given token.
  101. Args:
  102. token: The token from which we are streaming from, i.e. we shouldn't
  103. notify for things that happened before this.
  104. """
  105. # Immediately wake up stream if something has already since happened
  106. # since their last token.
  107. if self.last_notified_token.is_after(token):
  108. return _NotificationListener(defer.succeed(self.current_token))
  109. else:
  110. return _NotificationListener(self.notify_deferred.observe())
  111. class EventStreamResult(namedtuple("EventStreamResult", ("events", "tokens"))):
  112. def __nonzero__(self):
  113. return bool(self.events)
  114. __bool__ = __nonzero__ # python3
  115. class Notifier(object):
  116. """ This class is responsible for notifying any listeners when there are
  117. new events available for it.
  118. Primarily used from the /events stream.
  119. """
  120. UNUSED_STREAM_EXPIRY_MS = 10 * 60 * 1000
  121. def __init__(self, hs):
  122. self.user_to_user_stream = {}
  123. self.room_to_user_streams = {}
  124. self.hs = hs
  125. self.storage = hs.get_storage()
  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. # 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 list(self.room_to_user_streams.values()):
  146. all_user_streams |= x
  147. for x in list(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. LaterGauge("synapse_notifier_listeners", "", [], count_listeners)
  151. LaterGauge(
  152. "synapse_notifier_rooms",
  153. "",
  154. [],
  155. lambda: count(bool, list(self.room_to_user_streams.values())),
  156. )
  157. LaterGauge(
  158. "synapse_notifier_users", "", [], 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. It should *not* return a Deferred - if
  163. it needs to do any asynchronous work, a background thread should be started and
  164. wrapped with run_as_background_process.
  165. """
  166. self.replication_callbacks.append(cb)
  167. def on_new_room_event(
  168. self, event, room_stream_id, max_room_stream_id, extra_users=[]
  169. ):
  170. """ Used by handlers to inform the notifier something has happened
  171. in the room, room event wise.
  172. This triggers the notifier to wake up any listeners that are
  173. listening to the room, and any listeners for the users in the
  174. `extra_users` param.
  175. The events can be peristed out of order. The notifier will wait
  176. until all previous events have been persisted before notifying
  177. the client streams.
  178. """
  179. self.pending_new_room_events.append((room_stream_id, event, extra_users))
  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_as_background_process(
  202. "notify_app_services", 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, users=extra_users, 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 happened 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(
  243. self, user_id, timeout, callback, room_ids=None, from_token=StreamToken.START
  244. ):
  245. """Wait until the callback returns a non empty response or the
  246. timeout fires.
  247. """
  248. user_stream = self.user_to_user_stream.get(user_id)
  249. if user_stream is None:
  250. current_token = yield self.event_sources.get_current_token()
  251. if room_ids is None:
  252. room_ids = yield self.store.get_rooms_for_user(user_id)
  253. user_stream = _NotifierUserStream(
  254. user_id=user_id,
  255. rooms=room_ids,
  256. current_token=current_token,
  257. time_now_ms=self.clock.time_msec(),
  258. )
  259. self._register_with_keys(user_stream)
  260. result = None
  261. prev_token = from_token
  262. if timeout:
  263. end_time = self.clock.time_msec() + timeout
  264. while not result:
  265. try:
  266. now = self.clock.time_msec()
  267. if end_time <= now:
  268. break
  269. # Now we wait for the _NotifierUserStream to be told there
  270. # is a new token.
  271. listener = user_stream.new_listener(prev_token)
  272. listener.deferred = timeout_deferred(
  273. listener.deferred,
  274. (end_time - now) / 1000.0,
  275. self.hs.get_reactor(),
  276. )
  277. with PreserveLoggingContext():
  278. yield listener.deferred
  279. current_token = user_stream.current_token
  280. result = yield callback(prev_token, current_token)
  281. if result:
  282. break
  283. # Update the prev_token to the current_token since nothing
  284. # has happened between the old prev_token and the current_token
  285. prev_token = current_token
  286. except defer.TimeoutError:
  287. break
  288. except defer.CancelledError:
  289. break
  290. if result is None:
  291. # This happened if there was no timeout or if the timeout had
  292. # already expired.
  293. current_token = user_stream.current_token
  294. result = yield callback(prev_token, current_token)
  295. return result
  296. @defer.inlineCallbacks
  297. def get_events_for(
  298. self,
  299. user,
  300. pagination_config,
  301. timeout,
  302. only_keys=None,
  303. is_guest=False,
  304. explicit_room_id=None,
  305. ):
  306. """ For the given user and rooms, return any new events for them. If
  307. there are no new events wait for up to `timeout` milliseconds for any
  308. new events to happen before returning.
  309. If `only_keys` is not None, events from keys will be sent down.
  310. If explicit_room_id is not set, the user's joined rooms will be polled
  311. for events.
  312. If explicit_room_id is set, that room will be polled for events only if
  313. it is world readable or the user has joined the room.
  314. """
  315. from_token = pagination_config.from_token
  316. if not from_token:
  317. from_token = yield self.event_sources.get_current_token()
  318. limit = pagination_config.limit
  319. room_ids, is_joined = yield self._get_room_ids(user, explicit_room_id)
  320. is_peeking = not is_joined
  321. @defer.inlineCallbacks
  322. def check_for_updates(before_token, after_token):
  323. if not after_token.is_after(before_token):
  324. return EventStreamResult([], (from_token, from_token))
  325. events = []
  326. end_token = from_token
  327. for name, source in self.event_sources.sources.items():
  328. keyname = "%s_key" % name
  329. before_id = getattr(before_token, keyname)
  330. after_id = getattr(after_token, keyname)
  331. if before_id == after_id:
  332. continue
  333. if only_keys and name not in only_keys:
  334. continue
  335. new_events, new_key = yield source.get_new_events(
  336. user=user,
  337. from_key=getattr(from_token, keyname),
  338. limit=limit,
  339. is_guest=is_peeking,
  340. room_ids=room_ids,
  341. explicit_room_id=explicit_room_id,
  342. )
  343. if name == "room":
  344. new_events = yield filter_events_for_client(
  345. self.storage,
  346. user.to_string(),
  347. new_events,
  348. is_peeking=is_peeking,
  349. )
  350. elif name == "presence":
  351. now = self.clock.time_msec()
  352. new_events[:] = [
  353. {
  354. "type": "m.presence",
  355. "content": format_user_presence_state(event, now),
  356. }
  357. for event in new_events
  358. ]
  359. events.extend(new_events)
  360. end_token = end_token.copy_and_replace(keyname, new_key)
  361. return EventStreamResult(events, (from_token, end_token))
  362. user_id_for_stream = user.to_string()
  363. if is_peeking:
  364. # Internally, the notifier keeps an event stream per user_id.
  365. # This is used by both /sync and /events.
  366. # We want /events to be used for peeking independently of /sync,
  367. # without polluting its contents. So we invent an illegal user ID
  368. # (which thus cannot clash with any real users) for keying peeking
  369. # over /events.
  370. #
  371. # I am sorry for what I have done.
  372. user_id_for_stream = "_PEEKING_%s_%s" % (
  373. explicit_room_id,
  374. user_id_for_stream,
  375. )
  376. result = yield self.wait_for_events(
  377. user_id_for_stream,
  378. timeout,
  379. check_for_updates,
  380. room_ids=room_ids,
  381. from_token=from_token,
  382. )
  383. return result
  384. @defer.inlineCallbacks
  385. def _get_room_ids(self, user, explicit_room_id):
  386. joined_room_ids = yield self.store.get_rooms_for_user(user.to_string())
  387. if explicit_room_id:
  388. if explicit_room_id in joined_room_ids:
  389. return [explicit_room_id], True
  390. if (yield self._is_world_readable(explicit_room_id)):
  391. return [explicit_room_id], False
  392. raise AuthError(403, "Non-joined access not allowed")
  393. return joined_room_ids, True
  394. @defer.inlineCallbacks
  395. def _is_world_readable(self, room_id):
  396. state = yield self.state_handler.get_current_state(
  397. room_id, EventTypes.RoomHistoryVisibility, ""
  398. )
  399. if state and "history_visibility" in state.content:
  400. return state.content["history_visibility"] == "world_readable"
  401. else:
  402. return False
  403. @log_function
  404. def remove_expired_streams(self):
  405. time_now_ms = self.clock.time_msec()
  406. expired_streams = []
  407. expire_before_ts = time_now_ms - self.UNUSED_STREAM_EXPIRY_MS
  408. for stream in self.user_to_user_stream.values():
  409. if stream.count_listeners():
  410. continue
  411. if stream.last_notified_ms < expire_before_ts:
  412. expired_streams.append(stream)
  413. for expired_stream in expired_streams:
  414. expired_stream.remove(self)
  415. @log_function
  416. def _register_with_keys(self, user_stream):
  417. self.user_to_user_stream[user_stream.user_id] = user_stream
  418. for room in user_stream.rooms:
  419. s = self.room_to_user_streams.setdefault(room, set())
  420. s.add(user_stream)
  421. def _user_joined_room(self, user_id, room_id):
  422. new_user_stream = self.user_to_user_stream.get(user_id)
  423. if new_user_stream is not None:
  424. room_streams = self.room_to_user_streams.setdefault(room_id, set())
  425. room_streams.add(new_user_stream)
  426. new_user_stream.rooms.add(room_id)
  427. def notify_replication(self):
  428. """Notify the any replication listeners that there's a new event"""
  429. for cb in self.replication_callbacks:
  430. cb()