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.
 
 
 
 
 
 

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