notifier.py 25 KB

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