Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

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