notifier.py 22 KB

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