presence.py 90 KB

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