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.
 
 
 
 
 
 

447 lines
16 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, cast
  15. from synapse.api.presence import PresenceState, UserPresenceState
  16. from synapse.replication.tcp.streams import PresenceStream
  17. from synapse.storage._base import SQLBaseStore, make_in_list_sql_clause
  18. from synapse.storage.database import (
  19. DatabasePool,
  20. LoggingDatabaseConnection,
  21. LoggingTransaction,
  22. )
  23. from synapse.storage.databases.main.cache import CacheInvalidationWorkerStore
  24. from synapse.storage.engines import PostgresEngine
  25. from synapse.storage.types import Connection
  26. from synapse.storage.util.id_generators import (
  27. AbstractStreamIdGenerator,
  28. MultiWriterIdGenerator,
  29. StreamIdGenerator,
  30. )
  31. from synapse.util.caches.descriptors import cached, cachedList
  32. from synapse.util.caches.stream_change_cache import StreamChangeCache
  33. from synapse.util.iterutils import batch_iter
  34. if TYPE_CHECKING:
  35. from synapse.server import HomeServer
  36. class PresenceBackgroundUpdateStore(SQLBaseStore):
  37. def __init__(
  38. self,
  39. database: DatabasePool,
  40. db_conn: LoggingDatabaseConnection,
  41. hs: "HomeServer",
  42. ) -> None:
  43. super().__init__(database, db_conn, hs)
  44. # Used by `PresenceStore._get_active_presence()`
  45. self.db_pool.updates.register_background_index_update(
  46. "presence_stream_not_offline_index",
  47. index_name="presence_stream_state_not_offline_idx",
  48. table="presence_stream",
  49. columns=["state"],
  50. where_clause="state != 'offline'",
  51. )
  52. class PresenceStore(PresenceBackgroundUpdateStore, CacheInvalidationWorkerStore):
  53. def __init__(
  54. self,
  55. database: DatabasePool,
  56. db_conn: LoggingDatabaseConnection,
  57. hs: "HomeServer",
  58. ) -> None:
  59. super().__init__(database, db_conn, hs)
  60. self._instance_name = hs.get_instance_name()
  61. self._presence_id_gen: AbstractStreamIdGenerator
  62. self._can_persist_presence = (
  63. self._instance_name in hs.config.worker.writers.presence
  64. )
  65. if isinstance(database.engine, PostgresEngine):
  66. self._presence_id_gen = MultiWriterIdGenerator(
  67. db_conn=db_conn,
  68. db=database,
  69. stream_name="presence_stream",
  70. instance_name=self._instance_name,
  71. tables=[("presence_stream", "instance_name", "stream_id")],
  72. sequence_name="presence_stream_sequence",
  73. writers=hs.config.worker.writers.presence,
  74. )
  75. else:
  76. self._presence_id_gen = StreamIdGenerator(
  77. db_conn, "presence_stream", "stream_id"
  78. )
  79. self.hs = hs
  80. self._presence_on_startup = self._get_active_presence(db_conn)
  81. presence_cache_prefill, min_presence_val = self.db_pool.get_cache_dict(
  82. db_conn,
  83. "presence_stream",
  84. entity_column="user_id",
  85. stream_column="stream_id",
  86. max_value=self._presence_id_gen.get_current_token(),
  87. )
  88. self.presence_stream_cache = StreamChangeCache(
  89. "PresenceStreamChangeCache",
  90. min_presence_val,
  91. prefilled_cache=presence_cache_prefill,
  92. )
  93. async def update_presence(
  94. self, presence_states: List[UserPresenceState]
  95. ) -> Tuple[int, int]:
  96. assert self._can_persist_presence
  97. stream_ordering_manager = self._presence_id_gen.get_next_mult(
  98. len(presence_states)
  99. )
  100. async with stream_ordering_manager as stream_orderings:
  101. await self.db_pool.runInteraction(
  102. "update_presence",
  103. self._update_presence_txn,
  104. stream_orderings,
  105. presence_states,
  106. )
  107. return stream_orderings[-1], self._presence_id_gen.get_current_token()
  108. def _update_presence_txn(
  109. self,
  110. txn: LoggingTransaction,
  111. stream_orderings: List[int],
  112. presence_states: List[UserPresenceState],
  113. ) -> None:
  114. for stream_id, state in zip(stream_orderings, presence_states):
  115. txn.call_after(
  116. self.presence_stream_cache.entity_has_changed, state.user_id, stream_id
  117. )
  118. txn.call_after(self._get_presence_for_user.invalidate, (state.user_id,))
  119. # Delete old rows to stop database from getting really big
  120. sql = "DELETE FROM presence_stream WHERE stream_id < ? AND "
  121. for states in batch_iter(presence_states, 50):
  122. clause, args = make_in_list_sql_clause(
  123. self.database_engine, "user_id", [s.user_id for s in states]
  124. )
  125. txn.execute(sql + clause, [stream_id] + list(args))
  126. # Actually insert new rows
  127. self.db_pool.simple_insert_many_txn(
  128. txn,
  129. table="presence_stream",
  130. keys=(
  131. "stream_id",
  132. "user_id",
  133. "state",
  134. "last_active_ts",
  135. "last_federation_update_ts",
  136. "last_user_sync_ts",
  137. "status_msg",
  138. "currently_active",
  139. "instance_name",
  140. ),
  141. values=[
  142. (
  143. stream_id,
  144. state.user_id,
  145. state.state,
  146. state.last_active_ts,
  147. state.last_federation_update_ts,
  148. state.last_user_sync_ts,
  149. state.status_msg,
  150. state.currently_active,
  151. self._instance_name,
  152. )
  153. for stream_id, state in zip(stream_orderings, presence_states)
  154. ],
  155. )
  156. async def get_all_presence_updates(
  157. self, instance_name: str, last_id: int, current_id: int, limit: int
  158. ) -> Tuple[List[Tuple[int, list]], int, bool]:
  159. """Get updates for presence replication stream.
  160. Args:
  161. instance_name: The writer we want to fetch updates from. Unused
  162. here since there is only ever one writer.
  163. last_id: The token to fetch updates from. Exclusive.
  164. current_id: The token to fetch updates up to. Inclusive.
  165. limit: The requested limit for the number of rows to return. The
  166. function may return more or fewer rows.
  167. Returns:
  168. A tuple consisting of: the updates, a token to use to fetch
  169. subsequent updates, and whether we returned fewer rows than exists
  170. between the requested tokens due to the limit.
  171. The token returned can be used in a subsequent call to this
  172. function to get further updatees.
  173. The updates are a list of 2-tuples of stream ID and the row data
  174. """
  175. if last_id == current_id:
  176. return [], current_id, False
  177. def get_all_presence_updates_txn(
  178. txn: LoggingTransaction,
  179. ) -> Tuple[List[Tuple[int, list]], int, bool]:
  180. sql = """
  181. SELECT stream_id, user_id, state, last_active_ts,
  182. last_federation_update_ts, last_user_sync_ts,
  183. status_msg, currently_active
  184. FROM presence_stream
  185. WHERE ? < stream_id AND stream_id <= ?
  186. ORDER BY stream_id ASC
  187. LIMIT ?
  188. """
  189. txn.execute(sql, (last_id, current_id, limit))
  190. updates = cast(
  191. List[Tuple[int, list]],
  192. [(row[0], row[1:]) for row in txn],
  193. )
  194. upper_bound = current_id
  195. limited = False
  196. if len(updates) >= limit:
  197. upper_bound = updates[-1][0]
  198. limited = True
  199. return updates, upper_bound, limited
  200. return await self.db_pool.runInteraction(
  201. "get_all_presence_updates", get_all_presence_updates_txn
  202. )
  203. @cached()
  204. def _get_presence_for_user(self, user_id: str) -> None:
  205. raise NotImplementedError()
  206. @cachedList(
  207. cached_method_name="_get_presence_for_user",
  208. list_name="user_ids",
  209. num_args=1,
  210. )
  211. async def get_presence_for_users(
  212. self, user_ids: Iterable[str]
  213. ) -> Dict[str, UserPresenceState]:
  214. rows = await self.db_pool.simple_select_many_batch(
  215. table="presence_stream",
  216. column="user_id",
  217. iterable=user_ids,
  218. keyvalues={},
  219. retcols=(
  220. "user_id",
  221. "state",
  222. "last_active_ts",
  223. "last_federation_update_ts",
  224. "last_user_sync_ts",
  225. "status_msg",
  226. "currently_active",
  227. ),
  228. desc="get_presence_for_users",
  229. )
  230. for row in rows:
  231. row["currently_active"] = bool(row["currently_active"])
  232. return {row["user_id"]: UserPresenceState(**row) for row in rows}
  233. async def should_user_receive_full_presence_with_token(
  234. self,
  235. user_id: str,
  236. from_token: int,
  237. ) -> bool:
  238. """Check whether the given user should receive full presence using the stream token
  239. they're updating from.
  240. Args:
  241. user_id: The ID of the user to check.
  242. from_token: The stream token included in their /sync token.
  243. Returns:
  244. True if the user should have full presence sent to them, False otherwise.
  245. """
  246. token = await self._get_full_presence_stream_token_for_user(user_id)
  247. if token is None:
  248. return False
  249. return from_token <= token
  250. @cached()
  251. async def _get_full_presence_stream_token_for_user(
  252. self, user_id: str
  253. ) -> Optional[int]:
  254. """Get the presence token corresponding to the last full presence update
  255. for this user.
  256. If the user presents a sync token with a presence stream token at least
  257. as old as the result, then we need to send them a full presence update.
  258. If this user has never needed a full presence update, returns `None`.
  259. """
  260. return await self.db_pool.simple_select_one_onecol(
  261. table="users_to_send_full_presence_to",
  262. keyvalues={"user_id": user_id},
  263. retcol="presence_stream_id",
  264. allow_none=True,
  265. desc="_get_full_presence_stream_token_for_user",
  266. )
  267. async def add_users_to_send_full_presence_to(self, user_ids: Iterable[str]) -> None:
  268. """Adds to the list of users who should receive a full snapshot of presence
  269. upon their next sync.
  270. Args:
  271. user_ids: An iterable of user IDs.
  272. """
  273. # Add user entries to the table, updating the presence_stream_id column if the user already
  274. # exists in the table.
  275. presence_stream_id = self._presence_id_gen.get_current_token()
  276. def _add_users_to_send_full_presence_to(txn: LoggingTransaction) -> None:
  277. self.db_pool.simple_upsert_many_txn(
  278. txn,
  279. table="users_to_send_full_presence_to",
  280. key_names=("user_id",),
  281. key_values=[(user_id,) for user_id in user_ids],
  282. value_names=("presence_stream_id",),
  283. # We save the current presence stream ID token along with the user ID entry so
  284. # that when a user /sync's, even if they syncing multiple times across separate
  285. # devices at different times, each device will receive full presence once - when
  286. # the presence stream ID in their sync token is less than the one in the table
  287. # for their user ID.
  288. value_values=[(presence_stream_id,) for _ in user_ids],
  289. )
  290. for user_id in user_ids:
  291. self._invalidate_cache_and_stream(
  292. txn, self._get_full_presence_stream_token_for_user, (user_id,)
  293. )
  294. return await self.db_pool.runInteraction(
  295. "add_users_to_send_full_presence_to", _add_users_to_send_full_presence_to
  296. )
  297. async def get_presence_for_all_users(
  298. self,
  299. include_offline: bool = True,
  300. ) -> Dict[str, UserPresenceState]:
  301. """Retrieve the current presence state for all users.
  302. Note that the presence_stream table is culled frequently, so it should only
  303. contain the latest presence state for each user.
  304. Args:
  305. include_offline: Whether to include offline presence states
  306. Returns:
  307. A dict of user IDs to their current UserPresenceState.
  308. """
  309. users_to_state = {}
  310. exclude_keyvalues = None
  311. if not include_offline:
  312. # Exclude offline presence state
  313. exclude_keyvalues = {"state": "offline"}
  314. # This may be a very heavy database query.
  315. # We paginate in order to not block a database connection.
  316. limit = 100
  317. offset = 0
  318. while True:
  319. rows = await self.db_pool.runInteraction(
  320. "get_presence_for_all_users",
  321. self.db_pool.simple_select_list_paginate_txn,
  322. "presence_stream",
  323. orderby="stream_id",
  324. start=offset,
  325. limit=limit,
  326. exclude_keyvalues=exclude_keyvalues,
  327. retcols=(
  328. "user_id",
  329. "state",
  330. "last_active_ts",
  331. "last_federation_update_ts",
  332. "last_user_sync_ts",
  333. "status_msg",
  334. "currently_active",
  335. ),
  336. order_direction="ASC",
  337. )
  338. for row in rows:
  339. users_to_state[row["user_id"]] = UserPresenceState(**row)
  340. # We've run out of updates to query
  341. if len(rows) < limit:
  342. break
  343. offset += limit
  344. return users_to_state
  345. def get_current_presence_token(self) -> int:
  346. return self._presence_id_gen.get_current_token()
  347. def _get_active_presence(self, db_conn: Connection) -> List[UserPresenceState]:
  348. """Fetch non-offline presence from the database so that we can register
  349. the appropriate time outs.
  350. """
  351. # The `presence_stream_state_not_offline_idx` index should be used for this
  352. # query.
  353. sql = (
  354. "SELECT user_id, state, last_active_ts, last_federation_update_ts,"
  355. " last_user_sync_ts, status_msg, currently_active FROM presence_stream"
  356. " WHERE state != ?"
  357. )
  358. txn = db_conn.cursor()
  359. txn.execute(sql, (PresenceState.OFFLINE,))
  360. rows = self.db_pool.cursor_to_dict(txn)
  361. txn.close()
  362. for row in rows:
  363. row["currently_active"] = bool(row["currently_active"])
  364. return [UserPresenceState(**row) for row in rows]
  365. def take_presence_startup_info(self) -> List[UserPresenceState]:
  366. active_on_startup = self._presence_on_startup
  367. self._presence_on_startup = []
  368. return active_on_startup
  369. def process_replication_rows(
  370. self,
  371. stream_name: str,
  372. instance_name: str,
  373. token: int,
  374. rows: Iterable[Any],
  375. ) -> None:
  376. if stream_name == PresenceStream.NAME:
  377. self._presence_id_gen.advance(instance_name, token)
  378. for row in rows:
  379. self.presence_stream_cache.entity_has_changed(row.user_id, token)
  380. self._get_presence_for_user.invalidate((row.user_id,))
  381. return super().process_replication_rows(stream_name, instance_name, token, rows)