You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

866 lines
31 KiB

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