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.
 
 
 
 
 
 

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