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.
 
 
 
 
 
 

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