PageRenderTime 28ms CodeModel.GetById 43ms RepoModel.GetById 6ms app.codeStats 0ms

/synapse/notifier.py

https://gitlab.com/JigmeDatse/synapse
Python | 533 lines | 358 code | 62 blank | 113 comment | 41 complexity | 54cc5f5ec4c0af0d80d7c3ef1780043d MD5 | raw file
  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.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. self.clock.looping_call(
  120. self.remove_expired_streams, self.UNUSED_STREAM_EXPIRY_MS
  121. )
  122. self.replication_deferred = ObservableDeferred(defer.Deferred())
  123. # This is not a very cheap test to perform, but it's only executed
  124. # when rendering the metrics page, which is likely once per minute at
  125. # most when scraping it.
  126. def count_listeners():
  127. all_user_streams = set()
  128. for x in self.room_to_user_streams.values():
  129. all_user_streams |= x
  130. for x in self.user_to_user_stream.values():
  131. all_user_streams.add(x)
  132. for x in self.appservice_to_user_streams.values():
  133. all_user_streams |= x
  134. return sum(stream.count_listeners() for stream in all_user_streams)
  135. metrics.register_callback("listeners", count_listeners)
  136. metrics.register_callback(
  137. "rooms",
  138. lambda: count(bool, self.room_to_user_streams.values()),
  139. )
  140. metrics.register_callback(
  141. "users",
  142. lambda: len(self.user_to_user_stream),
  143. )
  144. metrics.register_callback(
  145. "appservices",
  146. lambda: count(bool, self.appservice_to_user_streams.values()),
  147. )
  148. def on_new_room_event(self, event, room_stream_id, max_room_stream_id,
  149. extra_users=[]):
  150. """ Used by handlers to inform the notifier something has happened
  151. in the room, room event wise.
  152. This triggers the notifier to wake up any listeners that are
  153. listening to the room, and any listeners for the users in the
  154. `extra_users` param.
  155. The events can be peristed out of order. The notifier will wait
  156. until all previous events have been persisted before notifying
  157. the client streams.
  158. """
  159. with PreserveLoggingContext():
  160. self.pending_new_room_events.append((
  161. room_stream_id, event, extra_users
  162. ))
  163. self._notify_pending_new_room_events(max_room_stream_id)
  164. self.notify_replication()
  165. def _notify_pending_new_room_events(self, max_room_stream_id):
  166. """Notify for the room events that were queued waiting for a previous
  167. event to be persisted.
  168. Args:
  169. max_room_stream_id(int): The highest stream_id below which all
  170. events have been persisted.
  171. """
  172. pending = self.pending_new_room_events
  173. self.pending_new_room_events = []
  174. for room_stream_id, event, extra_users in pending:
  175. if room_stream_id > max_room_stream_id:
  176. self.pending_new_room_events.append((
  177. room_stream_id, event, extra_users
  178. ))
  179. else:
  180. self._on_new_room_event(event, room_stream_id, extra_users)
  181. def _on_new_room_event(self, event, room_stream_id, extra_users=[]):
  182. """Notify any user streams that are interested in this room event"""
  183. # poke any interested application service.
  184. self.appservice_handler.notify_interested_services(event)
  185. app_streams = set()
  186. for appservice in self.appservice_to_user_streams:
  187. # TODO (kegan): Redundant appservice listener checks?
  188. # App services will already be in the room_to_user_streams set, but
  189. # that isn't enough. They need to be checked here in order to
  190. # receive *invites* for users they are interested in. Does this
  191. # make the room_to_user_streams check somewhat obselete?
  192. if appservice.is_interested(event):
  193. app_user_streams = self.appservice_to_user_streams.get(
  194. appservice, set()
  195. )
  196. app_streams |= app_user_streams
  197. if event.type == EventTypes.Member and event.membership == Membership.JOIN:
  198. self._user_joined_room(event.state_key, event.room_id)
  199. self.on_new_event(
  200. "room_key", room_stream_id,
  201. users=extra_users,
  202. rooms=[event.room_id],
  203. extra_streams=app_streams,
  204. )
  205. def on_new_event(self, stream_key, new_token, users=[], rooms=[],
  206. extra_streams=set()):
  207. """ Used to inform listeners that something has happend event wise.
  208. Will wake up all listeners for the given users and rooms.
  209. """
  210. with PreserveLoggingContext():
  211. user_streams = set()
  212. for user in users:
  213. user_stream = self.user_to_user_stream.get(str(user))
  214. if user_stream is not None:
  215. user_streams.add(user_stream)
  216. for room in rooms:
  217. user_streams |= self.room_to_user_streams.get(room, set())
  218. time_now_ms = self.clock.time_msec()
  219. for user_stream in user_streams:
  220. try:
  221. user_stream.notify(stream_key, new_token, time_now_ms)
  222. except:
  223. logger.exception("Failed to notify listener")
  224. self.notify_replication()
  225. def on_new_replication_data(self):
  226. """Used to inform replication listeners that something has happend
  227. without waking up any of the normal user event streams"""
  228. with PreserveLoggingContext():
  229. self.notify_replication()
  230. @defer.inlineCallbacks
  231. def wait_for_events(self, user_id, timeout, callback, room_ids=None,
  232. from_token=StreamToken.START):
  233. """Wait until the callback returns a non empty response or the
  234. timeout fires.
  235. """
  236. user_stream = self.user_to_user_stream.get(user_id)
  237. if user_stream is None:
  238. appservice = yield self.store.get_app_service_by_user_id(user_id)
  239. current_token = yield self.event_sources.get_current_token()
  240. if room_ids is None:
  241. rooms = yield self.store.get_rooms_for_user(user_id)
  242. room_ids = [room.room_id for room in rooms]
  243. user_stream = _NotifierUserStream(
  244. user_id=user_id,
  245. rooms=room_ids,
  246. appservice=appservice,
  247. current_token=current_token,
  248. time_now_ms=self.clock.time_msec(),
  249. )
  250. self._register_with_keys(user_stream)
  251. result = None
  252. if timeout:
  253. # Will be set to a _NotificationListener that we'll be waiting on.
  254. # Allows us to cancel it.
  255. listener = None
  256. def timed_out():
  257. if listener:
  258. listener.deferred.cancel()
  259. timer = self.clock.call_later(timeout / 1000., timed_out)
  260. prev_token = from_token
  261. while not result:
  262. try:
  263. current_token = user_stream.current_token
  264. result = yield callback(prev_token, current_token)
  265. if result:
  266. break
  267. # Now we wait for the _NotifierUserStream to be told there
  268. # is a new token.
  269. # We need to supply the token we supplied to callback so
  270. # that we don't miss any current_token updates.
  271. prev_token = current_token
  272. listener = user_stream.new_listener(prev_token)
  273. with PreserveLoggingContext():
  274. yield listener.deferred
  275. except defer.CancelledError:
  276. break
  277. self.clock.cancel_call_later(timer, ignore_errs=True)
  278. else:
  279. current_token = user_stream.current_token
  280. result = yield callback(from_token, current_token)
  281. defer.returnValue(result)
  282. @defer.inlineCallbacks
  283. def get_events_for(self, user, pagination_config, timeout,
  284. only_keys=None,
  285. is_guest=False, explicit_room_id=None):
  286. """ For the given user and rooms, return any new events for them. If
  287. there are no new events wait for up to `timeout` milliseconds for any
  288. new events to happen before returning.
  289. If `only_keys` is not None, events from keys will be sent down.
  290. If explicit_room_id is not set, the user's joined rooms will be polled
  291. for events.
  292. If explicit_room_id is set, that room will be polled for events only if
  293. it is world readable or the user has joined the room.
  294. """
  295. from_token = pagination_config.from_token
  296. if not from_token:
  297. from_token = yield self.event_sources.get_current_token()
  298. limit = pagination_config.limit
  299. room_ids, is_joined = yield self._get_room_ids(user, explicit_room_id)
  300. is_peeking = not is_joined
  301. @defer.inlineCallbacks
  302. def check_for_updates(before_token, after_token):
  303. if not after_token.is_after(before_token):
  304. defer.returnValue(EventStreamResult([], (from_token, from_token)))
  305. events = []
  306. end_token = from_token
  307. for name, source in self.event_sources.sources.items():
  308. keyname = "%s_key" % name
  309. before_id = getattr(before_token, keyname)
  310. after_id = getattr(after_token, keyname)
  311. if before_id == after_id:
  312. continue
  313. if only_keys and name not in only_keys:
  314. continue
  315. new_events, new_key = yield source.get_new_events(
  316. user=user,
  317. from_key=getattr(from_token, keyname),
  318. limit=limit,
  319. is_guest=is_peeking,
  320. room_ids=room_ids,
  321. )
  322. if name == "room":
  323. new_events = yield filter_events_for_client(
  324. self.store,
  325. user.to_string(),
  326. new_events,
  327. is_peeking=is_peeking,
  328. )
  329. events.extend(new_events)
  330. end_token = end_token.copy_and_replace(keyname, new_key)
  331. defer.returnValue(EventStreamResult(events, (from_token, end_token)))
  332. user_id_for_stream = user.to_string()
  333. if is_peeking:
  334. # Internally, the notifier keeps an event stream per user_id.
  335. # This is used by both /sync and /events.
  336. # We want /events to be used for peeking independently of /sync,
  337. # without polluting its contents. So we invent an illegal user ID
  338. # (which thus cannot clash with any real users) for keying peeking
  339. # over /events.
  340. #
  341. # I am sorry for what I have done.
  342. user_id_for_stream = "_PEEKING_%s_%s" % (
  343. explicit_room_id, user_id_for_stream
  344. )
  345. result = yield self.wait_for_events(
  346. user_id_for_stream,
  347. timeout,
  348. check_for_updates,
  349. room_ids=room_ids,
  350. from_token=from_token,
  351. )
  352. defer.returnValue(result)
  353. @defer.inlineCallbacks
  354. def _get_room_ids(self, user, explicit_room_id):
  355. joined_rooms = yield self.store.get_rooms_for_user(user.to_string())
  356. joined_room_ids = map(lambda r: r.room_id, joined_rooms)
  357. if explicit_room_id:
  358. if explicit_room_id in joined_room_ids:
  359. defer.returnValue(([explicit_room_id], True))
  360. if (yield self._is_world_readable(explicit_room_id)):
  361. defer.returnValue(([explicit_room_id], False))
  362. raise AuthError(403, "Non-joined access not allowed")
  363. defer.returnValue((joined_room_ids, True))
  364. @defer.inlineCallbacks
  365. def _is_world_readable(self, room_id):
  366. state = yield self.state_handler.get_current_state(
  367. room_id,
  368. EventTypes.RoomHistoryVisibility
  369. )
  370. if state and "history_visibility" in state.content:
  371. defer.returnValue(state.content["history_visibility"] == "world_readable")
  372. else:
  373. defer.returnValue(False)
  374. @log_function
  375. def remove_expired_streams(self):
  376. time_now_ms = self.clock.time_msec()
  377. expired_streams = []
  378. expire_before_ts = time_now_ms - self.UNUSED_STREAM_EXPIRY_MS
  379. for stream in self.user_to_user_stream.values():
  380. if stream.count_listeners():
  381. continue
  382. if stream.last_notified_ms < expire_before_ts:
  383. expired_streams.append(stream)
  384. for expired_stream in expired_streams:
  385. expired_stream.remove(self)
  386. @log_function
  387. def _register_with_keys(self, user_stream):
  388. self.user_to_user_stream[user_stream.user_id] = user_stream
  389. for room in user_stream.rooms:
  390. s = self.room_to_user_streams.setdefault(room, set())
  391. s.add(user_stream)
  392. if user_stream.appservice:
  393. self.appservice_to_user_stream.setdefault(
  394. user_stream.appservice, set()
  395. ).add(user_stream)
  396. def _user_joined_room(self, user_id, room_id):
  397. new_user_stream = self.user_to_user_stream.get(user_id)
  398. if new_user_stream is not None:
  399. room_streams = self.room_to_user_streams.setdefault(room_id, set())
  400. room_streams.add(new_user_stream)
  401. new_user_stream.rooms.add(room_id)
  402. def notify_replication(self):
  403. """Notify the any replication listeners that there's a new event"""
  404. with PreserveLoggingContext():
  405. deferred = self.replication_deferred
  406. self.replication_deferred = ObservableDeferred(defer.Deferred())
  407. deferred.callback(None)
  408. @defer.inlineCallbacks
  409. def wait_for_replication(self, callback, timeout):
  410. """Wait for an event to happen.
  411. Args:
  412. callback: Gets called whenever an event happens. If this returns a
  413. truthy value then ``wait_for_replication`` returns, otherwise
  414. it waits for another event.
  415. timeout: How many milliseconds to wait for callback return a truthy
  416. value.
  417. Returns:
  418. A deferred that resolves with the value returned by the callback.
  419. """
  420. listener = _NotificationListener(None)
  421. def timed_out():
  422. listener.deferred.cancel()
  423. timer = self.clock.call_later(timeout / 1000., timed_out)
  424. while True:
  425. listener.deferred = self.replication_deferred.observe()
  426. result = yield callback()
  427. if result:
  428. break
  429. try:
  430. with PreserveLoggingContext():
  431. yield listener.deferred
  432. except defer.CancelledError:
  433. break
  434. self.clock.cancel_call_later(timer, ignore_errs=True)
  435. defer.returnValue(result)