Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

826 Zeilen
30 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. 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: StrCollection,
  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_module_api_callbacks().third_party_event_rules
  190. # List of callbacks to be notified when a lock is released
  191. self._lock_released_callback: List[Callable[[str, str, str], None]] = []
  192. self.clock = hs.get_clock()
  193. self.appservice_handler = hs.get_application_service_handler()
  194. self._pusher_pool = hs.get_pusherpool()
  195. self.federation_sender = None
  196. if hs.should_send_federation():
  197. self.federation_sender = hs.get_federation_sender()
  198. self.state_handler = hs.get_state_handler()
  199. self.clock.looping_call(
  200. self.remove_expired_streams, self.UNUSED_STREAM_EXPIRY_MS
  201. )
  202. # This is not a very cheap test to perform, but it's only executed
  203. # when rendering the metrics page, which is likely once per minute at
  204. # most when scraping it.
  205. def count_listeners() -> int:
  206. all_user_streams: Set[_NotifierUserStream] = set()
  207. for streams in list(self.room_to_user_streams.values()):
  208. all_user_streams |= streams
  209. for stream in list(self.user_to_user_stream.values()):
  210. all_user_streams.add(stream)
  211. return sum(stream.count_listeners() for stream in all_user_streams)
  212. LaterGauge("synapse_notifier_listeners", "", [], count_listeners)
  213. LaterGauge(
  214. "synapse_notifier_rooms",
  215. "",
  216. [],
  217. lambda: count(bool, list(self.room_to_user_streams.values())),
  218. )
  219. LaterGauge(
  220. "synapse_notifier_users", "", [], lambda: len(self.user_to_user_stream)
  221. )
  222. def add_replication_callback(self, cb: Callable[[], None]) -> None:
  223. """Add a callback that will be called when some new data is available.
  224. Callback is not given any arguments. It should *not* return a Deferred - if
  225. it needs to do any asynchronous work, a background thread should be started and
  226. wrapped with run_as_background_process.
  227. """
  228. self._replication_notifier.add_replication_callback(cb)
  229. def add_new_join_in_room_callback(self, cb: Callable[[str, str], None]) -> None:
  230. """Add a callback that will be called when a user joins a room.
  231. This only fires on genuine membership changes, e.g. "invite" -> "join".
  232. Membership transitions like "join" -> "join" (for e.g. displayname changes) do
  233. not trigger the callback.
  234. When called, the callback receives two arguments: the event ID and the room ID.
  235. It should *not* return a Deferred - if it needs to do any asynchronous work, a
  236. background thread should be started and wrapped with run_as_background_process.
  237. """
  238. self._new_join_in_room_callbacks.append(cb)
  239. async def on_new_room_events(
  240. self,
  241. events_and_pos: List[Tuple[EventBase, PersistedEventPosition]],
  242. max_room_stream_token: RoomStreamToken,
  243. extra_users: Optional[Collection[UserID]] = None,
  244. ) -> None:
  245. """Creates a _PendingRoomEventEntry for each of the listed events and calls
  246. notify_new_room_events with the results."""
  247. event_entries = []
  248. for event, pos in events_and_pos:
  249. entry = self.create_pending_room_event_entry(
  250. pos,
  251. extra_users,
  252. event.room_id,
  253. event.type,
  254. event.get("state_key"),
  255. event.content.get("membership"),
  256. )
  257. event_entries.append((entry, event.event_id))
  258. await self.notify_new_room_events(event_entries, max_room_stream_token)
  259. async def on_un_partial_stated_room(
  260. self,
  261. room_id: str,
  262. new_token: int,
  263. ) -> None:
  264. """Used by the resync background processes to wake up all listeners
  265. of this room when it is un-partial-stated.
  266. It will also notify replication listeners of the change in stream.
  267. """
  268. # Wake up all related user stream notifiers
  269. user_streams = self.room_to_user_streams.get(room_id, set())
  270. time_now_ms = self.clock.time_msec()
  271. for user_stream in user_streams:
  272. try:
  273. user_stream.notify(
  274. StreamKeyType.UN_PARTIAL_STATED_ROOMS, new_token, time_now_ms
  275. )
  276. except Exception:
  277. logger.exception("Failed to notify listener")
  278. # Poke the replication so that other workers also see the write to
  279. # the un-partial-stated rooms stream.
  280. self.notify_replication()
  281. async def notify_new_room_events(
  282. self,
  283. event_entries: List[Tuple[_PendingRoomEventEntry, str]],
  284. max_room_stream_token: RoomStreamToken,
  285. ) -> None:
  286. """Used by handlers to inform the notifier something has happened
  287. in the room, room event wise.
  288. This triggers the notifier to wake up any listeners that are
  289. listening to the room, and any listeners for the users in the
  290. `extra_users` param.
  291. This also notifies modules listening on new events via the
  292. `on_new_event` callback.
  293. The events can be persisted out of order. The notifier will wait
  294. until all previous events have been persisted before notifying
  295. the client streams.
  296. """
  297. for event_entry, event_id in event_entries:
  298. self.pending_new_room_events.append(event_entry)
  299. await self._third_party_rules.on_new_event(event_id)
  300. self._notify_pending_new_room_events(max_room_stream_token)
  301. self.notify_replication()
  302. def create_pending_room_event_entry(
  303. self,
  304. event_pos: PersistedEventPosition,
  305. extra_users: Optional[Collection[UserID]],
  306. room_id: str,
  307. event_type: str,
  308. state_key: Optional[str],
  309. membership: Optional[str],
  310. ) -> _PendingRoomEventEntry:
  311. """Creates and returns a _PendingRoomEventEntry"""
  312. return _PendingRoomEventEntry(
  313. event_pos=event_pos,
  314. extra_users=extra_users or [],
  315. room_id=room_id,
  316. type=event_type,
  317. state_key=state_key,
  318. membership=membership,
  319. )
  320. def _notify_pending_new_room_events(
  321. self, max_room_stream_token: RoomStreamToken
  322. ) -> None:
  323. """Notify for the room events that were queued waiting for a previous
  324. event to be persisted.
  325. Args:
  326. max_room_stream_token: The highest stream_id below which all
  327. events have been persisted.
  328. """
  329. pending = self.pending_new_room_events
  330. self.pending_new_room_events = []
  331. users: Set[UserID] = set()
  332. rooms: Set[str] = set()
  333. for entry in pending:
  334. if entry.event_pos.persisted_after(max_room_stream_token):
  335. self.pending_new_room_events.append(entry)
  336. else:
  337. if (
  338. entry.type == EventTypes.Member
  339. and entry.membership == Membership.JOIN
  340. and entry.state_key
  341. ):
  342. self._user_joined_room(entry.state_key, entry.room_id)
  343. users.update(entry.extra_users)
  344. rooms.add(entry.room_id)
  345. if users or rooms:
  346. self.on_new_event(
  347. StreamKeyType.ROOM,
  348. max_room_stream_token,
  349. users=users,
  350. rooms=rooms,
  351. )
  352. self._on_updated_room_token(max_room_stream_token)
  353. def _on_updated_room_token(self, max_room_stream_token: RoomStreamToken) -> None:
  354. """Poke services that might care that the room position has been
  355. updated.
  356. """
  357. # poke any interested application service.
  358. self._notify_app_services(max_room_stream_token)
  359. self._notify_pusher_pool(max_room_stream_token)
  360. if self.federation_sender:
  361. self.federation_sender.notify_new_events(max_room_stream_token)
  362. def _notify_app_services(self, max_room_stream_token: RoomStreamToken) -> None:
  363. try:
  364. self.appservice_handler.notify_interested_services(max_room_stream_token)
  365. except Exception:
  366. logger.exception("Error notifying application services of event")
  367. def _notify_pusher_pool(self, max_room_stream_token: RoomStreamToken) -> None:
  368. try:
  369. self._pusher_pool.on_new_notifications(max_room_stream_token)
  370. except Exception:
  371. logger.exception("Error pusher pool of event")
  372. def on_new_event(
  373. self,
  374. stream_key: str,
  375. new_token: Union[int, RoomStreamToken],
  376. users: Optional[Collection[Union[str, UserID]]] = None,
  377. rooms: Optional[StrCollection] = None,
  378. ) -> None:
  379. """Used to inform listeners that something has happened event wise.
  380. Will wake up all listeners for the given users and rooms.
  381. Args:
  382. stream_key: The stream the event came from.
  383. new_token: The value of the new stream token.
  384. users: The users that should be informed of the new event.
  385. rooms: A collection of room IDs for which each joined member will be
  386. informed of the new event.
  387. """
  388. users = users or []
  389. rooms = rooms or []
  390. with Measure(self.clock, "on_new_event"):
  391. user_streams = set()
  392. log_kv(
  393. {
  394. "waking_up_explicit_users": len(users),
  395. "waking_up_explicit_rooms": len(rooms),
  396. }
  397. )
  398. for user in users:
  399. user_stream = self.user_to_user_stream.get(str(user))
  400. if user_stream is not None:
  401. user_streams.add(user_stream)
  402. for room in rooms:
  403. user_streams |= self.room_to_user_streams.get(room, set())
  404. if stream_key == StreamKeyType.TO_DEVICE:
  405. issue9533_logger.debug(
  406. "to-device messages stream id %s, awaking streams for %s",
  407. new_token,
  408. users,
  409. )
  410. time_now_ms = self.clock.time_msec()
  411. for user_stream in user_streams:
  412. try:
  413. user_stream.notify(stream_key, new_token, time_now_ms)
  414. except Exception:
  415. logger.exception("Failed to notify listener")
  416. self.notify_replication()
  417. # Notify appservices.
  418. try:
  419. self.appservice_handler.notify_interested_services_ephemeral(
  420. stream_key,
  421. new_token,
  422. users,
  423. )
  424. except Exception:
  425. logger.exception(
  426. "Error notifying application services of ephemeral events"
  427. )
  428. def on_new_replication_data(self) -> None:
  429. """Used to inform replication listeners that something has happened
  430. without waking up any of the normal user event streams"""
  431. self.notify_replication()
  432. async def wait_for_events(
  433. self,
  434. user_id: str,
  435. timeout: int,
  436. callback: Callable[[StreamToken, StreamToken], Awaitable[T]],
  437. room_ids: Optional[StrCollection] = None,
  438. from_token: StreamToken = StreamToken.START,
  439. ) -> T:
  440. """Wait until the callback returns a non empty response or the
  441. timeout fires.
  442. """
  443. user_stream = self.user_to_user_stream.get(user_id)
  444. if user_stream is None:
  445. current_token = self.event_sources.get_current_token()
  446. if room_ids is None:
  447. room_ids = await self.store.get_rooms_for_user(user_id)
  448. user_stream = _NotifierUserStream(
  449. user_id=user_id,
  450. rooms=room_ids,
  451. current_token=current_token,
  452. time_now_ms=self.clock.time_msec(),
  453. )
  454. self._register_with_keys(user_stream)
  455. result = None
  456. prev_token = from_token
  457. if timeout:
  458. end_time = self.clock.time_msec() + timeout
  459. while not result:
  460. with start_active_span("wait_for_events"):
  461. try:
  462. now = self.clock.time_msec()
  463. if end_time <= now:
  464. break
  465. # Now we wait for the _NotifierUserStream to be told there
  466. # is a new token.
  467. listener = user_stream.new_listener(prev_token)
  468. listener.deferred = timeout_deferred(
  469. listener.deferred,
  470. (end_time - now) / 1000.0,
  471. self.hs.get_reactor(),
  472. )
  473. log_kv(
  474. {
  475. "wait_for_events": "sleep",
  476. "token": prev_token,
  477. }
  478. )
  479. with PreserveLoggingContext():
  480. await listener.deferred
  481. log_kv(
  482. {
  483. "wait_for_events": "woken",
  484. "token": user_stream.current_token,
  485. }
  486. )
  487. current_token = user_stream.current_token
  488. result = await callback(prev_token, current_token)
  489. log_kv(
  490. {
  491. "wait_for_events": "result",
  492. "result": bool(result),
  493. }
  494. )
  495. if result:
  496. break
  497. # Update the prev_token to the current_token since nothing
  498. # has happened between the old prev_token and the current_token
  499. prev_token = current_token
  500. except defer.TimeoutError:
  501. log_kv({"wait_for_events": "timeout"})
  502. break
  503. except defer.CancelledError:
  504. log_kv({"wait_for_events": "cancelled"})
  505. break
  506. if result is None:
  507. # This happened if there was no timeout or if the timeout had
  508. # already expired.
  509. current_token = user_stream.current_token
  510. result = await callback(prev_token, current_token)
  511. return result
  512. async def get_events_for(
  513. self,
  514. user: UserID,
  515. pagination_config: PaginationConfig,
  516. timeout: int,
  517. is_guest: bool = False,
  518. explicit_room_id: Optional[str] = None,
  519. ) -> EventStreamResult:
  520. """For the given user and rooms, return any new events for them. If
  521. there are no new events wait for up to `timeout` milliseconds for any
  522. new events to happen before returning.
  523. If explicit_room_id is not set, the user's joined rooms will be polled
  524. for events.
  525. If explicit_room_id is set, that room will be polled for events only if
  526. it is world readable or the user has joined the room.
  527. """
  528. if pagination_config.from_token:
  529. from_token = pagination_config.from_token
  530. else:
  531. from_token = self.event_sources.get_current_token()
  532. limit = pagination_config.limit
  533. room_ids, is_joined = await self._get_room_ids(user, explicit_room_id)
  534. is_peeking = not is_joined
  535. async def check_for_updates(
  536. before_token: StreamToken, after_token: StreamToken
  537. ) -> EventStreamResult:
  538. if after_token == before_token:
  539. return EventStreamResult([], from_token, from_token)
  540. # The events fetched from each source are a JsonDict, EventBase, or
  541. # UserPresenceState, but see below for UserPresenceState being
  542. # converted to JsonDict.
  543. events: List[Union[JsonDict, EventBase]] = []
  544. end_token = from_token
  545. for name, source in self.event_sources.sources.get_sources():
  546. keyname = "%s_key" % name
  547. before_id = getattr(before_token, keyname)
  548. after_id = getattr(after_token, keyname)
  549. if before_id == after_id:
  550. continue
  551. new_events, new_key = await source.get_new_events(
  552. user=user,
  553. from_key=getattr(from_token, keyname),
  554. limit=limit,
  555. is_guest=is_peeking,
  556. room_ids=room_ids,
  557. explicit_room_id=explicit_room_id,
  558. )
  559. if name == "room":
  560. new_events = await filter_events_for_client(
  561. self._storage_controllers,
  562. user.to_string(),
  563. new_events,
  564. is_peeking=is_peeking,
  565. )
  566. elif name == "presence":
  567. now = self.clock.time_msec()
  568. new_events[:] = [
  569. {
  570. "type": EduTypes.PRESENCE,
  571. "content": format_user_presence_state(event, now),
  572. }
  573. for event in new_events
  574. ]
  575. events.extend(new_events)
  576. end_token = end_token.copy_and_replace(keyname, new_key)
  577. return EventStreamResult(events, from_token, end_token)
  578. user_id_for_stream = user.to_string()
  579. if is_peeking:
  580. # Internally, the notifier keeps an event stream per user_id.
  581. # This is used by both /sync and /events.
  582. # We want /events to be used for peeking independently of /sync,
  583. # without polluting its contents. So we invent an illegal user ID
  584. # (which thus cannot clash with any real users) for keying peeking
  585. # over /events.
  586. #
  587. # I am sorry for what I have done.
  588. user_id_for_stream = "_PEEKING_%s_%s" % (
  589. explicit_room_id,
  590. user_id_for_stream,
  591. )
  592. result = await self.wait_for_events(
  593. user_id_for_stream,
  594. timeout,
  595. check_for_updates,
  596. room_ids=room_ids,
  597. from_token=from_token,
  598. )
  599. return result
  600. async def _get_room_ids(
  601. self, user: UserID, explicit_room_id: Optional[str]
  602. ) -> Tuple[StrCollection, bool]:
  603. joined_room_ids = await self.store.get_rooms_for_user(user.to_string())
  604. if explicit_room_id:
  605. if explicit_room_id in joined_room_ids:
  606. return [explicit_room_id], True
  607. if await self._is_world_readable(explicit_room_id):
  608. return [explicit_room_id], False
  609. raise AuthError(403, "Non-joined access not allowed")
  610. return joined_room_ids, True
  611. async def _is_world_readable(self, room_id: str) -> bool:
  612. state = await self._storage_controllers.state.get_current_state_event(
  613. room_id, EventTypes.RoomHistoryVisibility, ""
  614. )
  615. if state and "history_visibility" in state.content:
  616. return (
  617. state.content["history_visibility"] == HistoryVisibility.WORLD_READABLE
  618. )
  619. else:
  620. return False
  621. def remove_expired_streams(self) -> None:
  622. time_now_ms = self.clock.time_msec()
  623. expired_streams = []
  624. expire_before_ts = time_now_ms - self.UNUSED_STREAM_EXPIRY_MS
  625. for stream in self.user_to_user_stream.values():
  626. if stream.count_listeners():
  627. continue
  628. if stream.last_notified_ms < expire_before_ts:
  629. expired_streams.append(stream)
  630. for expired_stream in expired_streams:
  631. expired_stream.remove(self)
  632. def _register_with_keys(self, user_stream: _NotifierUserStream) -> None:
  633. self.user_to_user_stream[user_stream.user_id] = user_stream
  634. for room in user_stream.rooms:
  635. s = self.room_to_user_streams.setdefault(room, set())
  636. s.add(user_stream)
  637. def _user_joined_room(self, user_id: str, room_id: str) -> None:
  638. new_user_stream = self.user_to_user_stream.get(user_id)
  639. if new_user_stream is not None:
  640. room_streams = self.room_to_user_streams.setdefault(room_id, set())
  641. room_streams.add(new_user_stream)
  642. new_user_stream.rooms.add(room_id)
  643. def notify_replication(self) -> None:
  644. """Notify the any replication listeners that there's a new event"""
  645. self._replication_notifier.notify_replication()
  646. def notify_user_joined_room(self, event_id: str, room_id: str) -> None:
  647. for cb in self._new_join_in_room_callbacks:
  648. cb(event_id, room_id)
  649. def notify_remote_server_up(self, server: str) -> None:
  650. """Notify any replication that a remote server has come back up"""
  651. # We call federation_sender directly rather than registering as a
  652. # callback as a) we already have a reference to it and b) it introduces
  653. # circular dependencies.
  654. if self.federation_sender:
  655. self.federation_sender.wake_destination(server)
  656. # Tell the federation client about the fact the server is back up, so
  657. # that any in flight requests can be immediately retried.
  658. self._federation_client.wake_destination(server)
  659. def add_lock_released_callback(
  660. self, callback: Callable[[str, str, str], None]
  661. ) -> None:
  662. """Add a function to be called whenever we are notified about a released lock."""
  663. self._lock_released_callback.append(callback)
  664. def notify_lock_released(
  665. self, instance_name: str, lock_name: str, lock_key: str
  666. ) -> None:
  667. """Notify the callbacks that a lock has been released."""
  668. for cb in self._lock_released_callback:
  669. cb(instance_name, lock_name, lock_key)
  670. @attr.s(auto_attribs=True)
  671. class ReplicationNotifier:
  672. """Tracks callbacks for things that need to know about stream changes.
  673. This is separate from the notifier to avoid circular dependencies.
  674. """
  675. _replication_callbacks: List[Callable[[], None]] = attr.Factory(list)
  676. def add_replication_callback(self, cb: Callable[[], None]) -> None:
  677. """Add a callback that will be called when some new data is available.
  678. Callback is not given any arguments. It should *not* return a Deferred - if
  679. it needs to do any asynchronous work, a background thread should be started and
  680. wrapped with run_as_background_process.
  681. """
  682. self._replication_callbacks.append(cb)
  683. def notify_replication(self) -> None:
  684. """Notify the any replication listeners that there's a new event"""
  685. for cb in self._replication_callbacks:
  686. cb()