events_bg_updates.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 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 canonicaljson import json
  17. from twisted.internet import defer
  18. from synapse.api.constants import EventContentFields
  19. from synapse.storage._base import SQLBaseStore, make_in_list_sql_clause
  20. from synapse.storage.database import Database
  21. logger = logging.getLogger(__name__)
  22. class EventsBackgroundUpdatesStore(SQLBaseStore):
  23. EVENT_ORIGIN_SERVER_TS_NAME = "event_origin_server_ts"
  24. EVENT_FIELDS_SENDER_URL_UPDATE_NAME = "event_fields_sender_url"
  25. DELETE_SOFT_FAILED_EXTREMITIES = "delete_soft_failed_extremities"
  26. def __init__(self, database: Database, db_conn, hs):
  27. super(EventsBackgroundUpdatesStore, self).__init__(database, db_conn, hs)
  28. self.db.updates.register_background_update_handler(
  29. self.EVENT_ORIGIN_SERVER_TS_NAME, self._background_reindex_origin_server_ts
  30. )
  31. self.db.updates.register_background_update_handler(
  32. self.EVENT_FIELDS_SENDER_URL_UPDATE_NAME,
  33. self._background_reindex_fields_sender,
  34. )
  35. self.db.updates.register_background_index_update(
  36. "event_contains_url_index",
  37. index_name="event_contains_url_index",
  38. table="events",
  39. columns=["room_id", "topological_ordering", "stream_ordering"],
  40. where_clause="contains_url = true AND outlier = false",
  41. )
  42. # an event_id index on event_search is useful for the purge_history
  43. # api. Plus it means we get to enforce some integrity with a UNIQUE
  44. # clause
  45. self.db.updates.register_background_index_update(
  46. "event_search_event_id_idx",
  47. index_name="event_search_event_id_idx",
  48. table="event_search",
  49. columns=["event_id"],
  50. unique=True,
  51. psql_only=True,
  52. )
  53. self.db.updates.register_background_update_handler(
  54. self.DELETE_SOFT_FAILED_EXTREMITIES, self._cleanup_extremities_bg_update
  55. )
  56. self.db.updates.register_background_update_handler(
  57. "redactions_received_ts", self._redactions_received_ts
  58. )
  59. # This index gets deleted in `event_fix_redactions_bytes` update
  60. self.db.updates.register_background_index_update(
  61. "event_fix_redactions_bytes_create_index",
  62. index_name="redactions_censored_redacts",
  63. table="redactions",
  64. columns=["redacts"],
  65. where_clause="have_censored",
  66. )
  67. self.db.updates.register_background_update_handler(
  68. "event_fix_redactions_bytes", self._event_fix_redactions_bytes
  69. )
  70. self.db.updates.register_background_update_handler(
  71. "event_store_labels", self._event_store_labels
  72. )
  73. self.db.updates.register_background_index_update(
  74. "redactions_have_censored_ts_idx",
  75. index_name="redactions_have_censored_ts",
  76. table="redactions",
  77. columns=["received_ts"],
  78. where_clause="NOT have_censored",
  79. )
  80. @defer.inlineCallbacks
  81. def _background_reindex_fields_sender(self, progress, batch_size):
  82. target_min_stream_id = progress["target_min_stream_id_inclusive"]
  83. max_stream_id = progress["max_stream_id_exclusive"]
  84. rows_inserted = progress.get("rows_inserted", 0)
  85. INSERT_CLUMP_SIZE = 1000
  86. def reindex_txn(txn):
  87. sql = (
  88. "SELECT stream_ordering, event_id, json FROM events"
  89. " INNER JOIN event_json USING (event_id)"
  90. " WHERE ? <= stream_ordering AND stream_ordering < ?"
  91. " ORDER BY stream_ordering DESC"
  92. " LIMIT ?"
  93. )
  94. txn.execute(sql, (target_min_stream_id, max_stream_id, batch_size))
  95. rows = txn.fetchall()
  96. if not rows:
  97. return 0
  98. min_stream_id = rows[-1][0]
  99. update_rows = []
  100. for row in rows:
  101. try:
  102. event_id = row[1]
  103. event_json = json.loads(row[2])
  104. sender = event_json["sender"]
  105. content = event_json["content"]
  106. contains_url = "url" in content
  107. if contains_url:
  108. contains_url &= isinstance(content["url"], str)
  109. except (KeyError, AttributeError):
  110. # If the event is missing a necessary field then
  111. # skip over it.
  112. continue
  113. update_rows.append((sender, contains_url, event_id))
  114. sql = "UPDATE events SET sender = ?, contains_url = ? WHERE event_id = ?"
  115. for index in range(0, len(update_rows), INSERT_CLUMP_SIZE):
  116. clump = update_rows[index : index + INSERT_CLUMP_SIZE]
  117. txn.executemany(sql, clump)
  118. progress = {
  119. "target_min_stream_id_inclusive": target_min_stream_id,
  120. "max_stream_id_exclusive": min_stream_id,
  121. "rows_inserted": rows_inserted + len(rows),
  122. }
  123. self.db.updates._background_update_progress_txn(
  124. txn, self.EVENT_FIELDS_SENDER_URL_UPDATE_NAME, progress
  125. )
  126. return len(rows)
  127. result = yield self.db.runInteraction(
  128. self.EVENT_FIELDS_SENDER_URL_UPDATE_NAME, reindex_txn
  129. )
  130. if not result:
  131. yield self.db.updates._end_background_update(
  132. self.EVENT_FIELDS_SENDER_URL_UPDATE_NAME
  133. )
  134. return result
  135. @defer.inlineCallbacks
  136. def _background_reindex_origin_server_ts(self, progress, batch_size):
  137. target_min_stream_id = progress["target_min_stream_id_inclusive"]
  138. max_stream_id = progress["max_stream_id_exclusive"]
  139. rows_inserted = progress.get("rows_inserted", 0)
  140. INSERT_CLUMP_SIZE = 1000
  141. def reindex_search_txn(txn):
  142. sql = (
  143. "SELECT stream_ordering, event_id FROM events"
  144. " WHERE ? <= stream_ordering AND stream_ordering < ?"
  145. " ORDER BY stream_ordering DESC"
  146. " LIMIT ?"
  147. )
  148. txn.execute(sql, (target_min_stream_id, max_stream_id, batch_size))
  149. rows = txn.fetchall()
  150. if not rows:
  151. return 0
  152. min_stream_id = rows[-1][0]
  153. event_ids = [row[1] for row in rows]
  154. rows_to_update = []
  155. chunks = [event_ids[i : i + 100] for i in range(0, len(event_ids), 100)]
  156. for chunk in chunks:
  157. ev_rows = self.db.simple_select_many_txn(
  158. txn,
  159. table="event_json",
  160. column="event_id",
  161. iterable=chunk,
  162. retcols=["event_id", "json"],
  163. keyvalues={},
  164. )
  165. for row in ev_rows:
  166. event_id = row["event_id"]
  167. event_json = json.loads(row["json"])
  168. try:
  169. origin_server_ts = event_json["origin_server_ts"]
  170. except (KeyError, AttributeError):
  171. # If the event is missing a necessary field then
  172. # skip over it.
  173. continue
  174. rows_to_update.append((origin_server_ts, event_id))
  175. sql = "UPDATE events SET origin_server_ts = ? WHERE event_id = ?"
  176. for index in range(0, len(rows_to_update), INSERT_CLUMP_SIZE):
  177. clump = rows_to_update[index : index + INSERT_CLUMP_SIZE]
  178. txn.executemany(sql, clump)
  179. progress = {
  180. "target_min_stream_id_inclusive": target_min_stream_id,
  181. "max_stream_id_exclusive": min_stream_id,
  182. "rows_inserted": rows_inserted + len(rows_to_update),
  183. }
  184. self.db.updates._background_update_progress_txn(
  185. txn, self.EVENT_ORIGIN_SERVER_TS_NAME, progress
  186. )
  187. return len(rows_to_update)
  188. result = yield self.db.runInteraction(
  189. self.EVENT_ORIGIN_SERVER_TS_NAME, reindex_search_txn
  190. )
  191. if not result:
  192. yield self.db.updates._end_background_update(
  193. self.EVENT_ORIGIN_SERVER_TS_NAME
  194. )
  195. return result
  196. @defer.inlineCallbacks
  197. def _cleanup_extremities_bg_update(self, progress, batch_size):
  198. """Background update to clean out extremities that should have been
  199. deleted previously.
  200. Mainly used to deal with the aftermath of #5269.
  201. """
  202. # This works by first copying all existing forward extremities into the
  203. # `_extremities_to_check` table at start up, and then checking each
  204. # event in that table whether we have any descendants that are not
  205. # soft-failed/rejected. If that is the case then we delete that event
  206. # from the forward extremities table.
  207. #
  208. # For efficiency, we do this in batches by recursively pulling out all
  209. # descendants of a batch until we find the non soft-failed/rejected
  210. # events, i.e. the set of descendants whose chain of prev events back
  211. # to the batch of extremities are all soft-failed or rejected.
  212. # Typically, we won't find any such events as extremities will rarely
  213. # have any descendants, but if they do then we should delete those
  214. # extremities.
  215. def _cleanup_extremities_bg_update_txn(txn):
  216. # The set of extremity event IDs that we're checking this round
  217. original_set = set()
  218. # A dict[str, set[str]] of event ID to their prev events.
  219. graph = {}
  220. # The set of descendants of the original set that are not rejected
  221. # nor soft-failed. Ancestors of these events should be removed
  222. # from the forward extremities table.
  223. non_rejected_leaves = set()
  224. # Set of event IDs that have been soft failed, and for which we
  225. # should check if they have descendants which haven't been soft
  226. # failed.
  227. soft_failed_events_to_lookup = set()
  228. # First, we get `batch_size` events from the table, pulling out
  229. # their successor events, if any, and the successor events'
  230. # rejection status.
  231. txn.execute(
  232. """SELECT prev_event_id, event_id, internal_metadata,
  233. rejections.event_id IS NOT NULL, events.outlier
  234. FROM (
  235. SELECT event_id AS prev_event_id
  236. FROM _extremities_to_check
  237. LIMIT ?
  238. ) AS f
  239. LEFT JOIN event_edges USING (prev_event_id)
  240. LEFT JOIN events USING (event_id)
  241. LEFT JOIN event_json USING (event_id)
  242. LEFT JOIN rejections USING (event_id)
  243. """,
  244. (batch_size,),
  245. )
  246. for prev_event_id, event_id, metadata, rejected, outlier in txn:
  247. original_set.add(prev_event_id)
  248. if not event_id or outlier:
  249. # Common case where the forward extremity doesn't have any
  250. # descendants.
  251. continue
  252. graph.setdefault(event_id, set()).add(prev_event_id)
  253. soft_failed = False
  254. if metadata:
  255. soft_failed = json.loads(metadata).get("soft_failed")
  256. if soft_failed or rejected:
  257. soft_failed_events_to_lookup.add(event_id)
  258. else:
  259. non_rejected_leaves.add(event_id)
  260. # Now we recursively check all the soft-failed descendants we
  261. # found above in the same way, until we have nothing left to
  262. # check.
  263. while soft_failed_events_to_lookup:
  264. # We only want to do 100 at a time, so we split given list
  265. # into two.
  266. batch = list(soft_failed_events_to_lookup)
  267. to_check, to_defer = batch[:100], batch[100:]
  268. soft_failed_events_to_lookup = set(to_defer)
  269. sql = """SELECT prev_event_id, event_id, internal_metadata,
  270. rejections.event_id IS NOT NULL
  271. FROM event_edges
  272. INNER JOIN events USING (event_id)
  273. INNER JOIN event_json USING (event_id)
  274. LEFT JOIN rejections USING (event_id)
  275. WHERE
  276. NOT events.outlier
  277. AND
  278. """
  279. clause, args = make_in_list_sql_clause(
  280. self.database_engine, "prev_event_id", to_check
  281. )
  282. txn.execute(sql + clause, list(args))
  283. for prev_event_id, event_id, metadata, rejected in txn:
  284. if event_id in graph:
  285. # Already handled this event previously, but we still
  286. # want to record the edge.
  287. graph[event_id].add(prev_event_id)
  288. continue
  289. graph[event_id] = {prev_event_id}
  290. soft_failed = json.loads(metadata).get("soft_failed")
  291. if soft_failed or rejected:
  292. soft_failed_events_to_lookup.add(event_id)
  293. else:
  294. non_rejected_leaves.add(event_id)
  295. # We have a set of non-soft-failed descendants, so we recurse up
  296. # the graph to find all ancestors and add them to the set of event
  297. # IDs that we can delete from forward extremities table.
  298. to_delete = set()
  299. while non_rejected_leaves:
  300. event_id = non_rejected_leaves.pop()
  301. prev_event_ids = graph.get(event_id, set())
  302. non_rejected_leaves.update(prev_event_ids)
  303. to_delete.update(prev_event_ids)
  304. to_delete.intersection_update(original_set)
  305. deleted = self.db.simple_delete_many_txn(
  306. txn=txn,
  307. table="event_forward_extremities",
  308. column="event_id",
  309. iterable=to_delete,
  310. keyvalues={},
  311. )
  312. logger.info(
  313. "Deleted %d forward extremities of %d checked, to clean up #5269",
  314. deleted,
  315. len(original_set),
  316. )
  317. if deleted:
  318. # We now need to invalidate the caches of these rooms
  319. rows = self.db.simple_select_many_txn(
  320. txn,
  321. table="events",
  322. column="event_id",
  323. iterable=to_delete,
  324. keyvalues={},
  325. retcols=("room_id",),
  326. )
  327. room_ids = {row["room_id"] for row in rows}
  328. for room_id in room_ids:
  329. txn.call_after(
  330. self.get_latest_event_ids_in_room.invalidate, (room_id,)
  331. )
  332. self.db.simple_delete_many_txn(
  333. txn=txn,
  334. table="_extremities_to_check",
  335. column="event_id",
  336. iterable=original_set,
  337. keyvalues={},
  338. )
  339. return len(original_set)
  340. num_handled = yield self.db.runInteraction(
  341. "_cleanup_extremities_bg_update", _cleanup_extremities_bg_update_txn
  342. )
  343. if not num_handled:
  344. yield self.db.updates._end_background_update(
  345. self.DELETE_SOFT_FAILED_EXTREMITIES
  346. )
  347. def _drop_table_txn(txn):
  348. txn.execute("DROP TABLE _extremities_to_check")
  349. yield self.db.runInteraction(
  350. "_cleanup_extremities_bg_update_drop_table", _drop_table_txn
  351. )
  352. return num_handled
  353. @defer.inlineCallbacks
  354. def _redactions_received_ts(self, progress, batch_size):
  355. """Handles filling out the `received_ts` column in redactions.
  356. """
  357. last_event_id = progress.get("last_event_id", "")
  358. def _redactions_received_ts_txn(txn):
  359. # Fetch the set of event IDs that we want to update
  360. sql = """
  361. SELECT event_id FROM redactions
  362. WHERE event_id > ?
  363. ORDER BY event_id ASC
  364. LIMIT ?
  365. """
  366. txn.execute(sql, (last_event_id, batch_size))
  367. rows = txn.fetchall()
  368. if not rows:
  369. return 0
  370. (upper_event_id,) = rows[-1]
  371. # Update the redactions with the received_ts.
  372. #
  373. # Note: Not all events have an associated received_ts, so we
  374. # fallback to using origin_server_ts. If we for some reason don't
  375. # have an origin_server_ts, lets just use the current timestamp.
  376. #
  377. # We don't want to leave it null, as then we'll never try and
  378. # censor those redactions.
  379. sql = """
  380. UPDATE redactions
  381. SET received_ts = (
  382. SELECT COALESCE(received_ts, origin_server_ts, ?) FROM events
  383. WHERE events.event_id = redactions.event_id
  384. )
  385. WHERE ? <= event_id AND event_id <= ?
  386. """
  387. txn.execute(sql, (self._clock.time_msec(), last_event_id, upper_event_id))
  388. self.db.updates._background_update_progress_txn(
  389. txn, "redactions_received_ts", {"last_event_id": upper_event_id}
  390. )
  391. return len(rows)
  392. count = yield self.db.runInteraction(
  393. "_redactions_received_ts", _redactions_received_ts_txn
  394. )
  395. if not count:
  396. yield self.db.updates._end_background_update("redactions_received_ts")
  397. return count
  398. @defer.inlineCallbacks
  399. def _event_fix_redactions_bytes(self, progress, batch_size):
  400. """Undoes hex encoded censored redacted event JSON.
  401. """
  402. def _event_fix_redactions_bytes_txn(txn):
  403. # This update is quite fast due to new index.
  404. txn.execute(
  405. """
  406. UPDATE event_json
  407. SET
  408. json = convert_from(json::bytea, 'utf8')
  409. FROM redactions
  410. WHERE
  411. redactions.have_censored
  412. AND event_json.event_id = redactions.redacts
  413. AND json NOT LIKE '{%';
  414. """
  415. )
  416. txn.execute("DROP INDEX redactions_censored_redacts")
  417. yield self.db.runInteraction(
  418. "_event_fix_redactions_bytes", _event_fix_redactions_bytes_txn
  419. )
  420. yield self.db.updates._end_background_update("event_fix_redactions_bytes")
  421. return 1
  422. @defer.inlineCallbacks
  423. def _event_store_labels(self, progress, batch_size):
  424. """Background update handler which will store labels for existing events."""
  425. last_event_id = progress.get("last_event_id", "")
  426. def _event_store_labels_txn(txn):
  427. txn.execute(
  428. """
  429. SELECT event_id, json FROM event_json
  430. LEFT JOIN event_labels USING (event_id)
  431. WHERE event_id > ? AND label IS NULL
  432. ORDER BY event_id LIMIT ?
  433. """,
  434. (last_event_id, batch_size),
  435. )
  436. results = list(txn)
  437. nbrows = 0
  438. last_row_event_id = ""
  439. for (event_id, event_json_raw) in results:
  440. try:
  441. event_json = json.loads(event_json_raw)
  442. self.db.simple_insert_many_txn(
  443. txn=txn,
  444. table="event_labels",
  445. values=[
  446. {
  447. "event_id": event_id,
  448. "label": label,
  449. "room_id": event_json["room_id"],
  450. "topological_ordering": event_json["depth"],
  451. }
  452. for label in event_json["content"].get(
  453. EventContentFields.LABELS, []
  454. )
  455. if isinstance(label, str)
  456. ],
  457. )
  458. except Exception as e:
  459. logger.warning(
  460. "Unable to load event %s (no labels will be imported): %s",
  461. event_id,
  462. e,
  463. )
  464. nbrows += 1
  465. last_row_event_id = event_id
  466. self.db.updates._background_update_progress_txn(
  467. txn, "event_store_labels", {"last_event_id": last_row_event_id}
  468. )
  469. return nbrows
  470. num_rows = yield self.db.runInteraction(
  471. desc="event_store_labels", func=_event_store_labels_txn
  472. )
  473. if not num_rows:
  474. yield self.db.updates._end_background_update("event_store_labels")
  475. return num_rows