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.
 
 
 
 
 
 

701 lines
25 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 collections.abc
  16. import logging
  17. from typing import TYPE_CHECKING, Any, Collection, Dict, Iterable, Optional, Set, Tuple
  18. import attr
  19. from synapse.api.constants import EventTypes, Membership
  20. from synapse.api.errors import NotFoundError, UnsupportedRoomVersionError
  21. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion
  22. from synapse.events import EventBase
  23. from synapse.events.snapshot import EventContext
  24. from synapse.logging.opentracing import trace
  25. from synapse.replication.tcp.streams import UnPartialStatedEventStream
  26. from synapse.replication.tcp.streams.partial_state import UnPartialStatedEventStreamRow
  27. from synapse.storage._base import SQLBaseStore
  28. from synapse.storage.database import (
  29. DatabasePool,
  30. LoggingDatabaseConnection,
  31. LoggingTransaction,
  32. make_in_list_sql_clause,
  33. )
  34. from synapse.storage.databases.main.events_worker import EventsWorkerStore
  35. from synapse.storage.databases.main.roommember import RoomMemberWorkerStore
  36. from synapse.types import JsonDict, JsonMapping, StateMap
  37. from synapse.types.state import StateFilter
  38. from synapse.util.caches import intern_string
  39. from synapse.util.caches.descriptors import cached, cachedList
  40. from synapse.util.cancellation import cancellable
  41. from synapse.util.iterutils import batch_iter
  42. if TYPE_CHECKING:
  43. from synapse.server import HomeServer
  44. logger = logging.getLogger(__name__)
  45. MAX_STATE_DELTA_HOPS = 100
  46. @attr.s(slots=True, frozen=True, auto_attribs=True)
  47. class EventMetadata:
  48. """Returned by `get_metadata_for_events`"""
  49. room_id: str
  50. event_type: str
  51. state_key: Optional[str]
  52. rejection_reason: Optional[str]
  53. def _retrieve_and_check_room_version(room_id: str, room_version_id: str) -> RoomVersion:
  54. v = KNOWN_ROOM_VERSIONS.get(room_version_id)
  55. if not v:
  56. raise UnsupportedRoomVersionError(
  57. "Room %s uses a room version %s which is no longer supported"
  58. % (room_id, room_version_id)
  59. )
  60. return v
  61. # this inherits from EventsWorkerStore because it calls self.get_events
  62. class StateGroupWorkerStore(EventsWorkerStore, SQLBaseStore):
  63. """The parts of StateGroupStore that can be called from workers."""
  64. def __init__(
  65. self,
  66. database: DatabasePool,
  67. db_conn: LoggingDatabaseConnection,
  68. hs: "HomeServer",
  69. ):
  70. super().__init__(database, db_conn, hs)
  71. self._instance_name: str = hs.get_instance_name()
  72. def process_replication_rows(
  73. self,
  74. stream_name: str,
  75. instance_name: str,
  76. token: int,
  77. rows: Iterable[Any],
  78. ) -> None:
  79. if stream_name == UnPartialStatedEventStream.NAME:
  80. for row in rows:
  81. assert isinstance(row, UnPartialStatedEventStreamRow)
  82. self._get_state_group_for_event.invalidate((row.event_id,))
  83. self.is_partial_state_event.invalidate((row.event_id,))
  84. super().process_replication_rows(stream_name, instance_name, token, rows)
  85. async def get_room_version(self, room_id: str) -> RoomVersion:
  86. """Get the room_version of a given room
  87. Raises:
  88. NotFoundError: if the room is unknown
  89. UnsupportedRoomVersionError: if the room uses an unknown room version.
  90. Typically this happens if support for the room's version has been
  91. removed from Synapse.
  92. """
  93. room_version_id = await self.get_room_version_id(room_id)
  94. return _retrieve_and_check_room_version(room_id, room_version_id)
  95. def get_room_version_txn(
  96. self, txn: LoggingTransaction, room_id: str
  97. ) -> RoomVersion:
  98. """Get the room_version of a given room
  99. Args:
  100. txn: Transaction object
  101. room_id: The room_id of the room you are trying to get the version for
  102. Raises:
  103. NotFoundError: if the room is unknown
  104. UnsupportedRoomVersionError: if the room uses an unknown room version.
  105. Typically this happens if support for the room's version has been
  106. removed from Synapse.
  107. """
  108. room_version_id = self.get_room_version_id_txn(txn, room_id)
  109. return _retrieve_and_check_room_version(room_id, room_version_id)
  110. @cached(max_entries=10000)
  111. async def get_room_version_id(self, room_id: str) -> str:
  112. """Get the room_version of a given room
  113. Raises:
  114. NotFoundError: if the room is unknown
  115. """
  116. return await self.db_pool.runInteraction(
  117. "get_room_version_id_txn",
  118. self.get_room_version_id_txn,
  119. room_id,
  120. )
  121. def get_room_version_id_txn(self, txn: LoggingTransaction, room_id: str) -> str:
  122. """Get the room_version of a given room
  123. Args:
  124. txn: Transaction object
  125. room_id: The room_id of the room you are trying to get the version for
  126. Raises:
  127. NotFoundError: if the room is unknown
  128. """
  129. # We really should have an entry in the rooms table for every room we
  130. # care about, but let's be a bit paranoid.
  131. room_version = self.db_pool.simple_select_one_onecol_txn(
  132. txn,
  133. table="rooms",
  134. keyvalues={"room_id": room_id},
  135. retcol="room_version",
  136. allow_none=True,
  137. )
  138. if room_version is None:
  139. raise NotFoundError("Could not find room_version for %s" % (room_id,))
  140. return room_version
  141. @trace
  142. async def get_metadata_for_events(
  143. self, event_ids: Collection[str]
  144. ) -> Dict[str, EventMetadata]:
  145. """Get some metadata (room_id, type, state_key) for the given events.
  146. This method is a faster alternative than fetching the full events from
  147. the DB, and should be used when the full event is not needed.
  148. Returns metadata for rejected and redacted events. Events that have not
  149. been persisted are omitted from the returned dict.
  150. """
  151. def get_metadata_for_events_txn(
  152. txn: LoggingTransaction,
  153. batch_ids: Collection[str],
  154. ) -> Dict[str, EventMetadata]:
  155. clause, args = make_in_list_sql_clause(
  156. self.database_engine, "e.event_id", batch_ids
  157. )
  158. sql = f"""
  159. SELECT e.event_id, e.room_id, e.type, se.state_key, r.reason
  160. FROM events AS e
  161. LEFT JOIN state_events se USING (event_id)
  162. LEFT JOIN rejections r USING (event_id)
  163. WHERE {clause}
  164. """
  165. txn.execute(sql, args)
  166. return {
  167. event_id: EventMetadata(
  168. room_id=room_id,
  169. event_type=event_type,
  170. state_key=state_key,
  171. rejection_reason=rejection_reason,
  172. )
  173. for event_id, room_id, event_type, state_key, rejection_reason in txn
  174. }
  175. result_map: Dict[str, EventMetadata] = {}
  176. for batch_ids in batch_iter(event_ids, 1000):
  177. result_map.update(
  178. await self.db_pool.runInteraction(
  179. "get_metadata_for_events",
  180. get_metadata_for_events_txn,
  181. batch_ids=batch_ids,
  182. )
  183. )
  184. return result_map
  185. async def get_room_predecessor(self, room_id: str) -> Optional[JsonMapping]:
  186. """Get the predecessor of an upgraded room if it exists.
  187. Otherwise return None.
  188. Args:
  189. room_id: The room ID.
  190. Returns:
  191. A dictionary containing the structure of the predecessor
  192. field from the room's create event. The structure is subject to other servers,
  193. but it is expected to be:
  194. * room_id (str): The room ID of the predecessor room
  195. * event_id (str): The ID of the tombstone event in the predecessor room
  196. None if a predecessor key is not found, or is not a dictionary.
  197. Raises:
  198. NotFoundError if the given room is unknown
  199. """
  200. # Retrieve the room's create event
  201. create_event = await self.get_create_event_for_room(room_id)
  202. # Retrieve the predecessor key of the create event
  203. predecessor = create_event.content.get("predecessor", None)
  204. # Ensure the key is a dictionary
  205. if not isinstance(predecessor, collections.abc.Mapping):
  206. return None
  207. # The keys must be strings since the data is JSON.
  208. return predecessor
  209. async def get_create_event_for_room(self, room_id: str) -> EventBase:
  210. """Get the create state event for a room.
  211. Args:
  212. room_id: The room ID.
  213. Returns:
  214. The room creation event.
  215. Raises:
  216. NotFoundError if the room is unknown
  217. """
  218. state_ids = await self.get_partial_current_state_ids(room_id)
  219. if not state_ids:
  220. raise NotFoundError(f"Current state for room {room_id} is empty")
  221. create_id = state_ids.get((EventTypes.Create, ""))
  222. # If we can't find the create event, assume we've hit a dead end
  223. if not create_id:
  224. raise NotFoundError(f"No create event in current state for room {room_id}")
  225. # Retrieve the room's create event and return
  226. create_event = await self.get_event(create_id)
  227. return create_event
  228. @cached(max_entries=100000, iterable=True)
  229. async def get_partial_current_state_ids(self, room_id: str) -> StateMap[str]:
  230. """Get the current state event ids for a room based on the
  231. current_state_events table.
  232. This may be the partial state if we're lazy joining the room.
  233. Args:
  234. room_id: The room to get the state IDs of.
  235. Returns:
  236. The current state of the room.
  237. """
  238. def _get_current_state_ids_txn(txn: LoggingTransaction) -> StateMap[str]:
  239. txn.execute(
  240. """SELECT type, state_key, event_id FROM current_state_events
  241. WHERE room_id = ?
  242. """,
  243. (room_id,),
  244. )
  245. return {(intern_string(r[0]), intern_string(r[1])): r[2] for r in txn}
  246. return await self.db_pool.runInteraction(
  247. "get_partial_current_state_ids", _get_current_state_ids_txn
  248. )
  249. # FIXME: how should this be cached?
  250. @cancellable
  251. async def get_partial_filtered_current_state_ids(
  252. self, room_id: str, state_filter: Optional[StateFilter] = None
  253. ) -> StateMap[str]:
  254. """Get the current state event of a given type for a room based on the
  255. current_state_events table. This may not be as up-to-date as the result
  256. of doing a fresh state resolution as per state_handler.get_current_state
  257. This may be the partial state if we're lazy joining the room.
  258. Args:
  259. room_id
  260. state_filter: The state filter used to fetch state
  261. from the database.
  262. Returns:
  263. Map from type/state_key to event ID.
  264. """
  265. where_clause, where_args = (
  266. state_filter or StateFilter.all()
  267. ).make_sql_filter_clause()
  268. if not where_clause:
  269. # We delegate to the cached version
  270. return await self.get_partial_current_state_ids(room_id)
  271. def _get_filtered_current_state_ids_txn(
  272. txn: LoggingTransaction,
  273. ) -> StateMap[str]:
  274. results = {}
  275. sql = """
  276. SELECT type, state_key, event_id FROM current_state_events
  277. WHERE room_id = ?
  278. """
  279. if where_clause:
  280. sql += " AND (%s)" % (where_clause,)
  281. args = [room_id]
  282. args.extend(where_args)
  283. txn.execute(sql, args)
  284. for row in txn:
  285. typ, state_key, event_id = row
  286. key = (intern_string(typ), intern_string(state_key))
  287. results[key] = event_id
  288. return results
  289. return await self.db_pool.runInteraction(
  290. "get_filtered_current_state_ids", _get_filtered_current_state_ids_txn
  291. )
  292. @cached(max_entries=50000)
  293. async def _get_state_group_for_event(self, event_id: str) -> Optional[int]:
  294. return await self.db_pool.simple_select_one_onecol(
  295. table="event_to_state_groups",
  296. keyvalues={"event_id": event_id},
  297. retcol="state_group",
  298. allow_none=True,
  299. desc="_get_state_group_for_event",
  300. )
  301. @cachedList(
  302. cached_method_name="_get_state_group_for_event",
  303. list_name="event_ids",
  304. num_args=1,
  305. )
  306. async def _get_state_group_for_events(
  307. self, event_ids: Collection[str]
  308. ) -> Dict[str, int]:
  309. """Returns mapping event_id -> state_group.
  310. Raises:
  311. RuntimeError if the state is unknown at any of the given events
  312. """
  313. rows = await self.db_pool.simple_select_many_batch(
  314. table="event_to_state_groups",
  315. column="event_id",
  316. iterable=event_ids,
  317. keyvalues={},
  318. retcols=("event_id", "state_group"),
  319. desc="_get_state_group_for_events",
  320. )
  321. res = {row["event_id"]: row["state_group"] for row in rows}
  322. for e in event_ids:
  323. if e not in res:
  324. raise RuntimeError("No state group for unknown or outlier event %s" % e)
  325. return res
  326. async def get_referenced_state_groups(
  327. self, state_groups: Iterable[int]
  328. ) -> Set[int]:
  329. """Check if the state groups are referenced by events.
  330. Args:
  331. state_groups
  332. Returns:
  333. The subset of state groups that are referenced.
  334. """
  335. rows = await self.db_pool.simple_select_many_batch(
  336. table="event_to_state_groups",
  337. column="state_group",
  338. iterable=state_groups,
  339. keyvalues={},
  340. retcols=("DISTINCT state_group",),
  341. desc="get_referenced_state_groups",
  342. )
  343. return {row["state_group"] for row in rows}
  344. async def update_state_for_partial_state_event(
  345. self,
  346. event: EventBase,
  347. context: EventContext,
  348. ) -> None:
  349. """Update the state group for a partial state event"""
  350. async with self._un_partial_stated_events_stream_id_gen.get_next() as un_partial_state_event_stream_id:
  351. await self.db_pool.runInteraction(
  352. "update_state_for_partial_state_event",
  353. self._update_state_for_partial_state_event_txn,
  354. event,
  355. context,
  356. un_partial_state_event_stream_id,
  357. )
  358. def _update_state_for_partial_state_event_txn(
  359. self,
  360. txn: LoggingTransaction,
  361. event: EventBase,
  362. context: EventContext,
  363. un_partial_state_event_stream_id: int,
  364. ) -> None:
  365. # we shouldn't have any outliers here
  366. assert not event.internal_metadata.is_outlier()
  367. # anything that was rejected should have the same state as its
  368. # predecessor.
  369. if context.rejected:
  370. state_group = context.state_group_before_event
  371. else:
  372. state_group = context.state_group
  373. self.db_pool.simple_update_txn(
  374. txn,
  375. table="event_to_state_groups",
  376. keyvalues={"event_id": event.event_id},
  377. updatevalues={"state_group": state_group},
  378. )
  379. # the event may now be rejected where it was not before, or vice versa,
  380. # in which case we need to update the rejected flags.
  381. rejection_status_changed = bool(context.rejected) != (
  382. event.rejected_reason is not None
  383. )
  384. if rejection_status_changed:
  385. self.mark_event_rejected_txn(txn, event.event_id, context.rejected)
  386. self.db_pool.simple_delete_one_txn(
  387. txn,
  388. table="partial_state_events",
  389. keyvalues={"event_id": event.event_id},
  390. )
  391. txn.call_after(self.is_partial_state_event.invalidate, (event.event_id,))
  392. txn.call_after(
  393. self._get_state_group_for_event.prefill,
  394. (event.event_id,),
  395. state_group,
  396. )
  397. self.db_pool.simple_insert_txn(
  398. txn,
  399. "un_partial_stated_event_stream",
  400. {
  401. "stream_id": un_partial_state_event_stream_id,
  402. "instance_name": self._instance_name,
  403. "event_id": event.event_id,
  404. "rejection_status_changed": rejection_status_changed,
  405. },
  406. )
  407. txn.call_after(self.hs.get_notifier().on_new_replication_data)
  408. class MainStateBackgroundUpdateStore(RoomMemberWorkerStore):
  409. CURRENT_STATE_INDEX_UPDATE_NAME = "current_state_members_idx"
  410. EVENT_STATE_GROUP_INDEX_UPDATE_NAME = "event_to_state_groups_sg_index"
  411. DELETE_CURRENT_STATE_UPDATE_NAME = "delete_old_current_state_events"
  412. def __init__(
  413. self,
  414. database: DatabasePool,
  415. db_conn: LoggingDatabaseConnection,
  416. hs: "HomeServer",
  417. ):
  418. super().__init__(database, db_conn, hs)
  419. self.server_name: str = hs.hostname
  420. self.db_pool.updates.register_background_index_update(
  421. self.CURRENT_STATE_INDEX_UPDATE_NAME,
  422. index_name="current_state_events_member_index",
  423. table="current_state_events",
  424. columns=["state_key"],
  425. where_clause="type='m.room.member'",
  426. )
  427. self.db_pool.updates.register_background_index_update(
  428. self.EVENT_STATE_GROUP_INDEX_UPDATE_NAME,
  429. index_name="event_to_state_groups_sg_index",
  430. table="event_to_state_groups",
  431. columns=["state_group"],
  432. )
  433. self.db_pool.updates.register_background_update_handler(
  434. self.DELETE_CURRENT_STATE_UPDATE_NAME,
  435. self._background_remove_left_rooms,
  436. )
  437. async def _background_remove_left_rooms(
  438. self, progress: JsonDict, batch_size: int
  439. ) -> int:
  440. """Background update to delete rows from `current_state_events` and
  441. `event_forward_extremities` tables of rooms that the server is no
  442. longer joined to.
  443. """
  444. last_room_id = progress.get("last_room_id", "")
  445. def _background_remove_left_rooms_txn(
  446. txn: LoggingTransaction,
  447. ) -> Tuple[bool, Set[str]]:
  448. # get a batch of room ids to consider
  449. sql = """
  450. SELECT DISTINCT room_id FROM current_state_events
  451. WHERE room_id > ? ORDER BY room_id LIMIT ?
  452. """
  453. txn.execute(sql, (last_room_id, batch_size))
  454. room_ids = [row[0] for row in txn]
  455. if not room_ids:
  456. return True, set()
  457. ###########################################################################
  458. #
  459. # exclude rooms where we have active members
  460. sql = """
  461. SELECT room_id
  462. FROM local_current_membership
  463. WHERE
  464. room_id > ? AND room_id <= ?
  465. AND membership = 'join'
  466. GROUP BY room_id
  467. """
  468. txn.execute(sql, (last_room_id, room_ids[-1]))
  469. joined_room_ids = {row[0] for row in txn}
  470. to_delete = set(room_ids) - joined_room_ids
  471. ###########################################################################
  472. #
  473. # exclude rooms which we are in the process of constructing; these otherwise
  474. # qualify as "rooms with no local users", and would have their
  475. # forward extremities cleaned up.
  476. # the following query will return a list of rooms which have forward
  477. # extremities that are *not* also the create event in the room - ie
  478. # those that are not being created currently.
  479. sql = """
  480. SELECT DISTINCT efe.room_id
  481. FROM event_forward_extremities efe
  482. LEFT JOIN current_state_events cse ON
  483. cse.event_id = efe.event_id
  484. AND cse.type = 'm.room.create'
  485. AND cse.state_key = ''
  486. WHERE
  487. cse.event_id IS NULL
  488. AND efe.room_id > ? AND efe.room_id <= ?
  489. """
  490. txn.execute(sql, (last_room_id, room_ids[-1]))
  491. # build a set of those rooms within `to_delete` that do not appear in
  492. # the above, leaving us with the rooms in `to_delete` that *are* being
  493. # created.
  494. creating_rooms = to_delete.difference(row[0] for row in txn)
  495. logger.info("skipping rooms which are being created: %s", creating_rooms)
  496. # now remove the rooms being created from the list of those to delete.
  497. #
  498. # (we could have just taken the intersection of `to_delete` with the result
  499. # of the sql query, but it's useful to be able to log `creating_rooms`; and
  500. # having done so, it's quicker to remove the (few) creating rooms from
  501. # `to_delete` than it is to form the intersection with the (larger) list of
  502. # not-creating-rooms)
  503. to_delete -= creating_rooms
  504. ###########################################################################
  505. #
  506. # now clear the state for the rooms
  507. logger.info("Deleting current state left rooms: %r", to_delete)
  508. # First we get all users that we still think were joined to the
  509. # room. This is so that we can mark those device lists as
  510. # potentially stale, since there may have been a period where the
  511. # server didn't share a room with the remote user and therefore may
  512. # have missed any device updates.
  513. rows = self.db_pool.simple_select_many_txn(
  514. txn,
  515. table="current_state_events",
  516. column="room_id",
  517. iterable=to_delete,
  518. keyvalues={"type": EventTypes.Member, "membership": Membership.JOIN},
  519. retcols=("state_key",),
  520. )
  521. potentially_left_users = {row["state_key"] for row in rows}
  522. # Now lets actually delete the rooms from the DB.
  523. self.db_pool.simple_delete_many_txn(
  524. txn,
  525. table="current_state_events",
  526. column="room_id",
  527. values=to_delete,
  528. keyvalues={},
  529. )
  530. self.db_pool.simple_delete_many_txn(
  531. txn,
  532. table="event_forward_extremities",
  533. column="room_id",
  534. values=to_delete,
  535. keyvalues={},
  536. )
  537. self.db_pool.updates._background_update_progress_txn(
  538. txn,
  539. self.DELETE_CURRENT_STATE_UPDATE_NAME,
  540. {"last_room_id": room_ids[-1]},
  541. )
  542. return False, potentially_left_users
  543. finished, potentially_left_users = await self.db_pool.runInteraction(
  544. "_background_remove_left_rooms", _background_remove_left_rooms_txn
  545. )
  546. if finished:
  547. await self.db_pool.updates._end_background_update(
  548. self.DELETE_CURRENT_STATE_UPDATE_NAME
  549. )
  550. # Now go and check if we still share a room with the remote users in
  551. # the deleted rooms. If not mark their device lists as stale.
  552. joined_users = await self.get_users_server_still_shares_room_with(
  553. potentially_left_users
  554. )
  555. for user_id in potentially_left_users - joined_users:
  556. await self.mark_remote_user_device_list_as_unsubscribed(user_id) # type: ignore[attr-defined]
  557. return batch_size
  558. class StateStore(StateGroupWorkerStore, MainStateBackgroundUpdateStore):
  559. """Keeps track of the state at a given event.
  560. This is done by the concept of `state groups`. Every event is a assigned
  561. a state group (identified by an arbitrary string), which references a
  562. collection of state events. The current state of an event is then the
  563. collection of state events referenced by the event's state group.
  564. Hence, every change in the current state causes a new state group to be
  565. generated. However, if no change happens (e.g., if we get a message event
  566. with only one parent it inherits the state group from its parent.)
  567. There are three tables:
  568. * `state_groups`: Stores group name, first event with in the group and
  569. room id.
  570. * `event_to_state_groups`: Maps events to state groups.
  571. * `state_groups_state`: Maps state group to state events.
  572. """
  573. def __init__(
  574. self,
  575. database: DatabasePool,
  576. db_conn: LoggingDatabaseConnection,
  577. hs: "HomeServer",
  578. ):
  579. super().__init__(database, db_conn, hs)