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.
 
 
 
 
 
 

2387 lines
85 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2019, 2022 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 abc import abstractmethod
  17. from enum import Enum
  18. from typing import (
  19. TYPE_CHECKING,
  20. Any,
  21. Awaitable,
  22. Collection,
  23. Dict,
  24. List,
  25. Mapping,
  26. Optional,
  27. Sequence,
  28. Tuple,
  29. Union,
  30. cast,
  31. )
  32. import attr
  33. from synapse.api.constants import (
  34. EventContentFields,
  35. EventTypes,
  36. JoinRules,
  37. PublicRoomsFilterFields,
  38. )
  39. from synapse.api.errors import StoreError
  40. from synapse.api.room_versions import RoomVersion, RoomVersions
  41. from synapse.config.homeserver import HomeServerConfig
  42. from synapse.events import EventBase
  43. from synapse.replication.tcp.streams.partial_state import UnPartialStatedRoomStream
  44. from synapse.storage._base import SQLBaseStore, db_to_json, make_in_list_sql_clause
  45. from synapse.storage.database import (
  46. DatabasePool,
  47. LoggingDatabaseConnection,
  48. LoggingTransaction,
  49. )
  50. from synapse.storage.databases.main.cache import CacheInvalidationWorkerStore
  51. from synapse.storage.engines import PostgresEngine
  52. from synapse.storage.types import Cursor
  53. from synapse.storage.util.id_generators import (
  54. AbstractStreamIdGenerator,
  55. IdGenerator,
  56. MultiWriterIdGenerator,
  57. StreamIdGenerator,
  58. )
  59. from synapse.types import JsonDict, RetentionPolicy, ThirdPartyInstanceID
  60. from synapse.util import json_encoder
  61. from synapse.util.caches.descriptors import cached
  62. from synapse.util.stringutils import MXC_REGEX
  63. if TYPE_CHECKING:
  64. from synapse.server import HomeServer
  65. logger = logging.getLogger(__name__)
  66. @attr.s(slots=True, frozen=True, auto_attribs=True)
  67. class RatelimitOverride:
  68. messages_per_second: int
  69. burst_count: int
  70. class RoomSortOrder(Enum):
  71. """
  72. Enum to define the sorting method used when returning rooms with get_rooms_paginate
  73. NAME = sort rooms alphabetically by name
  74. JOINED_MEMBERS = sort rooms by membership size, highest to lowest
  75. """
  76. # ALPHABETICAL and SIZE are deprecated.
  77. # ALPHABETICAL is the same as NAME.
  78. ALPHABETICAL = "alphabetical"
  79. # SIZE is the same as JOINED_MEMBERS.
  80. SIZE = "size"
  81. NAME = "name"
  82. CANONICAL_ALIAS = "canonical_alias"
  83. JOINED_MEMBERS = "joined_members"
  84. JOINED_LOCAL_MEMBERS = "joined_local_members"
  85. VERSION = "version"
  86. CREATOR = "creator"
  87. ENCRYPTION = "encryption"
  88. FEDERATABLE = "federatable"
  89. PUBLIC = "public"
  90. JOIN_RULES = "join_rules"
  91. GUEST_ACCESS = "guest_access"
  92. HISTORY_VISIBILITY = "history_visibility"
  93. STATE_EVENTS = "state_events"
  94. @attr.s(slots=True, frozen=True, auto_attribs=True)
  95. class PartialStateResyncInfo:
  96. joined_via: Optional[str]
  97. servers_in_room: List[str] = attr.ib(factory=list)
  98. class RoomWorkerStore(CacheInvalidationWorkerStore):
  99. def __init__(
  100. self,
  101. database: DatabasePool,
  102. db_conn: LoggingDatabaseConnection,
  103. hs: "HomeServer",
  104. ):
  105. super().__init__(database, db_conn, hs)
  106. self.config: HomeServerConfig = hs.config
  107. self._un_partial_stated_rooms_stream_id_gen: AbstractStreamIdGenerator
  108. if isinstance(database.engine, PostgresEngine):
  109. self._un_partial_stated_rooms_stream_id_gen = MultiWriterIdGenerator(
  110. db_conn=db_conn,
  111. db=database,
  112. notifier=hs.get_replication_notifier(),
  113. stream_name="un_partial_stated_room_stream",
  114. instance_name=self._instance_name,
  115. tables=[
  116. ("un_partial_stated_room_stream", "instance_name", "stream_id")
  117. ],
  118. sequence_name="un_partial_stated_room_stream_sequence",
  119. # TODO(faster_joins, multiple writers) Support multiple writers.
  120. writers=["master"],
  121. )
  122. else:
  123. self._un_partial_stated_rooms_stream_id_gen = StreamIdGenerator(
  124. db_conn,
  125. hs.get_replication_notifier(),
  126. "un_partial_stated_room_stream",
  127. "stream_id",
  128. )
  129. def process_replication_position(
  130. self, stream_name: str, instance_name: str, token: int
  131. ) -> None:
  132. if stream_name == UnPartialStatedRoomStream.NAME:
  133. self._un_partial_stated_rooms_stream_id_gen.advance(instance_name, token)
  134. return super().process_replication_position(stream_name, instance_name, token)
  135. async def store_room(
  136. self,
  137. room_id: str,
  138. room_creator_user_id: str,
  139. is_public: bool,
  140. room_version: RoomVersion,
  141. ) -> None:
  142. """Stores a room.
  143. Args:
  144. room_id: The desired room ID, can be None.
  145. room_creator_user_id: The user ID of the room creator.
  146. is_public: True to indicate that this room should appear in
  147. public room lists.
  148. room_version: The version of the room
  149. Raises:
  150. StoreError if the room could not be stored.
  151. """
  152. try:
  153. await self.db_pool.simple_insert(
  154. "rooms",
  155. {
  156. "room_id": room_id,
  157. "creator": room_creator_user_id,
  158. "is_public": is_public,
  159. "room_version": room_version.identifier,
  160. "has_auth_chain_index": True,
  161. },
  162. desc="store_room",
  163. )
  164. except Exception as e:
  165. logger.error("store_room with room_id=%s failed: %s", room_id, e)
  166. raise StoreError(500, "Problem creating room.")
  167. async def get_room(self, room_id: str) -> Optional[Dict[str, Any]]:
  168. """Retrieve a room.
  169. Args:
  170. room_id: The ID of the room to retrieve.
  171. Returns:
  172. A dict containing the room information, or None if the room is unknown.
  173. """
  174. return await self.db_pool.simple_select_one(
  175. table="rooms",
  176. keyvalues={"room_id": room_id},
  177. retcols=("room_id", "is_public", "creator", "has_auth_chain_index"),
  178. desc="get_room",
  179. allow_none=True,
  180. )
  181. async def get_room_with_stats(self, room_id: str) -> Optional[Dict[str, Any]]:
  182. """Retrieve room with statistics.
  183. Args:
  184. room_id: The ID of the room to retrieve.
  185. Returns:
  186. A dict containing the room information, or None if the room is unknown.
  187. """
  188. def get_room_with_stats_txn(
  189. txn: LoggingTransaction, room_id: str
  190. ) -> Optional[Dict[str, Any]]:
  191. sql = """
  192. SELECT room_id, state.name, state.canonical_alias, curr.joined_members,
  193. curr.local_users_in_room AS joined_local_members, rooms.room_version AS version,
  194. rooms.creator, state.encryption, state.is_federatable AS federatable,
  195. rooms.is_public AS public, state.join_rules, state.guest_access,
  196. state.history_visibility, curr.current_state_events AS state_events,
  197. state.avatar, state.topic, state.room_type
  198. FROM rooms
  199. LEFT JOIN room_stats_state state USING (room_id)
  200. LEFT JOIN room_stats_current curr USING (room_id)
  201. WHERE room_id = ?
  202. """
  203. txn.execute(sql, [room_id])
  204. # Catch error if sql returns empty result to return "None" instead of an error
  205. try:
  206. res = self.db_pool.cursor_to_dict(txn)[0]
  207. except IndexError:
  208. return None
  209. res["federatable"] = bool(res["federatable"])
  210. res["public"] = bool(res["public"])
  211. return res
  212. return await self.db_pool.runInteraction(
  213. "get_room_with_stats", get_room_with_stats_txn, room_id
  214. )
  215. async def get_public_room_ids(self) -> List[str]:
  216. return await self.db_pool.simple_select_onecol(
  217. table="rooms",
  218. keyvalues={"is_public": True},
  219. retcol="room_id",
  220. desc="get_public_room_ids",
  221. )
  222. def _construct_room_type_where_clause(
  223. self, room_types: Union[List[Union[str, None]], None]
  224. ) -> Tuple[Union[str, None], list]:
  225. if not room_types:
  226. return None, []
  227. # Since None is used to represent a room without a type, care needs to
  228. # be taken into account when constructing the where clause.
  229. clauses = []
  230. args: list = []
  231. room_types_set = set(room_types)
  232. # We use None to represent a room without a type.
  233. if None in room_types_set:
  234. clauses.append("room_type IS NULL")
  235. room_types_set.remove(None)
  236. # If there are other room types, generate the proper clause.
  237. if room_types:
  238. list_clause, args = make_in_list_sql_clause(
  239. self.database_engine, "room_type", room_types_set
  240. )
  241. clauses.append(list_clause)
  242. return f"({' OR '.join(clauses)})", args
  243. async def count_public_rooms(
  244. self,
  245. network_tuple: Optional[ThirdPartyInstanceID],
  246. ignore_non_federatable: bool,
  247. search_filter: Optional[dict],
  248. ) -> int:
  249. """Counts the number of public rooms as tracked in the room_stats_current
  250. and room_stats_state table.
  251. Args:
  252. network_tuple
  253. ignore_non_federatable: If true filters out non-federatable rooms
  254. search_filter
  255. """
  256. def _count_public_rooms_txn(txn: LoggingTransaction) -> int:
  257. query_args = []
  258. if network_tuple:
  259. if network_tuple.appservice_id:
  260. published_sql = """
  261. SELECT room_id from appservice_room_list
  262. WHERE appservice_id = ? AND network_id = ?
  263. """
  264. query_args.append(network_tuple.appservice_id)
  265. assert network_tuple.network_id is not None
  266. query_args.append(network_tuple.network_id)
  267. else:
  268. published_sql = """
  269. SELECT room_id FROM rooms WHERE is_public
  270. """
  271. else:
  272. published_sql = """
  273. SELECT room_id FROM rooms WHERE is_public
  274. UNION SELECT room_id from appservice_room_list
  275. """
  276. room_type_clause, args = self._construct_room_type_where_clause(
  277. search_filter.get(PublicRoomsFilterFields.ROOM_TYPES, None)
  278. if search_filter
  279. else None
  280. )
  281. room_type_clause = f" AND {room_type_clause}" if room_type_clause else ""
  282. query_args += args
  283. sql = f"""
  284. SELECT
  285. COUNT(*)
  286. FROM (
  287. {published_sql}
  288. ) published
  289. INNER JOIN room_stats_state USING (room_id)
  290. INNER JOIN room_stats_current USING (room_id)
  291. WHERE
  292. (
  293. join_rules = '{JoinRules.PUBLIC}'
  294. OR join_rules = '{JoinRules.KNOCK}'
  295. OR join_rules = '{JoinRules.KNOCK_RESTRICTED}'
  296. OR history_visibility = 'world_readable'
  297. )
  298. {room_type_clause}
  299. AND joined_members > 0
  300. """
  301. txn.execute(sql, query_args)
  302. return cast(Tuple[int], txn.fetchone())[0]
  303. return await self.db_pool.runInteraction(
  304. "count_public_rooms", _count_public_rooms_txn
  305. )
  306. async def get_room_count(self) -> int:
  307. """Retrieve the total number of rooms."""
  308. def f(txn: LoggingTransaction) -> int:
  309. sql = "SELECT count(*) FROM rooms"
  310. txn.execute(sql)
  311. row = cast(Tuple[int], txn.fetchone())
  312. return row[0]
  313. return await self.db_pool.runInteraction("get_rooms", f)
  314. async def get_largest_public_rooms(
  315. self,
  316. network_tuple: Optional[ThirdPartyInstanceID],
  317. search_filter: Optional[dict],
  318. limit: Optional[int],
  319. bounds: Optional[Tuple[int, str]],
  320. forwards: bool,
  321. ignore_non_federatable: bool = False,
  322. ) -> List[Dict[str, Any]]:
  323. """Gets the largest public rooms (where largest is in terms of joined
  324. members, as tracked in the statistics table).
  325. Args:
  326. network_tuple
  327. search_filter
  328. limit: Maxmimum number of rows to return, unlimited otherwise.
  329. bounds: An uppoer or lower bound to apply to result set if given,
  330. consists of a joined member count and room_id (these are
  331. excluded from result set).
  332. forwards: true iff going forwards, going backwards otherwise
  333. ignore_non_federatable: If true filters out non-federatable rooms.
  334. Returns:
  335. Rooms in order: biggest number of joined users first.
  336. We then arbitrarily use the room_id as a tie breaker.
  337. """
  338. where_clauses = []
  339. query_args: List[Union[str, int]] = []
  340. if network_tuple:
  341. if network_tuple.appservice_id:
  342. published_sql = """
  343. SELECT room_id from appservice_room_list
  344. WHERE appservice_id = ? AND network_id = ?
  345. """
  346. query_args.append(network_tuple.appservice_id)
  347. assert network_tuple.network_id is not None
  348. query_args.append(network_tuple.network_id)
  349. else:
  350. published_sql = """
  351. SELECT room_id FROM rooms WHERE is_public
  352. """
  353. else:
  354. published_sql = """
  355. SELECT room_id FROM rooms WHERE is_public
  356. UNION SELECT room_id from appservice_room_list
  357. """
  358. # Work out the bounds if we're given them, these bounds look slightly
  359. # odd, but are designed to help query planner use indices by pulling
  360. # out a common bound.
  361. if bounds:
  362. last_joined_members, last_room_id = bounds
  363. if forwards:
  364. where_clauses.append(
  365. """
  366. joined_members <= ? AND (
  367. joined_members < ? OR room_id < ?
  368. )
  369. """
  370. )
  371. else:
  372. where_clauses.append(
  373. """
  374. joined_members >= ? AND (
  375. joined_members > ? OR room_id > ?
  376. )
  377. """
  378. )
  379. query_args += [last_joined_members, last_joined_members, last_room_id]
  380. if ignore_non_federatable:
  381. where_clauses.append("is_federatable")
  382. if search_filter and search_filter.get(
  383. PublicRoomsFilterFields.GENERIC_SEARCH_TERM, None
  384. ):
  385. search_term = (
  386. "%" + search_filter[PublicRoomsFilterFields.GENERIC_SEARCH_TERM] + "%"
  387. )
  388. where_clauses.append(
  389. """
  390. (
  391. LOWER(name) LIKE ?
  392. OR LOWER(topic) LIKE ?
  393. OR LOWER(canonical_alias) LIKE ?
  394. )
  395. """
  396. )
  397. query_args += [
  398. search_term.lower(),
  399. search_term.lower(),
  400. search_term.lower(),
  401. ]
  402. room_type_clause, args = self._construct_room_type_where_clause(
  403. search_filter.get(PublicRoomsFilterFields.ROOM_TYPES, None)
  404. if search_filter
  405. else None
  406. )
  407. if room_type_clause:
  408. where_clauses.append(room_type_clause)
  409. query_args += args
  410. where_clause = ""
  411. if where_clauses:
  412. where_clause = " AND " + " AND ".join(where_clauses)
  413. dir = "DESC" if forwards else "ASC"
  414. sql = f"""
  415. SELECT
  416. room_id, name, topic, canonical_alias, joined_members,
  417. avatar, history_visibility, guest_access, join_rules, room_type
  418. FROM (
  419. {published_sql}
  420. ) published
  421. INNER JOIN room_stats_state USING (room_id)
  422. INNER JOIN room_stats_current USING (room_id)
  423. WHERE
  424. (
  425. join_rules = '{JoinRules.PUBLIC}'
  426. OR join_rules = '{JoinRules.KNOCK}'
  427. OR join_rules = '{JoinRules.KNOCK_RESTRICTED}'
  428. OR history_visibility = 'world_readable'
  429. )
  430. AND joined_members > 0
  431. {where_clause}
  432. ORDER BY
  433. joined_members {dir},
  434. room_id {dir}
  435. """
  436. if limit is not None:
  437. query_args.append(limit)
  438. sql += """
  439. LIMIT ?
  440. """
  441. def _get_largest_public_rooms_txn(
  442. txn: LoggingTransaction,
  443. ) -> List[Dict[str, Any]]:
  444. txn.execute(sql, query_args)
  445. results = self.db_pool.cursor_to_dict(txn)
  446. if not forwards:
  447. results.reverse()
  448. return results
  449. ret_val = await self.db_pool.runInteraction(
  450. "get_largest_public_rooms", _get_largest_public_rooms_txn
  451. )
  452. return ret_val
  453. @cached(max_entries=10000)
  454. async def is_room_blocked(self, room_id: str) -> Optional[bool]:
  455. return await self.db_pool.simple_select_one_onecol(
  456. table="blocked_rooms",
  457. keyvalues={"room_id": room_id},
  458. retcol="1",
  459. allow_none=True,
  460. desc="is_room_blocked",
  461. )
  462. async def room_is_blocked_by(self, room_id: str) -> Optional[str]:
  463. """
  464. Function to retrieve user who has blocked the room.
  465. user_id is non-nullable
  466. It returns None if the room is not blocked.
  467. """
  468. return await self.db_pool.simple_select_one_onecol(
  469. table="blocked_rooms",
  470. keyvalues={"room_id": room_id},
  471. retcol="user_id",
  472. allow_none=True,
  473. desc="room_is_blocked_by",
  474. )
  475. async def get_rooms_paginate(
  476. self,
  477. start: int,
  478. limit: int,
  479. order_by: str,
  480. reverse_order: bool,
  481. search_term: Optional[str],
  482. ) -> Tuple[List[Dict[str, Any]], int]:
  483. """Function to retrieve a paginated list of rooms as json.
  484. Args:
  485. start: offset in the list
  486. limit: maximum amount of rooms to retrieve
  487. order_by: the sort order of the returned list
  488. reverse_order: whether to reverse the room list
  489. search_term: a string to filter room names,
  490. canonical alias and room ids by.
  491. Room ID must match exactly. Canonical alias must match a substring of the local part.
  492. Returns:
  493. A list of room dicts and an integer representing the total number of
  494. rooms that exist given this query
  495. """
  496. # Filter room names by a string
  497. where_statement = ""
  498. search_pattern: List[object] = []
  499. if search_term:
  500. where_statement = """
  501. WHERE LOWER(state.name) LIKE ?
  502. OR LOWER(state.canonical_alias) LIKE ?
  503. OR state.room_id = ?
  504. """
  505. # Our postgres db driver converts ? -> %s in SQL strings as that's the
  506. # placeholder for postgres.
  507. # HOWEVER, if you put a % into your SQL then everything goes wibbly.
  508. # To get around this, we're going to surround search_term with %'s
  509. # before giving it to the database in python instead
  510. search_pattern = [
  511. "%" + search_term.lower() + "%",
  512. "#%" + search_term.lower() + "%:%",
  513. search_term,
  514. ]
  515. # Set ordering
  516. if RoomSortOrder(order_by) == RoomSortOrder.SIZE:
  517. # Deprecated in favour of RoomSortOrder.JOINED_MEMBERS
  518. order_by_column = "curr.joined_members"
  519. order_by_asc = False
  520. elif RoomSortOrder(order_by) == RoomSortOrder.ALPHABETICAL:
  521. # Deprecated in favour of RoomSortOrder.NAME
  522. order_by_column = "state.name"
  523. order_by_asc = True
  524. elif RoomSortOrder(order_by) == RoomSortOrder.NAME:
  525. order_by_column = "state.name"
  526. order_by_asc = True
  527. elif RoomSortOrder(order_by) == RoomSortOrder.CANONICAL_ALIAS:
  528. order_by_column = "state.canonical_alias"
  529. order_by_asc = True
  530. elif RoomSortOrder(order_by) == RoomSortOrder.JOINED_MEMBERS:
  531. order_by_column = "curr.joined_members"
  532. order_by_asc = False
  533. elif RoomSortOrder(order_by) == RoomSortOrder.JOINED_LOCAL_MEMBERS:
  534. order_by_column = "curr.local_users_in_room"
  535. order_by_asc = False
  536. elif RoomSortOrder(order_by) == RoomSortOrder.VERSION:
  537. order_by_column = "rooms.room_version"
  538. order_by_asc = False
  539. elif RoomSortOrder(order_by) == RoomSortOrder.CREATOR:
  540. order_by_column = "rooms.creator"
  541. order_by_asc = True
  542. elif RoomSortOrder(order_by) == RoomSortOrder.ENCRYPTION:
  543. order_by_column = "state.encryption"
  544. order_by_asc = True
  545. elif RoomSortOrder(order_by) == RoomSortOrder.FEDERATABLE:
  546. order_by_column = "state.is_federatable"
  547. order_by_asc = True
  548. elif RoomSortOrder(order_by) == RoomSortOrder.PUBLIC:
  549. order_by_column = "rooms.is_public"
  550. order_by_asc = True
  551. elif RoomSortOrder(order_by) == RoomSortOrder.JOIN_RULES:
  552. order_by_column = "state.join_rules"
  553. order_by_asc = True
  554. elif RoomSortOrder(order_by) == RoomSortOrder.GUEST_ACCESS:
  555. order_by_column = "state.guest_access"
  556. order_by_asc = True
  557. elif RoomSortOrder(order_by) == RoomSortOrder.HISTORY_VISIBILITY:
  558. order_by_column = "state.history_visibility"
  559. order_by_asc = True
  560. elif RoomSortOrder(order_by) == RoomSortOrder.STATE_EVENTS:
  561. order_by_column = "curr.current_state_events"
  562. order_by_asc = False
  563. else:
  564. raise StoreError(
  565. 500, "Incorrect value for order_by provided: %s" % order_by
  566. )
  567. # Whether to return the list in reverse order
  568. if reverse_order:
  569. # Flip the boolean
  570. order_by_asc = not order_by_asc
  571. # Create one query for getting the limited number of events that the user asked
  572. # for, and another query for getting the total number of events that could be
  573. # returned. Thus allowing us to see if there are more events to paginate through
  574. info_sql = """
  575. SELECT state.room_id, state.name, state.canonical_alias, curr.joined_members,
  576. curr.local_users_in_room, rooms.room_version, rooms.creator,
  577. state.encryption, state.is_federatable, rooms.is_public, state.join_rules,
  578. state.guest_access, state.history_visibility, curr.current_state_events,
  579. state.room_type
  580. FROM room_stats_state state
  581. INNER JOIN room_stats_current curr USING (room_id)
  582. INNER JOIN rooms USING (room_id)
  583. {where}
  584. ORDER BY {order_by} {direction}, state.room_id {direction}
  585. LIMIT ?
  586. OFFSET ?
  587. """.format(
  588. where=where_statement,
  589. order_by=order_by_column,
  590. direction="ASC" if order_by_asc else "DESC",
  591. )
  592. # Use a nested SELECT statement as SQL can't count(*) with an OFFSET
  593. count_sql = """
  594. SELECT count(*) FROM (
  595. SELECT room_id FROM room_stats_state state
  596. {where}
  597. ) AS get_room_ids
  598. """.format(
  599. where=where_statement,
  600. )
  601. def _get_rooms_paginate_txn(
  602. txn: LoggingTransaction,
  603. ) -> Tuple[List[Dict[str, Any]], int]:
  604. # Add the search term into the WHERE clause
  605. # and execute the data query
  606. txn.execute(info_sql, search_pattern + [limit, start])
  607. # Refactor room query data into a structured dictionary
  608. rooms = []
  609. for room in txn:
  610. rooms.append(
  611. {
  612. "room_id": room[0],
  613. "name": room[1],
  614. "canonical_alias": room[2],
  615. "joined_members": room[3],
  616. "joined_local_members": room[4],
  617. "version": room[5],
  618. "creator": room[6],
  619. "encryption": room[7],
  620. # room_stats_state.federatable is an integer on sqlite.
  621. "federatable": bool(room[8]),
  622. # rooms.is_public is an integer on sqlite.
  623. "public": bool(room[9]),
  624. "join_rules": room[10],
  625. "guest_access": room[11],
  626. "history_visibility": room[12],
  627. "state_events": room[13],
  628. "room_type": room[14],
  629. }
  630. )
  631. # Execute the count query
  632. # Add the search term into the WHERE clause if present
  633. txn.execute(count_sql, search_pattern)
  634. room_count = cast(Tuple[int], txn.fetchone())
  635. return rooms, room_count[0]
  636. return await self.db_pool.runInteraction(
  637. "get_rooms_paginate",
  638. _get_rooms_paginate_txn,
  639. )
  640. @cached(max_entries=10000)
  641. async def get_ratelimit_for_user(self, user_id: str) -> Optional[RatelimitOverride]:
  642. """Check if there are any overrides for ratelimiting for the given user
  643. Args:
  644. user_id: user ID of the user
  645. Returns:
  646. RatelimitOverride if there is an override, else None. If the contents
  647. of RatelimitOverride are None or 0 then ratelimitng has been
  648. disabled for that user entirely.
  649. """
  650. row = await self.db_pool.simple_select_one(
  651. table="ratelimit_override",
  652. keyvalues={"user_id": user_id},
  653. retcols=("messages_per_second", "burst_count"),
  654. allow_none=True,
  655. desc="get_ratelimit_for_user",
  656. )
  657. if row:
  658. return RatelimitOverride(
  659. messages_per_second=row["messages_per_second"],
  660. burst_count=row["burst_count"],
  661. )
  662. else:
  663. return None
  664. async def set_ratelimit_for_user(
  665. self, user_id: str, messages_per_second: int, burst_count: int
  666. ) -> None:
  667. """Sets whether a user is set an overridden ratelimit.
  668. Args:
  669. user_id: user ID of the user
  670. messages_per_second: The number of actions that can be performed in a second.
  671. burst_count: How many actions that can be performed before being limited.
  672. """
  673. def set_ratelimit_txn(txn: LoggingTransaction) -> None:
  674. self.db_pool.simple_upsert_txn(
  675. txn,
  676. table="ratelimit_override",
  677. keyvalues={"user_id": user_id},
  678. values={
  679. "messages_per_second": messages_per_second,
  680. "burst_count": burst_count,
  681. },
  682. )
  683. self._invalidate_cache_and_stream(
  684. txn, self.get_ratelimit_for_user, (user_id,)
  685. )
  686. await self.db_pool.runInteraction("set_ratelimit", set_ratelimit_txn)
  687. async def delete_ratelimit_for_user(self, user_id: str) -> None:
  688. """Delete an overridden ratelimit for a user.
  689. Args:
  690. user_id: user ID of the user
  691. """
  692. def delete_ratelimit_txn(txn: LoggingTransaction) -> None:
  693. row = self.db_pool.simple_select_one_txn(
  694. txn,
  695. table="ratelimit_override",
  696. keyvalues={"user_id": user_id},
  697. retcols=["user_id"],
  698. allow_none=True,
  699. )
  700. if not row:
  701. return
  702. # They are there, delete them.
  703. self.db_pool.simple_delete_one_txn(
  704. txn, "ratelimit_override", keyvalues={"user_id": user_id}
  705. )
  706. self._invalidate_cache_and_stream(
  707. txn, self.get_ratelimit_for_user, (user_id,)
  708. )
  709. await self.db_pool.runInteraction("delete_ratelimit", delete_ratelimit_txn)
  710. @cached()
  711. async def get_retention_policy_for_room(self, room_id: str) -> RetentionPolicy:
  712. """Get the retention policy for a given room.
  713. If no retention policy has been found for this room, returns a policy defined
  714. by the configured default policy (which has None as both the 'min_lifetime' and
  715. the 'max_lifetime' if no default policy has been defined in the server's
  716. configuration).
  717. If support for retention policies is disabled, a policy with a 'min_lifetime' and
  718. 'max_lifetime' of None is returned.
  719. Args:
  720. room_id: The ID of the room to get the retention policy of.
  721. Returns:
  722. A dict containing "min_lifetime" and "max_lifetime" for this room.
  723. """
  724. # If the room retention feature is disabled, return a policy with no minimum nor
  725. # maximum. This prevents incorrectly filtering out events when sending to
  726. # the client.
  727. if not self.config.retention.retention_enabled:
  728. return RetentionPolicy()
  729. def get_retention_policy_for_room_txn(
  730. txn: LoggingTransaction,
  731. ) -> List[Dict[str, Optional[int]]]:
  732. txn.execute(
  733. """
  734. SELECT min_lifetime, max_lifetime FROM room_retention
  735. INNER JOIN current_state_events USING (event_id, room_id)
  736. WHERE room_id = ?;
  737. """,
  738. (room_id,),
  739. )
  740. return self.db_pool.cursor_to_dict(txn)
  741. ret = await self.db_pool.runInteraction(
  742. "get_retention_policy_for_room",
  743. get_retention_policy_for_room_txn,
  744. )
  745. # If we don't know this room ID, ret will be None, in this case return the default
  746. # policy.
  747. if not ret:
  748. return RetentionPolicy(
  749. min_lifetime=self.config.retention.retention_default_min_lifetime,
  750. max_lifetime=self.config.retention.retention_default_max_lifetime,
  751. )
  752. min_lifetime = ret[0]["min_lifetime"]
  753. max_lifetime = ret[0]["max_lifetime"]
  754. # If one of the room's policy's attributes isn't defined, use the matching
  755. # attribute from the default policy.
  756. # The default values will be None if no default policy has been defined, or if one
  757. # of the attributes is missing from the default policy.
  758. if min_lifetime is None:
  759. min_lifetime = self.config.retention.retention_default_min_lifetime
  760. if max_lifetime is None:
  761. max_lifetime = self.config.retention.retention_default_max_lifetime
  762. return RetentionPolicy(
  763. min_lifetime=min_lifetime,
  764. max_lifetime=max_lifetime,
  765. )
  766. async def get_media_mxcs_in_room(self, room_id: str) -> Tuple[List[str], List[str]]:
  767. """Retrieves all the local and remote media MXC URIs in a given room
  768. Args:
  769. room_id
  770. Returns:
  771. The local and remote media as a lists of the media IDs.
  772. """
  773. def _get_media_mxcs_in_room_txn(
  774. txn: LoggingTransaction,
  775. ) -> Tuple[List[str], List[str]]:
  776. local_mxcs, remote_mxcs = self._get_media_mxcs_in_room_txn(txn, room_id)
  777. local_media_mxcs = []
  778. remote_media_mxcs = []
  779. # Convert the IDs to MXC URIs
  780. for media_id in local_mxcs:
  781. local_media_mxcs.append("mxc://%s/%s" % (self.hs.hostname, media_id))
  782. for hostname, media_id in remote_mxcs:
  783. remote_media_mxcs.append("mxc://%s/%s" % (hostname, media_id))
  784. return local_media_mxcs, remote_media_mxcs
  785. return await self.db_pool.runInteraction(
  786. "get_media_ids_in_room", _get_media_mxcs_in_room_txn
  787. )
  788. async def quarantine_media_ids_in_room(
  789. self, room_id: str, quarantined_by: str
  790. ) -> int:
  791. """For a room loops through all events with media and quarantines
  792. the associated media
  793. """
  794. logger.info("Quarantining media in room: %s", room_id)
  795. def _quarantine_media_in_room_txn(txn: LoggingTransaction) -> int:
  796. local_mxcs, remote_mxcs = self._get_media_mxcs_in_room_txn(txn, room_id)
  797. return self._quarantine_media_txn(
  798. txn, local_mxcs, remote_mxcs, quarantined_by
  799. )
  800. return await self.db_pool.runInteraction(
  801. "quarantine_media_in_room", _quarantine_media_in_room_txn
  802. )
  803. def _get_media_mxcs_in_room_txn(
  804. self, txn: LoggingTransaction, room_id: str
  805. ) -> Tuple[List[str], List[Tuple[str, str]]]:
  806. """Retrieves all the local and remote media MXC URIs in a given room
  807. Returns:
  808. The local and remote media as a lists of tuples where the key is
  809. the hostname and the value is the media ID.
  810. """
  811. sql = """
  812. SELECT stream_ordering, json FROM events
  813. JOIN event_json USING (room_id, event_id)
  814. WHERE room_id = ?
  815. %(where_clause)s
  816. AND contains_url = ? AND outlier = ?
  817. ORDER BY stream_ordering DESC
  818. LIMIT ?
  819. """
  820. txn.execute(sql % {"where_clause": ""}, (room_id, True, False, 100))
  821. local_media_mxcs = []
  822. remote_media_mxcs = []
  823. while True:
  824. next_token = None
  825. for stream_ordering, content_json in txn:
  826. next_token = stream_ordering
  827. event_json = db_to_json(content_json)
  828. content = event_json["content"]
  829. content_url = content.get("url")
  830. info = content.get("info")
  831. if isinstance(info, dict):
  832. thumbnail_url = info.get("thumbnail_url")
  833. else:
  834. thumbnail_url = None
  835. for url in (content_url, thumbnail_url):
  836. if not url:
  837. continue
  838. matches = MXC_REGEX.match(url)
  839. if matches:
  840. hostname = matches.group(1)
  841. media_id = matches.group(2)
  842. if hostname == self.hs.hostname:
  843. local_media_mxcs.append(media_id)
  844. else:
  845. remote_media_mxcs.append((hostname, media_id))
  846. if next_token is None:
  847. # We've gone through the whole room, so we're finished.
  848. break
  849. txn.execute(
  850. sql % {"where_clause": "AND stream_ordering < ?"},
  851. (room_id, next_token, True, False, 100),
  852. )
  853. return local_media_mxcs, remote_media_mxcs
  854. async def quarantine_media_by_id(
  855. self,
  856. server_name: str,
  857. media_id: str,
  858. quarantined_by: Optional[str],
  859. ) -> int:
  860. """quarantines or unquarantines a single local or remote media id
  861. Args:
  862. server_name: The name of the server that holds this media
  863. media_id: The ID of the media to be quarantined
  864. quarantined_by: The user ID that initiated the quarantine request
  865. If it is `None` media will be removed from quarantine
  866. """
  867. logger.info("Quarantining media: %s/%s", server_name, media_id)
  868. is_local = server_name == self.config.server.server_name
  869. def _quarantine_media_by_id_txn(txn: LoggingTransaction) -> int:
  870. local_mxcs = [media_id] if is_local else []
  871. remote_mxcs = [(server_name, media_id)] if not is_local else []
  872. return self._quarantine_media_txn(
  873. txn, local_mxcs, remote_mxcs, quarantined_by
  874. )
  875. return await self.db_pool.runInteraction(
  876. "quarantine_media_by_user", _quarantine_media_by_id_txn
  877. )
  878. async def quarantine_media_ids_by_user(
  879. self, user_id: str, quarantined_by: str
  880. ) -> int:
  881. """quarantines all local media associated with a single user
  882. Args:
  883. user_id: The ID of the user to quarantine media of
  884. quarantined_by: The ID of the user who made the quarantine request
  885. """
  886. def _quarantine_media_by_user_txn(txn: LoggingTransaction) -> int:
  887. local_media_ids = self._get_media_ids_by_user_txn(txn, user_id)
  888. return self._quarantine_media_txn(txn, local_media_ids, [], quarantined_by)
  889. return await self.db_pool.runInteraction(
  890. "quarantine_media_by_user", _quarantine_media_by_user_txn
  891. )
  892. def _get_media_ids_by_user_txn(
  893. self, txn: LoggingTransaction, user_id: str, filter_quarantined: bool = True
  894. ) -> List[str]:
  895. """Retrieves local media IDs by a given user
  896. Args:
  897. txn (cursor)
  898. user_id: The ID of the user to retrieve media IDs of
  899. Returns:
  900. The local and remote media as a lists of tuples where the key is
  901. the hostname and the value is the media ID.
  902. """
  903. # Local media
  904. sql = """
  905. SELECT media_id
  906. FROM local_media_repository
  907. WHERE user_id = ?
  908. """
  909. if filter_quarantined:
  910. sql += "AND quarantined_by IS NULL"
  911. txn.execute(sql, (user_id,))
  912. local_media_ids = [row[0] for row in txn]
  913. # TODO: Figure out all remote media a user has referenced in a message
  914. return local_media_ids
  915. def _quarantine_media_txn(
  916. self,
  917. txn: LoggingTransaction,
  918. local_mxcs: List[str],
  919. remote_mxcs: List[Tuple[str, str]],
  920. quarantined_by: Optional[str],
  921. ) -> int:
  922. """Quarantine and unquarantine local and remote media items
  923. Args:
  924. txn (cursor)
  925. local_mxcs: A list of local mxc URLs
  926. remote_mxcs: A list of (remote server, media id) tuples representing
  927. remote mxc URLs
  928. quarantined_by: The ID of the user who initiated the quarantine request
  929. If it is `None` media will be removed from quarantine
  930. Returns:
  931. The total number of media items quarantined
  932. """
  933. # Update all the tables to set the quarantined_by flag
  934. sql = """
  935. UPDATE local_media_repository
  936. SET quarantined_by = ?
  937. WHERE media_id = ?
  938. """
  939. # set quarantine
  940. if quarantined_by is not None:
  941. sql += "AND safe_from_quarantine = ?"
  942. txn.executemany(
  943. sql, [(quarantined_by, media_id, False) for media_id in local_mxcs]
  944. )
  945. # remove from quarantine
  946. else:
  947. txn.executemany(
  948. sql, [(quarantined_by, media_id) for media_id in local_mxcs]
  949. )
  950. # Note that a rowcount of -1 can be used to indicate no rows were affected.
  951. total_media_quarantined = txn.rowcount if txn.rowcount > 0 else 0
  952. txn.executemany(
  953. """
  954. UPDATE remote_media_cache
  955. SET quarantined_by = ?
  956. WHERE media_origin = ? AND media_id = ?
  957. """,
  958. ((quarantined_by, origin, media_id) for origin, media_id in remote_mxcs),
  959. )
  960. total_media_quarantined += txn.rowcount if txn.rowcount > 0 else 0
  961. return total_media_quarantined
  962. async def get_rooms_for_retention_period_in_range(
  963. self, min_ms: Optional[int], max_ms: Optional[int], include_null: bool = False
  964. ) -> Dict[str, RetentionPolicy]:
  965. """Retrieves all of the rooms within the given retention range.
  966. Optionally includes the rooms which don't have a retention policy.
  967. Args:
  968. min_ms: Duration in milliseconds that define the lower limit of
  969. the range to handle (exclusive). If None, doesn't set a lower limit.
  970. max_ms: Duration in milliseconds that define the upper limit of
  971. the range to handle (inclusive). If None, doesn't set an upper limit.
  972. include_null: Whether to include rooms which retention policy is NULL
  973. in the returned set.
  974. Returns:
  975. The rooms within this range, along with their retention
  976. policy. The key is "room_id", and maps to a dict describing the retention
  977. policy associated with this room ID. The keys for this nested dict are
  978. "min_lifetime" (int|None), and "max_lifetime" (int|None).
  979. """
  980. def get_rooms_for_retention_period_in_range_txn(
  981. txn: LoggingTransaction,
  982. ) -> Dict[str, RetentionPolicy]:
  983. range_conditions = []
  984. args = []
  985. if min_ms is not None:
  986. range_conditions.append("max_lifetime > ?")
  987. args.append(min_ms)
  988. if max_ms is not None:
  989. range_conditions.append("max_lifetime <= ?")
  990. args.append(max_ms)
  991. # Do a first query which will retrieve the rooms that have a retention policy
  992. # in their current state.
  993. sql = """
  994. SELECT room_id, min_lifetime, max_lifetime FROM room_retention
  995. INNER JOIN current_state_events USING (event_id, room_id)
  996. """
  997. if len(range_conditions):
  998. sql += " WHERE (" + " AND ".join(range_conditions) + ")"
  999. if include_null:
  1000. sql += " OR max_lifetime IS NULL"
  1001. txn.execute(sql, args)
  1002. rows = self.db_pool.cursor_to_dict(txn)
  1003. rooms_dict = {}
  1004. for row in rows:
  1005. rooms_dict[row["room_id"]] = RetentionPolicy(
  1006. min_lifetime=row["min_lifetime"],
  1007. max_lifetime=row["max_lifetime"],
  1008. )
  1009. if include_null:
  1010. # If required, do a second query that retrieves all of the rooms we know
  1011. # of so we can handle rooms with no retention policy.
  1012. sql = "SELECT DISTINCT room_id FROM current_state_events"
  1013. txn.execute(sql)
  1014. rows = self.db_pool.cursor_to_dict(txn)
  1015. # If a room isn't already in the dict (i.e. it doesn't have a retention
  1016. # policy in its state), add it with a null policy.
  1017. for row in rows:
  1018. if row["room_id"] not in rooms_dict:
  1019. rooms_dict[row["room_id"]] = RetentionPolicy()
  1020. return rooms_dict
  1021. return await self.db_pool.runInteraction(
  1022. "get_rooms_for_retention_period_in_range",
  1023. get_rooms_for_retention_period_in_range_txn,
  1024. )
  1025. @cached(iterable=True)
  1026. async def get_partial_state_servers_at_join(self, room_id: str) -> Sequence[str]:
  1027. """Gets the list of servers in a partial state room at the time we joined it.
  1028. Returns:
  1029. The `servers_in_room` list from the `/send_join` response for partial state
  1030. rooms. May not be accurate or complete, as it comes from a remote
  1031. homeserver.
  1032. An empty list for full state rooms.
  1033. """
  1034. return await self.db_pool.simple_select_onecol(
  1035. "partial_state_rooms_servers",
  1036. keyvalues={"room_id": room_id},
  1037. retcol="server_name",
  1038. desc="get_partial_state_servers_at_join",
  1039. )
  1040. async def get_partial_state_room_resync_info(
  1041. self,
  1042. ) -> Mapping[str, PartialStateResyncInfo]:
  1043. """Get all rooms containing events with partial state, and the information
  1044. needed to restart a "resync" of those rooms.
  1045. Returns:
  1046. A dictionary of rooms with partial state, with room IDs as keys and
  1047. lists of servers in rooms as values.
  1048. """
  1049. room_servers: Dict[str, PartialStateResyncInfo] = {}
  1050. rows = await self.db_pool.simple_select_list(
  1051. table="partial_state_rooms",
  1052. keyvalues={},
  1053. retcols=("room_id", "joined_via"),
  1054. desc="get_server_which_served_partial_join",
  1055. )
  1056. for row in rows:
  1057. room_id = row["room_id"]
  1058. joined_via = row["joined_via"]
  1059. room_servers[room_id] = PartialStateResyncInfo(joined_via=joined_via)
  1060. rows = await self.db_pool.simple_select_list(
  1061. "partial_state_rooms_servers",
  1062. keyvalues=None,
  1063. retcols=("room_id", "server_name"),
  1064. desc="get_partial_state_rooms",
  1065. )
  1066. for row in rows:
  1067. room_id = row["room_id"]
  1068. server_name = row["server_name"]
  1069. entry = room_servers.get(room_id)
  1070. if entry is None:
  1071. # There is a foreign key constraint which enforces that every room_id in
  1072. # partial_state_rooms_servers appears in partial_state_rooms. So we
  1073. # expect `entry` to be non-null. (This reasoning fails if we've
  1074. # partial-joined between the two SELECTs, but this is unlikely to happen
  1075. # in practice.)
  1076. continue
  1077. entry.servers_in_room.append(server_name)
  1078. return room_servers
  1079. @cached()
  1080. async def is_partial_state_room(self, room_id: str) -> bool:
  1081. """Checks if this room has partial state.
  1082. Returns true if this is a "partial-state" room, which means that the state
  1083. at events in the room, and `current_state_events`, may not yet be
  1084. complete.
  1085. """
  1086. entry = await self.db_pool.simple_select_one_onecol(
  1087. table="partial_state_rooms",
  1088. keyvalues={"room_id": room_id},
  1089. retcol="room_id",
  1090. allow_none=True,
  1091. desc="is_partial_state_room",
  1092. )
  1093. return entry is not None
  1094. async def get_join_event_id_and_device_lists_stream_id_for_partial_state(
  1095. self, room_id: str
  1096. ) -> Tuple[str, int]:
  1097. """Get the event ID of the initial join that started the partial
  1098. join, and the device list stream ID at the point we started the partial
  1099. join.
  1100. """
  1101. result = await self.db_pool.simple_select_one(
  1102. table="partial_state_rooms",
  1103. keyvalues={"room_id": room_id},
  1104. retcols=("join_event_id", "device_lists_stream_id"),
  1105. desc="get_join_event_id_for_partial_state",
  1106. )
  1107. return result["join_event_id"], result["device_lists_stream_id"]
  1108. def get_un_partial_stated_rooms_token(self, instance_name: str) -> int:
  1109. return self._un_partial_stated_rooms_stream_id_gen.get_current_token_for_writer(
  1110. instance_name
  1111. )
  1112. async def get_un_partial_stated_rooms_from_stream(
  1113. self, instance_name: str, last_id: int, current_id: int, limit: int
  1114. ) -> Tuple[List[Tuple[int, Tuple[str]]], int, bool]:
  1115. """Get updates for caches replication stream.
  1116. Args:
  1117. instance_name: The writer we want to fetch updates from. Unused
  1118. here since there is only ever one writer.
  1119. last_id: The token to fetch updates from. Exclusive.
  1120. current_id: The token to fetch updates up to. Inclusive.
  1121. limit: The requested limit for the number of rows to return. The
  1122. function may return more or fewer rows.
  1123. Returns:
  1124. A tuple consisting of: the updates, a token to use to fetch
  1125. subsequent updates, and whether we returned fewer rows than exists
  1126. between the requested tokens due to the limit.
  1127. The token returned can be used in a subsequent call to this
  1128. function to get further updatees.
  1129. The updates are a list of 2-tuples of stream ID and the row data
  1130. """
  1131. if last_id == current_id:
  1132. return [], current_id, False
  1133. def get_un_partial_stated_rooms_from_stream_txn(
  1134. txn: LoggingTransaction,
  1135. ) -> Tuple[List[Tuple[int, Tuple[str]]], int, bool]:
  1136. sql = """
  1137. SELECT stream_id, room_id
  1138. FROM un_partial_stated_room_stream
  1139. WHERE ? < stream_id AND stream_id <= ? AND instance_name = ?
  1140. ORDER BY stream_id ASC
  1141. LIMIT ?
  1142. """
  1143. txn.execute(sql, (last_id, current_id, instance_name, limit))
  1144. updates = [(row[0], (row[1],)) for row in txn]
  1145. limited = False
  1146. upto_token = current_id
  1147. if len(updates) >= limit:
  1148. upto_token = updates[-1][0]
  1149. limited = True
  1150. return updates, upto_token, limited
  1151. return await self.db_pool.runInteraction(
  1152. "get_un_partial_stated_rooms_from_stream",
  1153. get_un_partial_stated_rooms_from_stream_txn,
  1154. )
  1155. class _BackgroundUpdates:
  1156. REMOVE_TOMESTONED_ROOMS_BG_UPDATE = "remove_tombstoned_rooms_from_directory"
  1157. ADD_ROOMS_ROOM_VERSION_COLUMN = "add_rooms_room_version_column"
  1158. POPULATE_ROOM_DEPTH_MIN_DEPTH2 = "populate_room_depth_min_depth2"
  1159. REPLACE_ROOM_DEPTH_MIN_DEPTH = "replace_room_depth_min_depth"
  1160. POPULATE_ROOMS_CREATOR_COLUMN = "populate_rooms_creator_column"
  1161. ADD_ROOM_TYPE_COLUMN = "add_room_type_column"
  1162. _REPLACE_ROOM_DEPTH_SQL_COMMANDS = (
  1163. "DROP TRIGGER populate_min_depth2_trigger ON room_depth",
  1164. "DROP FUNCTION populate_min_depth2()",
  1165. "ALTER TABLE room_depth DROP COLUMN min_depth",
  1166. "ALTER TABLE room_depth RENAME COLUMN min_depth2 TO min_depth",
  1167. )
  1168. class RoomBackgroundUpdateStore(SQLBaseStore):
  1169. def __init__(
  1170. self,
  1171. database: DatabasePool,
  1172. db_conn: LoggingDatabaseConnection,
  1173. hs: "HomeServer",
  1174. ):
  1175. super().__init__(database, db_conn, hs)
  1176. self.db_pool.updates.register_background_update_handler(
  1177. "insert_room_retention",
  1178. self._background_insert_retention,
  1179. )
  1180. self.db_pool.updates.register_background_update_handler(
  1181. _BackgroundUpdates.REMOVE_TOMESTONED_ROOMS_BG_UPDATE,
  1182. self._remove_tombstoned_rooms_from_directory,
  1183. )
  1184. self.db_pool.updates.register_background_update_handler(
  1185. _BackgroundUpdates.ADD_ROOMS_ROOM_VERSION_COLUMN,
  1186. self._background_add_rooms_room_version_column,
  1187. )
  1188. self.db_pool.updates.register_background_update_handler(
  1189. _BackgroundUpdates.ADD_ROOM_TYPE_COLUMN,
  1190. self._background_add_room_type_column,
  1191. )
  1192. # BG updates to change the type of room_depth.min_depth
  1193. self.db_pool.updates.register_background_update_handler(
  1194. _BackgroundUpdates.POPULATE_ROOM_DEPTH_MIN_DEPTH2,
  1195. self._background_populate_room_depth_min_depth2,
  1196. )
  1197. self.db_pool.updates.register_background_update_handler(
  1198. _BackgroundUpdates.REPLACE_ROOM_DEPTH_MIN_DEPTH,
  1199. self._background_replace_room_depth_min_depth,
  1200. )
  1201. self.db_pool.updates.register_background_update_handler(
  1202. _BackgroundUpdates.POPULATE_ROOMS_CREATOR_COLUMN,
  1203. self._background_populate_rooms_creator_column,
  1204. )
  1205. async def _background_insert_retention(
  1206. self, progress: JsonDict, batch_size: int
  1207. ) -> int:
  1208. """Retrieves a list of all rooms within a range and inserts an entry for each of
  1209. them into the room_retention table.
  1210. NULLs the property's columns if missing from the retention event in the room's
  1211. state (or NULLs all of them if there's no retention event in the room's state),
  1212. so that we fall back to the server's retention policy.
  1213. """
  1214. last_room = progress.get("room_id", "")
  1215. def _background_insert_retention_txn(txn: LoggingTransaction) -> bool:
  1216. txn.execute(
  1217. """
  1218. SELECT state.room_id, state.event_id, events.json
  1219. FROM current_state_events as state
  1220. LEFT JOIN event_json AS events ON (state.event_id = events.event_id)
  1221. WHERE state.room_id > ? AND state.type = '%s'
  1222. ORDER BY state.room_id ASC
  1223. LIMIT ?;
  1224. """
  1225. % EventTypes.Retention,
  1226. (last_room, batch_size),
  1227. )
  1228. rows = self.db_pool.cursor_to_dict(txn)
  1229. if not rows:
  1230. return True
  1231. for row in rows:
  1232. if not row["json"]:
  1233. retention_policy = {}
  1234. else:
  1235. ev = db_to_json(row["json"])
  1236. retention_policy = ev["content"]
  1237. self.db_pool.simple_insert_txn(
  1238. txn=txn,
  1239. table="room_retention",
  1240. values={
  1241. "room_id": row["room_id"],
  1242. "event_id": row["event_id"],
  1243. "min_lifetime": retention_policy.get("min_lifetime"),
  1244. "max_lifetime": retention_policy.get("max_lifetime"),
  1245. },
  1246. )
  1247. logger.info("Inserted %d rows into room_retention", len(rows))
  1248. self.db_pool.updates._background_update_progress_txn(
  1249. txn, "insert_room_retention", {"room_id": rows[-1]["room_id"]}
  1250. )
  1251. if batch_size > len(rows):
  1252. return True
  1253. else:
  1254. return False
  1255. end = await self.db_pool.runInteraction(
  1256. "insert_room_retention",
  1257. _background_insert_retention_txn,
  1258. )
  1259. if end:
  1260. await self.db_pool.updates._end_background_update("insert_room_retention")
  1261. return batch_size
  1262. async def _background_add_rooms_room_version_column(
  1263. self, progress: JsonDict, batch_size: int
  1264. ) -> int:
  1265. """Background update to go and add room version information to `rooms`
  1266. table from `current_state_events` table.
  1267. """
  1268. last_room_id = progress.get("room_id", "")
  1269. def _background_add_rooms_room_version_column_txn(
  1270. txn: LoggingTransaction,
  1271. ) -> bool:
  1272. sql = """
  1273. SELECT room_id, json FROM current_state_events
  1274. INNER JOIN event_json USING (room_id, event_id)
  1275. WHERE room_id > ? AND type = 'm.room.create' AND state_key = ''
  1276. ORDER BY room_id
  1277. LIMIT ?
  1278. """
  1279. txn.execute(sql, (last_room_id, batch_size))
  1280. updates = []
  1281. for room_id, event_json in txn:
  1282. event_dict = db_to_json(event_json)
  1283. room_version_id = event_dict.get("content", {}).get(
  1284. "room_version", RoomVersions.V1.identifier
  1285. )
  1286. creator = event_dict.get("content").get("creator")
  1287. updates.append((room_id, creator, room_version_id))
  1288. if not updates:
  1289. return True
  1290. new_last_room_id = ""
  1291. for room_id, creator, room_version_id in updates:
  1292. # We upsert here just in case we don't already have a row,
  1293. # mainly for paranoia as much badness would happen if we don't
  1294. # insert the row and then try and get the room version for the
  1295. # room.
  1296. self.db_pool.simple_upsert_txn(
  1297. txn,
  1298. table="rooms",
  1299. keyvalues={"room_id": room_id},
  1300. values={"room_version": room_version_id},
  1301. insertion_values={"is_public": False, "creator": creator},
  1302. )
  1303. new_last_room_id = room_id
  1304. self.db_pool.updates._background_update_progress_txn(
  1305. txn,
  1306. _BackgroundUpdates.ADD_ROOMS_ROOM_VERSION_COLUMN,
  1307. {"room_id": new_last_room_id},
  1308. )
  1309. return False
  1310. end = await self.db_pool.runInteraction(
  1311. "_background_add_rooms_room_version_column",
  1312. _background_add_rooms_room_version_column_txn,
  1313. )
  1314. if end:
  1315. await self.db_pool.updates._end_background_update(
  1316. _BackgroundUpdates.ADD_ROOMS_ROOM_VERSION_COLUMN
  1317. )
  1318. return batch_size
  1319. async def _remove_tombstoned_rooms_from_directory(
  1320. self, progress: JsonDict, batch_size: int
  1321. ) -> int:
  1322. """Removes any rooms with tombstone events from the room directory
  1323. Nowadays this is handled by the room upgrade handler, but we may have some
  1324. that got left behind
  1325. """
  1326. last_room = progress.get("room_id", "")
  1327. def _get_rooms(txn: LoggingTransaction) -> List[str]:
  1328. txn.execute(
  1329. """
  1330. SELECT room_id
  1331. FROM rooms r
  1332. INNER JOIN current_state_events cse USING (room_id)
  1333. WHERE room_id > ? AND r.is_public
  1334. AND cse.type = '%s' AND cse.state_key = ''
  1335. ORDER BY room_id ASC
  1336. LIMIT ?;
  1337. """
  1338. % EventTypes.Tombstone,
  1339. (last_room, batch_size),
  1340. )
  1341. return [row[0] for row in txn]
  1342. rooms = await self.db_pool.runInteraction(
  1343. "get_tombstoned_directory_rooms", _get_rooms
  1344. )
  1345. if not rooms:
  1346. await self.db_pool.updates._end_background_update(
  1347. _BackgroundUpdates.REMOVE_TOMESTONED_ROOMS_BG_UPDATE
  1348. )
  1349. return 0
  1350. for room_id in rooms:
  1351. logger.info("Removing tombstoned room %s from the directory", room_id)
  1352. await self.set_room_is_public(room_id, False)
  1353. await self.db_pool.updates._background_update_progress(
  1354. _BackgroundUpdates.REMOVE_TOMESTONED_ROOMS_BG_UPDATE, {"room_id": rooms[-1]}
  1355. )
  1356. return len(rooms)
  1357. @abstractmethod
  1358. def set_room_is_public(self, room_id: str, is_public: bool) -> Awaitable[None]:
  1359. # this will need to be implemented if a background update is performed with
  1360. # existing (tombstoned, public) rooms in the database.
  1361. #
  1362. # It's overridden by RoomStore for the synapse master.
  1363. raise NotImplementedError()
  1364. async def has_auth_chain_index(self, room_id: str) -> bool:
  1365. """Check if the room has (or can have) a chain cover index.
  1366. Defaults to True if we don't have an entry in `rooms` table nor any
  1367. events for the room.
  1368. """
  1369. has_auth_chain_index = await self.db_pool.simple_select_one_onecol(
  1370. table="rooms",
  1371. keyvalues={"room_id": room_id},
  1372. retcol="has_auth_chain_index",
  1373. desc="has_auth_chain_index",
  1374. allow_none=True,
  1375. )
  1376. if has_auth_chain_index:
  1377. return True
  1378. # It's possible that we already have events for the room in our DB
  1379. # without a corresponding room entry. If we do then we don't want to
  1380. # mark the room as having an auth chain cover index.
  1381. max_ordering = await self.db_pool.simple_select_one_onecol(
  1382. table="events",
  1383. keyvalues={"room_id": room_id},
  1384. retcol="MAX(stream_ordering)",
  1385. allow_none=True,
  1386. desc="has_auth_chain_index_fallback",
  1387. )
  1388. return max_ordering is None
  1389. async def _background_populate_room_depth_min_depth2(
  1390. self, progress: JsonDict, batch_size: int
  1391. ) -> int:
  1392. """Populate room_depth.min_depth2
  1393. This is to deal with the fact that min_depth was initially created as a
  1394. 32-bit integer field.
  1395. """
  1396. def process(txn: LoggingTransaction) -> int:
  1397. last_room = progress.get("last_room", "")
  1398. txn.execute(
  1399. """
  1400. UPDATE room_depth SET min_depth2=min_depth
  1401. WHERE room_id IN (
  1402. SELECT room_id FROM room_depth WHERE room_id > ?
  1403. ORDER BY room_id LIMIT ?
  1404. )
  1405. RETURNING room_id;
  1406. """,
  1407. (last_room, batch_size),
  1408. )
  1409. row_count = txn.rowcount
  1410. if row_count == 0:
  1411. return 0
  1412. last_room = max(row[0] for row in txn)
  1413. logger.info("populated room_depth up to %s", last_room)
  1414. self.db_pool.updates._background_update_progress_txn(
  1415. txn,
  1416. _BackgroundUpdates.POPULATE_ROOM_DEPTH_MIN_DEPTH2,
  1417. {"last_room": last_room},
  1418. )
  1419. return row_count
  1420. result = await self.db_pool.runInteraction(
  1421. "_background_populate_min_depth2", process
  1422. )
  1423. if result != 0:
  1424. return result
  1425. await self.db_pool.updates._end_background_update(
  1426. _BackgroundUpdates.POPULATE_ROOM_DEPTH_MIN_DEPTH2
  1427. )
  1428. return 0
  1429. async def _background_replace_room_depth_min_depth(
  1430. self, progress: JsonDict, batch_size: int
  1431. ) -> int:
  1432. """Drop the old 'min_depth' column and rename 'min_depth2' into its place."""
  1433. def process(txn: Cursor) -> None:
  1434. for sql in _REPLACE_ROOM_DEPTH_SQL_COMMANDS:
  1435. logger.info("completing room_depth migration: %s", sql)
  1436. txn.execute(sql)
  1437. await self.db_pool.runInteraction("_background_replace_room_depth", process)
  1438. await self.db_pool.updates._end_background_update(
  1439. _BackgroundUpdates.REPLACE_ROOM_DEPTH_MIN_DEPTH,
  1440. )
  1441. return 0
  1442. async def _background_populate_rooms_creator_column(
  1443. self, progress: JsonDict, batch_size: int
  1444. ) -> int:
  1445. """Background update to go and add creator information to `rooms`
  1446. table from `current_state_events` table.
  1447. """
  1448. last_room_id = progress.get("room_id", "")
  1449. def _background_populate_rooms_creator_column_txn(
  1450. txn: LoggingTransaction,
  1451. ) -> bool:
  1452. sql = """
  1453. SELECT room_id, json FROM event_json
  1454. INNER JOIN rooms AS room USING (room_id)
  1455. INNER JOIN current_state_events AS state_event USING (room_id, event_id)
  1456. WHERE room_id > ? AND (room.creator IS NULL OR room.creator = '') AND state_event.type = 'm.room.create' AND state_event.state_key = ''
  1457. ORDER BY room_id
  1458. LIMIT ?
  1459. """
  1460. txn.execute(sql, (last_room_id, batch_size))
  1461. room_id_to_create_event_results = txn.fetchall()
  1462. new_last_room_id = ""
  1463. for room_id, event_json in room_id_to_create_event_results:
  1464. event_dict = db_to_json(event_json)
  1465. creator = event_dict.get("content").get(EventContentFields.ROOM_CREATOR)
  1466. self.db_pool.simple_update_txn(
  1467. txn,
  1468. table="rooms",
  1469. keyvalues={"room_id": room_id},
  1470. updatevalues={"creator": creator},
  1471. )
  1472. new_last_room_id = room_id
  1473. if new_last_room_id == "":
  1474. return True
  1475. self.db_pool.updates._background_update_progress_txn(
  1476. txn,
  1477. _BackgroundUpdates.POPULATE_ROOMS_CREATOR_COLUMN,
  1478. {"room_id": new_last_room_id},
  1479. )
  1480. return False
  1481. end = await self.db_pool.runInteraction(
  1482. "_background_populate_rooms_creator_column",
  1483. _background_populate_rooms_creator_column_txn,
  1484. )
  1485. if end:
  1486. await self.db_pool.updates._end_background_update(
  1487. _BackgroundUpdates.POPULATE_ROOMS_CREATOR_COLUMN
  1488. )
  1489. return batch_size
  1490. async def _background_add_room_type_column(
  1491. self, progress: JsonDict, batch_size: int
  1492. ) -> int:
  1493. """Background update to go and add room_type information to `room_stats_state`
  1494. table from `event_json` table.
  1495. """
  1496. last_room_id = progress.get("room_id", "")
  1497. def _background_add_room_type_column_txn(
  1498. txn: LoggingTransaction,
  1499. ) -> bool:
  1500. sql = """
  1501. SELECT state.room_id, json FROM event_json
  1502. INNER JOIN current_state_events AS state USING (event_id)
  1503. WHERE state.room_id > ? AND type = 'm.room.create'
  1504. ORDER BY state.room_id
  1505. LIMIT ?
  1506. """
  1507. txn.execute(sql, (last_room_id, batch_size))
  1508. room_id_to_create_event_results = txn.fetchall()
  1509. new_last_room_id = None
  1510. for room_id, event_json in room_id_to_create_event_results:
  1511. event_dict = db_to_json(event_json)
  1512. room_type = event_dict.get("content", {}).get(
  1513. EventContentFields.ROOM_TYPE, None
  1514. )
  1515. if isinstance(room_type, str):
  1516. self.db_pool.simple_update_txn(
  1517. txn,
  1518. table="room_stats_state",
  1519. keyvalues={"room_id": room_id},
  1520. updatevalues={"room_type": room_type},
  1521. )
  1522. new_last_room_id = room_id
  1523. if new_last_room_id is None:
  1524. return True
  1525. self.db_pool.updates._background_update_progress_txn(
  1526. txn,
  1527. _BackgroundUpdates.ADD_ROOM_TYPE_COLUMN,
  1528. {"room_id": new_last_room_id},
  1529. )
  1530. return False
  1531. end = await self.db_pool.runInteraction(
  1532. "_background_add_room_type_column",
  1533. _background_add_room_type_column_txn,
  1534. )
  1535. if end:
  1536. await self.db_pool.updates._end_background_update(
  1537. _BackgroundUpdates.ADD_ROOM_TYPE_COLUMN
  1538. )
  1539. return batch_size
  1540. class RoomStore(RoomBackgroundUpdateStore, RoomWorkerStore):
  1541. def __init__(
  1542. self,
  1543. database: DatabasePool,
  1544. db_conn: LoggingDatabaseConnection,
  1545. hs: "HomeServer",
  1546. ):
  1547. super().__init__(database, db_conn, hs)
  1548. self._event_reports_id_gen = IdGenerator(db_conn, "event_reports", "id")
  1549. self._instance_name = hs.get_instance_name()
  1550. async def upsert_room_on_join(
  1551. self, room_id: str, room_version: RoomVersion, state_events: List[EventBase]
  1552. ) -> None:
  1553. """Ensure that the room is stored in the table
  1554. Called when we join a room over federation, and overwrites any room version
  1555. currently in the table.
  1556. """
  1557. # It's possible that we already have events for the room in our DB
  1558. # without a corresponding room entry. If we do then we don't want to
  1559. # mark the room as having an auth chain cover index.
  1560. has_auth_chain_index = await self.has_auth_chain_index(room_id)
  1561. create_event = None
  1562. for e in state_events:
  1563. if (e.type, e.state_key) == (EventTypes.Create, ""):
  1564. create_event = e
  1565. break
  1566. if create_event is None:
  1567. # If the state doesn't have a create event then the room is
  1568. # invalid, and it would fail auth checks anyway.
  1569. raise StoreError(400, "No create event in state")
  1570. room_creator = create_event.content.get(EventContentFields.ROOM_CREATOR)
  1571. if not isinstance(room_creator, str):
  1572. # If the create event does not have a creator then the room is
  1573. # invalid, and it would fail auth checks anyway.
  1574. raise StoreError(400, "No creator defined on the create event")
  1575. await self.db_pool.simple_upsert(
  1576. desc="upsert_room_on_join",
  1577. table="rooms",
  1578. keyvalues={"room_id": room_id},
  1579. values={"room_version": room_version.identifier},
  1580. insertion_values={
  1581. "is_public": False,
  1582. "creator": room_creator,
  1583. "has_auth_chain_index": has_auth_chain_index,
  1584. },
  1585. )
  1586. async def store_partial_state_room(
  1587. self,
  1588. room_id: str,
  1589. servers: Collection[str],
  1590. device_lists_stream_id: int,
  1591. joined_via: str,
  1592. ) -> None:
  1593. """Mark the given room as containing events with partial state.
  1594. We also store additional data that describes _when_ we first partial-joined this
  1595. room, which helps us to keep other homeservers in sync when we finally fully
  1596. join this room.
  1597. We do not include a `join_event_id` here---we need to wait for the join event
  1598. to be persisted first.
  1599. Args:
  1600. room_id: the ID of the room
  1601. servers: other servers known to be in the room
  1602. device_lists_stream_id: the device_lists stream ID at the time when we first
  1603. joined the room.
  1604. joined_via: the server name we requested a partial join from.
  1605. """
  1606. await self.db_pool.runInteraction(
  1607. "store_partial_state_room",
  1608. self._store_partial_state_room_txn,
  1609. room_id,
  1610. servers,
  1611. device_lists_stream_id,
  1612. joined_via,
  1613. )
  1614. def _store_partial_state_room_txn(
  1615. self,
  1616. txn: LoggingTransaction,
  1617. room_id: str,
  1618. servers: Collection[str],
  1619. device_lists_stream_id: int,
  1620. joined_via: str,
  1621. ) -> None:
  1622. DatabasePool.simple_insert_txn(
  1623. txn,
  1624. table="partial_state_rooms",
  1625. values={
  1626. "room_id": room_id,
  1627. "device_lists_stream_id": device_lists_stream_id,
  1628. # To be updated later once the join event is persisted.
  1629. "join_event_id": None,
  1630. "joined_via": joined_via,
  1631. },
  1632. )
  1633. DatabasePool.simple_insert_many_txn(
  1634. txn,
  1635. table="partial_state_rooms_servers",
  1636. keys=("room_id", "server_name"),
  1637. values=((room_id, s) for s in servers),
  1638. )
  1639. self._invalidate_cache_and_stream(txn, self.is_partial_state_room, (room_id,))
  1640. self._invalidate_cache_and_stream(
  1641. txn, self.get_partial_state_servers_at_join, (room_id,)
  1642. )
  1643. async def write_partial_state_rooms_join_event_id(
  1644. self,
  1645. room_id: str,
  1646. join_event_id: str,
  1647. ) -> None:
  1648. """Record the join event which resulted from a partial join.
  1649. We do this separately to `store_partial_state_room` because we need to wait for
  1650. the join event to be persisted. Otherwise we violate a foreign key constraint.
  1651. """
  1652. await self.db_pool.runInteraction(
  1653. "write_partial_state_rooms_join_event_id",
  1654. self._write_partial_state_rooms_join_event_id,
  1655. room_id,
  1656. join_event_id,
  1657. )
  1658. def _write_partial_state_rooms_join_event_id(
  1659. self,
  1660. txn: LoggingTransaction,
  1661. room_id: str,
  1662. join_event_id: str,
  1663. ) -> None:
  1664. DatabasePool.simple_update_txn(
  1665. txn,
  1666. table="partial_state_rooms",
  1667. keyvalues={"room_id": room_id},
  1668. updatevalues={"join_event_id": join_event_id},
  1669. )
  1670. async def maybe_store_room_on_outlier_membership(
  1671. self, room_id: str, room_version: RoomVersion
  1672. ) -> None:
  1673. """
  1674. When we receive an invite or any other event over federation that may relate to a room
  1675. we are not in, store the version of the room if we don't already know the room version.
  1676. """
  1677. # It's possible that we already have events for the room in our DB
  1678. # without a corresponding room entry. If we do then we don't want to
  1679. # mark the room as having an auth chain cover index.
  1680. has_auth_chain_index = await self.has_auth_chain_index(room_id)
  1681. await self.db_pool.simple_upsert(
  1682. desc="maybe_store_room_on_outlier_membership",
  1683. table="rooms",
  1684. keyvalues={"room_id": room_id},
  1685. values={},
  1686. insertion_values={
  1687. "room_version": room_version.identifier,
  1688. "is_public": False,
  1689. # We don't worry about setting the `creator` here because
  1690. # we don't process any messages in a room while a user is
  1691. # invited (only after the join).
  1692. "creator": "",
  1693. "has_auth_chain_index": has_auth_chain_index,
  1694. },
  1695. )
  1696. async def set_room_is_public(self, room_id: str, is_public: bool) -> None:
  1697. await self.db_pool.simple_update_one(
  1698. table="rooms",
  1699. keyvalues={"room_id": room_id},
  1700. updatevalues={"is_public": is_public},
  1701. desc="set_room_is_public",
  1702. )
  1703. self.hs.get_notifier().on_new_replication_data()
  1704. async def set_room_is_public_appservice(
  1705. self, room_id: str, appservice_id: str, network_id: str, is_public: bool
  1706. ) -> None:
  1707. """Edit the appservice/network specific public room list.
  1708. Each appservice can have a number of published room lists associated
  1709. with them, keyed off of an appservice defined `network_id`, which
  1710. basically represents a single instance of a bridge to a third party
  1711. network.
  1712. Args:
  1713. room_id
  1714. appservice_id
  1715. network_id
  1716. is_public: Whether to publish or unpublish the room from the list.
  1717. """
  1718. if is_public:
  1719. await self.db_pool.simple_upsert(
  1720. table="appservice_room_list",
  1721. keyvalues={
  1722. "appservice_id": appservice_id,
  1723. "network_id": network_id,
  1724. "room_id": room_id,
  1725. },
  1726. values={},
  1727. insertion_values={
  1728. "appservice_id": appservice_id,
  1729. "network_id": network_id,
  1730. "room_id": room_id,
  1731. },
  1732. desc="set_room_is_public_appservice_true",
  1733. )
  1734. else:
  1735. await self.db_pool.simple_delete(
  1736. table="appservice_room_list",
  1737. keyvalues={
  1738. "appservice_id": appservice_id,
  1739. "network_id": network_id,
  1740. "room_id": room_id,
  1741. },
  1742. desc="set_room_is_public_appservice_false",
  1743. )
  1744. self.hs.get_notifier().on_new_replication_data()
  1745. async def add_event_report(
  1746. self,
  1747. room_id: str,
  1748. event_id: str,
  1749. user_id: str,
  1750. reason: Optional[str],
  1751. content: JsonDict,
  1752. received_ts: int,
  1753. ) -> None:
  1754. next_id = self._event_reports_id_gen.get_next()
  1755. await self.db_pool.simple_insert(
  1756. table="event_reports",
  1757. values={
  1758. "id": next_id,
  1759. "received_ts": received_ts,
  1760. "room_id": room_id,
  1761. "event_id": event_id,
  1762. "user_id": user_id,
  1763. "reason": reason,
  1764. "content": json_encoder.encode(content),
  1765. },
  1766. desc="add_event_report",
  1767. )
  1768. async def get_event_report(self, report_id: int) -> Optional[Dict[str, Any]]:
  1769. """Retrieve an event report
  1770. Args:
  1771. report_id: ID of reported event in database
  1772. Returns:
  1773. JSON dict of information from an event report or None if the
  1774. report does not exist.
  1775. """
  1776. def _get_event_report_txn(
  1777. txn: LoggingTransaction, report_id: int
  1778. ) -> Optional[Dict[str, Any]]:
  1779. sql = """
  1780. SELECT
  1781. er.id,
  1782. er.received_ts,
  1783. er.room_id,
  1784. er.event_id,
  1785. er.user_id,
  1786. er.content,
  1787. events.sender,
  1788. room_stats_state.canonical_alias,
  1789. room_stats_state.name,
  1790. event_json.json AS event_json
  1791. FROM event_reports AS er
  1792. LEFT JOIN events
  1793. ON events.event_id = er.event_id
  1794. JOIN event_json
  1795. ON event_json.event_id = er.event_id
  1796. JOIN room_stats_state
  1797. ON room_stats_state.room_id = er.room_id
  1798. WHERE er.id = ?
  1799. """
  1800. txn.execute(sql, [report_id])
  1801. row = txn.fetchone()
  1802. if not row:
  1803. return None
  1804. event_report = {
  1805. "id": row[0],
  1806. "received_ts": row[1],
  1807. "room_id": row[2],
  1808. "event_id": row[3],
  1809. "user_id": row[4],
  1810. "score": db_to_json(row[5]).get("score"),
  1811. "reason": db_to_json(row[5]).get("reason"),
  1812. "sender": row[6],
  1813. "canonical_alias": row[7],
  1814. "name": row[8],
  1815. "event_json": db_to_json(row[9]),
  1816. }
  1817. return event_report
  1818. return await self.db_pool.runInteraction(
  1819. "get_event_report", _get_event_report_txn, report_id
  1820. )
  1821. async def get_event_reports_paginate(
  1822. self,
  1823. start: int,
  1824. limit: int,
  1825. direction: str = "b",
  1826. user_id: Optional[str] = None,
  1827. room_id: Optional[str] = None,
  1828. ) -> Tuple[List[Dict[str, Any]], int]:
  1829. """Retrieve a paginated list of event reports
  1830. Args:
  1831. start: event offset to begin the query from
  1832. limit: number of rows to retrieve
  1833. direction: Whether to fetch the most recent first (`"b"`) or the
  1834. oldest first (`"f"`)
  1835. user_id: search for user_id. Ignored if user_id is None
  1836. room_id: search for room_id. Ignored if room_id is None
  1837. Returns:
  1838. Tuple of:
  1839. json list of event reports
  1840. total number of event reports matching the filter criteria
  1841. """
  1842. def _get_event_reports_paginate_txn(
  1843. txn: LoggingTransaction,
  1844. ) -> Tuple[List[Dict[str, Any]], int]:
  1845. filters = []
  1846. args: List[object] = []
  1847. if user_id:
  1848. filters.append("er.user_id LIKE ?")
  1849. args.extend(["%" + user_id + "%"])
  1850. if room_id:
  1851. filters.append("er.room_id LIKE ?")
  1852. args.extend(["%" + room_id + "%"])
  1853. if direction == "b":
  1854. order = "DESC"
  1855. else:
  1856. order = "ASC"
  1857. where_clause = "WHERE " + " AND ".join(filters) if len(filters) > 0 else ""
  1858. # We join on room_stats_state despite not using any columns from it
  1859. # because the join can influence the number of rows returned;
  1860. # e.g. a room that doesn't have state, maybe because it was deleted.
  1861. # The query returning the total count should be consistent with
  1862. # the query returning the results.
  1863. sql = """
  1864. SELECT COUNT(*) as total_event_reports
  1865. FROM event_reports AS er
  1866. JOIN room_stats_state ON room_stats_state.room_id = er.room_id
  1867. {}
  1868. """.format(
  1869. where_clause
  1870. )
  1871. txn.execute(sql, args)
  1872. count = cast(Tuple[int], txn.fetchone())[0]
  1873. sql = """
  1874. SELECT
  1875. er.id,
  1876. er.received_ts,
  1877. er.room_id,
  1878. er.event_id,
  1879. er.user_id,
  1880. er.content,
  1881. events.sender,
  1882. room_stats_state.canonical_alias,
  1883. room_stats_state.name
  1884. FROM event_reports AS er
  1885. LEFT JOIN events
  1886. ON events.event_id = er.event_id
  1887. JOIN room_stats_state
  1888. ON room_stats_state.room_id = er.room_id
  1889. {where_clause}
  1890. ORDER BY er.received_ts {order}
  1891. LIMIT ?
  1892. OFFSET ?
  1893. """.format(
  1894. where_clause=where_clause,
  1895. order=order,
  1896. )
  1897. args += [limit, start]
  1898. txn.execute(sql, args)
  1899. event_reports = []
  1900. for row in txn:
  1901. try:
  1902. s = db_to_json(row[5]).get("score")
  1903. r = db_to_json(row[5]).get("reason")
  1904. except Exception:
  1905. logger.error("Unable to parse json from event_reports: %s", row[0])
  1906. continue
  1907. event_reports.append(
  1908. {
  1909. "id": row[0],
  1910. "received_ts": row[1],
  1911. "room_id": row[2],
  1912. "event_id": row[3],
  1913. "user_id": row[4],
  1914. "score": s,
  1915. "reason": r,
  1916. "sender": row[6],
  1917. "canonical_alias": row[7],
  1918. "name": row[8],
  1919. }
  1920. )
  1921. return event_reports, count
  1922. return await self.db_pool.runInteraction(
  1923. "get_event_reports_paginate", _get_event_reports_paginate_txn
  1924. )
  1925. async def block_room(self, room_id: str, user_id: str) -> None:
  1926. """Marks the room as blocked.
  1927. Can be called multiple times (though we'll only track the last user to
  1928. block this room).
  1929. Can be called on a room unknown to this homeserver.
  1930. Args:
  1931. room_id: Room to block
  1932. user_id: Who blocked it
  1933. """
  1934. await self.db_pool.simple_upsert(
  1935. table="blocked_rooms",
  1936. keyvalues={"room_id": room_id},
  1937. values={},
  1938. insertion_values={"user_id": user_id},
  1939. desc="block_room",
  1940. )
  1941. await self.db_pool.runInteraction(
  1942. "block_room_invalidation",
  1943. self._invalidate_cache_and_stream,
  1944. self.is_room_blocked,
  1945. (room_id,),
  1946. )
  1947. async def unblock_room(self, room_id: str) -> None:
  1948. """Remove the room from blocking list.
  1949. Args:
  1950. room_id: Room to unblock
  1951. """
  1952. await self.db_pool.simple_delete(
  1953. table="blocked_rooms",
  1954. keyvalues={"room_id": room_id},
  1955. desc="unblock_room",
  1956. )
  1957. await self.db_pool.runInteraction(
  1958. "block_room_invalidation",
  1959. self._invalidate_cache_and_stream,
  1960. self.is_room_blocked,
  1961. (room_id,),
  1962. )
  1963. async def clear_partial_state_room(self, room_id: str) -> bool:
  1964. """Clears the partial state flag for a room.
  1965. Args:
  1966. room_id: The room whose partial state flag is to be cleared.
  1967. Returns:
  1968. `True` if the partial state flag has been cleared successfully.
  1969. `False` if the partial state flag could not be cleared because the room
  1970. still contains events with partial state.
  1971. """
  1972. try:
  1973. async with self._un_partial_stated_rooms_stream_id_gen.get_next() as un_partial_state_room_stream_id:
  1974. await self.db_pool.runInteraction(
  1975. "clear_partial_state_room",
  1976. self._clear_partial_state_room_txn,
  1977. room_id,
  1978. un_partial_state_room_stream_id,
  1979. )
  1980. return True
  1981. except self.db_pool.engine.module.IntegrityError as e:
  1982. # Assume that any `IntegrityError`s are due to partial state events.
  1983. logger.info(
  1984. "Exception while clearing lazy partial-state-room %s, retrying: %s",
  1985. room_id,
  1986. e,
  1987. )
  1988. return False
  1989. def _clear_partial_state_room_txn(
  1990. self,
  1991. txn: LoggingTransaction,
  1992. room_id: str,
  1993. un_partial_state_room_stream_id: int,
  1994. ) -> None:
  1995. DatabasePool.simple_delete_txn(
  1996. txn,
  1997. table="partial_state_rooms_servers",
  1998. keyvalues={"room_id": room_id},
  1999. )
  2000. DatabasePool.simple_delete_one_txn(
  2001. txn,
  2002. table="partial_state_rooms",
  2003. keyvalues={"room_id": room_id},
  2004. )
  2005. self._invalidate_cache_and_stream(txn, self.is_partial_state_room, (room_id,))
  2006. self._invalidate_cache_and_stream(
  2007. txn, self.get_partial_state_servers_at_join, (room_id,)
  2008. )
  2009. DatabasePool.simple_insert_txn(
  2010. txn,
  2011. "un_partial_stated_room_stream",
  2012. {
  2013. "stream_id": un_partial_state_room_stream_id,
  2014. "instance_name": self._instance_name,
  2015. "room_id": room_id,
  2016. },
  2017. )
  2018. # We now delete anything from `device_lists_remote_pending` with a
  2019. # stream ID less than the minimum
  2020. # `partial_state_rooms.device_lists_stream_id`, as we no longer need them.
  2021. device_lists_stream_id = DatabasePool.simple_select_one_onecol_txn(
  2022. txn,
  2023. table="partial_state_rooms",
  2024. keyvalues={},
  2025. retcol="MIN(device_lists_stream_id)",
  2026. allow_none=True,
  2027. )
  2028. if device_lists_stream_id is None:
  2029. # There are no rooms being currently partially joined, so we delete everything.
  2030. txn.execute("DELETE FROM device_lists_remote_pending")
  2031. else:
  2032. sql = """
  2033. DELETE FROM device_lists_remote_pending
  2034. WHERE stream_id <= ?
  2035. """
  2036. txn.execute(sql, (device_lists_stream_id,))