Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

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