notifier.py 25 KB

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