Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

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