You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1327 line
48 KiB

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