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.
 
 
 
 
 
 

445 rivejä
16 KiB

  1. # Copyright 2020 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. from typing import Any, List, Set, Tuple
  16. from synapse.api.errors import SynapseError
  17. from synapse.storage.databases.main import CacheInvalidationWorkerStore
  18. from synapse.storage.databases.main.state import StateGroupWorkerStore
  19. from synapse.types import RoomStreamToken
  20. logger = logging.getLogger(__name__)
  21. class PurgeEventsStore(StateGroupWorkerStore, CacheInvalidationWorkerStore):
  22. async def purge_history(
  23. self, room_id: str, token: str, delete_local_events: bool
  24. ) -> Set[int]:
  25. """Deletes room history before a certain point.
  26. Note that only a single purge can occur at once, this is guaranteed via
  27. a higher level (in the PaginationHandler).
  28. Args:
  29. room_id:
  30. token: A topological token to delete events before
  31. delete_local_events:
  32. if True, we will delete local events as well as remote ones
  33. (instead of just marking them as outliers and deleting their
  34. state groups).
  35. Returns:
  36. The set of state groups that are referenced by deleted events.
  37. """
  38. parsed_token = await RoomStreamToken.parse(self, token)
  39. return await self.db_pool.runInteraction(
  40. "purge_history",
  41. self._purge_history_txn,
  42. room_id,
  43. parsed_token,
  44. delete_local_events,
  45. )
  46. def _purge_history_txn(
  47. self, txn, room_id: str, token: RoomStreamToken, delete_local_events: bool
  48. ) -> Set[int]:
  49. # Tables that should be pruned:
  50. # event_auth
  51. # event_backward_extremities
  52. # event_edges
  53. # event_forward_extremities
  54. # event_json
  55. # event_push_actions
  56. # event_reference_hashes
  57. # event_relations
  58. # event_search
  59. # event_to_state_groups
  60. # events
  61. # rejections
  62. # room_depth
  63. # state_groups
  64. # state_groups_state
  65. # destination_rooms
  66. # we will build a temporary table listing the events so that we don't
  67. # have to keep shovelling the list back and forth across the
  68. # connection. Annoyingly the python sqlite driver commits the
  69. # transaction on CREATE, so let's do this first.
  70. #
  71. # furthermore, we might already have the table from a previous (failed)
  72. # purge attempt, so let's drop the table first.
  73. txn.execute("DROP TABLE IF EXISTS events_to_purge")
  74. txn.execute(
  75. "CREATE TEMPORARY TABLE events_to_purge ("
  76. " event_id TEXT NOT NULL,"
  77. " should_delete BOOLEAN NOT NULL"
  78. ")"
  79. )
  80. # First ensure that we're not about to delete all the forward extremeties
  81. txn.execute(
  82. "SELECT e.event_id, e.depth FROM events as e "
  83. "INNER JOIN event_forward_extremities as f "
  84. "ON e.event_id = f.event_id "
  85. "AND e.room_id = f.room_id "
  86. "WHERE f.room_id = ?",
  87. (room_id,),
  88. )
  89. rows = txn.fetchall()
  90. max_depth = max(row[1] for row in rows)
  91. if max_depth < token.topological:
  92. # We need to ensure we don't delete all the events from the database
  93. # otherwise we wouldn't be able to send any events (due to not
  94. # having any backwards extremities)
  95. raise SynapseError(
  96. 400, "topological_ordering is greater than forward extremeties"
  97. )
  98. logger.info("[purge] looking for events to delete")
  99. should_delete_expr = "state_key IS NULL"
  100. should_delete_params = () # type: Tuple[Any, ...]
  101. if not delete_local_events:
  102. should_delete_expr += " AND event_id NOT LIKE ?"
  103. # We include the parameter twice since we use the expression twice
  104. should_delete_params += ("%:" + self.hs.hostname, "%:" + self.hs.hostname)
  105. should_delete_params += (room_id, token.topological)
  106. # Note that we insert events that are outliers and aren't going to be
  107. # deleted, as nothing will happen to them.
  108. txn.execute(
  109. "INSERT INTO events_to_purge"
  110. " SELECT event_id, %s"
  111. " FROM events AS e LEFT JOIN state_events USING (event_id)"
  112. " WHERE (NOT outlier OR (%s)) AND e.room_id = ? AND topological_ordering < ?"
  113. % (should_delete_expr, should_delete_expr),
  114. should_delete_params,
  115. )
  116. # We create the indices *after* insertion as that's a lot faster.
  117. # create an index on should_delete because later we'll be looking for
  118. # the should_delete / shouldn't_delete subsets
  119. txn.execute(
  120. "CREATE INDEX events_to_purge_should_delete"
  121. " ON events_to_purge(should_delete)"
  122. )
  123. # We do joins against events_to_purge for e.g. calculating state
  124. # groups to purge, etc., so lets make an index.
  125. txn.execute("CREATE INDEX events_to_purge_id ON events_to_purge(event_id)")
  126. txn.execute("SELECT event_id, should_delete FROM events_to_purge")
  127. event_rows = txn.fetchall()
  128. logger.info(
  129. "[purge] found %i events before cutoff, of which %i can be deleted",
  130. len(event_rows),
  131. sum(1 for e in event_rows if e[1]),
  132. )
  133. logger.info("[purge] Finding new backward extremities")
  134. # We calculate the new entries for the backward extremities by finding
  135. # events to be purged that are pointed to by events we're not going to
  136. # purge.
  137. txn.execute(
  138. "SELECT DISTINCT e.event_id FROM events_to_purge AS e"
  139. " INNER JOIN event_edges AS ed ON e.event_id = ed.prev_event_id"
  140. " LEFT JOIN events_to_purge AS ep2 ON ed.event_id = ep2.event_id"
  141. " WHERE ep2.event_id IS NULL"
  142. )
  143. new_backwards_extrems = txn.fetchall()
  144. logger.info("[purge] replacing backward extremities: %r", new_backwards_extrems)
  145. txn.execute(
  146. "DELETE FROM event_backward_extremities WHERE room_id = ?", (room_id,)
  147. )
  148. # Update backward extremeties
  149. txn.execute_batch(
  150. "INSERT INTO event_backward_extremities (room_id, event_id)"
  151. " VALUES (?, ?)",
  152. [(room_id, event_id) for event_id, in new_backwards_extrems],
  153. )
  154. logger.info("[purge] finding state groups referenced by deleted events")
  155. # Get all state groups that are referenced by events that are to be
  156. # deleted.
  157. txn.execute(
  158. """
  159. SELECT DISTINCT state_group FROM events_to_purge
  160. INNER JOIN event_to_state_groups USING (event_id)
  161. """
  162. )
  163. referenced_state_groups = {sg for sg, in txn}
  164. logger.info(
  165. "[purge] found %i referenced state groups", len(referenced_state_groups)
  166. )
  167. logger.info("[purge] removing events from event_to_state_groups")
  168. txn.execute(
  169. "DELETE FROM event_to_state_groups "
  170. "WHERE event_id IN (SELECT event_id from events_to_purge)"
  171. )
  172. # Delete all remote non-state events
  173. for table in (
  174. "events",
  175. "event_json",
  176. "event_auth",
  177. "event_edges",
  178. "event_forward_extremities",
  179. "event_reference_hashes",
  180. "event_relations",
  181. "event_search",
  182. "rejections",
  183. ):
  184. logger.info("[purge] removing events from %s", table)
  185. txn.execute(
  186. "DELETE FROM %s WHERE event_id IN ("
  187. " SELECT event_id FROM events_to_purge WHERE should_delete"
  188. ")" % (table,)
  189. )
  190. # event_push_actions lacks an index on event_id, and has one on
  191. # (room_id, event_id) instead.
  192. for table in ("event_push_actions",):
  193. logger.info("[purge] removing events from %s", table)
  194. txn.execute(
  195. "DELETE FROM %s WHERE room_id = ? AND event_id IN ("
  196. " SELECT event_id FROM events_to_purge WHERE should_delete"
  197. ")" % (table,),
  198. (room_id,),
  199. )
  200. # Mark all state and own events as outliers
  201. logger.info("[purge] marking remaining events as outliers")
  202. txn.execute(
  203. "UPDATE events SET outlier = ?"
  204. " WHERE event_id IN ("
  205. " SELECT event_id FROM events_to_purge "
  206. " WHERE NOT should_delete"
  207. ")",
  208. (True,),
  209. )
  210. # synapse tries to take out an exclusive lock on room_depth whenever it
  211. # persists events (because upsert), and once we run this update, we
  212. # will block that for the rest of our transaction.
  213. #
  214. # So, let's stick it at the end so that we don't block event
  215. # persistence.
  216. #
  217. # We do this by calculating the minimum depth of the backwards
  218. # extremities. However, the events in event_backward_extremities
  219. # are ones we don't have yet so we need to look at the events that
  220. # point to it via event_edges table.
  221. txn.execute(
  222. """
  223. SELECT COALESCE(MIN(depth), 0)
  224. FROM event_backward_extremities AS eb
  225. INNER JOIN event_edges AS eg ON eg.prev_event_id = eb.event_id
  226. INNER JOIN events AS e ON e.event_id = eg.event_id
  227. WHERE eb.room_id = ?
  228. """,
  229. (room_id,),
  230. )
  231. (min_depth,) = txn.fetchone()
  232. logger.info("[purge] updating room_depth to %d", min_depth)
  233. txn.execute(
  234. "UPDATE room_depth SET min_depth = ? WHERE room_id = ?",
  235. (min_depth, room_id),
  236. )
  237. # finally, drop the temp table. this will commit the txn in sqlite,
  238. # so make sure to keep this actually last.
  239. txn.execute("DROP TABLE events_to_purge")
  240. for event_id, should_delete in event_rows:
  241. self._invalidate_cache_and_stream(
  242. txn, self._get_state_group_for_event, (event_id,)
  243. )
  244. # XXX: This is racy, since have_seen_events could be called between the
  245. # transaction completing and the invalidation running. On the other hand,
  246. # that's no different to calling `have_seen_events` just before the
  247. # event is deleted from the database.
  248. if should_delete:
  249. self._invalidate_cache_and_stream(
  250. txn, self.have_seen_event, (room_id, event_id)
  251. )
  252. logger.info("[purge] done")
  253. return referenced_state_groups
  254. async def purge_room(self, room_id: str) -> List[int]:
  255. """Deletes all record of a room
  256. Args:
  257. room_id
  258. Returns:
  259. The list of state groups to delete.
  260. """
  261. return await self.db_pool.runInteraction(
  262. "purge_room", self._purge_room_txn, room_id
  263. )
  264. def _purge_room_txn(self, txn, room_id: str) -> List[int]:
  265. # First we fetch all the state groups that should be deleted, before
  266. # we delete that information.
  267. txn.execute(
  268. """
  269. SELECT DISTINCT state_group FROM events
  270. INNER JOIN event_to_state_groups USING(event_id)
  271. WHERE events.room_id = ?
  272. """,
  273. (room_id,),
  274. )
  275. state_groups = [row[0] for row in txn]
  276. # Get all the auth chains that are referenced by events that are to be
  277. # deleted.
  278. txn.execute(
  279. """
  280. SELECT chain_id, sequence_number FROM events
  281. LEFT JOIN event_auth_chains USING (event_id)
  282. WHERE room_id = ?
  283. """,
  284. (room_id,),
  285. )
  286. referenced_chain_id_tuples = list(txn)
  287. logger.info("[purge] removing events from event_auth_chain_links")
  288. txn.executemany(
  289. """
  290. DELETE FROM event_auth_chain_links WHERE
  291. origin_chain_id = ? AND origin_sequence_number = ?
  292. """,
  293. referenced_chain_id_tuples,
  294. )
  295. # Now we delete tables which lack an index on room_id but have one on event_id
  296. for table in (
  297. "event_auth",
  298. "event_edges",
  299. "event_json",
  300. "event_push_actions_staging",
  301. "event_reference_hashes",
  302. "event_relations",
  303. "event_to_state_groups",
  304. "event_auth_chains",
  305. "event_auth_chain_to_calculate",
  306. "redactions",
  307. "rejections",
  308. "state_events",
  309. ):
  310. logger.info("[purge] removing %s from %s", room_id, table)
  311. txn.execute(
  312. """
  313. DELETE FROM %s WHERE event_id IN (
  314. SELECT event_id FROM events WHERE room_id=?
  315. )
  316. """
  317. % (table,),
  318. (room_id,),
  319. )
  320. # and finally, the tables with an index on room_id (or no useful index)
  321. for table in (
  322. "current_state_events",
  323. "destination_rooms",
  324. "event_backward_extremities",
  325. "event_forward_extremities",
  326. "event_push_actions",
  327. "event_search",
  328. "events",
  329. "group_rooms",
  330. "public_room_list_stream",
  331. "receipts_graph",
  332. "receipts_linearized",
  333. "room_aliases",
  334. "room_depth",
  335. "room_memberships",
  336. "room_stats_state",
  337. "room_stats_current",
  338. "room_stats_earliest_token",
  339. "rooms",
  340. "stream_ordering_to_exterm",
  341. "users_in_public_rooms",
  342. "users_who_share_private_rooms",
  343. # no useful index, but let's clear them anyway
  344. "appservice_room_list",
  345. "e2e_room_keys",
  346. "event_push_summary",
  347. "pusher_throttle",
  348. "group_summary_rooms",
  349. "room_account_data",
  350. "room_tags",
  351. "local_current_membership",
  352. ):
  353. logger.info("[purge] removing %s from %s", room_id, table)
  354. txn.execute("DELETE FROM %s WHERE room_id=?" % (table,), (room_id,))
  355. # Other tables we do NOT need to clear out:
  356. #
  357. # - blocked_rooms
  358. # This is important, to make sure that we don't accidentally rejoin a blocked
  359. # room after it was purged
  360. #
  361. # - user_directory
  362. # This has a room_id column, but it is unused
  363. #
  364. # Other tables that we might want to consider clearing out include:
  365. #
  366. # - event_reports
  367. # Given that these are intended for abuse management my initial
  368. # inclination is to leave them in place.
  369. #
  370. # - current_state_delta_stream
  371. # - ex_outlier_stream
  372. # - room_tags_revisions
  373. # The problem with these is that they are largeish and there is no room_id
  374. # index on them. In any case we should be clearing out 'stream' tables
  375. # periodically anyway (#5888)
  376. # TODO: we could probably usefully do a bunch more cache invalidation here
  377. # XXX: as with purge_history, this is racy, but no worse than other races
  378. # that already exist.
  379. self._invalidate_cache_and_stream(txn, self.have_seen_event, (room_id,))
  380. logger.info("[purge] done")
  381. return state_groups