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.
 
 
 
 
 
 

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