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.
 
 
 
 
 
 

2286 lines
88 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2020 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """This module is responsible for keeping track of presence status of local
  16. and remote users.
  17. The methods that define policy are:
  18. - PresenceHandler._update_states
  19. - PresenceHandler._handle_timeouts
  20. - should_notify
  21. """
  22. import abc
  23. import contextlib
  24. import logging
  25. from bisect import bisect
  26. from contextlib import contextmanager
  27. from types import TracebackType
  28. from typing import (
  29. TYPE_CHECKING,
  30. Any,
  31. Callable,
  32. Collection,
  33. ContextManager,
  34. Dict,
  35. Generator,
  36. Iterable,
  37. List,
  38. Optional,
  39. Set,
  40. Tuple,
  41. Type,
  42. )
  43. from prometheus_client import Counter
  44. import synapse.metrics
  45. from synapse.api.constants import EduTypes, EventTypes, Membership, PresenceState
  46. from synapse.api.errors import SynapseError
  47. from synapse.api.presence import UserPresenceState
  48. from synapse.appservice import ApplicationService
  49. from synapse.events.presence_router import PresenceRouter
  50. from synapse.logging.context import run_in_background
  51. from synapse.metrics import LaterGauge
  52. from synapse.metrics.background_process_metrics import (
  53. run_as_background_process,
  54. wrap_as_background_process,
  55. )
  56. from synapse.replication.http.presence import (
  57. ReplicationBumpPresenceActiveTime,
  58. ReplicationPresenceSetState,
  59. )
  60. from synapse.replication.http.streams import ReplicationGetStreamUpdates
  61. from synapse.replication.tcp.commands import ClearUserSyncsCommand
  62. from synapse.replication.tcp.streams import PresenceFederationStream, PresenceStream
  63. from synapse.storage.databases.main import DataStore
  64. from synapse.streams import EventSource
  65. from synapse.types import (
  66. JsonDict,
  67. StrCollection,
  68. StreamKeyType,
  69. UserID,
  70. get_domain_from_id,
  71. )
  72. from synapse.util.async_helpers import Linearizer
  73. from synapse.util.metrics import Measure
  74. from synapse.util.wheel_timer import WheelTimer
  75. if TYPE_CHECKING:
  76. from synapse.server import HomeServer
  77. logger = logging.getLogger(__name__)
  78. notified_presence_counter = Counter("synapse_handler_presence_notified_presence", "")
  79. federation_presence_out_counter = Counter(
  80. "synapse_handler_presence_federation_presence_out", ""
  81. )
  82. presence_updates_counter = Counter("synapse_handler_presence_presence_updates", "")
  83. timers_fired_counter = Counter("synapse_handler_presence_timers_fired", "")
  84. federation_presence_counter = Counter(
  85. "synapse_handler_presence_federation_presence", ""
  86. )
  87. bump_active_time_counter = Counter("synapse_handler_presence_bump_active_time", "")
  88. get_updates_counter = Counter("synapse_handler_presence_get_updates", "", ["type"])
  89. notify_reason_counter = Counter(
  90. "synapse_handler_presence_notify_reason", "", ["locality", "reason"]
  91. )
  92. state_transition_counter = Counter(
  93. "synapse_handler_presence_state_transition", "", ["locality", "from", "to"]
  94. )
  95. # If a user was last active in the last LAST_ACTIVE_GRANULARITY, consider them
  96. # "currently_active"
  97. LAST_ACTIVE_GRANULARITY = 60 * 1000
  98. # How long to wait until a new /events or /sync request before assuming
  99. # the client has gone.
  100. SYNC_ONLINE_TIMEOUT = 30 * 1000
  101. # How long to wait before marking the user as idle. Compared against last active
  102. IDLE_TIMER = 5 * 60 * 1000
  103. # How often we expect remote servers to resend us presence.
  104. FEDERATION_TIMEOUT = 30 * 60 * 1000
  105. # How often to resend presence to remote servers
  106. FEDERATION_PING_INTERVAL = 25 * 60 * 1000
  107. # How long we will wait before assuming that the syncs from an external process
  108. # are dead.
  109. EXTERNAL_PROCESS_EXPIRY = 5 * 60 * 1000
  110. # Delay before a worker tells the presence handler that a user has stopped
  111. # syncing.
  112. UPDATE_SYNCING_USERS_MS = 10 * 1000
  113. assert LAST_ACTIVE_GRANULARITY < IDLE_TIMER
  114. class BasePresenceHandler(abc.ABC):
  115. """Parts of the PresenceHandler that are shared between workers and presence
  116. writer"""
  117. def __init__(self, hs: "HomeServer"):
  118. self.clock = hs.get_clock()
  119. self.store = hs.get_datastores().main
  120. self._storage_controllers = hs.get_storage_controllers()
  121. self.presence_router = hs.get_presence_router()
  122. self.state = hs.get_state_handler()
  123. self.is_mine_id = hs.is_mine_id
  124. self._presence_enabled = hs.config.server.use_presence
  125. self._federation = None
  126. if hs.should_send_federation():
  127. self._federation = hs.get_federation_sender()
  128. self._federation_queue = PresenceFederationQueue(hs, self)
  129. self._busy_presence_enabled = hs.config.experimental.msc3026_enabled
  130. self.VALID_PRESENCE: Tuple[str, ...] = (
  131. PresenceState.ONLINE,
  132. PresenceState.UNAVAILABLE,
  133. PresenceState.OFFLINE,
  134. )
  135. if self._busy_presence_enabled:
  136. self.VALID_PRESENCE += (PresenceState.BUSY,)
  137. active_presence = self.store.take_presence_startup_info()
  138. self.user_to_current_state = {state.user_id: state for state in active_presence}
  139. @abc.abstractmethod
  140. async def user_syncing(
  141. self, user_id: str, affect_presence: bool, presence_state: str
  142. ) -> ContextManager[None]:
  143. """Returns a context manager that should surround any stream requests
  144. from the user.
  145. This allows us to keep track of who is currently streaming and who isn't
  146. without having to have timers outside of this module to avoid flickering
  147. when users disconnect/reconnect.
  148. Args:
  149. user_id: the user that is starting a sync
  150. affect_presence: If false this function will be a no-op.
  151. Useful for streams that are not associated with an actual
  152. client that is being used by a user.
  153. presence_state: The presence state indicated in the sync request
  154. """
  155. @abc.abstractmethod
  156. def get_currently_syncing_users_for_replication(self) -> Iterable[str]:
  157. """Get an iterable of syncing users on this worker, to send to the presence handler
  158. This is called when a replication connection is established. It should return
  159. a list of user ids, which are then sent as USER_SYNC commands to inform the
  160. process handling presence about those users.
  161. Returns:
  162. An iterable of user_id strings.
  163. """
  164. async def get_state(self, target_user: UserID) -> UserPresenceState:
  165. results = await self.get_states([target_user.to_string()])
  166. return results[0]
  167. async def get_states(
  168. self, target_user_ids: Iterable[str]
  169. ) -> List[UserPresenceState]:
  170. """Get the presence state for users."""
  171. updates_d = await self.current_state_for_users(target_user_ids)
  172. updates = list(updates_d.values())
  173. for user_id in set(target_user_ids) - {u.user_id for u in updates}:
  174. updates.append(UserPresenceState.default(user_id))
  175. return updates
  176. async def current_state_for_users(
  177. self, user_ids: Iterable[str]
  178. ) -> Dict[str, UserPresenceState]:
  179. """Get the current presence state for multiple users.
  180. Returns:
  181. A mapping of `user_id` -> `UserPresenceState`
  182. """
  183. states = {}
  184. missing = []
  185. for user_id in user_ids:
  186. state = self.user_to_current_state.get(user_id, None)
  187. if state:
  188. states[user_id] = state
  189. else:
  190. missing.append(user_id)
  191. if missing:
  192. # There are things not in our in memory cache. Lets pull them out of
  193. # the database.
  194. res = await self.store.get_presence_for_users(missing)
  195. states.update(res)
  196. for user_id in missing:
  197. # if user has no state in database, create the state
  198. if not res.get(user_id, None):
  199. new_state = UserPresenceState.default(user_id)
  200. states[user_id] = new_state
  201. self.user_to_current_state[user_id] = new_state
  202. return states
  203. async def current_state_for_user(self, user_id: str) -> UserPresenceState:
  204. """Get the current presence state for a user."""
  205. res = await self.current_state_for_users([user_id])
  206. return res[user_id]
  207. @abc.abstractmethod
  208. async def set_state(
  209. self,
  210. target_user: UserID,
  211. state: JsonDict,
  212. ignore_status_msg: bool = False,
  213. force_notify: bool = False,
  214. ) -> None:
  215. """Set the presence state of the user.
  216. Args:
  217. target_user: The ID of the user to set the presence state of.
  218. state: The presence state as a JSON dictionary.
  219. ignore_status_msg: True to ignore the "status_msg" field of the `state` dict.
  220. If False, the user's current status will be updated.
  221. force_notify: Whether to force notification of the update to clients.
  222. """
  223. @abc.abstractmethod
  224. async def bump_presence_active_time(self, user: UserID) -> None:
  225. """We've seen the user do something that indicates they're interacting
  226. with the app.
  227. """
  228. async def update_external_syncs_row( # noqa: B027 (no-op by design)
  229. self, process_id: str, user_id: str, is_syncing: bool, sync_time_msec: int
  230. ) -> None:
  231. """Update the syncing users for an external process as a delta.
  232. This is a no-op when presence is handled by a different worker.
  233. Args:
  234. process_id: An identifier for the process the users are
  235. syncing against. This allows synapse to process updates
  236. as user start and stop syncing against a given process.
  237. user_id: The user who has started or stopped syncing
  238. is_syncing: Whether or not the user is now syncing
  239. sync_time_msec: Time in ms when the user was last syncing
  240. """
  241. async def update_external_syncs_clear( # noqa: B027 (no-op by design)
  242. self, process_id: str
  243. ) -> None:
  244. """Marks all users that had been marked as syncing by a given process
  245. as offline.
  246. Used when the process has stopped/disappeared.
  247. This is a no-op when presence is handled by a different worker.
  248. """
  249. async def process_replication_rows(
  250. self, stream_name: str, instance_name: str, token: int, rows: list
  251. ) -> None:
  252. """Process streams received over replication."""
  253. await self._federation_queue.process_replication_rows(
  254. stream_name, instance_name, token, rows
  255. )
  256. def get_federation_queue(self) -> "PresenceFederationQueue":
  257. """Get the presence federation queue."""
  258. return self._federation_queue
  259. async def maybe_send_presence_to_interested_destinations(
  260. self, states: List[UserPresenceState]
  261. ) -> None:
  262. """If this instance is a federation sender, send the states to all
  263. destinations that are interested. Filters out any states for remote
  264. users.
  265. """
  266. if not self._federation:
  267. return
  268. states = [s for s in states if self.is_mine_id(s.user_id)]
  269. if not states:
  270. return
  271. hosts_to_states = await get_interested_remotes(
  272. self.store,
  273. self.presence_router,
  274. states,
  275. )
  276. for destination, host_states in hosts_to_states.items():
  277. self._federation.send_presence_to_destinations(host_states, [destination])
  278. async def send_full_presence_to_users(self, user_ids: StrCollection) -> None:
  279. """
  280. Adds to the list of users who should receive a full snapshot of presence
  281. upon their next sync. Note that this only works for local users.
  282. Then, grabs the current presence state for a given set of users and adds it
  283. to the top of the presence stream.
  284. Args:
  285. user_ids: The IDs of the local users to send full presence to.
  286. """
  287. # Retrieve one of the users from the given set
  288. if not user_ids:
  289. raise Exception(
  290. "send_full_presence_to_users must be called with at least one user"
  291. )
  292. user_id = next(iter(user_ids))
  293. # Mark all users as receiving full presence on their next sync
  294. await self.store.add_users_to_send_full_presence_to(user_ids)
  295. # Add a new entry to the presence stream. Since we use stream tokens to determine whether a
  296. # local user should receive a full snapshot of presence when they sync, we need to bump the
  297. # presence stream so that subsequent syncs with no presence activity in between won't result
  298. # in the client receiving multiple full snapshots of presence.
  299. #
  300. # If we bump the stream ID, then the user will get a higher stream token next sync, and thus
  301. # correctly won't receive a second snapshot.
  302. # Get the current presence state for one of the users (defaults to offline if not found)
  303. current_presence_state = await self.get_state(UserID.from_string(user_id))
  304. # Convert the UserPresenceState object into a serializable dict
  305. state = {
  306. "presence": current_presence_state.state,
  307. "status_message": current_presence_state.status_msg,
  308. }
  309. # Copy the presence state to the tip of the presence stream.
  310. # We set force_notify=True here so that this presence update is guaranteed to
  311. # increment the presence stream ID (which resending the current user's presence
  312. # otherwise would not do).
  313. await self.set_state(UserID.from_string(user_id), state, force_notify=True)
  314. async def is_visible(self, observed_user: UserID, observer_user: UserID) -> bool:
  315. raise NotImplementedError(
  316. "Attempting to check presence on a non-presence worker."
  317. )
  318. class _NullContextManager(ContextManager[None]):
  319. """A context manager which does nothing."""
  320. def __exit__(
  321. self,
  322. exc_type: Optional[Type[BaseException]],
  323. exc_val: Optional[BaseException],
  324. exc_tb: Optional[TracebackType],
  325. ) -> None:
  326. pass
  327. class WorkerPresenceHandler(BasePresenceHandler):
  328. def __init__(self, hs: "HomeServer"):
  329. super().__init__(hs)
  330. self.hs = hs
  331. self._presence_writer_instance = hs.config.worker.writers.presence[0]
  332. # Route presence EDUs to the right worker
  333. hs.get_federation_registry().register_instances_for_edu(
  334. EduTypes.PRESENCE,
  335. hs.config.worker.writers.presence,
  336. )
  337. # The number of ongoing syncs on this process, by user id.
  338. # Empty if _presence_enabled is false.
  339. self._user_to_num_current_syncs: Dict[str, int] = {}
  340. self.notifier = hs.get_notifier()
  341. self.instance_id = hs.get_instance_id()
  342. # user_id -> last_sync_ms. Lists the users that have stopped syncing but
  343. # we haven't notified the presence writer of that yet
  344. self.users_going_offline: Dict[str, int] = {}
  345. self._bump_active_client = ReplicationBumpPresenceActiveTime.make_client(hs)
  346. self._set_state_client = ReplicationPresenceSetState.make_client(hs)
  347. self._send_stop_syncing_loop = self.clock.looping_call(
  348. self.send_stop_syncing, UPDATE_SYNCING_USERS_MS
  349. )
  350. hs.get_reactor().addSystemEventTrigger(
  351. "before",
  352. "shutdown",
  353. run_as_background_process,
  354. "generic_presence.on_shutdown",
  355. self._on_shutdown,
  356. )
  357. async def _on_shutdown(self) -> None:
  358. if self._presence_enabled:
  359. self.hs.get_replication_command_handler().send_command(
  360. ClearUserSyncsCommand(self.instance_id)
  361. )
  362. def send_user_sync(self, user_id: str, is_syncing: bool, last_sync_ms: int) -> None:
  363. if self._presence_enabled:
  364. self.hs.get_replication_command_handler().send_user_sync(
  365. self.instance_id, user_id, is_syncing, last_sync_ms
  366. )
  367. def mark_as_coming_online(self, user_id: str) -> None:
  368. """A user has started syncing. Send a UserSync to the presence writer,
  369. unless they had recently stopped syncing.
  370. """
  371. going_offline = self.users_going_offline.pop(user_id, None)
  372. if not going_offline:
  373. # Safe to skip because we haven't yet told the presence writer they
  374. # were offline
  375. self.send_user_sync(user_id, True, self.clock.time_msec())
  376. def mark_as_going_offline(self, user_id: str) -> None:
  377. """A user has stopped syncing. We wait before notifying the presence
  378. writer as its likely they'll come back soon. This allows us to avoid
  379. sending a stopped syncing immediately followed by a started syncing
  380. notification to the presence writer
  381. """
  382. self.users_going_offline[user_id] = self.clock.time_msec()
  383. def send_stop_syncing(self) -> None:
  384. """Check if there are any users who have stopped syncing a while ago and
  385. haven't come back yet. If there are poke the presence writer about them.
  386. """
  387. now = self.clock.time_msec()
  388. for user_id, last_sync_ms in list(self.users_going_offline.items()):
  389. if now - last_sync_ms > UPDATE_SYNCING_USERS_MS:
  390. self.users_going_offline.pop(user_id, None)
  391. self.send_user_sync(user_id, False, last_sync_ms)
  392. async def user_syncing(
  393. self, user_id: str, affect_presence: bool, presence_state: str
  394. ) -> ContextManager[None]:
  395. """Record that a user is syncing.
  396. Called by the sync and events servlets to record that a user has connected to
  397. this worker and is waiting for some events.
  398. """
  399. if not affect_presence or not self._presence_enabled:
  400. return _NullContextManager()
  401. prev_state = await self.current_state_for_user(user_id)
  402. if prev_state.state != PresenceState.BUSY:
  403. # We set state here but pass ignore_status_msg = True as we don't want to
  404. # cause the status message to be cleared.
  405. # Note that this causes last_active_ts to be incremented which is not
  406. # what the spec wants: see comment in the BasePresenceHandler version
  407. # of this function.
  408. await self.set_state(
  409. UserID.from_string(user_id),
  410. {"presence": presence_state},
  411. ignore_status_msg=True,
  412. )
  413. curr_sync = self._user_to_num_current_syncs.get(user_id, 0)
  414. self._user_to_num_current_syncs[user_id] = curr_sync + 1
  415. # If we went from no in flight sync to some, notify replication
  416. if self._user_to_num_current_syncs[user_id] == 1:
  417. self.mark_as_coming_online(user_id)
  418. def _end() -> None:
  419. # We check that the user_id is in user_to_num_current_syncs because
  420. # user_to_num_current_syncs may have been cleared if we are
  421. # shutting down.
  422. if user_id in self._user_to_num_current_syncs:
  423. self._user_to_num_current_syncs[user_id] -= 1
  424. # If we went from one in flight sync to non, notify replication
  425. if self._user_to_num_current_syncs[user_id] == 0:
  426. self.mark_as_going_offline(user_id)
  427. @contextlib.contextmanager
  428. def _user_syncing() -> Generator[None, None, None]:
  429. try:
  430. yield
  431. finally:
  432. _end()
  433. return _user_syncing()
  434. async def notify_from_replication(
  435. self, states: List[UserPresenceState], stream_id: int
  436. ) -> None:
  437. parties = await get_interested_parties(self.store, self.presence_router, states)
  438. room_ids_to_states, users_to_states = parties
  439. self.notifier.on_new_event(
  440. StreamKeyType.PRESENCE,
  441. stream_id,
  442. rooms=room_ids_to_states.keys(),
  443. users=users_to_states.keys(),
  444. )
  445. async def process_replication_rows(
  446. self, stream_name: str, instance_name: str, token: int, rows: list
  447. ) -> None:
  448. await super().process_replication_rows(stream_name, instance_name, token, rows)
  449. if stream_name != PresenceStream.NAME:
  450. return
  451. states = [
  452. UserPresenceState(
  453. row.user_id,
  454. row.state,
  455. row.last_active_ts,
  456. row.last_federation_update_ts,
  457. row.last_user_sync_ts,
  458. row.status_msg,
  459. row.currently_active,
  460. )
  461. for row in rows
  462. ]
  463. # The list of states to notify sync streams and remote servers about.
  464. # This is calculated by comparing the old and new states for each user
  465. # using `should_notify(..)`.
  466. #
  467. # Note that this is necessary as the presence writer will periodically
  468. # flush presence state changes that should not be notified about to the
  469. # DB, and so will be sent over the replication stream.
  470. state_to_notify = []
  471. for new_state in states:
  472. old_state = self.user_to_current_state.get(new_state.user_id)
  473. self.user_to_current_state[new_state.user_id] = new_state
  474. is_mine = self.is_mine_id(new_state.user_id)
  475. if not old_state or should_notify(old_state, new_state, is_mine):
  476. state_to_notify.append(new_state)
  477. stream_id = token
  478. await self.notify_from_replication(state_to_notify, stream_id)
  479. # If this is a federation sender, notify about presence updates.
  480. await self.maybe_send_presence_to_interested_destinations(state_to_notify)
  481. def get_currently_syncing_users_for_replication(self) -> Iterable[str]:
  482. return [
  483. user_id
  484. for user_id, count in self._user_to_num_current_syncs.items()
  485. if count > 0
  486. ]
  487. async def set_state(
  488. self,
  489. target_user: UserID,
  490. state: JsonDict,
  491. ignore_status_msg: bool = False,
  492. force_notify: bool = False,
  493. ) -> None:
  494. """Set the presence state of the user.
  495. Args:
  496. target_user: The ID of the user to set the presence state of.
  497. state: The presence state as a JSON dictionary.
  498. ignore_status_msg: True to ignore the "status_msg" field of the `state` dict.
  499. If False, the user's current status will be updated.
  500. force_notify: Whether to force notification of the update to clients.
  501. """
  502. presence = state["presence"]
  503. if presence not in self.VALID_PRESENCE:
  504. raise SynapseError(400, "Invalid presence state")
  505. user_id = target_user.to_string()
  506. # If presence is disabled, no-op
  507. if not self._presence_enabled:
  508. return
  509. # Proxy request to instance that writes presence
  510. await self._set_state_client(
  511. instance_name=self._presence_writer_instance,
  512. user_id=user_id,
  513. state=state,
  514. ignore_status_msg=ignore_status_msg,
  515. force_notify=force_notify,
  516. )
  517. async def bump_presence_active_time(self, user: UserID) -> None:
  518. """We've seen the user do something that indicates they're interacting
  519. with the app.
  520. """
  521. # If presence is disabled, no-op
  522. if not self._presence_enabled:
  523. return
  524. # Proxy request to instance that writes presence
  525. user_id = user.to_string()
  526. await self._bump_active_client(
  527. instance_name=self._presence_writer_instance, user_id=user_id
  528. )
  529. class PresenceHandler(BasePresenceHandler):
  530. def __init__(self, hs: "HomeServer"):
  531. super().__init__(hs)
  532. self.hs = hs
  533. self.wheel_timer: WheelTimer[str] = WheelTimer()
  534. self.notifier = hs.get_notifier()
  535. federation_registry = hs.get_federation_registry()
  536. federation_registry.register_edu_handler(
  537. EduTypes.PRESENCE, self.incoming_presence
  538. )
  539. LaterGauge(
  540. "synapse_handlers_presence_user_to_current_state_size",
  541. "",
  542. [],
  543. lambda: len(self.user_to_current_state),
  544. )
  545. now = self.clock.time_msec()
  546. if self._presence_enabled:
  547. for state in self.user_to_current_state.values():
  548. self.wheel_timer.insert(
  549. now=now, obj=state.user_id, then=state.last_active_ts + IDLE_TIMER
  550. )
  551. self.wheel_timer.insert(
  552. now=now,
  553. obj=state.user_id,
  554. then=state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT,
  555. )
  556. if self.is_mine_id(state.user_id):
  557. self.wheel_timer.insert(
  558. now=now,
  559. obj=state.user_id,
  560. then=state.last_federation_update_ts + FEDERATION_PING_INTERVAL,
  561. )
  562. else:
  563. self.wheel_timer.insert(
  564. now=now,
  565. obj=state.user_id,
  566. then=state.last_federation_update_ts + FEDERATION_TIMEOUT,
  567. )
  568. # Set of users who have presence in the `user_to_current_state` that
  569. # have not yet been persisted
  570. self.unpersisted_users_changes: Set[str] = set()
  571. hs.get_reactor().addSystemEventTrigger(
  572. "before",
  573. "shutdown",
  574. run_as_background_process,
  575. "presence.on_shutdown",
  576. self._on_shutdown,
  577. )
  578. # Keeps track of the number of *ongoing* syncs on this process. While
  579. # this is non zero a user will never go offline.
  580. self.user_to_num_current_syncs: Dict[str, int] = {}
  581. # Keeps track of the number of *ongoing* syncs on other processes.
  582. # While any sync is ongoing on another process the user will never
  583. # go offline.
  584. # Each process has a unique identifier and an update frequency. If
  585. # no update is received from that process within the update period then
  586. # we assume that all the sync requests on that process have stopped.
  587. # Stored as a dict from process_id to set of user_id, and a dict of
  588. # process_id to millisecond timestamp last updated.
  589. self.external_process_to_current_syncs: Dict[str, Set[str]] = {}
  590. self.external_process_last_updated_ms: Dict[str, int] = {}
  591. self.external_sync_linearizer = Linearizer(name="external_sync_linearizer")
  592. if self._presence_enabled:
  593. # Start a LoopingCall in 30s that fires every 5s.
  594. # The initial delay is to allow disconnected clients a chance to
  595. # reconnect before we treat them as offline.
  596. self.clock.call_later(
  597. 30, self.clock.looping_call, self._handle_timeouts, 5000
  598. )
  599. self.clock.call_later(
  600. 60,
  601. self.clock.looping_call,
  602. self._persist_unpersisted_changes,
  603. 60 * 1000,
  604. )
  605. LaterGauge(
  606. "synapse_handlers_presence_wheel_timer_size",
  607. "",
  608. [],
  609. lambda: len(self.wheel_timer),
  610. )
  611. # Used to handle sending of presence to newly joined users/servers
  612. if self._presence_enabled:
  613. self.notifier.add_replication_callback(self.notify_new_event)
  614. # Presence is best effort and quickly heals itself, so lets just always
  615. # stream from the current state when we restart.
  616. self._event_pos = self.store.get_room_max_stream_ordering()
  617. self._event_processing = False
  618. async def _on_shutdown(self) -> None:
  619. """Gets called when shutting down. This lets us persist any updates that
  620. we haven't yet persisted, e.g. updates that only changes some internal
  621. timers. This allows changes to persist across startup without having to
  622. persist every single change.
  623. If this does not run it simply means that some of the timers will fire
  624. earlier than they should when synapse is restarted. This affect of this
  625. is some spurious presence changes that will self-correct.
  626. """
  627. # If the DB pool has already terminated, don't try updating
  628. if not self.store.db_pool.is_running():
  629. return
  630. logger.info(
  631. "Performing _on_shutdown. Persisting %d unpersisted changes",
  632. len(self.user_to_current_state),
  633. )
  634. if self.unpersisted_users_changes:
  635. await self.store.update_presence(
  636. [
  637. self.user_to_current_state[user_id]
  638. for user_id in self.unpersisted_users_changes
  639. ]
  640. )
  641. logger.info("Finished _on_shutdown")
  642. @wrap_as_background_process("persist_presence_changes")
  643. async def _persist_unpersisted_changes(self) -> None:
  644. """We periodically persist the unpersisted changes, as otherwise they
  645. may stack up and slow down shutdown times.
  646. """
  647. unpersisted = self.unpersisted_users_changes
  648. self.unpersisted_users_changes = set()
  649. if unpersisted:
  650. logger.info("Persisting %d unpersisted presence updates", len(unpersisted))
  651. await self.store.update_presence(
  652. [self.user_to_current_state[user_id] for user_id in unpersisted]
  653. )
  654. async def _update_states(
  655. self, new_states: Iterable[UserPresenceState], force_notify: bool = False
  656. ) -> None:
  657. """Updates presence of users. Sets the appropriate timeouts. Pokes
  658. the notifier and federation if and only if the changed presence state
  659. should be sent to clients/servers.
  660. Args:
  661. new_states: The new user presence state updates to process.
  662. force_notify: Whether to force notifying clients of this presence state update,
  663. even if it doesn't change the state of a user's presence (e.g online -> online).
  664. This is currently used to bump the max presence stream ID without changing any
  665. user's presence (see PresenceHandler.add_users_to_send_full_presence_to).
  666. """
  667. if not self._presence_enabled:
  668. # We shouldn't get here if presence is disabled, but we check anyway
  669. # to ensure that we don't a) send out presence federation and b)
  670. # don't add things to the wheel timer that will never be handled.
  671. logger.warning("Tried to update presence states when presence is disabled")
  672. return
  673. now = self.clock.time_msec()
  674. with Measure(self.clock, "presence_update_states"):
  675. # NOTE: We purposefully don't await between now and when we've
  676. # calculated what we want to do with the new states, to avoid races.
  677. to_notify = {} # Changes we want to notify everyone about
  678. to_federation_ping = {} # These need sending keep-alives
  679. # Only bother handling the last presence change for each user
  680. new_states_dict = {}
  681. for new_state in new_states:
  682. new_states_dict[new_state.user_id] = new_state
  683. new_states = new_states_dict.values()
  684. for new_state in new_states:
  685. user_id = new_state.user_id
  686. # Its fine to not hit the database here, as the only thing not in
  687. # the current state cache are OFFLINE states, where the only field
  688. # of interest is last_active which is safe enough to assume is 0
  689. # here.
  690. prev_state = self.user_to_current_state.get(
  691. user_id, UserPresenceState.default(user_id)
  692. )
  693. new_state, should_notify, should_ping = handle_update(
  694. prev_state,
  695. new_state,
  696. is_mine=self.is_mine_id(user_id),
  697. wheel_timer=self.wheel_timer,
  698. now=now,
  699. )
  700. if force_notify:
  701. should_notify = True
  702. self.user_to_current_state[user_id] = new_state
  703. if should_notify:
  704. to_notify[user_id] = new_state
  705. elif should_ping:
  706. to_federation_ping[user_id] = new_state
  707. # TODO: We should probably ensure there are no races hereafter
  708. presence_updates_counter.inc(len(new_states))
  709. if to_notify:
  710. notified_presence_counter.inc(len(to_notify))
  711. await self._persist_and_notify(list(to_notify.values()))
  712. self.unpersisted_users_changes |= {s.user_id for s in new_states}
  713. self.unpersisted_users_changes -= set(to_notify.keys())
  714. # Check if we need to resend any presence states to remote hosts. We
  715. # only do this for states that haven't been updated in a while to
  716. # ensure that the remote host doesn't time the presence state out.
  717. #
  718. # Note that since these are states that have *not* been updated,
  719. # they won't get sent down the normal presence replication stream,
  720. # and so we have to explicitly send them via the federation stream.
  721. to_federation_ping = {
  722. user_id: state
  723. for user_id, state in to_federation_ping.items()
  724. if user_id not in to_notify
  725. }
  726. if to_federation_ping:
  727. federation_presence_out_counter.inc(len(to_federation_ping))
  728. hosts_to_states = await get_interested_remotes(
  729. self.store,
  730. self.presence_router,
  731. list(to_federation_ping.values()),
  732. )
  733. for destination, states in hosts_to_states.items():
  734. self._federation_queue.send_presence_to_destinations(
  735. states, [destination]
  736. )
  737. @wrap_as_background_process("handle_presence_timeouts")
  738. async def _handle_timeouts(self) -> None:
  739. """Checks the presence of users that have timed out and updates as
  740. appropriate.
  741. """
  742. logger.debug("Handling presence timeouts")
  743. now = self.clock.time_msec()
  744. # Fetch the list of users that *may* have timed out. Things may have
  745. # changed since the timeout was set, so we won't necessarily have to
  746. # take any action.
  747. users_to_check = set(self.wheel_timer.fetch(now))
  748. # Check whether the lists of syncing processes from an external
  749. # process have expired.
  750. expired_process_ids = [
  751. process_id
  752. for process_id, last_update in self.external_process_last_updated_ms.items()
  753. if now - last_update > EXTERNAL_PROCESS_EXPIRY
  754. ]
  755. for process_id in expired_process_ids:
  756. # For each expired process drop tracking info and check the users
  757. # that were syncing on that process to see if they need to be timed
  758. # out.
  759. users_to_check.update(
  760. self.external_process_to_current_syncs.pop(process_id, ())
  761. )
  762. self.external_process_last_updated_ms.pop(process_id)
  763. states = [
  764. self.user_to_current_state.get(user_id, UserPresenceState.default(user_id))
  765. for user_id in users_to_check
  766. ]
  767. timers_fired_counter.inc(len(states))
  768. syncing_user_ids = {
  769. user_id
  770. for user_id, count in self.user_to_num_current_syncs.items()
  771. if count
  772. }
  773. for user_ids in self.external_process_to_current_syncs.values():
  774. syncing_user_ids.update(user_ids)
  775. changes = handle_timeouts(
  776. states,
  777. is_mine_fn=self.is_mine_id,
  778. syncing_user_ids=syncing_user_ids,
  779. now=now,
  780. )
  781. return await self._update_states(changes)
  782. async def bump_presence_active_time(self, user: UserID) -> None:
  783. """We've seen the user do something that indicates they're interacting
  784. with the app.
  785. """
  786. # If presence is disabled, no-op
  787. if not self._presence_enabled:
  788. return
  789. user_id = user.to_string()
  790. bump_active_time_counter.inc()
  791. prev_state = await self.current_state_for_user(user_id)
  792. new_fields: Dict[str, Any] = {"last_active_ts": self.clock.time_msec()}
  793. if prev_state.state == PresenceState.UNAVAILABLE:
  794. new_fields["state"] = PresenceState.ONLINE
  795. await self._update_states([prev_state.copy_and_replace(**new_fields)])
  796. async def user_syncing(
  797. self,
  798. user_id: str,
  799. affect_presence: bool = True,
  800. presence_state: str = PresenceState.ONLINE,
  801. ) -> ContextManager[None]:
  802. """Returns a context manager that should surround any stream requests
  803. from the user.
  804. This allows us to keep track of who is currently streaming and who isn't
  805. without having to have timers outside of this module to avoid flickering
  806. when users disconnect/reconnect.
  807. Args:
  808. user_id
  809. affect_presence: If false this function will be a no-op.
  810. Useful for streams that are not associated with an actual
  811. client that is being used by a user.
  812. presence_state: The presence state indicated in the sync request
  813. """
  814. if not affect_presence or not self._presence_enabled:
  815. return _NullContextManager()
  816. curr_sync = self.user_to_num_current_syncs.get(user_id, 0)
  817. self.user_to_num_current_syncs[user_id] = curr_sync + 1
  818. prev_state = await self.current_state_for_user(user_id)
  819. # If they're busy then they don't stop being busy just by syncing,
  820. # so just update the last sync time.
  821. if prev_state.state != PresenceState.BUSY:
  822. # XXX: We set_state separately here and just update the last_active_ts above
  823. # This keeps the logic as similar as possible between the worker and single
  824. # process modes. Using set_state will actually cause last_active_ts to be
  825. # updated always, which is not what the spec calls for, but synapse has done
  826. # this for... forever, I think.
  827. await self.set_state(
  828. UserID.from_string(user_id),
  829. {"presence": presence_state},
  830. ignore_status_msg=True,
  831. )
  832. # Retrieve the new state for the logic below. This should come from the
  833. # in-memory cache.
  834. prev_state = await self.current_state_for_user(user_id)
  835. # To keep the single process behaviour consistent with worker mode, run the
  836. # same logic as `update_external_syncs_row`, even though it looks weird.
  837. if prev_state.state == PresenceState.OFFLINE:
  838. await self._update_states(
  839. [
  840. prev_state.copy_and_replace(
  841. state=PresenceState.ONLINE,
  842. last_active_ts=self.clock.time_msec(),
  843. last_user_sync_ts=self.clock.time_msec(),
  844. )
  845. ]
  846. )
  847. # otherwise, set the new presence state & update the last sync time,
  848. # but don't update last_active_ts as this isn't an indication that
  849. # they've been active (even though it's probably been updated by
  850. # set_state above)
  851. else:
  852. await self._update_states(
  853. [prev_state.copy_and_replace(last_user_sync_ts=self.clock.time_msec())]
  854. )
  855. async def _end() -> None:
  856. try:
  857. self.user_to_num_current_syncs[user_id] -= 1
  858. prev_state = await self.current_state_for_user(user_id)
  859. await self._update_states(
  860. [
  861. prev_state.copy_and_replace(
  862. last_user_sync_ts=self.clock.time_msec()
  863. )
  864. ]
  865. )
  866. except Exception:
  867. logger.exception("Error updating presence after sync")
  868. @contextmanager
  869. def _user_syncing() -> Generator[None, None, None]:
  870. try:
  871. yield
  872. finally:
  873. run_in_background(_end)
  874. return _user_syncing()
  875. def get_currently_syncing_users_for_replication(self) -> Iterable[str]:
  876. # since we are the process handling presence, there is nothing to do here.
  877. return []
  878. async def update_external_syncs_row(
  879. self, process_id: str, user_id: str, is_syncing: bool, sync_time_msec: int
  880. ) -> None:
  881. """Update the syncing users for an external process as a delta.
  882. Args:
  883. process_id: An identifier for the process the users are
  884. syncing against. This allows synapse to process updates
  885. as user start and stop syncing against a given process.
  886. user_id: The user who has started or stopped syncing
  887. is_syncing: Whether or not the user is now syncing
  888. sync_time_msec: Time in ms when the user was last syncing
  889. """
  890. async with self.external_sync_linearizer.queue(process_id):
  891. prev_state = await self.current_state_for_user(user_id)
  892. process_presence = self.external_process_to_current_syncs.setdefault(
  893. process_id, set()
  894. )
  895. updates = []
  896. if is_syncing and user_id not in process_presence:
  897. if prev_state.state == PresenceState.OFFLINE:
  898. updates.append(
  899. prev_state.copy_and_replace(
  900. state=PresenceState.ONLINE,
  901. last_active_ts=sync_time_msec,
  902. last_user_sync_ts=sync_time_msec,
  903. )
  904. )
  905. else:
  906. updates.append(
  907. prev_state.copy_and_replace(last_user_sync_ts=sync_time_msec)
  908. )
  909. process_presence.add(user_id)
  910. elif user_id in process_presence:
  911. updates.append(
  912. prev_state.copy_and_replace(last_user_sync_ts=sync_time_msec)
  913. )
  914. if not is_syncing:
  915. process_presence.discard(user_id)
  916. if updates:
  917. await self._update_states(updates)
  918. self.external_process_last_updated_ms[process_id] = self.clock.time_msec()
  919. async def update_external_syncs_clear(self, process_id: str) -> None:
  920. """Marks all users that had been marked as syncing by a given process
  921. as offline.
  922. Used when the process has stopped/disappeared.
  923. """
  924. async with self.external_sync_linearizer.queue(process_id):
  925. process_presence = self.external_process_to_current_syncs.pop(
  926. process_id, set()
  927. )
  928. prev_states = await self.current_state_for_users(process_presence)
  929. time_now_ms = self.clock.time_msec()
  930. await self._update_states(
  931. [
  932. prev_state.copy_and_replace(last_user_sync_ts=time_now_ms)
  933. for prev_state in prev_states.values()
  934. ]
  935. )
  936. self.external_process_last_updated_ms.pop(process_id, None)
  937. async def _persist_and_notify(self, states: List[UserPresenceState]) -> None:
  938. """Persist states in the database, poke the notifier and send to
  939. interested remote servers
  940. """
  941. stream_id, max_token = await self.store.update_presence(states)
  942. parties = await get_interested_parties(self.store, self.presence_router, states)
  943. room_ids_to_states, users_to_states = parties
  944. self.notifier.on_new_event(
  945. StreamKeyType.PRESENCE,
  946. stream_id,
  947. rooms=room_ids_to_states.keys(),
  948. users=[UserID.from_string(u) for u in users_to_states],
  949. )
  950. # We only want to poke the local federation sender, if any, as other
  951. # workers will receive the presence updates via the presence replication
  952. # stream (which is updated by `store.update_presence`).
  953. await self.maybe_send_presence_to_interested_destinations(states)
  954. async def incoming_presence(self, origin: str, content: JsonDict) -> None:
  955. """Called when we receive a `m.presence` EDU from a remote server."""
  956. if not self._presence_enabled:
  957. return
  958. now = self.clock.time_msec()
  959. updates = []
  960. for push in content.get("push", []):
  961. # A "push" contains a list of presence that we are probably interested
  962. # in.
  963. user_id = push.get("user_id", None)
  964. if not user_id:
  965. logger.info(
  966. "Got presence update from %r with no 'user_id': %r", origin, push
  967. )
  968. continue
  969. if get_domain_from_id(user_id) != origin:
  970. logger.info(
  971. "Got presence update from %r with bad 'user_id': %r",
  972. origin,
  973. user_id,
  974. )
  975. continue
  976. presence_state = push.get("presence", None)
  977. if not presence_state:
  978. logger.info(
  979. "Got presence update from %r with no 'presence_state': %r",
  980. origin,
  981. push,
  982. )
  983. continue
  984. new_fields = {"state": presence_state, "last_federation_update_ts": now}
  985. last_active_ago = push.get("last_active_ago", None)
  986. if last_active_ago is not None:
  987. new_fields["last_active_ts"] = now - last_active_ago
  988. new_fields["status_msg"] = push.get("status_msg", None)
  989. new_fields["currently_active"] = push.get("currently_active", False)
  990. prev_state = await self.current_state_for_user(user_id)
  991. updates.append(prev_state.copy_and_replace(**new_fields))
  992. if updates:
  993. federation_presence_counter.inc(len(updates))
  994. await self._update_states(updates)
  995. async def set_state(
  996. self,
  997. target_user: UserID,
  998. state: JsonDict,
  999. ignore_status_msg: bool = False,
  1000. force_notify: bool = False,
  1001. ) -> None:
  1002. """Set the presence state of the user.
  1003. Args:
  1004. target_user: The ID of the user to set the presence state of.
  1005. state: The presence state as a JSON dictionary.
  1006. ignore_status_msg: True to ignore the "status_msg" field of the `state` dict.
  1007. If False, the user's current status will be updated.
  1008. force_notify: Whether to force notification of the update to clients.
  1009. """
  1010. status_msg = state.get("status_msg", None)
  1011. presence = state["presence"]
  1012. if presence not in self.VALID_PRESENCE:
  1013. raise SynapseError(400, "Invalid presence state")
  1014. # If presence is disabled, no-op
  1015. if not self._presence_enabled:
  1016. return
  1017. user_id = target_user.to_string()
  1018. prev_state = await self.current_state_for_user(user_id)
  1019. new_fields = {"state": presence}
  1020. if not ignore_status_msg:
  1021. new_fields["status_msg"] = status_msg
  1022. if presence == PresenceState.ONLINE or (
  1023. presence == PresenceState.BUSY and self._busy_presence_enabled
  1024. ):
  1025. new_fields["last_active_ts"] = self.clock.time_msec()
  1026. await self._update_states(
  1027. [prev_state.copy_and_replace(**new_fields)], force_notify=force_notify
  1028. )
  1029. async def is_visible(self, observed_user: UserID, observer_user: UserID) -> bool:
  1030. """Returns whether a user can see another user's presence."""
  1031. observer_room_ids = await self.store.get_rooms_for_user(
  1032. observer_user.to_string()
  1033. )
  1034. observed_room_ids = await self.store.get_rooms_for_user(
  1035. observed_user.to_string()
  1036. )
  1037. if observer_room_ids & observed_room_ids:
  1038. return True
  1039. return False
  1040. async def get_all_presence_updates(
  1041. self, instance_name: str, last_id: int, current_id: int, limit: int
  1042. ) -> Tuple[List[Tuple[int, list]], int, bool]:
  1043. """
  1044. Gets a list of presence update rows from between the given stream ids.
  1045. Each row has:
  1046. - stream_id(str)
  1047. - user_id(str)
  1048. - state(str)
  1049. - last_active_ts(int)
  1050. - last_federation_update_ts(int)
  1051. - last_user_sync_ts(int)
  1052. - status_msg(int)
  1053. - currently_active(int)
  1054. Args:
  1055. instance_name: The writer we want to fetch updates from. Unused
  1056. here since there is only ever one writer.
  1057. last_id: The token to fetch updates from. Exclusive.
  1058. current_id: The token to fetch updates up to. Inclusive.
  1059. limit: The requested limit for the number of rows to return. The
  1060. function may return more or fewer rows.
  1061. Returns:
  1062. A tuple consisting of: the updates, a token to use to fetch
  1063. subsequent updates, and whether we returned fewer rows than exists
  1064. between the requested tokens due to the limit.
  1065. The token returned can be used in a subsequent call to this
  1066. function to get further updates.
  1067. The updates are a list of 2-tuples of stream ID and the row data
  1068. """
  1069. # TODO(markjh): replicate the unpersisted changes.
  1070. # This could use the in-memory stores for recent changes.
  1071. rows = await self.store.get_all_presence_updates(
  1072. instance_name, last_id, current_id, limit
  1073. )
  1074. return rows
  1075. def notify_new_event(self) -> None:
  1076. """Called when new events have happened. Handles users and servers
  1077. joining rooms and require being sent presence.
  1078. """
  1079. if self._event_processing:
  1080. return
  1081. async def _process_presence() -> None:
  1082. assert not self._event_processing
  1083. self._event_processing = True
  1084. try:
  1085. await self._unsafe_process()
  1086. finally:
  1087. self._event_processing = False
  1088. run_as_background_process("presence.notify_new_event", _process_presence)
  1089. async def _unsafe_process(self) -> None:
  1090. # Loop round handling deltas until we're up to date
  1091. while True:
  1092. with Measure(self.clock, "presence_delta"):
  1093. room_max_stream_ordering = self.store.get_room_max_stream_ordering()
  1094. if self._event_pos == room_max_stream_ordering:
  1095. return
  1096. logger.debug(
  1097. "Processing presence stats %s->%s",
  1098. self._event_pos,
  1099. room_max_stream_ordering,
  1100. )
  1101. (
  1102. max_pos,
  1103. deltas,
  1104. ) = await self._storage_controllers.state.get_current_state_deltas(
  1105. self._event_pos, room_max_stream_ordering
  1106. )
  1107. # We may get multiple deltas for different rooms, but we want to
  1108. # handle them on a room by room basis, so we batch them up by
  1109. # room.
  1110. deltas_by_room: Dict[str, List[JsonDict]] = {}
  1111. for delta in deltas:
  1112. deltas_by_room.setdefault(delta["room_id"], []).append(delta)
  1113. for room_id, deltas_for_room in deltas_by_room.items():
  1114. await self._handle_state_delta(room_id, deltas_for_room)
  1115. self._event_pos = max_pos
  1116. # Expose current event processing position to prometheus
  1117. synapse.metrics.event_processing_positions.labels("presence").set(
  1118. max_pos
  1119. )
  1120. async def _handle_state_delta(self, room_id: str, deltas: List[JsonDict]) -> None:
  1121. """Process current state deltas for the room to find new joins that need
  1122. to be handled.
  1123. """
  1124. # Sets of newly joined users. Note that if the local server is
  1125. # joining a remote room for the first time we'll see both the joining
  1126. # user and all remote users as newly joined.
  1127. newly_joined_users = set()
  1128. for delta in deltas:
  1129. assert room_id == delta["room_id"]
  1130. typ = delta["type"]
  1131. state_key = delta["state_key"]
  1132. event_id = delta["event_id"]
  1133. prev_event_id = delta["prev_event_id"]
  1134. logger.debug("Handling: %r %r, %s", typ, state_key, event_id)
  1135. # Drop any event that isn't a membership join
  1136. if typ != EventTypes.Member:
  1137. continue
  1138. if event_id is None:
  1139. # state has been deleted, so this is not a join. We only care about
  1140. # joins.
  1141. continue
  1142. event = await self.store.get_event(event_id, allow_none=True)
  1143. if not event or event.content.get("membership") != Membership.JOIN:
  1144. # We only care about joins
  1145. continue
  1146. if prev_event_id:
  1147. prev_event = await self.store.get_event(prev_event_id, allow_none=True)
  1148. if (
  1149. prev_event
  1150. and prev_event.content.get("membership") == Membership.JOIN
  1151. ):
  1152. # Ignore changes to join events.
  1153. continue
  1154. newly_joined_users.add(state_key)
  1155. if not newly_joined_users:
  1156. # If nobody has joined then there's nothing to do.
  1157. return
  1158. # We want to send:
  1159. # 1. presence states of all local users in the room to newly joined
  1160. # remote servers
  1161. # 2. presence states of newly joined users to all remote servers in
  1162. # the room.
  1163. #
  1164. # TODO: Only send presence states to remote hosts that don't already
  1165. # have them (because they already share rooms).
  1166. # Get all the users who were already in the room, by fetching the
  1167. # current users in the room and removing the newly joined users.
  1168. users = await self.store.get_users_in_room(room_id)
  1169. prev_users = set(users) - newly_joined_users
  1170. # Construct sets for all the local users and remote hosts that were
  1171. # already in the room
  1172. prev_local_users = []
  1173. prev_remote_hosts = set()
  1174. for user_id in prev_users:
  1175. if self.is_mine_id(user_id):
  1176. prev_local_users.append(user_id)
  1177. else:
  1178. prev_remote_hosts.add(get_domain_from_id(user_id))
  1179. # Similarly, construct sets for all the local users and remote hosts
  1180. # that were *not* already in the room. Care needs to be taken with the
  1181. # calculating the remote hosts, as a host may have already been in the
  1182. # room even if there is a newly joined user from that host.
  1183. newly_joined_local_users = []
  1184. newly_joined_remote_hosts = set()
  1185. for user_id in newly_joined_users:
  1186. if self.is_mine_id(user_id):
  1187. newly_joined_local_users.append(user_id)
  1188. else:
  1189. host = get_domain_from_id(user_id)
  1190. if host not in prev_remote_hosts:
  1191. newly_joined_remote_hosts.add(host)
  1192. # Send presence states of all local users in the room to newly joined
  1193. # remote servers. (We actually only send states for local users already
  1194. # in the room, as we'll send states for newly joined local users below.)
  1195. if prev_local_users and newly_joined_remote_hosts:
  1196. local_states = await self.current_state_for_users(prev_local_users)
  1197. # Filter out old presence, i.e. offline presence states where
  1198. # the user hasn't been active for a week. We can change this
  1199. # depending on what we want the UX to be, but at the least we
  1200. # should filter out offline presence where the state is just the
  1201. # default state.
  1202. now = self.clock.time_msec()
  1203. states = [
  1204. state
  1205. for state in local_states.values()
  1206. if state.state != PresenceState.OFFLINE
  1207. or now - state.last_active_ts < 7 * 24 * 60 * 60 * 1000
  1208. or state.status_msg is not None
  1209. ]
  1210. self._federation_queue.send_presence_to_destinations(
  1211. destinations=newly_joined_remote_hosts,
  1212. states=states,
  1213. )
  1214. # Send presence states of newly joined users to all remote servers in
  1215. # the room
  1216. if newly_joined_local_users and (
  1217. prev_remote_hosts or newly_joined_remote_hosts
  1218. ):
  1219. local_states = await self.current_state_for_users(newly_joined_local_users)
  1220. self._federation_queue.send_presence_to_destinations(
  1221. destinations=prev_remote_hosts | newly_joined_remote_hosts,
  1222. states=list(local_states.values()),
  1223. )
  1224. def should_notify(
  1225. old_state: UserPresenceState, new_state: UserPresenceState, is_mine: bool
  1226. ) -> bool:
  1227. """Decides if a presence state change should be sent to interested parties."""
  1228. user_location = "remote"
  1229. if is_mine:
  1230. user_location = "local"
  1231. if old_state == new_state:
  1232. return False
  1233. if old_state.status_msg != new_state.status_msg:
  1234. notify_reason_counter.labels(user_location, "status_msg_change").inc()
  1235. return True
  1236. if old_state.state != new_state.state:
  1237. notify_reason_counter.labels(user_location, "state_change").inc()
  1238. state_transition_counter.labels(
  1239. user_location, old_state.state, new_state.state
  1240. ).inc()
  1241. return True
  1242. if old_state.state == PresenceState.ONLINE:
  1243. if new_state.currently_active != old_state.currently_active:
  1244. notify_reason_counter.labels(user_location, "current_active_change").inc()
  1245. return True
  1246. if (
  1247. new_state.last_active_ts - old_state.last_active_ts
  1248. > LAST_ACTIVE_GRANULARITY
  1249. ):
  1250. # Only notify about last active bumps if we're not currently active
  1251. if not new_state.currently_active:
  1252. notify_reason_counter.labels(
  1253. user_location, "last_active_change_online"
  1254. ).inc()
  1255. return True
  1256. elif new_state.last_active_ts - old_state.last_active_ts > LAST_ACTIVE_GRANULARITY:
  1257. # Always notify for a transition where last active gets bumped.
  1258. notify_reason_counter.labels(
  1259. user_location, "last_active_change_not_online"
  1260. ).inc()
  1261. return True
  1262. return False
  1263. def format_user_presence_state(
  1264. state: UserPresenceState, now: int, include_user_id: bool = True
  1265. ) -> JsonDict:
  1266. """Convert UserPresenceState to a JSON format that can be sent down to clients
  1267. and to other servers.
  1268. Args:
  1269. state: The user presence state to format.
  1270. now: The current timestamp since the epoch in ms.
  1271. include_user_id: Whether to include `user_id` in the returned dictionary.
  1272. As this function can be used both to format presence updates for client /sync
  1273. responses and for federation /send requests, only the latter needs the include
  1274. the `user_id` field.
  1275. Returns:
  1276. A JSON dictionary with the following keys:
  1277. * presence: The presence state as a str.
  1278. * user_id: Optional. Included if `include_user_id` is truthy. The canonical
  1279. Matrix ID of the user.
  1280. * last_active_ago: Optional. Included if `last_active_ts` is set on `state`.
  1281. The timestamp that the user was last active.
  1282. * status_msg: Optional. Included if `status_msg` is set on `state`. The user's
  1283. status.
  1284. * currently_active: Optional. Included only if `state.state` is "online".
  1285. Example:
  1286. {
  1287. "presence": "online",
  1288. "user_id": "@alice:example.com",
  1289. "last_active_ago": 16783813918,
  1290. "status_msg": "Hello world!",
  1291. "currently_active": True
  1292. }
  1293. """
  1294. content: JsonDict = {"presence": state.state}
  1295. if include_user_id:
  1296. content["user_id"] = state.user_id
  1297. if state.last_active_ts:
  1298. content["last_active_ago"] = now - state.last_active_ts
  1299. if state.status_msg:
  1300. content["status_msg"] = state.status_msg
  1301. if state.state == PresenceState.ONLINE:
  1302. content["currently_active"] = state.currently_active
  1303. return content
  1304. class PresenceEventSource(EventSource[int, UserPresenceState]):
  1305. def __init__(self, hs: "HomeServer"):
  1306. # We can't call get_presence_handler here because there's a cycle:
  1307. #
  1308. # Presence -> Notifier -> PresenceEventSource -> Presence
  1309. #
  1310. # Same with get_presence_router:
  1311. #
  1312. # AuthHandler -> Notifier -> PresenceEventSource -> ModuleApi -> AuthHandler
  1313. self.get_presence_handler = hs.get_presence_handler
  1314. self.get_presence_router = hs.get_presence_router
  1315. self.clock = hs.get_clock()
  1316. self.store = hs.get_datastores().main
  1317. async def get_new_events(
  1318. self,
  1319. user: UserID,
  1320. from_key: Optional[int],
  1321. # Having a default limit doesn't match the EventSource API, but some
  1322. # callers do not provide it. It is unused in this class.
  1323. limit: int = 0,
  1324. room_ids: Optional[StrCollection] = None,
  1325. is_guest: bool = False,
  1326. explicit_room_id: Optional[str] = None,
  1327. include_offline: bool = True,
  1328. service: Optional[ApplicationService] = None,
  1329. ) -> Tuple[List[UserPresenceState], int]:
  1330. # The process for getting presence events are:
  1331. # 1. Get the rooms the user is in.
  1332. # 2. Get the list of user in the rooms.
  1333. # 3. Get the list of users that are in the user's presence list.
  1334. # 4. If there is a from_key set, cross reference the list of users
  1335. # with the `presence_stream_cache` to see which ones we actually
  1336. # need to check.
  1337. # 5. Load current state for the users.
  1338. #
  1339. # We don't try and limit the presence updates by the current token, as
  1340. # sending down the rare duplicate is not a concern.
  1341. user_id = user.to_string()
  1342. stream_change_cache = self.store.presence_stream_cache
  1343. with Measure(self.clock, "presence.get_new_events"):
  1344. if from_key is not None:
  1345. from_key = int(from_key)
  1346. # Check if this user should receive all current, online user presence. We only
  1347. # bother to do this if from_key is set, as otherwise the user will receive all
  1348. # user presence anyways.
  1349. if await self.store.should_user_receive_full_presence_with_token(
  1350. user_id, from_key
  1351. ):
  1352. # This user has been specified by a module to receive all current, online
  1353. # user presence. Removing from_key and setting include_offline to false
  1354. # will do effectively this.
  1355. from_key = None
  1356. include_offline = False
  1357. max_token = self.store.get_current_presence_token()
  1358. if from_key == max_token:
  1359. # This is necessary as due to the way stream ID generators work
  1360. # we may get updates that have a stream ID greater than the max
  1361. # token (e.g. max_token is N but stream generator may return
  1362. # results for N+2, due to N+1 not having finished being
  1363. # persisted yet).
  1364. #
  1365. # This is usually fine, as it just means that we may send down
  1366. # some presence updates multiple times. However, we need to be
  1367. # careful that the sync stream either actually does make some
  1368. # progress or doesn't return, otherwise clients will end up
  1369. # tight looping calling /sync due to it immediately returning
  1370. # the same token repeatedly.
  1371. #
  1372. # Hence this guard where we just return nothing so that the sync
  1373. # doesn't return. C.f. #5503.
  1374. return [], max_token
  1375. # Figure out which other users this user should explicitly receive
  1376. # updates for
  1377. additional_users_interested_in = (
  1378. await self.get_presence_router().get_interested_users(user.to_string())
  1379. )
  1380. # We have a set of users that we're interested in the presence of. We want to
  1381. # cross-reference that with the users that have actually changed their presence.
  1382. # Check whether this user should see all user updates
  1383. if additional_users_interested_in == PresenceRouter.ALL_USERS:
  1384. # Provide presence state for all users
  1385. presence_updates = await self._filter_all_presence_updates_for_user(
  1386. user_id, include_offline, from_key
  1387. )
  1388. return presence_updates, max_token
  1389. # Make mypy happy. users_interested_in should now be a set
  1390. assert not isinstance(additional_users_interested_in, str)
  1391. # We always care about our own presence.
  1392. additional_users_interested_in.add(user_id)
  1393. if explicit_room_id:
  1394. user_ids = await self.store.get_users_in_room(explicit_room_id)
  1395. additional_users_interested_in.update(user_ids)
  1396. # The set of users that we're interested in and that have had a presence update.
  1397. # We'll actually pull the presence updates for these users at the end.
  1398. interested_and_updated_users: StrCollection
  1399. if from_key is not None:
  1400. # First get all users that have had a presence update
  1401. result = stream_change_cache.get_all_entities_changed(from_key)
  1402. # Cross-reference users we're interested in with those that have had updates.
  1403. if result.hit:
  1404. updated_users = result.entities
  1405. # If we have the full list of changes for presence we can
  1406. # simply check which ones share a room with the user.
  1407. get_updates_counter.labels("stream").inc()
  1408. sharing_users = await self.store.do_users_share_a_room(
  1409. user_id, updated_users
  1410. )
  1411. interested_and_updated_users = (
  1412. sharing_users.union(additional_users_interested_in)
  1413. ).intersection(updated_users)
  1414. else:
  1415. # Too many possible updates. Find all users we can see and check
  1416. # if any of them have changed.
  1417. get_updates_counter.labels("full").inc()
  1418. users_interested_in = (
  1419. await self.store.get_users_who_share_room_with_user(user_id)
  1420. )
  1421. users_interested_in.update(additional_users_interested_in)
  1422. interested_and_updated_users = (
  1423. stream_change_cache.get_entities_changed(
  1424. users_interested_in, from_key
  1425. )
  1426. )
  1427. else:
  1428. # No from_key has been specified. Return the presence for all users
  1429. # this user is interested in
  1430. interested_and_updated_users = (
  1431. await self.store.get_users_who_share_room_with_user(user_id)
  1432. )
  1433. interested_and_updated_users.update(additional_users_interested_in)
  1434. # Retrieve the current presence state for each user
  1435. users_to_state = await self.get_presence_handler().current_state_for_users(
  1436. interested_and_updated_users
  1437. )
  1438. presence_updates = list(users_to_state.values())
  1439. if not include_offline:
  1440. # Filter out offline presence states
  1441. presence_updates = self._filter_offline_presence_state(presence_updates)
  1442. return presence_updates, max_token
  1443. async def _filter_all_presence_updates_for_user(
  1444. self,
  1445. user_id: str,
  1446. include_offline: bool,
  1447. from_key: Optional[int] = None,
  1448. ) -> List[UserPresenceState]:
  1449. """
  1450. Computes the presence updates a user should receive.
  1451. First pulls presence updates from the database. Then consults PresenceRouter
  1452. for whether any updates should be excluded by user ID.
  1453. Args:
  1454. user_id: The User ID of the user to compute presence updates for.
  1455. include_offline: Whether to include offline presence states from the results.
  1456. from_key: The minimum stream ID of updates to pull from the database
  1457. before filtering.
  1458. Returns:
  1459. A list of presence states for the given user to receive.
  1460. """
  1461. updated_users = None
  1462. if from_key:
  1463. # Only return updates since the last sync
  1464. result = self.store.presence_stream_cache.get_all_entities_changed(from_key)
  1465. if result.hit:
  1466. updated_users = result.entities
  1467. if updated_users is not None:
  1468. # Get the actual presence update for each change
  1469. users_to_state = await self.get_presence_handler().current_state_for_users(
  1470. updated_users
  1471. )
  1472. presence_updates = list(users_to_state.values())
  1473. if not include_offline:
  1474. # Filter out offline states
  1475. presence_updates = self._filter_offline_presence_state(presence_updates)
  1476. else:
  1477. users_to_state = await self.store.get_presence_for_all_users(
  1478. include_offline=include_offline
  1479. )
  1480. presence_updates = list(users_to_state.values())
  1481. # TODO: This feels wildly inefficient, and it's unfortunate we need to ask the
  1482. # module for information on a number of users when we then only take the info
  1483. # for a single user
  1484. # Filter through the presence router
  1485. users_to_state_set = await self.get_presence_router().get_users_for_states(
  1486. presence_updates
  1487. )
  1488. # We only want the mapping for the syncing user
  1489. presence_updates = list(users_to_state_set[user_id])
  1490. # Return presence information for all users
  1491. return presence_updates
  1492. def _filter_offline_presence_state(
  1493. self, presence_updates: Iterable[UserPresenceState]
  1494. ) -> List[UserPresenceState]:
  1495. """Given an iterable containing user presence updates, return a list with any offline
  1496. presence states removed.
  1497. Args:
  1498. presence_updates: Presence states to filter
  1499. Returns:
  1500. A new list with any offline presence states removed.
  1501. """
  1502. return [
  1503. update
  1504. for update in presence_updates
  1505. if update.state != PresenceState.OFFLINE
  1506. ]
  1507. def get_current_key(self) -> int:
  1508. return self.store.get_current_presence_token()
  1509. def handle_timeouts(
  1510. user_states: List[UserPresenceState],
  1511. is_mine_fn: Callable[[str], bool],
  1512. syncing_user_ids: Set[str],
  1513. now: int,
  1514. ) -> List[UserPresenceState]:
  1515. """Checks the presence of users that have timed out and updates as
  1516. appropriate.
  1517. Args:
  1518. user_states: List of UserPresenceState's to check.
  1519. is_mine_fn: Function that returns if a user_id is ours
  1520. syncing_user_ids: Set of user_ids with active syncs.
  1521. now: Current time in ms.
  1522. Returns:
  1523. List of UserPresenceState updates
  1524. """
  1525. changes = {} # Actual changes we need to notify people about
  1526. for state in user_states:
  1527. is_mine = is_mine_fn(state.user_id)
  1528. new_state = handle_timeout(state, is_mine, syncing_user_ids, now)
  1529. if new_state:
  1530. changes[state.user_id] = new_state
  1531. return list(changes.values())
  1532. def handle_timeout(
  1533. state: UserPresenceState, is_mine: bool, syncing_user_ids: Set[str], now: int
  1534. ) -> Optional[UserPresenceState]:
  1535. """Checks the presence of the user to see if any of the timers have elapsed
  1536. Args:
  1537. state
  1538. is_mine: Whether the user is ours
  1539. syncing_user_ids: Set of user_ids with active syncs.
  1540. now: Current time in ms.
  1541. Returns:
  1542. A UserPresenceState update or None if no update.
  1543. """
  1544. if state.state == PresenceState.OFFLINE:
  1545. # No timeouts are associated with offline states.
  1546. return None
  1547. changed = False
  1548. user_id = state.user_id
  1549. if is_mine:
  1550. if state.state == PresenceState.ONLINE:
  1551. if now - state.last_active_ts > IDLE_TIMER:
  1552. # Currently online, but last activity ages ago so auto
  1553. # idle
  1554. state = state.copy_and_replace(state=PresenceState.UNAVAILABLE)
  1555. changed = True
  1556. elif now - state.last_active_ts > LAST_ACTIVE_GRANULARITY:
  1557. # So that we send down a notification that we've
  1558. # stopped updating.
  1559. changed = True
  1560. if now - state.last_federation_update_ts > FEDERATION_PING_INTERVAL:
  1561. # Need to send ping to other servers to ensure they don't
  1562. # timeout and set us to offline
  1563. changed = True
  1564. # If there are have been no sync for a while (and none ongoing),
  1565. # set presence to offline
  1566. if user_id not in syncing_user_ids:
  1567. # If the user has done something recently but hasn't synced,
  1568. # don't set them as offline.
  1569. sync_or_active = max(state.last_user_sync_ts, state.last_active_ts)
  1570. if now - sync_or_active > SYNC_ONLINE_TIMEOUT:
  1571. state = state.copy_and_replace(state=PresenceState.OFFLINE)
  1572. changed = True
  1573. else:
  1574. # We expect to be poked occasionally by the other side.
  1575. # This is to protect against forgetful/buggy servers, so that
  1576. # no one gets stuck online forever.
  1577. if now - state.last_federation_update_ts > FEDERATION_TIMEOUT:
  1578. # The other side seems to have disappeared.
  1579. state = state.copy_and_replace(state=PresenceState.OFFLINE)
  1580. changed = True
  1581. return state if changed else None
  1582. def handle_update(
  1583. prev_state: UserPresenceState,
  1584. new_state: UserPresenceState,
  1585. is_mine: bool,
  1586. wheel_timer: WheelTimer,
  1587. now: int,
  1588. ) -> Tuple[UserPresenceState, bool, bool]:
  1589. """Given a presence update:
  1590. 1. Add any appropriate timers.
  1591. 2. Check if we should notify anyone.
  1592. Args:
  1593. prev_state
  1594. new_state
  1595. is_mine: Whether the user is ours
  1596. wheel_timer
  1597. now: Time now in ms
  1598. Returns:
  1599. 3-tuple: `(new_state, persist_and_notify, federation_ping)` where:
  1600. - new_state: is the state to actually persist
  1601. - persist_and_notify: whether to persist and notify people
  1602. - federation_ping: whether we should send a ping over federation
  1603. """
  1604. user_id = new_state.user_id
  1605. persist_and_notify = False
  1606. federation_ping = False
  1607. # If the users are ours then we want to set up a bunch of timers
  1608. # to time things out.
  1609. if is_mine:
  1610. if new_state.state == PresenceState.ONLINE:
  1611. # Idle timer
  1612. wheel_timer.insert(
  1613. now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER
  1614. )
  1615. active = now - new_state.last_active_ts < LAST_ACTIVE_GRANULARITY
  1616. new_state = new_state.copy_and_replace(currently_active=active)
  1617. if active:
  1618. wheel_timer.insert(
  1619. now=now,
  1620. obj=user_id,
  1621. then=new_state.last_active_ts + LAST_ACTIVE_GRANULARITY,
  1622. )
  1623. if new_state.state != PresenceState.OFFLINE:
  1624. # User has stopped syncing
  1625. wheel_timer.insert(
  1626. now=now,
  1627. obj=user_id,
  1628. then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT,
  1629. )
  1630. last_federate = new_state.last_federation_update_ts
  1631. if now - last_federate > FEDERATION_PING_INTERVAL:
  1632. # Been a while since we've poked remote servers
  1633. new_state = new_state.copy_and_replace(last_federation_update_ts=now)
  1634. federation_ping = True
  1635. else:
  1636. wheel_timer.insert(
  1637. now=now,
  1638. obj=user_id,
  1639. then=new_state.last_federation_update_ts + FEDERATION_TIMEOUT,
  1640. )
  1641. # Check whether the change was something worth notifying about
  1642. if should_notify(prev_state, new_state, is_mine):
  1643. new_state = new_state.copy_and_replace(last_federation_update_ts=now)
  1644. persist_and_notify = True
  1645. return new_state, persist_and_notify, federation_ping
  1646. async def get_interested_parties(
  1647. store: DataStore, presence_router: PresenceRouter, states: List[UserPresenceState]
  1648. ) -> Tuple[Dict[str, List[UserPresenceState]], Dict[str, List[UserPresenceState]]]:
  1649. """Given a list of states return which entities (rooms, users)
  1650. are interested in the given states.
  1651. Args:
  1652. store: The homeserver's data store.
  1653. presence_router: A module for augmenting the destinations for presence updates.
  1654. states: A list of incoming user presence updates.
  1655. Returns:
  1656. A 2-tuple of `(room_ids_to_states, users_to_states)`,
  1657. with each item being a dict of `entity_name` -> `[UserPresenceState]`
  1658. """
  1659. room_ids_to_states: Dict[str, List[UserPresenceState]] = {}
  1660. users_to_states: Dict[str, List[UserPresenceState]] = {}
  1661. for state in states:
  1662. room_ids = await store.get_rooms_for_user(state.user_id)
  1663. for room_id in room_ids:
  1664. room_ids_to_states.setdefault(room_id, []).append(state)
  1665. # Always notify self
  1666. users_to_states.setdefault(state.user_id, []).append(state)
  1667. # Ask a presence routing module for any additional parties if one
  1668. # is loaded.
  1669. router_users_to_states = await presence_router.get_users_for_states(states)
  1670. # Update the dictionaries with additional destinations and state to send
  1671. for user_id, user_states in router_users_to_states.items():
  1672. users_to_states.setdefault(user_id, []).extend(user_states)
  1673. return room_ids_to_states, users_to_states
  1674. async def get_interested_remotes(
  1675. store: DataStore,
  1676. presence_router: PresenceRouter,
  1677. states: List[UserPresenceState],
  1678. ) -> Dict[str, Set[UserPresenceState]]:
  1679. """Given a list of presence states figure out which remote servers
  1680. should be sent which.
  1681. All the presence states should be for local users only.
  1682. Args:
  1683. store: The homeserver's data store.
  1684. presence_router: A module for augmenting the destinations for presence updates.
  1685. states: A list of incoming user presence updates.
  1686. Returns:
  1687. A map from destinations to presence states to send to that destination.
  1688. """
  1689. hosts_and_states: Dict[str, Set[UserPresenceState]] = {}
  1690. # First we look up the rooms each user is in (as well as any explicit
  1691. # subscriptions), then for each distinct room we look up the remote
  1692. # hosts in those rooms.
  1693. room_ids_to_states, users_to_states = await get_interested_parties(
  1694. store, presence_router, states
  1695. )
  1696. for room_id, states in room_ids_to_states.items():
  1697. hosts = await store.get_current_hosts_in_room(room_id)
  1698. for host in hosts:
  1699. hosts_and_states.setdefault(host, set()).update(states)
  1700. for user_id, states in users_to_states.items():
  1701. host = get_domain_from_id(user_id)
  1702. hosts_and_states.setdefault(host, set()).update(states)
  1703. return hosts_and_states
  1704. class PresenceFederationQueue:
  1705. """Handles sending ad hoc presence updates over federation, which are *not*
  1706. due to state updates (that get handled via the presence stream), e.g.
  1707. federation pings and sending existing present states to newly joined hosts.
  1708. Only the last N minutes will be queued, so if a federation sender instance
  1709. is down for longer then some updates will be dropped. This is OK as presence
  1710. is ephemeral, and so it will self correct eventually.
  1711. On workers the class tracks the last received position of the stream from
  1712. replication, and handles querying for missed updates over HTTP replication,
  1713. c.f. `get_current_token` and `get_replication_rows`.
  1714. """
  1715. # How long to keep entries in the queue for. Workers that are down for
  1716. # longer than this duration will miss out on older updates.
  1717. _KEEP_ITEMS_IN_QUEUE_FOR_MS = 5 * 60 * 1000
  1718. # How often to check if we can expire entries from the queue.
  1719. _CLEAR_ITEMS_EVERY_MS = 60 * 1000
  1720. def __init__(self, hs: "HomeServer", presence_handler: BasePresenceHandler):
  1721. self._clock = hs.get_clock()
  1722. self._notifier = hs.get_notifier()
  1723. self._instance_name = hs.get_instance_name()
  1724. self._presence_handler = presence_handler
  1725. self._repl_client = ReplicationGetStreamUpdates.make_client(hs)
  1726. # Should we keep a queue of recent presence updates? We only bother if
  1727. # another process may be handling federation sending.
  1728. self._queue_presence_updates = True
  1729. # Whether this instance is a presence writer.
  1730. self._presence_writer = self._instance_name in hs.config.worker.writers.presence
  1731. # The FederationSender instance, if this process sends federation traffic directly.
  1732. self._federation = None
  1733. if hs.should_send_federation():
  1734. self._federation = hs.get_federation_sender()
  1735. # We don't bother queuing up presence states if only this instance
  1736. # is sending federation.
  1737. if hs.config.worker.federation_shard_config.instances == [
  1738. self._instance_name
  1739. ]:
  1740. self._queue_presence_updates = False
  1741. # The queue of recently queued updates as tuples of: `(timestamp,
  1742. # stream_id, destinations, user_ids)`. We don't store the full states
  1743. # for efficiency, and remote workers will already have the full states
  1744. # cached.
  1745. self._queue: List[Tuple[int, int, StrCollection, Set[str]]] = []
  1746. self._next_id = 1
  1747. # Map from instance name to current token
  1748. self._current_tokens: Dict[str, int] = {}
  1749. if self._queue_presence_updates:
  1750. self._clock.looping_call(self._clear_queue, self._CLEAR_ITEMS_EVERY_MS)
  1751. def _clear_queue(self) -> None:
  1752. """Clear out older entries from the queue."""
  1753. clear_before = self._clock.time_msec() - self._KEEP_ITEMS_IN_QUEUE_FOR_MS
  1754. # The queue is sorted by timestamp, so we can bisect to find the right
  1755. # place to purge before. Note that we are searching using a 1-tuple with
  1756. # the time, which does The Right Thing since the queue is a tuple where
  1757. # the first item is a timestamp.
  1758. index = bisect(self._queue, (clear_before,))
  1759. self._queue = self._queue[index:]
  1760. def send_presence_to_destinations(
  1761. self, states: Collection[UserPresenceState], destinations: StrCollection
  1762. ) -> None:
  1763. """Send the presence states to the given destinations.
  1764. Will forward to the local federation sender (if there is one) and queue
  1765. to send over replication (if there are other federation sender instances.).
  1766. Must only be called on the presence writer process.
  1767. """
  1768. # This should only be called on a presence writer.
  1769. assert self._presence_writer
  1770. if not states or not destinations:
  1771. # Ignore calls which either don't have any new states or don't need
  1772. # to be sent anywhere.
  1773. return
  1774. if self._federation:
  1775. self._federation.send_presence_to_destinations(
  1776. states=states,
  1777. destinations=destinations,
  1778. )
  1779. if not self._queue_presence_updates:
  1780. return
  1781. now = self._clock.time_msec()
  1782. stream_id = self._next_id
  1783. self._next_id += 1
  1784. self._queue.append((now, stream_id, destinations, {s.user_id for s in states}))
  1785. self._notifier.notify_replication()
  1786. def get_current_token(self, instance_name: str) -> int:
  1787. """Get the current position of the stream.
  1788. On workers this returns the last stream ID received from replication.
  1789. """
  1790. if instance_name == self._instance_name:
  1791. return self._next_id - 1
  1792. else:
  1793. return self._current_tokens.get(instance_name, 0)
  1794. async def get_replication_rows(
  1795. self,
  1796. instance_name: str,
  1797. from_token: int,
  1798. upto_token: int,
  1799. target_row_count: int,
  1800. ) -> Tuple[List[Tuple[int, Tuple[str, str]]], int, bool]:
  1801. """Get all the updates between the two tokens.
  1802. We return rows in the form of `(destination, user_id)` to keep the size
  1803. of each row bounded (rather than returning the sets in a row).
  1804. On workers this will query the presence writer process via HTTP replication.
  1805. """
  1806. if instance_name != self._instance_name:
  1807. # If not local we query over http replication from the presence
  1808. # writer
  1809. result = await self._repl_client(
  1810. instance_name=instance_name,
  1811. stream_name=PresenceFederationStream.NAME,
  1812. from_token=from_token,
  1813. upto_token=upto_token,
  1814. )
  1815. return result["updates"], result["upto_token"], result["limited"]
  1816. # If the from_token is the current token then there's nothing to return
  1817. # and we can trivially no-op.
  1818. if from_token == self._next_id - 1:
  1819. return [], upto_token, False
  1820. # We can find the correct position in the queue by noting that there is
  1821. # exactly one entry per stream ID, and that the last entry has an ID of
  1822. # `self._next_id - 1`, so we can count backwards from the end.
  1823. #
  1824. # Since we are returning all states in the range `from_token < stream_id
  1825. # <= upto_token` we look for the index with a `stream_id` of `from_token
  1826. # + 1`.
  1827. #
  1828. # Since the start of the queue is periodically truncated we need to
  1829. # handle the case where `from_token` stream ID has already been dropped.
  1830. start_idx = max(from_token + 1 - self._next_id, -len(self._queue))
  1831. to_send: List[Tuple[int, Tuple[str, str]]] = []
  1832. limited = False
  1833. new_id = upto_token
  1834. for _, stream_id, destinations, user_ids in self._queue[start_idx:]:
  1835. if stream_id <= from_token:
  1836. # Paranoia check that we are actually only sending states that
  1837. # are have stream_id strictly greater than from_token. We should
  1838. # never hit this.
  1839. logger.warning(
  1840. "Tried returning presence federation stream ID: %d less than from_token: %d (next_id: %d, len: %d)",
  1841. stream_id,
  1842. from_token,
  1843. self._next_id,
  1844. len(self._queue),
  1845. )
  1846. continue
  1847. if stream_id > upto_token:
  1848. break
  1849. new_id = stream_id
  1850. to_send.extend(
  1851. (stream_id, (destination, user_id))
  1852. for destination in destinations
  1853. for user_id in user_ids
  1854. )
  1855. if len(to_send) > target_row_count:
  1856. limited = True
  1857. break
  1858. return to_send, new_id, limited
  1859. async def process_replication_rows(
  1860. self, stream_name: str, instance_name: str, token: int, rows: list
  1861. ) -> None:
  1862. if stream_name != PresenceFederationStream.NAME:
  1863. return
  1864. # We keep track of the current tokens (so that we can catch up with anything we missed after a disconnect)
  1865. self._current_tokens[instance_name] = token
  1866. # If we're a federation sender we pull out the presence states to send
  1867. # and forward them on.
  1868. if not self._federation:
  1869. return
  1870. hosts_to_users: Dict[str, Set[str]] = {}
  1871. for row in rows:
  1872. hosts_to_users.setdefault(row.destination, set()).add(row.user_id)
  1873. for host, user_ids in hosts_to_users.items():
  1874. states = await self._presence_handler.current_state_for_users(user_ids)
  1875. self._federation.send_presence_to_destinations(
  1876. states=states.values(),
  1877. destinations=[host],
  1878. )