notifier.py 20 KB

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