notifier.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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 typing import (
  16. TYPE_CHECKING,
  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. from synapse.api.constants import EduTypes, EventTypes, HistoryVisibility, 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 import issue9533_logger
  37. from synapse.logging.context import PreserveLoggingContext
  38. from synapse.logging.opentracing import log_kv, start_active_span
  39. from synapse.metrics import LaterGauge
  40. from synapse.streams.config import PaginationConfig
  41. from synapse.types import (
  42. JsonDict,
  43. PersistedEventPosition,
  44. RoomStreamToken,
  45. StrCollection,
  46. StreamKeyType,
  47. StreamToken,
  48. UserID,
  49. )
  50. from synapse.util.async_helpers import ObservableDeferred, timeout_deferred
  51. from synapse.util.metrics import Measure
  52. from synapse.visibility import filter_events_for_client
  53. if TYPE_CHECKING:
  54. from synapse.server import HomeServer
  55. logger = logging.getLogger(__name__)
  56. notified_events_counter = Counter("synapse_notifier_notified_events", "")
  57. users_woken_by_stream_counter = Counter(
  58. "synapse_notifier_users_woken_by_stream", "", ["stream"]
  59. )
  60. T = TypeVar("T")
  61. # TODO(paul): Should be shared somewhere
  62. def count(func: Callable[[T], bool], it: Iterable[T]) -> int:
  63. """Return the number of items in it for which func returns true."""
  64. n = 0
  65. for x in it:
  66. if func(x):
  67. n += 1
  68. return n
  69. class _NotificationListener:
  70. """This represents a single client connection to the events stream.
  71. The events stream handler will have yielded to the deferred, so to
  72. notify the handler it is sufficient to resolve the deferred.
  73. """
  74. __slots__ = ["deferred"]
  75. def __init__(self, deferred: "defer.Deferred"):
  76. self.deferred = deferred
  77. class _NotifierUserStream:
  78. """This represents a user connected to the event stream.
  79. It tracks the most recent stream token for that user.
  80. At a given point a user may have a number of streams listening for
  81. events.
  82. This listener will also keep track of which rooms it is listening in
  83. so that it can remove itself from the indexes in the Notifier class.
  84. """
  85. def __init__(
  86. self,
  87. user_id: str,
  88. rooms: Collection[str],
  89. current_token: StreamToken,
  90. time_now_ms: int,
  91. ):
  92. self.user_id = user_id
  93. self.rooms = set(rooms)
  94. self.current_token = current_token
  95. # The last token for which we should wake up any streams that have a
  96. # token that comes before it. This gets updated every time we get poked.
  97. # We start it at the current token since if we get any streams
  98. # that have a token from before we have no idea whether they should be
  99. # woken up or not, so lets just wake them up.
  100. self.last_notified_token = current_token
  101. self.last_notified_ms = time_now_ms
  102. self.notify_deferred: ObservableDeferred[StreamToken] = ObservableDeferred(
  103. defer.Deferred()
  104. )
  105. def notify(
  106. self,
  107. stream_key: str,
  108. stream_id: Union[int, RoomStreamToken],
  109. time_now_ms: int,
  110. ) -> None:
  111. """Notify any listeners for this user of a new event from an
  112. event source.
  113. Args:
  114. stream_key: The stream the event came from.
  115. stream_id: The new id for the stream the event came from.
  116. time_now_ms: The current time in milliseconds.
  117. """
  118. self.current_token = self.current_token.copy_and_advance(stream_key, stream_id)
  119. self.last_notified_token = self.current_token
  120. self.last_notified_ms = time_now_ms
  121. notify_deferred = self.notify_deferred
  122. log_kv(
  123. {
  124. "notify": self.user_id,
  125. "stream": stream_key,
  126. "stream_id": stream_id,
  127. "listeners": self.count_listeners(),
  128. }
  129. )
  130. users_woken_by_stream_counter.labels(stream_key).inc()
  131. with PreserveLoggingContext():
  132. self.notify_deferred = ObservableDeferred(defer.Deferred())
  133. notify_deferred.callback(self.current_token)
  134. def remove(self, notifier: "Notifier") -> None:
  135. """Remove this listener from all the indexes in the Notifier
  136. it knows about.
  137. """
  138. for room in self.rooms:
  139. lst = notifier.room_to_user_streams.get(room, set())
  140. lst.discard(self)
  141. notifier.user_to_user_stream.pop(self.user_id)
  142. def count_listeners(self) -> int:
  143. return len(self.notify_deferred.observers())
  144. def new_listener(self, token: StreamToken) -> _NotificationListener:
  145. """Returns a deferred that is resolved when there is a new token
  146. greater than the given token.
  147. Args:
  148. token: The token from which we are streaming from, i.e. we shouldn't
  149. notify for things that happened before this.
  150. """
  151. # Immediately wake up stream if something has already since happened
  152. # since their last token.
  153. if self.last_notified_token != token:
  154. return _NotificationListener(defer.succeed(self.current_token))
  155. else:
  156. return _NotificationListener(self.notify_deferred.observe())
  157. @attr.s(slots=True, frozen=True, auto_attribs=True)
  158. class EventStreamResult:
  159. events: List[Union[JsonDict, EventBase]]
  160. start_token: StreamToken
  161. end_token: StreamToken
  162. def __bool__(self) -> bool:
  163. return bool(self.events)
  164. @attr.s(slots=True, frozen=True, auto_attribs=True)
  165. class _PendingRoomEventEntry:
  166. event_pos: PersistedEventPosition
  167. extra_users: Collection[UserID]
  168. room_id: str
  169. type: str
  170. state_key: Optional[str]
  171. membership: Optional[str]
  172. class Notifier:
  173. """This class is responsible for notifying any listeners when there are
  174. new events available for it.
  175. Primarily used from the /events stream.
  176. """
  177. UNUSED_STREAM_EXPIRY_MS = 10 * 60 * 1000
  178. def __init__(self, hs: "HomeServer"):
  179. self.user_to_user_stream: Dict[str, _NotifierUserStream] = {}
  180. self.room_to_user_streams: Dict[str, Set[_NotifierUserStream]] = {}
  181. self.hs = hs
  182. self._storage_controllers = hs.get_storage_controllers()
  183. self.event_sources = hs.get_event_sources()
  184. self.store = hs.get_datastores().main
  185. self.pending_new_room_events: List[_PendingRoomEventEntry] = []
  186. self._replication_notifier = hs.get_replication_notifier()
  187. self._new_join_in_room_callbacks: List[Callable[[str, str], None]] = []
  188. self._federation_client = hs.get_federation_http_client()
  189. self._third_party_rules = hs.get_third_party_event_rules()
  190. self.clock = hs.get_clock()
  191. self.appservice_handler = hs.get_application_service_handler()
  192. self._pusher_pool = hs.get_pusherpool()
  193. self.federation_sender = None
  194. if hs.should_send_federation():
  195. self.federation_sender = hs.get_federation_sender()
  196. self.state_handler = hs.get_state_handler()
  197. self.clock.looping_call(
  198. self.remove_expired_streams, self.UNUSED_STREAM_EXPIRY_MS
  199. )
  200. # This is not a very cheap test to perform, but it's only executed
  201. # when rendering the metrics page, which is likely once per minute at
  202. # most when scraping it.
  203. def count_listeners() -> int:
  204. all_user_streams: Set[_NotifierUserStream] = set()
  205. for streams in list(self.room_to_user_streams.values()):
  206. all_user_streams |= streams
  207. for stream in list(self.user_to_user_stream.values()):
  208. all_user_streams.add(stream)
  209. return sum(stream.count_listeners() for stream in all_user_streams)
  210. LaterGauge("synapse_notifier_listeners", "", [], count_listeners)
  211. LaterGauge(
  212. "synapse_notifier_rooms",
  213. "",
  214. [],
  215. lambda: count(bool, list(self.room_to_user_streams.values())),
  216. )
  217. LaterGauge(
  218. "synapse_notifier_users", "", [], lambda: len(self.user_to_user_stream)
  219. )
  220. def add_replication_callback(self, cb: Callable[[], None]) -> None:
  221. """Add a callback that will be called when some new data is available.
  222. Callback is not given any arguments. It should *not* return a Deferred - if
  223. it needs to do any asynchronous work, a background thread should be started and
  224. wrapped with run_as_background_process.
  225. """
  226. self._replication_notifier.add_replication_callback(cb)
  227. def add_new_join_in_room_callback(self, cb: Callable[[str, str], None]) -> None:
  228. """Add a callback that will be called when a user joins a room.
  229. This only fires on genuine membership changes, e.g. "invite" -> "join".
  230. Membership transitions like "join" -> "join" (for e.g. displayname changes) do
  231. not trigger the callback.
  232. When called, the callback receives two arguments: the event ID and the room ID.
  233. It should *not* return a Deferred - if it needs to do any asynchronous work, a
  234. background thread should be started and wrapped with run_as_background_process.
  235. """
  236. self._new_join_in_room_callbacks.append(cb)
  237. async def on_new_room_events(
  238. self,
  239. events_and_pos: List[Tuple[EventBase, PersistedEventPosition]],
  240. max_room_stream_token: RoomStreamToken,
  241. extra_users: Optional[Collection[UserID]] = None,
  242. ) -> None:
  243. """Creates a _PendingRoomEventEntry for each of the listed events and calls
  244. notify_new_room_events with the results."""
  245. event_entries = []
  246. for event, pos in events_and_pos:
  247. entry = self.create_pending_room_event_entry(
  248. pos,
  249. extra_users,
  250. event.room_id,
  251. event.type,
  252. event.get("state_key"),
  253. event.content.get("membership"),
  254. )
  255. event_entries.append((entry, event.event_id))
  256. await self.notify_new_room_events(event_entries, max_room_stream_token)
  257. async def on_un_partial_stated_room(
  258. self,
  259. room_id: str,
  260. new_token: int,
  261. ) -> None:
  262. """Used by the resync background processes to wake up all listeners
  263. of this room when it is un-partial-stated.
  264. It will also notify replication listeners of the change in stream.
  265. """
  266. # Wake up all related user stream notifiers
  267. user_streams = self.room_to_user_streams.get(room_id, set())
  268. time_now_ms = self.clock.time_msec()
  269. for user_stream in user_streams:
  270. try:
  271. user_stream.notify(
  272. StreamKeyType.UN_PARTIAL_STATED_ROOMS, new_token, time_now_ms
  273. )
  274. except Exception:
  275. logger.exception("Failed to notify listener")
  276. # Poke the replication so that other workers also see the write to
  277. # the un-partial-stated rooms stream.
  278. self.notify_replication()
  279. async def notify_new_room_events(
  280. self,
  281. event_entries: List[Tuple[_PendingRoomEventEntry, str]],
  282. max_room_stream_token: RoomStreamToken,
  283. ) -> None:
  284. """Used by handlers to inform the notifier something has happened
  285. in the room, room event wise.
  286. This triggers the notifier to wake up any listeners that are
  287. listening to the room, and any listeners for the users in the
  288. `extra_users` param.
  289. This also notifies modules listening on new events via the
  290. `on_new_event` callback.
  291. The events can be persisted out of order. The notifier will wait
  292. until all previous events have been persisted before notifying
  293. the client streams.
  294. """
  295. for event_entry, event_id in event_entries:
  296. self.pending_new_room_events.append(event_entry)
  297. await self._third_party_rules.on_new_event(event_id)
  298. self._notify_pending_new_room_events(max_room_stream_token)
  299. self.notify_replication()
  300. def create_pending_room_event_entry(
  301. self,
  302. event_pos: PersistedEventPosition,
  303. extra_users: Optional[Collection[UserID]],
  304. room_id: str,
  305. event_type: str,
  306. state_key: Optional[str],
  307. membership: Optional[str],
  308. ) -> _PendingRoomEventEntry:
  309. """Creates and returns a _PendingRoomEventEntry"""
  310. return _PendingRoomEventEntry(
  311. event_pos=event_pos,
  312. extra_users=extra_users or [],
  313. room_id=room_id,
  314. type=event_type,
  315. state_key=state_key,
  316. membership=membership,
  317. )
  318. def _notify_pending_new_room_events(
  319. self, max_room_stream_token: RoomStreamToken
  320. ) -> None:
  321. """Notify for the room events that were queued waiting for a previous
  322. event to be persisted.
  323. Args:
  324. max_room_stream_token: The highest stream_id below which all
  325. events have been persisted.
  326. """
  327. pending = self.pending_new_room_events
  328. self.pending_new_room_events = []
  329. users: Set[UserID] = set()
  330. rooms: Set[str] = set()
  331. for entry in pending:
  332. if entry.event_pos.persisted_after(max_room_stream_token):
  333. self.pending_new_room_events.append(entry)
  334. else:
  335. if (
  336. entry.type == EventTypes.Member
  337. and entry.membership == Membership.JOIN
  338. and entry.state_key
  339. ):
  340. self._user_joined_room(entry.state_key, entry.room_id)
  341. users.update(entry.extra_users)
  342. rooms.add(entry.room_id)
  343. if users or rooms:
  344. self.on_new_event(
  345. StreamKeyType.ROOM,
  346. max_room_stream_token,
  347. users=users,
  348. rooms=rooms,
  349. )
  350. self._on_updated_room_token(max_room_stream_token)
  351. def _on_updated_room_token(self, max_room_stream_token: RoomStreamToken) -> None:
  352. """Poke services that might care that the room position has been
  353. updated.
  354. """
  355. # poke any interested application service.
  356. self._notify_app_services(max_room_stream_token)
  357. self._notify_pusher_pool(max_room_stream_token)
  358. if self.federation_sender:
  359. self.federation_sender.notify_new_events(max_room_stream_token)
  360. def _notify_app_services(self, max_room_stream_token: RoomStreamToken) -> None:
  361. try:
  362. self.appservice_handler.notify_interested_services(max_room_stream_token)
  363. except Exception:
  364. logger.exception("Error notifying application services of event")
  365. def _notify_pusher_pool(self, max_room_stream_token: RoomStreamToken) -> None:
  366. try:
  367. self._pusher_pool.on_new_notifications(max_room_stream_token)
  368. except Exception:
  369. logger.exception("Error pusher pool of event")
  370. def on_new_event(
  371. self,
  372. stream_key: str,
  373. new_token: Union[int, RoomStreamToken],
  374. users: Optional[Collection[Union[str, UserID]]] = None,
  375. rooms: Optional[Collection[str]] = None,
  376. ) -> None:
  377. """Used to inform listeners that something has happened event wise.
  378. Will wake up all listeners for the given users and rooms.
  379. Args:
  380. stream_key: The stream the event came from.
  381. new_token: The value of the new stream token.
  382. users: The users that should be informed of the new event.
  383. rooms: A collection of room IDs for which each joined member will be
  384. informed of the new event.
  385. """
  386. users = users or []
  387. rooms = rooms or []
  388. with Measure(self.clock, "on_new_event"):
  389. user_streams = set()
  390. log_kv(
  391. {
  392. "waking_up_explicit_users": len(users),
  393. "waking_up_explicit_rooms": len(rooms),
  394. }
  395. )
  396. for user in users:
  397. user_stream = self.user_to_user_stream.get(str(user))
  398. if user_stream is not None:
  399. user_streams.add(user_stream)
  400. for room in rooms:
  401. user_streams |= self.room_to_user_streams.get(room, set())
  402. if stream_key == StreamKeyType.TO_DEVICE:
  403. issue9533_logger.debug(
  404. "to-device messages stream id %s, awaking streams for %s",
  405. new_token,
  406. users,
  407. )
  408. time_now_ms = self.clock.time_msec()
  409. for user_stream in user_streams:
  410. try:
  411. user_stream.notify(stream_key, new_token, time_now_ms)
  412. except Exception:
  413. logger.exception("Failed to notify listener")
  414. self.notify_replication()
  415. # Notify appservices.
  416. try:
  417. self.appservice_handler.notify_interested_services_ephemeral(
  418. stream_key,
  419. new_token,
  420. users,
  421. )
  422. except Exception:
  423. logger.exception(
  424. "Error notifying application services of ephemeral events"
  425. )
  426. def on_new_replication_data(self) -> None:
  427. """Used to inform replication listeners that something has happened
  428. without waking up any of the normal user event streams"""
  429. self.notify_replication()
  430. async def wait_for_events(
  431. self,
  432. user_id: str,
  433. timeout: int,
  434. callback: Callable[[StreamToken, StreamToken], Awaitable[T]],
  435. room_ids: Optional[Collection[str]] = None,
  436. from_token: StreamToken = StreamToken.START,
  437. ) -> T:
  438. """Wait until the callback returns a non empty response or the
  439. timeout fires.
  440. """
  441. user_stream = self.user_to_user_stream.get(user_id)
  442. if user_stream is None:
  443. current_token = self.event_sources.get_current_token()
  444. if room_ids is None:
  445. room_ids = await self.store.get_rooms_for_user(user_id)
  446. user_stream = _NotifierUserStream(
  447. user_id=user_id,
  448. rooms=room_ids,
  449. current_token=current_token,
  450. time_now_ms=self.clock.time_msec(),
  451. )
  452. self._register_with_keys(user_stream)
  453. result = None
  454. prev_token = from_token
  455. if timeout:
  456. end_time = self.clock.time_msec() + timeout
  457. while not result:
  458. with start_active_span("wait_for_events"):
  459. try:
  460. now = self.clock.time_msec()
  461. if end_time <= now:
  462. break
  463. # Now we wait for the _NotifierUserStream to be told there
  464. # is a new token.
  465. listener = user_stream.new_listener(prev_token)
  466. listener.deferred = timeout_deferred(
  467. listener.deferred,
  468. (end_time - now) / 1000.0,
  469. self.hs.get_reactor(),
  470. )
  471. log_kv(
  472. {
  473. "wait_for_events": "sleep",
  474. "token": prev_token,
  475. }
  476. )
  477. with PreserveLoggingContext():
  478. await listener.deferred
  479. log_kv(
  480. {
  481. "wait_for_events": "woken",
  482. "token": user_stream.current_token,
  483. }
  484. )
  485. current_token = user_stream.current_token
  486. result = await callback(prev_token, current_token)
  487. log_kv(
  488. {
  489. "wait_for_events": "result",
  490. "result": bool(result),
  491. }
  492. )
  493. if result:
  494. break
  495. # Update the prev_token to the current_token since nothing
  496. # has happened between the old prev_token and the current_token
  497. prev_token = current_token
  498. except defer.TimeoutError:
  499. log_kv({"wait_for_events": "timeout"})
  500. break
  501. except defer.CancelledError:
  502. log_kv({"wait_for_events": "cancelled"})
  503. break
  504. if result is None:
  505. # This happened if there was no timeout or if the timeout had
  506. # already expired.
  507. current_token = user_stream.current_token
  508. result = await callback(prev_token, current_token)
  509. return result
  510. async def get_events_for(
  511. self,
  512. user: UserID,
  513. pagination_config: PaginationConfig,
  514. timeout: int,
  515. is_guest: bool = False,
  516. explicit_room_id: Optional[str] = None,
  517. ) -> EventStreamResult:
  518. """For the given user and rooms, return any new events for them. If
  519. there are no new events wait for up to `timeout` milliseconds for any
  520. new events to happen before returning.
  521. If explicit_room_id is not set, the user's joined rooms will be polled
  522. for events.
  523. If explicit_room_id is set, that room will be polled for events only if
  524. it is world readable or the user has joined the room.
  525. """
  526. if pagination_config.from_token:
  527. from_token = pagination_config.from_token
  528. else:
  529. from_token = self.event_sources.get_current_token()
  530. limit = pagination_config.limit
  531. room_ids, is_joined = await self._get_room_ids(user, explicit_room_id)
  532. is_peeking = not is_joined
  533. async def check_for_updates(
  534. before_token: StreamToken, after_token: StreamToken
  535. ) -> EventStreamResult:
  536. if after_token == before_token:
  537. return EventStreamResult([], from_token, from_token)
  538. # The events fetched from each source are a JsonDict, EventBase, or
  539. # UserPresenceState, but see below for UserPresenceState being
  540. # converted to JsonDict.
  541. events: List[Union[JsonDict, EventBase]] = []
  542. end_token = from_token
  543. for name, source in self.event_sources.sources.get_sources():
  544. keyname = "%s_key" % name
  545. before_id = getattr(before_token, keyname)
  546. after_id = getattr(after_token, keyname)
  547. if before_id == after_id:
  548. continue
  549. new_events, new_key = await source.get_new_events(
  550. user=user,
  551. from_key=getattr(from_token, keyname),
  552. limit=limit,
  553. is_guest=is_peeking,
  554. room_ids=room_ids,
  555. explicit_room_id=explicit_room_id,
  556. )
  557. if name == "room":
  558. new_events = await filter_events_for_client(
  559. self._storage_controllers,
  560. user.to_string(),
  561. new_events,
  562. is_peeking=is_peeking,
  563. )
  564. elif name == "presence":
  565. now = self.clock.time_msec()
  566. new_events[:] = [
  567. {
  568. "type": EduTypes.PRESENCE,
  569. "content": format_user_presence_state(event, now),
  570. }
  571. for event in new_events
  572. ]
  573. events.extend(new_events)
  574. end_token = end_token.copy_and_replace(keyname, new_key)
  575. return EventStreamResult(events, from_token, end_token)
  576. user_id_for_stream = user.to_string()
  577. if is_peeking:
  578. # Internally, the notifier keeps an event stream per user_id.
  579. # This is used by both /sync and /events.
  580. # We want /events to be used for peeking independently of /sync,
  581. # without polluting its contents. So we invent an illegal user ID
  582. # (which thus cannot clash with any real users) for keying peeking
  583. # over /events.
  584. #
  585. # I am sorry for what I have done.
  586. user_id_for_stream = "_PEEKING_%s_%s" % (
  587. explicit_room_id,
  588. user_id_for_stream,
  589. )
  590. result = await self.wait_for_events(
  591. user_id_for_stream,
  592. timeout,
  593. check_for_updates,
  594. room_ids=room_ids,
  595. from_token=from_token,
  596. )
  597. return result
  598. async def _get_room_ids(
  599. self, user: UserID, explicit_room_id: Optional[str]
  600. ) -> Tuple[StrCollection, bool]:
  601. joined_room_ids = await self.store.get_rooms_for_user(user.to_string())
  602. if explicit_room_id:
  603. if explicit_room_id in joined_room_ids:
  604. return [explicit_room_id], True
  605. if await self._is_world_readable(explicit_room_id):
  606. return [explicit_room_id], False
  607. raise AuthError(403, "Non-joined access not allowed")
  608. return joined_room_ids, True
  609. async def _is_world_readable(self, room_id: str) -> bool:
  610. state = await self._storage_controllers.state.get_current_state_event(
  611. room_id, EventTypes.RoomHistoryVisibility, ""
  612. )
  613. if state and "history_visibility" in state.content:
  614. return (
  615. state.content["history_visibility"] == HistoryVisibility.WORLD_READABLE
  616. )
  617. else:
  618. return False
  619. def remove_expired_streams(self) -> None:
  620. time_now_ms = self.clock.time_msec()
  621. expired_streams = []
  622. expire_before_ts = time_now_ms - self.UNUSED_STREAM_EXPIRY_MS
  623. for stream in self.user_to_user_stream.values():
  624. if stream.count_listeners():
  625. continue
  626. if stream.last_notified_ms < expire_before_ts:
  627. expired_streams.append(stream)
  628. for expired_stream in expired_streams:
  629. expired_stream.remove(self)
  630. def _register_with_keys(self, user_stream: _NotifierUserStream) -> None:
  631. self.user_to_user_stream[user_stream.user_id] = user_stream
  632. for room in user_stream.rooms:
  633. s = self.room_to_user_streams.setdefault(room, set())
  634. s.add(user_stream)
  635. def _user_joined_room(self, user_id: str, room_id: str) -> None:
  636. new_user_stream = self.user_to_user_stream.get(user_id)
  637. if new_user_stream is not None:
  638. room_streams = self.room_to_user_streams.setdefault(room_id, set())
  639. room_streams.add(new_user_stream)
  640. new_user_stream.rooms.add(room_id)
  641. def notify_replication(self) -> None:
  642. """Notify the any replication listeners that there's a new event"""
  643. self._replication_notifier.notify_replication()
  644. def notify_user_joined_room(self, event_id: str, room_id: str) -> None:
  645. for cb in self._new_join_in_room_callbacks:
  646. cb(event_id, room_id)
  647. def notify_remote_server_up(self, server: str) -> None:
  648. """Notify any replication that a remote server has come back up"""
  649. # We call federation_sender directly rather than registering as a
  650. # callback as a) we already have a reference to it and b) it introduces
  651. # circular dependencies.
  652. if self.federation_sender:
  653. self.federation_sender.wake_destination(server)
  654. # Tell the federation client about the fact the server is back up, so
  655. # that any in flight requests can be immediately retried.
  656. self._federation_client.wake_destination(server)
  657. @attr.s(auto_attribs=True)
  658. class ReplicationNotifier:
  659. """Tracks callbacks for things that need to know about stream changes.
  660. This is separate from the notifier to avoid circular dependencies.
  661. """
  662. _replication_callbacks: List[Callable[[], None]] = attr.Factory(list)
  663. def add_replication_callback(self, cb: Callable[[], None]) -> None:
  664. """Add a callback that will be called when some new data is available.
  665. Callback is not given any arguments. It should *not* return a Deferred - if
  666. it needs to do any asynchronous work, a background thread should be started and
  667. wrapped with run_as_background_process.
  668. """
  669. self._replication_callbacks.append(cb)
  670. def notify_replication(self) -> None:
  671. """Notify the any replication listeners that there's a new event"""
  672. for cb in self._replication_callbacks:
  673. cb()