No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

615 líneas
22 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2020 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from typing import TYPE_CHECKING, Collection, Dict, Iterable, Optional, Set, Tuple
  17. from frozendict import frozendict
  18. from synapse.api.constants import EventTypes, Membership
  19. from synapse.api.errors import NotFoundError, UnsupportedRoomVersionError
  20. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion
  21. from synapse.events import EventBase
  22. from synapse.events.snapshot import EventContext
  23. from synapse.storage._base import SQLBaseStore
  24. from synapse.storage.database import (
  25. DatabasePool,
  26. LoggingDatabaseConnection,
  27. LoggingTransaction,
  28. )
  29. from synapse.storage.databases.main.events_worker import EventsWorkerStore
  30. from synapse.storage.databases.main.roommember import RoomMemberWorkerStore
  31. from synapse.storage.state import StateFilter
  32. from synapse.types import JsonDict, JsonMapping, StateMap
  33. from synapse.util.caches import intern_string
  34. from synapse.util.caches.descriptors import cached, cachedList
  35. if TYPE_CHECKING:
  36. from synapse.server import HomeServer
  37. logger = logging.getLogger(__name__)
  38. MAX_STATE_DELTA_HOPS = 100
  39. def _retrieve_and_check_room_version(room_id: str, room_version_id: str) -> RoomVersion:
  40. v = KNOWN_ROOM_VERSIONS.get(room_version_id)
  41. if not v:
  42. raise UnsupportedRoomVersionError(
  43. "Room %s uses a room version %s which is no longer supported"
  44. % (room_id, room_version_id)
  45. )
  46. return v
  47. # this inherits from EventsWorkerStore because it calls self.get_events
  48. class StateGroupWorkerStore(EventsWorkerStore, SQLBaseStore):
  49. """The parts of StateGroupStore that can be called from workers."""
  50. def __init__(
  51. self,
  52. database: DatabasePool,
  53. db_conn: LoggingDatabaseConnection,
  54. hs: "HomeServer",
  55. ):
  56. super().__init__(database, db_conn, hs)
  57. async def get_room_version(self, room_id: str) -> RoomVersion:
  58. """Get the room_version of a given room
  59. Raises:
  60. NotFoundError: if the room is unknown
  61. UnsupportedRoomVersionError: if the room uses an unknown room version.
  62. Typically this happens if support for the room's version has been
  63. removed from Synapse.
  64. """
  65. room_version_id = await self.get_room_version_id(room_id)
  66. return _retrieve_and_check_room_version(room_id, room_version_id)
  67. def get_room_version_txn(
  68. self, txn: LoggingTransaction, room_id: str
  69. ) -> RoomVersion:
  70. """Get the room_version of a given room
  71. Args:
  72. txn: Transaction object
  73. room_id: The room_id of the room you are trying to get the version for
  74. Raises:
  75. NotFoundError: if the room is unknown
  76. UnsupportedRoomVersionError: if the room uses an unknown room version.
  77. Typically this happens if support for the room's version has been
  78. removed from Synapse.
  79. """
  80. room_version_id = self.get_room_version_id_txn(txn, room_id)
  81. return _retrieve_and_check_room_version(room_id, room_version_id)
  82. @cached(max_entries=10000)
  83. async def get_room_version_id(self, room_id: str) -> str:
  84. """Get the room_version of a given room
  85. Raises:
  86. NotFoundError: if the room is unknown
  87. """
  88. return await self.db_pool.runInteraction(
  89. "get_room_version_id_txn",
  90. self.get_room_version_id_txn,
  91. room_id,
  92. )
  93. def get_room_version_id_txn(self, txn: LoggingTransaction, room_id: str) -> str:
  94. """Get the room_version of a given room
  95. Args:
  96. txn: Transaction object
  97. room_id: The room_id of the room you are trying to get the version for
  98. Raises:
  99. NotFoundError: if the room is unknown
  100. """
  101. # First we try looking up room version from the database, but for old
  102. # rooms we might not have added the room version to it yet so we fall
  103. # back to previous behaviour and look in current state events.
  104. #
  105. # We really should have an entry in the rooms table for every room we
  106. # care about, but let's be a bit paranoid (at least while the background
  107. # update is happening) to avoid breaking existing rooms.
  108. room_version = self.db_pool.simple_select_one_onecol_txn(
  109. txn,
  110. table="rooms",
  111. keyvalues={"room_id": room_id},
  112. retcol="room_version",
  113. allow_none=True,
  114. )
  115. if room_version is None:
  116. raise NotFoundError("Could not find room_version for %s" % (room_id,))
  117. return room_version
  118. async def get_room_predecessor(self, room_id: str) -> Optional[JsonMapping]:
  119. """Get the predecessor of an upgraded room if it exists.
  120. Otherwise return None.
  121. Args:
  122. room_id: The room ID.
  123. Returns:
  124. A dictionary containing the structure of the predecessor
  125. field from the room's create event. The structure is subject to other servers,
  126. but it is expected to be:
  127. * room_id (str): The room ID of the predecessor room
  128. * event_id (str): The ID of the tombstone event in the predecessor room
  129. None if a predecessor key is not found, or is not a dictionary.
  130. Raises:
  131. NotFoundError if the given room is unknown
  132. """
  133. # Retrieve the room's create event
  134. create_event = await self.get_create_event_for_room(room_id)
  135. # Retrieve the predecessor key of the create event
  136. predecessor = create_event.content.get("predecessor", None)
  137. # Ensure the key is a dictionary
  138. if not isinstance(predecessor, (dict, frozendict)):
  139. return None
  140. # The keys must be strings since the data is JSON.
  141. return predecessor
  142. async def get_create_event_for_room(self, room_id: str) -> EventBase:
  143. """Get the create state event for a room.
  144. Args:
  145. room_id: The room ID.
  146. Returns:
  147. The room creation event.
  148. Raises:
  149. NotFoundError if the room is unknown
  150. """
  151. state_ids = await self.get_current_state_ids(room_id)
  152. if not state_ids:
  153. raise NotFoundError(f"Current state for room {room_id} is empty")
  154. create_id = state_ids.get((EventTypes.Create, ""))
  155. # If we can't find the create event, assume we've hit a dead end
  156. if not create_id:
  157. raise NotFoundError(f"No create event in current state for room {room_id}")
  158. # Retrieve the room's create event and return
  159. create_event = await self.get_event(create_id)
  160. return create_event
  161. @cached(max_entries=100000, iterable=True)
  162. async def get_current_state_ids(self, room_id: str) -> StateMap[str]:
  163. """Get the current state event ids for a room based on the
  164. current_state_events table.
  165. Args:
  166. room_id: The room to get the state IDs of.
  167. Returns:
  168. The current state of the room.
  169. """
  170. def _get_current_state_ids_txn(txn: LoggingTransaction) -> StateMap[str]:
  171. txn.execute(
  172. """SELECT type, state_key, event_id FROM current_state_events
  173. WHERE room_id = ?
  174. """,
  175. (room_id,),
  176. )
  177. return {(intern_string(r[0]), intern_string(r[1])): r[2] for r in txn}
  178. return await self.db_pool.runInteraction(
  179. "get_current_state_ids", _get_current_state_ids_txn
  180. )
  181. # FIXME: how should this be cached?
  182. async def get_filtered_current_state_ids(
  183. self, room_id: str, state_filter: Optional[StateFilter] = None
  184. ) -> StateMap[str]:
  185. """Get the current state event of a given type for a room based on the
  186. current_state_events table. This may not be as up-to-date as the result
  187. of doing a fresh state resolution as per state_handler.get_current_state
  188. Args:
  189. room_id
  190. state_filter: The state filter used to fetch state
  191. from the database.
  192. Returns:
  193. Map from type/state_key to event ID.
  194. """
  195. where_clause, where_args = (
  196. state_filter or StateFilter.all()
  197. ).make_sql_filter_clause()
  198. if not where_clause:
  199. # We delegate to the cached version
  200. return await self.get_current_state_ids(room_id)
  201. def _get_filtered_current_state_ids_txn(
  202. txn: LoggingTransaction,
  203. ) -> StateMap[str]:
  204. results = {}
  205. sql = """
  206. SELECT type, state_key, event_id FROM current_state_events
  207. WHERE room_id = ?
  208. """
  209. if where_clause:
  210. sql += " AND (%s)" % (where_clause,)
  211. args = [room_id]
  212. args.extend(where_args)
  213. txn.execute(sql, args)
  214. for row in txn:
  215. typ, state_key, event_id = row
  216. key = (intern_string(typ), intern_string(state_key))
  217. results[key] = event_id
  218. return results
  219. return await self.db_pool.runInteraction(
  220. "get_filtered_current_state_ids", _get_filtered_current_state_ids_txn
  221. )
  222. async def get_canonical_alias_for_room(self, room_id: str) -> Optional[str]:
  223. """Get canonical alias for room, if any
  224. Args:
  225. room_id: The room ID
  226. Returns:
  227. The canonical alias, if any
  228. """
  229. state = await self.get_filtered_current_state_ids(
  230. room_id, StateFilter.from_types([(EventTypes.CanonicalAlias, "")])
  231. )
  232. event_id = state.get((EventTypes.CanonicalAlias, ""))
  233. if not event_id:
  234. return None
  235. event = await self.get_event(event_id, allow_none=True)
  236. if not event:
  237. return None
  238. return event.content.get("canonical_alias")
  239. @cached(max_entries=50000)
  240. async def _get_state_group_for_event(self, event_id: str) -> Optional[int]:
  241. return await self.db_pool.simple_select_one_onecol(
  242. table="event_to_state_groups",
  243. keyvalues={"event_id": event_id},
  244. retcol="state_group",
  245. allow_none=True,
  246. desc="_get_state_group_for_event",
  247. )
  248. @cachedList(
  249. cached_method_name="_get_state_group_for_event",
  250. list_name="event_ids",
  251. num_args=1,
  252. )
  253. async def _get_state_group_for_events(
  254. self, event_ids: Collection[str]
  255. ) -> Dict[str, int]:
  256. """Returns mapping event_id -> state_group.
  257. Raises:
  258. RuntimeError if the state is unknown at any of the given events
  259. """
  260. rows = await self.db_pool.simple_select_many_batch(
  261. table="event_to_state_groups",
  262. column="event_id",
  263. iterable=event_ids,
  264. keyvalues={},
  265. retcols=("event_id", "state_group"),
  266. desc="_get_state_group_for_events",
  267. )
  268. res = {row["event_id"]: row["state_group"] for row in rows}
  269. for e in event_ids:
  270. if e not in res:
  271. raise RuntimeError("No state group for unknown or outlier event %s" % e)
  272. return res
  273. async def get_referenced_state_groups(
  274. self, state_groups: Iterable[int]
  275. ) -> Set[int]:
  276. """Check if the state groups are referenced by events.
  277. Args:
  278. state_groups
  279. Returns:
  280. The subset of state groups that are referenced.
  281. """
  282. rows = await self.db_pool.simple_select_many_batch(
  283. table="event_to_state_groups",
  284. column="state_group",
  285. iterable=state_groups,
  286. keyvalues={},
  287. retcols=("DISTINCT state_group",),
  288. desc="get_referenced_state_groups",
  289. )
  290. return {row["state_group"] for row in rows}
  291. async def update_state_for_partial_state_event(
  292. self,
  293. event: EventBase,
  294. context: EventContext,
  295. ) -> None:
  296. """Update the state group for a partial state event"""
  297. await self.db_pool.runInteraction(
  298. "update_state_for_partial_state_event",
  299. self._update_state_for_partial_state_event_txn,
  300. event,
  301. context,
  302. )
  303. def _update_state_for_partial_state_event_txn(
  304. self,
  305. txn,
  306. event: EventBase,
  307. context: EventContext,
  308. ):
  309. # we shouldn't have any outliers here
  310. assert not event.internal_metadata.is_outlier()
  311. # anything that was rejected should have the same state as its
  312. # predecessor.
  313. if context.rejected:
  314. assert context.state_group == context.state_group_before_event
  315. self.db_pool.simple_update_txn(
  316. txn,
  317. table="event_to_state_groups",
  318. keyvalues={"event_id": event.event_id},
  319. updatevalues={"state_group": context.state_group},
  320. )
  321. self.db_pool.simple_delete_one_txn(
  322. txn,
  323. table="partial_state_events",
  324. keyvalues={"event_id": event.event_id},
  325. )
  326. # TODO(faster_joins): need to do something about workers here
  327. txn.call_after(
  328. self._get_state_group_for_event.prefill,
  329. (event.event_id,),
  330. context.state_group,
  331. )
  332. class MainStateBackgroundUpdateStore(RoomMemberWorkerStore):
  333. CURRENT_STATE_INDEX_UPDATE_NAME = "current_state_members_idx"
  334. EVENT_STATE_GROUP_INDEX_UPDATE_NAME = "event_to_state_groups_sg_index"
  335. DELETE_CURRENT_STATE_UPDATE_NAME = "delete_old_current_state_events"
  336. def __init__(
  337. self,
  338. database: DatabasePool,
  339. db_conn: LoggingDatabaseConnection,
  340. hs: "HomeServer",
  341. ):
  342. super().__init__(database, db_conn, hs)
  343. self.server_name: str = hs.hostname
  344. self.db_pool.updates.register_background_index_update(
  345. self.CURRENT_STATE_INDEX_UPDATE_NAME,
  346. index_name="current_state_events_member_index",
  347. table="current_state_events",
  348. columns=["state_key"],
  349. where_clause="type='m.room.member'",
  350. )
  351. self.db_pool.updates.register_background_index_update(
  352. self.EVENT_STATE_GROUP_INDEX_UPDATE_NAME,
  353. index_name="event_to_state_groups_sg_index",
  354. table="event_to_state_groups",
  355. columns=["state_group"],
  356. )
  357. self.db_pool.updates.register_background_update_handler(
  358. self.DELETE_CURRENT_STATE_UPDATE_NAME,
  359. self._background_remove_left_rooms,
  360. )
  361. async def _background_remove_left_rooms(
  362. self, progress: JsonDict, batch_size: int
  363. ) -> int:
  364. """Background update to delete rows from `current_state_events` and
  365. `event_forward_extremities` tables of rooms that the server is no
  366. longer joined to.
  367. """
  368. last_room_id = progress.get("last_room_id", "")
  369. def _background_remove_left_rooms_txn(
  370. txn: LoggingTransaction,
  371. ) -> Tuple[bool, Set[str]]:
  372. # get a batch of room ids to consider
  373. sql = """
  374. SELECT DISTINCT room_id FROM current_state_events
  375. WHERE room_id > ? ORDER BY room_id LIMIT ?
  376. """
  377. txn.execute(sql, (last_room_id, batch_size))
  378. room_ids = [row[0] for row in txn]
  379. if not room_ids:
  380. return True, set()
  381. ###########################################################################
  382. #
  383. # exclude rooms where we have active members
  384. sql = """
  385. SELECT room_id
  386. FROM local_current_membership
  387. WHERE
  388. room_id > ? AND room_id <= ?
  389. AND membership = 'join'
  390. GROUP BY room_id
  391. """
  392. txn.execute(sql, (last_room_id, room_ids[-1]))
  393. joined_room_ids = {row[0] for row in txn}
  394. to_delete = set(room_ids) - joined_room_ids
  395. ###########################################################################
  396. #
  397. # exclude rooms which we are in the process of constructing; these otherwise
  398. # qualify as "rooms with no local users", and would have their
  399. # forward extremities cleaned up.
  400. # the following query will return a list of rooms which have forward
  401. # extremities that are *not* also the create event in the room - ie
  402. # those that are not being created currently.
  403. sql = """
  404. SELECT DISTINCT efe.room_id
  405. FROM event_forward_extremities efe
  406. LEFT JOIN current_state_events cse ON
  407. cse.event_id = efe.event_id
  408. AND cse.type = 'm.room.create'
  409. AND cse.state_key = ''
  410. WHERE
  411. cse.event_id IS NULL
  412. AND efe.room_id > ? AND efe.room_id <= ?
  413. """
  414. txn.execute(sql, (last_room_id, room_ids[-1]))
  415. # build a set of those rooms within `to_delete` that do not appear in
  416. # the above, leaving us with the rooms in `to_delete` that *are* being
  417. # created.
  418. creating_rooms = to_delete.difference(row[0] for row in txn)
  419. logger.info("skipping rooms which are being created: %s", creating_rooms)
  420. # now remove the rooms being created from the list of those to delete.
  421. #
  422. # (we could have just taken the intersection of `to_delete` with the result
  423. # of the sql query, but it's useful to be able to log `creating_rooms`; and
  424. # having done so, it's quicker to remove the (few) creating rooms from
  425. # `to_delete` than it is to form the intersection with the (larger) list of
  426. # not-creating-rooms)
  427. to_delete -= creating_rooms
  428. ###########################################################################
  429. #
  430. # now clear the state for the rooms
  431. logger.info("Deleting current state left rooms: %r", to_delete)
  432. # First we get all users that we still think were joined to the
  433. # room. This is so that we can mark those device lists as
  434. # potentially stale, since there may have been a period where the
  435. # server didn't share a room with the remote user and therefore may
  436. # have missed any device updates.
  437. rows = self.db_pool.simple_select_many_txn(
  438. txn,
  439. table="current_state_events",
  440. column="room_id",
  441. iterable=to_delete,
  442. keyvalues={"type": EventTypes.Member, "membership": Membership.JOIN},
  443. retcols=("state_key",),
  444. )
  445. potentially_left_users = {row["state_key"] for row in rows}
  446. # Now lets actually delete the rooms from the DB.
  447. self.db_pool.simple_delete_many_txn(
  448. txn,
  449. table="current_state_events",
  450. column="room_id",
  451. values=to_delete,
  452. keyvalues={},
  453. )
  454. self.db_pool.simple_delete_many_txn(
  455. txn,
  456. table="event_forward_extremities",
  457. column="room_id",
  458. values=to_delete,
  459. keyvalues={},
  460. )
  461. self.db_pool.updates._background_update_progress_txn(
  462. txn,
  463. self.DELETE_CURRENT_STATE_UPDATE_NAME,
  464. {"last_room_id": room_ids[-1]},
  465. )
  466. return False, potentially_left_users
  467. finished, potentially_left_users = await self.db_pool.runInteraction(
  468. "_background_remove_left_rooms", _background_remove_left_rooms_txn
  469. )
  470. if finished:
  471. await self.db_pool.updates._end_background_update(
  472. self.DELETE_CURRENT_STATE_UPDATE_NAME
  473. )
  474. # Now go and check if we still share a room with the remote users in
  475. # the deleted rooms. If not mark their device lists as stale.
  476. joined_users = await self.get_users_server_still_shares_room_with(
  477. potentially_left_users
  478. )
  479. for user_id in potentially_left_users - joined_users:
  480. await self.mark_remote_user_device_list_as_unsubscribed(user_id) # type: ignore[attr-defined]
  481. return batch_size
  482. class StateStore(StateGroupWorkerStore, MainStateBackgroundUpdateStore):
  483. """Keeps track of the state at a given event.
  484. This is done by the concept of `state groups`. Every event is a assigned
  485. a state group (identified by an arbitrary string), which references a
  486. collection of state events. The current state of an event is then the
  487. collection of state events referenced by the event's state group.
  488. Hence, every change in the current state causes a new state group to be
  489. generated. However, if no change happens (e.g., if we get a message event
  490. with only one parent it inherits the state group from its parent.)
  491. There are three tables:
  492. * `state_groups`: Stores group name, first event with in the group and
  493. room id.
  494. * `event_to_state_groups`: Maps events to state groups.
  495. * `state_groups_state`: Maps state group to state events.
  496. """
  497. def __init__(
  498. self,
  499. database: DatabasePool,
  500. db_conn: LoggingDatabaseConnection,
  501. hs: "HomeServer",
  502. ):
  503. super().__init__(database, db_conn, hs)