presence.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  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 logging
  23. from contextlib import contextmanager
  24. from six import iteritems, itervalues
  25. from prometheus_client import Counter
  26. from twisted.internet import defer
  27. from synapse.api.constants import PresenceState
  28. from synapse.api.errors import SynapseError
  29. from synapse.metrics import LaterGauge
  30. from synapse.storage.presence import UserPresenceState
  31. from synapse.types import UserID, get_domain_from_id
  32. from synapse.util.async import Linearizer
  33. from synapse.util.caches.descriptors import cachedInlineCallbacks
  34. from synapse.util.logcontext import run_in_background
  35. from synapse.util.logutils import log_function
  36. from synapse.util.metrics import Measure
  37. from synapse.util.wheel_timer import WheelTimer
  38. logger = logging.getLogger(__name__)
  39. notified_presence_counter = Counter("synapse_handler_presence_notified_presence", "")
  40. federation_presence_out_counter = Counter(
  41. "synapse_handler_presence_federation_presence_out", "")
  42. presence_updates_counter = Counter("synapse_handler_presence_presence_updates", "")
  43. timers_fired_counter = Counter("synapse_handler_presence_timers_fired", "")
  44. federation_presence_counter = Counter("synapse_handler_presence_federation_presence", "")
  45. bump_active_time_counter = Counter("synapse_handler_presence_bump_active_time", "")
  46. get_updates_counter = Counter("synapse_handler_presence_get_updates", "", ["type"])
  47. notify_reason_counter = Counter(
  48. "synapse_handler_presence_notify_reason", "", ["reason"])
  49. state_transition_counter = Counter(
  50. "synapse_handler_presence_state_transition", "", ["from", "to"]
  51. )
  52. # If a user was last active in the last LAST_ACTIVE_GRANULARITY, consider them
  53. # "currently_active"
  54. LAST_ACTIVE_GRANULARITY = 60 * 1000
  55. # How long to wait until a new /events or /sync request before assuming
  56. # the client has gone.
  57. SYNC_ONLINE_TIMEOUT = 30 * 1000
  58. # How long to wait before marking the user as idle. Compared against last active
  59. IDLE_TIMER = 5 * 60 * 1000
  60. # How often we expect remote servers to resend us presence.
  61. FEDERATION_TIMEOUT = 30 * 60 * 1000
  62. # How often to resend presence to remote servers
  63. FEDERATION_PING_INTERVAL = 25 * 60 * 1000
  64. # How long we will wait before assuming that the syncs from an external process
  65. # are dead.
  66. EXTERNAL_PROCESS_EXPIRY = 5 * 60 * 1000
  67. assert LAST_ACTIVE_GRANULARITY < IDLE_TIMER
  68. class PresenceHandler(object):
  69. def __init__(self, hs):
  70. """
  71. Args:
  72. hs (synapse.server.HomeServer):
  73. """
  74. self.is_mine = hs.is_mine
  75. self.is_mine_id = hs.is_mine_id
  76. self.clock = hs.get_clock()
  77. self.store = hs.get_datastore()
  78. self.wheel_timer = WheelTimer()
  79. self.notifier = hs.get_notifier()
  80. self.federation = hs.get_federation_sender()
  81. self.state = hs.get_state_handler()
  82. federation_registry = hs.get_federation_registry()
  83. federation_registry.register_edu_handler(
  84. "m.presence", self.incoming_presence
  85. )
  86. federation_registry.register_edu_handler(
  87. "m.presence_invite",
  88. lambda origin, content: self.invite_presence(
  89. observed_user=UserID.from_string(content["observed_user"]),
  90. observer_user=UserID.from_string(content["observer_user"]),
  91. )
  92. )
  93. federation_registry.register_edu_handler(
  94. "m.presence_accept",
  95. lambda origin, content: self.accept_presence(
  96. observed_user=UserID.from_string(content["observed_user"]),
  97. observer_user=UserID.from_string(content["observer_user"]),
  98. )
  99. )
  100. federation_registry.register_edu_handler(
  101. "m.presence_deny",
  102. lambda origin, content: self.deny_presence(
  103. observed_user=UserID.from_string(content["observed_user"]),
  104. observer_user=UserID.from_string(content["observer_user"]),
  105. )
  106. )
  107. distributor = hs.get_distributor()
  108. distributor.observe("user_joined_room", self.user_joined_room)
  109. active_presence = self.store.take_presence_startup_info()
  110. # A dictionary of the current state of users. This is prefilled with
  111. # non-offline presence from the DB. We should fetch from the DB if
  112. # we can't find a users presence in here.
  113. self.user_to_current_state = {
  114. state.user_id: state
  115. for state in active_presence
  116. }
  117. LaterGauge(
  118. "synapse_handlers_presence_user_to_current_state_size", "", [],
  119. lambda: len(self.user_to_current_state)
  120. )
  121. now = self.clock.time_msec()
  122. for state in active_presence:
  123. self.wheel_timer.insert(
  124. now=now,
  125. obj=state.user_id,
  126. then=state.last_active_ts + IDLE_TIMER,
  127. )
  128. self.wheel_timer.insert(
  129. now=now,
  130. obj=state.user_id,
  131. then=state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT,
  132. )
  133. if self.is_mine_id(state.user_id):
  134. self.wheel_timer.insert(
  135. now=now,
  136. obj=state.user_id,
  137. then=state.last_federation_update_ts + FEDERATION_PING_INTERVAL,
  138. )
  139. else:
  140. self.wheel_timer.insert(
  141. now=now,
  142. obj=state.user_id,
  143. then=state.last_federation_update_ts + FEDERATION_TIMEOUT,
  144. )
  145. # Set of users who have presence in the `user_to_current_state` that
  146. # have not yet been persisted
  147. self.unpersisted_users_changes = set()
  148. hs.get_reactor().addSystemEventTrigger("before", "shutdown", self._on_shutdown)
  149. self.serial_to_user = {}
  150. self._next_serial = 1
  151. # Keeps track of the number of *ongoing* syncs on this process. While
  152. # this is non zero a user will never go offline.
  153. self.user_to_num_current_syncs = {}
  154. # Keeps track of the number of *ongoing* syncs on other processes.
  155. # While any sync is ongoing on another process the user will never
  156. # go offline.
  157. # Each process has a unique identifier and an update frequency. If
  158. # no update is received from that process within the update period then
  159. # we assume that all the sync requests on that process have stopped.
  160. # Stored as a dict from process_id to set of user_id, and a dict of
  161. # process_id to millisecond timestamp last updated.
  162. self.external_process_to_current_syncs = {}
  163. self.external_process_last_updated_ms = {}
  164. self.external_sync_linearizer = Linearizer(name="external_sync_linearizer")
  165. # Start a LoopingCall in 30s that fires every 5s.
  166. # The initial delay is to allow disconnected clients a chance to
  167. # reconnect before we treat them as offline.
  168. self.clock.call_later(
  169. 30,
  170. self.clock.looping_call,
  171. self._handle_timeouts,
  172. 5000,
  173. )
  174. self.clock.call_later(
  175. 60,
  176. self.clock.looping_call,
  177. self._persist_unpersisted_changes,
  178. 60 * 1000,
  179. )
  180. LaterGauge("synapse_handlers_presence_wheel_timer_size", "", [],
  181. lambda: len(self.wheel_timer))
  182. @defer.inlineCallbacks
  183. def _on_shutdown(self):
  184. """Gets called when shutting down. This lets us persist any updates that
  185. we haven't yet persisted, e.g. updates that only changes some internal
  186. timers. This allows changes to persist across startup without having to
  187. persist every single change.
  188. If this does not run it simply means that some of the timers will fire
  189. earlier than they should when synapse is restarted. This affect of this
  190. is some spurious presence changes that will self-correct.
  191. """
  192. logger.info(
  193. "Performing _on_shutdown. Persisting %d unpersisted changes",
  194. len(self.user_to_current_state)
  195. )
  196. if self.unpersisted_users_changes:
  197. yield self.store.update_presence([
  198. self.user_to_current_state[user_id]
  199. for user_id in self.unpersisted_users_changes
  200. ])
  201. logger.info("Finished _on_shutdown")
  202. @defer.inlineCallbacks
  203. def _persist_unpersisted_changes(self):
  204. """We periodically persist the unpersisted changes, as otherwise they
  205. may stack up and slow down shutdown times.
  206. """
  207. logger.info(
  208. "Performing _persist_unpersisted_changes. Persisting %d unpersisted changes",
  209. len(self.unpersisted_users_changes)
  210. )
  211. unpersisted = self.unpersisted_users_changes
  212. self.unpersisted_users_changes = set()
  213. if unpersisted:
  214. yield self.store.update_presence([
  215. self.user_to_current_state[user_id]
  216. for user_id in unpersisted
  217. ])
  218. logger.info("Finished _persist_unpersisted_changes")
  219. @defer.inlineCallbacks
  220. def _update_states_and_catch_exception(self, new_states):
  221. try:
  222. res = yield self._update_states(new_states)
  223. defer.returnValue(res)
  224. except Exception:
  225. logger.exception("Error updating presence")
  226. @defer.inlineCallbacks
  227. def _update_states(self, new_states):
  228. """Updates presence of users. Sets the appropriate timeouts. Pokes
  229. the notifier and federation if and only if the changed presence state
  230. should be sent to clients/servers.
  231. """
  232. now = self.clock.time_msec()
  233. with Measure(self.clock, "presence_update_states"):
  234. # NOTE: We purposefully don't yield between now and when we've
  235. # calculated what we want to do with the new states, to avoid races.
  236. to_notify = {} # Changes we want to notify everyone about
  237. to_federation_ping = {} # These need sending keep-alives
  238. # Only bother handling the last presence change for each user
  239. new_states_dict = {}
  240. for new_state in new_states:
  241. new_states_dict[new_state.user_id] = new_state
  242. new_state = new_states_dict.values()
  243. for new_state in new_states:
  244. user_id = new_state.user_id
  245. # Its fine to not hit the database here, as the only thing not in
  246. # the current state cache are OFFLINE states, where the only field
  247. # of interest is last_active which is safe enough to assume is 0
  248. # here.
  249. prev_state = self.user_to_current_state.get(
  250. user_id, UserPresenceState.default(user_id)
  251. )
  252. new_state, should_notify, should_ping = handle_update(
  253. prev_state, new_state,
  254. is_mine=self.is_mine_id(user_id),
  255. wheel_timer=self.wheel_timer,
  256. now=now
  257. )
  258. self.user_to_current_state[user_id] = new_state
  259. if should_notify:
  260. to_notify[user_id] = new_state
  261. elif should_ping:
  262. to_federation_ping[user_id] = new_state
  263. # TODO: We should probably ensure there are no races hereafter
  264. presence_updates_counter.inc(len(new_states))
  265. if to_notify:
  266. notified_presence_counter.inc(len(to_notify))
  267. yield self._persist_and_notify(list(to_notify.values()))
  268. self.unpersisted_users_changes |= set(s.user_id for s in new_states)
  269. self.unpersisted_users_changes -= set(to_notify.keys())
  270. to_federation_ping = {
  271. user_id: state for user_id, state in to_federation_ping.items()
  272. if user_id not in to_notify
  273. }
  274. if to_federation_ping:
  275. federation_presence_out_counter.inc(len(to_federation_ping))
  276. self._push_to_remotes(to_federation_ping.values())
  277. def _handle_timeouts(self):
  278. """Checks the presence of users that have timed out and updates as
  279. appropriate.
  280. """
  281. logger.info("Handling presence timeouts")
  282. now = self.clock.time_msec()
  283. try:
  284. with Measure(self.clock, "presence_handle_timeouts"):
  285. # Fetch the list of users that *may* have timed out. Things may have
  286. # changed since the timeout was set, so we won't necessarily have to
  287. # take any action.
  288. users_to_check = set(self.wheel_timer.fetch(now))
  289. # Check whether the lists of syncing processes from an external
  290. # process have expired.
  291. expired_process_ids = [
  292. process_id for process_id, last_update
  293. in self.external_process_last_updated_ms.items()
  294. if now - last_update > EXTERNAL_PROCESS_EXPIRY
  295. ]
  296. for process_id in expired_process_ids:
  297. users_to_check.update(
  298. self.external_process_last_updated_ms.pop(process_id, ())
  299. )
  300. self.external_process_last_update.pop(process_id)
  301. states = [
  302. self.user_to_current_state.get(
  303. user_id, UserPresenceState.default(user_id)
  304. )
  305. for user_id in users_to_check
  306. ]
  307. timers_fired_counter.inc(len(states))
  308. changes = handle_timeouts(
  309. states,
  310. is_mine_fn=self.is_mine_id,
  311. syncing_user_ids=self.get_currently_syncing_users(),
  312. now=now,
  313. )
  314. run_in_background(self._update_states_and_catch_exception, changes)
  315. except Exception:
  316. logger.exception("Exception in _handle_timeouts loop")
  317. @defer.inlineCallbacks
  318. def bump_presence_active_time(self, user):
  319. """We've seen the user do something that indicates they're interacting
  320. with the app.
  321. """
  322. user_id = user.to_string()
  323. bump_active_time_counter.inc()
  324. prev_state = yield self.current_state_for_user(user_id)
  325. new_fields = {
  326. "last_active_ts": self.clock.time_msec(),
  327. }
  328. if prev_state.state == PresenceState.UNAVAILABLE:
  329. new_fields["state"] = PresenceState.ONLINE
  330. yield self._update_states([prev_state.copy_and_replace(**new_fields)])
  331. @defer.inlineCallbacks
  332. def user_syncing(self, user_id, affect_presence=True):
  333. """Returns a context manager that should surround any stream requests
  334. from the user.
  335. This allows us to keep track of who is currently streaming and who isn't
  336. without having to have timers outside of this module to avoid flickering
  337. when users disconnect/reconnect.
  338. Args:
  339. user_id (str)
  340. affect_presence (bool): If false this function will be a no-op.
  341. Useful for streams that are not associated with an actual
  342. client that is being used by a user.
  343. """
  344. if affect_presence:
  345. curr_sync = self.user_to_num_current_syncs.get(user_id, 0)
  346. self.user_to_num_current_syncs[user_id] = curr_sync + 1
  347. prev_state = yield self.current_state_for_user(user_id)
  348. if prev_state.state == PresenceState.OFFLINE:
  349. # If they're currently offline then bring them online, otherwise
  350. # just update the last sync times.
  351. yield self._update_states([prev_state.copy_and_replace(
  352. state=PresenceState.ONLINE,
  353. last_active_ts=self.clock.time_msec(),
  354. last_user_sync_ts=self.clock.time_msec(),
  355. )])
  356. else:
  357. yield self._update_states([prev_state.copy_and_replace(
  358. last_user_sync_ts=self.clock.time_msec(),
  359. )])
  360. @defer.inlineCallbacks
  361. def _end():
  362. try:
  363. self.user_to_num_current_syncs[user_id] -= 1
  364. prev_state = yield self.current_state_for_user(user_id)
  365. yield self._update_states([prev_state.copy_and_replace(
  366. last_user_sync_ts=self.clock.time_msec(),
  367. )])
  368. except Exception:
  369. logger.exception("Error updating presence after sync")
  370. @contextmanager
  371. def _user_syncing():
  372. try:
  373. yield
  374. finally:
  375. if affect_presence:
  376. run_in_background(_end)
  377. defer.returnValue(_user_syncing())
  378. def get_currently_syncing_users(self):
  379. """Get the set of user ids that are currently syncing on this HS.
  380. Returns:
  381. set(str): A set of user_id strings.
  382. """
  383. syncing_user_ids = {
  384. user_id for user_id, count in self.user_to_num_current_syncs.items()
  385. if count
  386. }
  387. for user_ids in self.external_process_to_current_syncs.values():
  388. syncing_user_ids.update(user_ids)
  389. return syncing_user_ids
  390. @defer.inlineCallbacks
  391. def update_external_syncs_row(self, process_id, user_id, is_syncing, sync_time_msec):
  392. """Update the syncing users for an external process as a delta.
  393. Args:
  394. process_id (str): An identifier for the process the users are
  395. syncing against. This allows synapse to process updates
  396. as user start and stop syncing against a given process.
  397. user_id (str): The user who has started or stopped syncing
  398. is_syncing (bool): Whether or not the user is now syncing
  399. sync_time_msec(int): Time in ms when the user was last syncing
  400. """
  401. with (yield self.external_sync_linearizer.queue(process_id)):
  402. prev_state = yield self.current_state_for_user(user_id)
  403. process_presence = self.external_process_to_current_syncs.setdefault(
  404. process_id, set()
  405. )
  406. updates = []
  407. if is_syncing and user_id not in process_presence:
  408. if prev_state.state == PresenceState.OFFLINE:
  409. updates.append(prev_state.copy_and_replace(
  410. state=PresenceState.ONLINE,
  411. last_active_ts=sync_time_msec,
  412. last_user_sync_ts=sync_time_msec,
  413. ))
  414. else:
  415. updates.append(prev_state.copy_and_replace(
  416. last_user_sync_ts=sync_time_msec,
  417. ))
  418. process_presence.add(user_id)
  419. elif user_id in process_presence:
  420. updates.append(prev_state.copy_and_replace(
  421. last_user_sync_ts=sync_time_msec,
  422. ))
  423. if not is_syncing:
  424. process_presence.discard(user_id)
  425. if updates:
  426. yield self._update_states(updates)
  427. self.external_process_last_updated_ms[process_id] = self.clock.time_msec()
  428. @defer.inlineCallbacks
  429. def update_external_syncs_clear(self, process_id):
  430. """Marks all users that had been marked as syncing by a given process
  431. as offline.
  432. Used when the process has stopped/disappeared.
  433. """
  434. with (yield self.external_sync_linearizer.queue(process_id)):
  435. process_presence = self.external_process_to_current_syncs.pop(
  436. process_id, set()
  437. )
  438. prev_states = yield self.current_state_for_users(process_presence)
  439. time_now_ms = self.clock.time_msec()
  440. yield self._update_states([
  441. prev_state.copy_and_replace(
  442. last_user_sync_ts=time_now_ms,
  443. )
  444. for prev_state in itervalues(prev_states)
  445. ])
  446. self.external_process_last_updated_ms.pop(process_id, None)
  447. @defer.inlineCallbacks
  448. def current_state_for_user(self, user_id):
  449. """Get the current presence state for a user.
  450. """
  451. res = yield self.current_state_for_users([user_id])
  452. defer.returnValue(res[user_id])
  453. @defer.inlineCallbacks
  454. def current_state_for_users(self, user_ids):
  455. """Get the current presence state for multiple users.
  456. Returns:
  457. dict: `user_id` -> `UserPresenceState`
  458. """
  459. states = {
  460. user_id: self.user_to_current_state.get(user_id, None)
  461. for user_id in user_ids
  462. }
  463. missing = [user_id for user_id, state in iteritems(states) if not state]
  464. if missing:
  465. # There are things not in our in memory cache. Lets pull them out of
  466. # the database.
  467. res = yield self.store.get_presence_for_users(missing)
  468. states.update(res)
  469. missing = [user_id for user_id, state in iteritems(states) if not state]
  470. if missing:
  471. new = {
  472. user_id: UserPresenceState.default(user_id)
  473. for user_id in missing
  474. }
  475. states.update(new)
  476. self.user_to_current_state.update(new)
  477. defer.returnValue(states)
  478. @defer.inlineCallbacks
  479. def _persist_and_notify(self, states):
  480. """Persist states in the database, poke the notifier and send to
  481. interested remote servers
  482. """
  483. stream_id, max_token = yield self.store.update_presence(states)
  484. parties = yield get_interested_parties(self.store, states)
  485. room_ids_to_states, users_to_states = parties
  486. self.notifier.on_new_event(
  487. "presence_key", stream_id, rooms=room_ids_to_states.keys(),
  488. users=[UserID.from_string(u) for u in users_to_states]
  489. )
  490. self._push_to_remotes(states)
  491. @defer.inlineCallbacks
  492. def notify_for_states(self, state, stream_id):
  493. parties = yield get_interested_parties(self.store, [state])
  494. room_ids_to_states, users_to_states = parties
  495. self.notifier.on_new_event(
  496. "presence_key", stream_id, rooms=room_ids_to_states.keys(),
  497. users=[UserID.from_string(u) for u in users_to_states]
  498. )
  499. def _push_to_remotes(self, states):
  500. """Sends state updates to remote servers.
  501. Args:
  502. states (list(UserPresenceState))
  503. """
  504. self.federation.send_presence(states)
  505. @defer.inlineCallbacks
  506. def incoming_presence(self, origin, content):
  507. """Called when we receive a `m.presence` EDU from a remote server.
  508. """
  509. now = self.clock.time_msec()
  510. updates = []
  511. for push in content.get("push", []):
  512. # A "push" contains a list of presence that we are probably interested
  513. # in.
  514. # TODO: Actually check if we're interested, rather than blindly
  515. # accepting presence updates.
  516. user_id = push.get("user_id", None)
  517. if not user_id:
  518. logger.info(
  519. "Got presence update from %r with no 'user_id': %r",
  520. origin, push,
  521. )
  522. continue
  523. if get_domain_from_id(user_id) != origin:
  524. logger.info(
  525. "Got presence update from %r with bad 'user_id': %r",
  526. origin, user_id,
  527. )
  528. continue
  529. presence_state = push.get("presence", None)
  530. if not presence_state:
  531. logger.info(
  532. "Got presence update from %r with no 'presence_state': %r",
  533. origin, push,
  534. )
  535. continue
  536. new_fields = {
  537. "state": presence_state,
  538. "last_federation_update_ts": now,
  539. }
  540. last_active_ago = push.get("last_active_ago", None)
  541. if last_active_ago is not None:
  542. new_fields["last_active_ts"] = now - last_active_ago
  543. new_fields["status_msg"] = push.get("status_msg", None)
  544. new_fields["currently_active"] = push.get("currently_active", False)
  545. prev_state = yield self.current_state_for_user(user_id)
  546. updates.append(prev_state.copy_and_replace(**new_fields))
  547. if updates:
  548. federation_presence_counter.inc(len(updates))
  549. yield self._update_states(updates)
  550. @defer.inlineCallbacks
  551. def get_state(self, target_user, as_event=False):
  552. results = yield self.get_states(
  553. [target_user.to_string()],
  554. as_event=as_event,
  555. )
  556. defer.returnValue(results[0])
  557. @defer.inlineCallbacks
  558. def get_states(self, target_user_ids, as_event=False):
  559. """Get the presence state for users.
  560. Args:
  561. target_user_ids (list)
  562. as_event (bool): Whether to format it as a client event or not.
  563. Returns:
  564. list
  565. """
  566. updates = yield self.current_state_for_users(target_user_ids)
  567. updates = list(updates.values())
  568. for user_id in set(target_user_ids) - set(u.user_id for u in updates):
  569. updates.append(UserPresenceState.default(user_id))
  570. now = self.clock.time_msec()
  571. if as_event:
  572. defer.returnValue([
  573. {
  574. "type": "m.presence",
  575. "content": format_user_presence_state(state, now),
  576. }
  577. for state in updates
  578. ])
  579. else:
  580. defer.returnValue(updates)
  581. @defer.inlineCallbacks
  582. def set_state(self, target_user, state, ignore_status_msg=False):
  583. """Set the presence state of the user.
  584. """
  585. status_msg = state.get("status_msg", None)
  586. presence = state["presence"]
  587. valid_presence = (
  588. PresenceState.ONLINE, PresenceState.UNAVAILABLE, PresenceState.OFFLINE
  589. )
  590. if presence not in valid_presence:
  591. raise SynapseError(400, "Invalid presence state")
  592. user_id = target_user.to_string()
  593. prev_state = yield self.current_state_for_user(user_id)
  594. new_fields = {
  595. "state": presence
  596. }
  597. if not ignore_status_msg:
  598. msg = status_msg if presence != PresenceState.OFFLINE else None
  599. new_fields["status_msg"] = msg
  600. if presence == PresenceState.ONLINE:
  601. new_fields["last_active_ts"] = self.clock.time_msec()
  602. yield self._update_states([prev_state.copy_and_replace(**new_fields)])
  603. @defer.inlineCallbacks
  604. def user_joined_room(self, user, room_id):
  605. """Called (via the distributor) when a user joins a room. This funciton
  606. sends presence updates to servers, either:
  607. 1. the joining user is a local user and we send their presence to
  608. all servers in the room.
  609. 2. the joining user is a remote user and so we send presence for all
  610. local users in the room.
  611. """
  612. # We only need to send presence to servers that don't have it yet. We
  613. # don't need to send to local clients here, as that is done as part
  614. # of the event stream/sync.
  615. # TODO: Only send to servers not already in the room.
  616. if self.is_mine(user):
  617. state = yield self.current_state_for_user(user.to_string())
  618. self._push_to_remotes([state])
  619. else:
  620. user_ids = yield self.store.get_users_in_room(room_id)
  621. user_ids = list(filter(self.is_mine_id, user_ids))
  622. states = yield self.current_state_for_users(user_ids)
  623. self._push_to_remotes(list(states.values()))
  624. @defer.inlineCallbacks
  625. def get_presence_list(self, observer_user, accepted=None):
  626. """Returns the presence for all users in their presence list.
  627. """
  628. if not self.is_mine(observer_user):
  629. raise SynapseError(400, "User is not hosted on this Home Server")
  630. presence_list = yield self.store.get_presence_list(
  631. observer_user.localpart, accepted=accepted
  632. )
  633. results = yield self.get_states(
  634. target_user_ids=[row["observed_user_id"] for row in presence_list],
  635. as_event=False,
  636. )
  637. now = self.clock.time_msec()
  638. results[:] = [format_user_presence_state(r, now) for r in results]
  639. is_accepted = {
  640. row["observed_user_id"]: row["accepted"] for row in presence_list
  641. }
  642. for result in results:
  643. result.update({
  644. "accepted": is_accepted,
  645. })
  646. defer.returnValue(results)
  647. @defer.inlineCallbacks
  648. def send_presence_invite(self, observer_user, observed_user):
  649. """Sends a presence invite.
  650. """
  651. yield self.store.add_presence_list_pending(
  652. observer_user.localpart, observed_user.to_string()
  653. )
  654. if self.is_mine(observed_user):
  655. yield self.invite_presence(observed_user, observer_user)
  656. else:
  657. yield self.federation.send_edu(
  658. destination=observed_user.domain,
  659. edu_type="m.presence_invite",
  660. content={
  661. "observed_user": observed_user.to_string(),
  662. "observer_user": observer_user.to_string(),
  663. }
  664. )
  665. @defer.inlineCallbacks
  666. def invite_presence(self, observed_user, observer_user):
  667. """Handles new presence invites.
  668. """
  669. if not self.is_mine(observed_user):
  670. raise SynapseError(400, "User is not hosted on this Home Server")
  671. # TODO: Don't auto accept
  672. if self.is_mine(observer_user):
  673. yield self.accept_presence(observed_user, observer_user)
  674. else:
  675. self.federation.send_edu(
  676. destination=observer_user.domain,
  677. edu_type="m.presence_accept",
  678. content={
  679. "observed_user": observed_user.to_string(),
  680. "observer_user": observer_user.to_string(),
  681. }
  682. )
  683. state_dict = yield self.get_state(observed_user, as_event=False)
  684. state_dict = format_user_presence_state(state_dict, self.clock.time_msec())
  685. self.federation.send_edu(
  686. destination=observer_user.domain,
  687. edu_type="m.presence",
  688. content={
  689. "push": [state_dict]
  690. }
  691. )
  692. @defer.inlineCallbacks
  693. def accept_presence(self, observed_user, observer_user):
  694. """Handles a m.presence_accept EDU. Mark a presence invite from a
  695. local or remote user as accepted in a local user's presence list.
  696. Starts polling for presence updates from the local or remote user.
  697. Args:
  698. observed_user(UserID): The user to update in the presence list.
  699. observer_user(UserID): The owner of the presence list to update.
  700. """
  701. yield self.store.set_presence_list_accepted(
  702. observer_user.localpart, observed_user.to_string()
  703. )
  704. @defer.inlineCallbacks
  705. def deny_presence(self, observed_user, observer_user):
  706. """Handle a m.presence_deny EDU. Removes a local or remote user from a
  707. local user's presence list.
  708. Args:
  709. observed_user(UserID): The local or remote user to remove from the
  710. list.
  711. observer_user(UserID): The local owner of the presence list.
  712. Returns:
  713. A Deferred.
  714. """
  715. yield self.store.del_presence_list(
  716. observer_user.localpart, observed_user.to_string()
  717. )
  718. # TODO(paul): Inform the user somehow?
  719. @defer.inlineCallbacks
  720. def drop(self, observed_user, observer_user):
  721. """Remove a local or remote user from a local user's presence list and
  722. unsubscribe the local user from updates that user.
  723. Args:
  724. observed_user(UserId): The local or remote user to remove from the
  725. list.
  726. observer_user(UserId): The local owner of the presence list.
  727. Returns:
  728. A Deferred.
  729. """
  730. if not self.is_mine(observer_user):
  731. raise SynapseError(400, "User is not hosted on this Home Server")
  732. yield self.store.del_presence_list(
  733. observer_user.localpart, observed_user.to_string()
  734. )
  735. # TODO: Inform the remote that we've dropped the presence list.
  736. @defer.inlineCallbacks
  737. def is_visible(self, observed_user, observer_user):
  738. """Returns whether a user can see another user's presence.
  739. """
  740. observer_room_ids = yield self.store.get_rooms_for_user(
  741. observer_user.to_string()
  742. )
  743. observed_room_ids = yield self.store.get_rooms_for_user(
  744. observed_user.to_string()
  745. )
  746. if observer_room_ids & observed_room_ids:
  747. defer.returnValue(True)
  748. accepted_observers = yield self.store.get_presence_list_observers_accepted(
  749. observed_user.to_string()
  750. )
  751. defer.returnValue(observer_user.to_string() in accepted_observers)
  752. @defer.inlineCallbacks
  753. def get_all_presence_updates(self, last_id, current_id):
  754. """
  755. Gets a list of presence update rows from between the given stream ids.
  756. Each row has:
  757. - stream_id(str)
  758. - user_id(str)
  759. - state(str)
  760. - last_active_ts(int)
  761. - last_federation_update_ts(int)
  762. - last_user_sync_ts(int)
  763. - status_msg(int)
  764. - currently_active(int)
  765. """
  766. # TODO(markjh): replicate the unpersisted changes.
  767. # This could use the in-memory stores for recent changes.
  768. rows = yield self.store.get_all_presence_updates(last_id, current_id)
  769. defer.returnValue(rows)
  770. def should_notify(old_state, new_state):
  771. """Decides if a presence state change should be sent to interested parties.
  772. """
  773. if old_state == new_state:
  774. return False
  775. if old_state.status_msg != new_state.status_msg:
  776. notify_reason_counter.labels("status_msg_change").inc()
  777. return True
  778. if old_state.state != new_state.state:
  779. notify_reason_counter.labels("state_change").inc()
  780. state_transition_counter.labels(old_state.state, new_state.state).inc()
  781. return True
  782. if old_state.state == PresenceState.ONLINE:
  783. if new_state.currently_active != old_state.currently_active:
  784. notify_reason_counter.labels("current_active_change").inc()
  785. return True
  786. if new_state.last_active_ts - old_state.last_active_ts > LAST_ACTIVE_GRANULARITY:
  787. # Only notify about last active bumps if we're not currently acive
  788. if not new_state.currently_active:
  789. notify_reason_counter.labels("last_active_change_online").inc()
  790. return True
  791. elif new_state.last_active_ts - old_state.last_active_ts > LAST_ACTIVE_GRANULARITY:
  792. # Always notify for a transition where last active gets bumped.
  793. notify_reason_counter.labels("last_active_change_not_online").inc()
  794. return True
  795. return False
  796. def format_user_presence_state(state, now, include_user_id=True):
  797. """Convert UserPresenceState to a format that can be sent down to clients
  798. and to other servers.
  799. The "user_id" is optional so that this function can be used to format presence
  800. updates for client /sync responses and for federation /send requests.
  801. """
  802. content = {
  803. "presence": state.state,
  804. }
  805. if include_user_id:
  806. content["user_id"] = state.user_id
  807. if state.last_active_ts:
  808. content["last_active_ago"] = now - state.last_active_ts
  809. if state.status_msg and state.state != PresenceState.OFFLINE:
  810. content["status_msg"] = state.status_msg
  811. if state.state == PresenceState.ONLINE:
  812. content["currently_active"] = state.currently_active
  813. return content
  814. class PresenceEventSource(object):
  815. def __init__(self, hs):
  816. # We can't call get_presence_handler here because there's a cycle:
  817. #
  818. # Presence -> Notifier -> PresenceEventSource -> Presence
  819. #
  820. self.get_presence_handler = hs.get_presence_handler
  821. self.clock = hs.get_clock()
  822. self.store = hs.get_datastore()
  823. self.state = hs.get_state_handler()
  824. @defer.inlineCallbacks
  825. @log_function
  826. def get_new_events(self, user, from_key, room_ids=None, include_offline=True,
  827. explicit_room_id=None, **kwargs):
  828. # The process for getting presence events are:
  829. # 1. Get the rooms the user is in.
  830. # 2. Get the list of user in the rooms.
  831. # 3. Get the list of users that are in the user's presence list.
  832. # 4. If there is a from_key set, cross reference the list of users
  833. # with the `presence_stream_cache` to see which ones we actually
  834. # need to check.
  835. # 5. Load current state for the users.
  836. #
  837. # We don't try and limit the presence updates by the current token, as
  838. # sending down the rare duplicate is not a concern.
  839. with Measure(self.clock, "presence.get_new_events"):
  840. if from_key is not None:
  841. from_key = int(from_key)
  842. presence = self.get_presence_handler()
  843. stream_change_cache = self.store.presence_stream_cache
  844. max_token = self.store.get_current_presence_token()
  845. users_interested_in = yield self._get_interested_in(user, explicit_room_id)
  846. user_ids_changed = set()
  847. changed = None
  848. if from_key:
  849. changed = stream_change_cache.get_all_entities_changed(from_key)
  850. if changed is not None and len(changed) < 500:
  851. # For small deltas, its quicker to get all changes and then
  852. # work out if we share a room or they're in our presence list
  853. get_updates_counter.labels("stream").inc()
  854. for other_user_id in changed:
  855. if other_user_id in users_interested_in:
  856. user_ids_changed.add(other_user_id)
  857. else:
  858. # Too many possible updates. Find all users we can see and check
  859. # if any of them have changed.
  860. get_updates_counter.labels("full").inc()
  861. if from_key:
  862. user_ids_changed = stream_change_cache.get_entities_changed(
  863. users_interested_in, from_key,
  864. )
  865. else:
  866. user_ids_changed = users_interested_in
  867. updates = yield presence.current_state_for_users(user_ids_changed)
  868. if include_offline:
  869. defer.returnValue((list(updates.values()), max_token))
  870. else:
  871. defer.returnValue(([
  872. s for s in itervalues(updates)
  873. if s.state != PresenceState.OFFLINE
  874. ], max_token))
  875. def get_current_key(self):
  876. return self.store.get_current_presence_token()
  877. def get_pagination_rows(self, user, pagination_config, key):
  878. return self.get_new_events(user, from_key=None, include_offline=False)
  879. @cachedInlineCallbacks(num_args=2, cache_context=True)
  880. def _get_interested_in(self, user, explicit_room_id, cache_context):
  881. """Returns the set of users that the given user should see presence
  882. updates for
  883. """
  884. user_id = user.to_string()
  885. plist = yield self.store.get_presence_list_accepted(
  886. user.localpart, on_invalidate=cache_context.invalidate,
  887. )
  888. users_interested_in = set(row["observed_user_id"] for row in plist)
  889. users_interested_in.add(user_id) # So that we receive our own presence
  890. users_who_share_room = yield self.store.get_users_who_share_room_with_user(
  891. user_id, on_invalidate=cache_context.invalidate,
  892. )
  893. users_interested_in.update(users_who_share_room)
  894. if explicit_room_id:
  895. user_ids = yield self.store.get_users_in_room(
  896. explicit_room_id, on_invalidate=cache_context.invalidate,
  897. )
  898. users_interested_in.update(user_ids)
  899. defer.returnValue(users_interested_in)
  900. def handle_timeouts(user_states, is_mine_fn, syncing_user_ids, now):
  901. """Checks the presence of users that have timed out and updates as
  902. appropriate.
  903. Args:
  904. user_states(list): List of UserPresenceState's to check.
  905. is_mine_fn (fn): Function that returns if a user_id is ours
  906. syncing_user_ids (set): Set of user_ids with active syncs.
  907. now (int): Current time in ms.
  908. Returns:
  909. List of UserPresenceState updates
  910. """
  911. changes = {} # Actual changes we need to notify people about
  912. for state in user_states:
  913. is_mine = is_mine_fn(state.user_id)
  914. new_state = handle_timeout(state, is_mine, syncing_user_ids, now)
  915. if new_state:
  916. changes[state.user_id] = new_state
  917. return list(changes.values())
  918. def handle_timeout(state, is_mine, syncing_user_ids, now):
  919. """Checks the presence of the user to see if any of the timers have elapsed
  920. Args:
  921. state (UserPresenceState)
  922. is_mine (bool): Whether the user is ours
  923. syncing_user_ids (set): Set of user_ids with active syncs.
  924. now (int): Current time in ms.
  925. Returns:
  926. A UserPresenceState update or None if no update.
  927. """
  928. if state.state == PresenceState.OFFLINE:
  929. # No timeouts are associated with offline states.
  930. return None
  931. changed = False
  932. user_id = state.user_id
  933. if is_mine:
  934. if state.state == PresenceState.ONLINE:
  935. if now - state.last_active_ts > IDLE_TIMER:
  936. # Currently online, but last activity ages ago so auto
  937. # idle
  938. state = state.copy_and_replace(
  939. state=PresenceState.UNAVAILABLE,
  940. )
  941. changed = True
  942. elif now - state.last_active_ts > LAST_ACTIVE_GRANULARITY:
  943. # So that we send down a notification that we've
  944. # stopped updating.
  945. changed = True
  946. if now - state.last_federation_update_ts > FEDERATION_PING_INTERVAL:
  947. # Need to send ping to other servers to ensure they don't
  948. # timeout and set us to offline
  949. changed = True
  950. # If there are have been no sync for a while (and none ongoing),
  951. # set presence to offline
  952. if user_id not in syncing_user_ids:
  953. # If the user has done something recently but hasn't synced,
  954. # don't set them as offline.
  955. sync_or_active = max(state.last_user_sync_ts, state.last_active_ts)
  956. if now - sync_or_active > SYNC_ONLINE_TIMEOUT:
  957. state = state.copy_and_replace(
  958. state=PresenceState.OFFLINE,
  959. status_msg=None,
  960. )
  961. changed = True
  962. else:
  963. # We expect to be poked occasionally by the other side.
  964. # This is to protect against forgetful/buggy servers, so that
  965. # no one gets stuck online forever.
  966. if now - state.last_federation_update_ts > FEDERATION_TIMEOUT:
  967. # The other side seems to have disappeared.
  968. state = state.copy_and_replace(
  969. state=PresenceState.OFFLINE,
  970. status_msg=None,
  971. )
  972. changed = True
  973. return state if changed else None
  974. def handle_update(prev_state, new_state, is_mine, wheel_timer, now):
  975. """Given a presence update:
  976. 1. Add any appropriate timers.
  977. 2. Check if we should notify anyone.
  978. Args:
  979. prev_state (UserPresenceState)
  980. new_state (UserPresenceState)
  981. is_mine (bool): Whether the user is ours
  982. wheel_timer (WheelTimer)
  983. now (int): Time now in ms
  984. Returns:
  985. 3-tuple: `(new_state, persist_and_notify, federation_ping)` where:
  986. - new_state: is the state to actually persist
  987. - persist_and_notify (bool): whether to persist and notify people
  988. - federation_ping (bool): whether we should send a ping over federation
  989. """
  990. user_id = new_state.user_id
  991. persist_and_notify = False
  992. federation_ping = False
  993. # If the users are ours then we want to set up a bunch of timers
  994. # to time things out.
  995. if is_mine:
  996. if new_state.state == PresenceState.ONLINE:
  997. # Idle timer
  998. wheel_timer.insert(
  999. now=now,
  1000. obj=user_id,
  1001. then=new_state.last_active_ts + IDLE_TIMER
  1002. )
  1003. active = now - new_state.last_active_ts < LAST_ACTIVE_GRANULARITY
  1004. new_state = new_state.copy_and_replace(
  1005. currently_active=active,
  1006. )
  1007. if active:
  1008. wheel_timer.insert(
  1009. now=now,
  1010. obj=user_id,
  1011. then=new_state.last_active_ts + LAST_ACTIVE_GRANULARITY
  1012. )
  1013. if new_state.state != PresenceState.OFFLINE:
  1014. # User has stopped syncing
  1015. wheel_timer.insert(
  1016. now=now,
  1017. obj=user_id,
  1018. then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT
  1019. )
  1020. last_federate = new_state.last_federation_update_ts
  1021. if now - last_federate > FEDERATION_PING_INTERVAL:
  1022. # Been a while since we've poked remote servers
  1023. new_state = new_state.copy_and_replace(
  1024. last_federation_update_ts=now,
  1025. )
  1026. federation_ping = True
  1027. else:
  1028. wheel_timer.insert(
  1029. now=now,
  1030. obj=user_id,
  1031. then=new_state.last_federation_update_ts + FEDERATION_TIMEOUT
  1032. )
  1033. # Check whether the change was something worth notifying about
  1034. if should_notify(prev_state, new_state):
  1035. new_state = new_state.copy_and_replace(
  1036. last_federation_update_ts=now,
  1037. )
  1038. persist_and_notify = True
  1039. return new_state, persist_and_notify, federation_ping
  1040. @defer.inlineCallbacks
  1041. def get_interested_parties(store, states):
  1042. """Given a list of states return which entities (rooms, users)
  1043. are interested in the given states.
  1044. Args:
  1045. states (list(UserPresenceState))
  1046. Returns:
  1047. 2-tuple: `(room_ids_to_states, users_to_states)`,
  1048. with each item being a dict of `entity_name` -> `[UserPresenceState]`
  1049. """
  1050. room_ids_to_states = {}
  1051. users_to_states = {}
  1052. for state in states:
  1053. room_ids = yield store.get_rooms_for_user(state.user_id)
  1054. for room_id in room_ids:
  1055. room_ids_to_states.setdefault(room_id, []).append(state)
  1056. plist = yield store.get_presence_list_observers_accepted(state.user_id)
  1057. for u in plist:
  1058. users_to_states.setdefault(u, []).append(state)
  1059. # Always notify self
  1060. users_to_states.setdefault(state.user_id, []).append(state)
  1061. defer.returnValue((room_ids_to_states, users_to_states))
  1062. @defer.inlineCallbacks
  1063. def get_interested_remotes(store, states, state_handler):
  1064. """Given a list of presence states figure out which remote servers
  1065. should be sent which.
  1066. All the presence states should be for local users only.
  1067. Args:
  1068. store (DataStore)
  1069. states (list(UserPresenceState))
  1070. Returns:
  1071. Deferred list of ([destinations], [UserPresenceState]), where for
  1072. each row the list of UserPresenceState should be sent to each
  1073. destination
  1074. """
  1075. hosts_and_states = []
  1076. # First we look up the rooms each user is in (as well as any explicit
  1077. # subscriptions), then for each distinct room we look up the remote
  1078. # hosts in those rooms.
  1079. room_ids_to_states, users_to_states = yield get_interested_parties(store, states)
  1080. for room_id, states in iteritems(room_ids_to_states):
  1081. hosts = yield state_handler.get_current_hosts_in_room(room_id)
  1082. hosts_and_states.append((hosts, states))
  1083. for user_id, states in iteritems(users_to_states):
  1084. host = get_domain_from_id(user_id)
  1085. hosts_and_states.append(([host], states))
  1086. defer.returnValue(hosts_and_states)