events.py 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2018-2019 New Vector Ltd
  4. # Copyright 2019 The Matrix.org Foundation C.I.C.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import itertools
  18. import logging
  19. from collections import Counter as c_counter, OrderedDict, deque, namedtuple
  20. from functools import wraps
  21. from six import iteritems, text_type
  22. from six.moves import range
  23. from canonicaljson import json
  24. from prometheus_client import Counter, Histogram
  25. from twisted.internet import defer
  26. import synapse.metrics
  27. from synapse.api.constants import EventTypes
  28. from synapse.api.errors import SynapseError
  29. from synapse.events import EventBase # noqa: F401
  30. from synapse.events.snapshot import EventContext # noqa: F401
  31. from synapse.logging.context import PreserveLoggingContext, make_deferred_yieldable
  32. from synapse.logging.utils import log_function
  33. from synapse.metrics import BucketCollector
  34. from synapse.metrics.background_process_metrics import run_as_background_process
  35. from synapse.state import StateResolutionStore
  36. from synapse.storage.background_updates import BackgroundUpdateStore
  37. from synapse.storage.event_federation import EventFederationStore
  38. from synapse.storage.events_worker import EventsWorkerStore
  39. from synapse.storage.state import StateGroupWorkerStore
  40. from synapse.types import RoomStreamToken, get_domain_from_id
  41. from synapse.util import batch_iter
  42. from synapse.util.async_helpers import ObservableDeferred
  43. from synapse.util.caches.descriptors import cached, cachedInlineCallbacks
  44. from synapse.util.frozenutils import frozendict_json_encoder
  45. from synapse.util.metrics import Measure
  46. logger = logging.getLogger(__name__)
  47. persist_event_counter = Counter("synapse_storage_events_persisted_events", "")
  48. event_counter = Counter(
  49. "synapse_storage_events_persisted_events_sep",
  50. "",
  51. ["type", "origin_type", "origin_entity"],
  52. )
  53. # The number of times we are recalculating the current state
  54. state_delta_counter = Counter("synapse_storage_events_state_delta", "")
  55. # The number of times we are recalculating state when there is only a
  56. # single forward extremity
  57. state_delta_single_event_counter = Counter(
  58. "synapse_storage_events_state_delta_single_event", ""
  59. )
  60. # The number of times we are reculating state when we could have resonably
  61. # calculated the delta when we calculated the state for an event we were
  62. # persisting.
  63. state_delta_reuse_delta_counter = Counter(
  64. "synapse_storage_events_state_delta_reuse_delta", ""
  65. )
  66. # The number of forward extremities for each new event.
  67. forward_extremities_counter = Histogram(
  68. "synapse_storage_events_forward_extremities_persisted",
  69. "Number of forward extremities for each new event",
  70. buckets=(1, 2, 3, 5, 7, 10, 15, 20, 50, 100, 200, 500, "+Inf"),
  71. )
  72. # The number of stale forward extremities for each new event. Stale extremities
  73. # are those that were in the previous set of extremities as well as the new.
  74. stale_forward_extremities_counter = Histogram(
  75. "synapse_storage_events_stale_forward_extremities_persisted",
  76. "Number of unchanged forward extremities for each new event",
  77. buckets=(0, 1, 2, 3, 5, 7, 10, 15, 20, 50, 100, 200, 500, "+Inf"),
  78. )
  79. def encode_json(json_object):
  80. """
  81. Encode a Python object as JSON and return it in a Unicode string.
  82. """
  83. out = frozendict_json_encoder.encode(json_object)
  84. if isinstance(out, bytes):
  85. out = out.decode("utf8")
  86. return out
  87. class _EventPeristenceQueue(object):
  88. """Queues up events so that they can be persisted in bulk with only one
  89. concurrent transaction per room.
  90. """
  91. _EventPersistQueueItem = namedtuple(
  92. "_EventPersistQueueItem", ("events_and_contexts", "backfilled", "deferred")
  93. )
  94. def __init__(self):
  95. self._event_persist_queues = {}
  96. self._currently_persisting_rooms = set()
  97. def add_to_queue(self, room_id, events_and_contexts, backfilled):
  98. """Add events to the queue, with the given persist_event options.
  99. NB: due to the normal usage pattern of this method, it does *not*
  100. follow the synapse logcontext rules, and leaves the logcontext in
  101. place whether or not the returned deferred is ready.
  102. Args:
  103. room_id (str):
  104. events_and_contexts (list[(EventBase, EventContext)]):
  105. backfilled (bool):
  106. Returns:
  107. defer.Deferred: a deferred which will resolve once the events are
  108. persisted. Runs its callbacks *without* a logcontext.
  109. """
  110. queue = self._event_persist_queues.setdefault(room_id, deque())
  111. if queue:
  112. # if the last item in the queue has the same `backfilled` setting,
  113. # we can just add these new events to that item.
  114. end_item = queue[-1]
  115. if end_item.backfilled == backfilled:
  116. end_item.events_and_contexts.extend(events_and_contexts)
  117. return end_item.deferred.observe()
  118. deferred = ObservableDeferred(defer.Deferred(), consumeErrors=True)
  119. queue.append(
  120. self._EventPersistQueueItem(
  121. events_and_contexts=events_and_contexts,
  122. backfilled=backfilled,
  123. deferred=deferred,
  124. )
  125. )
  126. return deferred.observe()
  127. def handle_queue(self, room_id, per_item_callback):
  128. """Attempts to handle the queue for a room if not already being handled.
  129. The given callback will be invoked with for each item in the queue,
  130. of type _EventPersistQueueItem. The per_item_callback will continuously
  131. be called with new items, unless the queue becomnes empty. The return
  132. value of the function will be given to the deferreds waiting on the item,
  133. exceptions will be passed to the deferreds as well.
  134. This function should therefore be called whenever anything is added
  135. to the queue.
  136. If another callback is currently handling the queue then it will not be
  137. invoked.
  138. """
  139. if room_id in self._currently_persisting_rooms:
  140. return
  141. self._currently_persisting_rooms.add(room_id)
  142. @defer.inlineCallbacks
  143. def handle_queue_loop():
  144. try:
  145. queue = self._get_drainining_queue(room_id)
  146. for item in queue:
  147. try:
  148. ret = yield per_item_callback(item)
  149. except Exception:
  150. with PreserveLoggingContext():
  151. item.deferred.errback()
  152. else:
  153. with PreserveLoggingContext():
  154. item.deferred.callback(ret)
  155. finally:
  156. queue = self._event_persist_queues.pop(room_id, None)
  157. if queue:
  158. self._event_persist_queues[room_id] = queue
  159. self._currently_persisting_rooms.discard(room_id)
  160. # set handle_queue_loop off in the background
  161. run_as_background_process("persist_events", handle_queue_loop)
  162. def _get_drainining_queue(self, room_id):
  163. queue = self._event_persist_queues.setdefault(room_id, deque())
  164. try:
  165. while True:
  166. yield queue.popleft()
  167. except IndexError:
  168. # Queue has been drained.
  169. pass
  170. _EventCacheEntry = namedtuple("_EventCacheEntry", ("event", "redacted_event"))
  171. def _retry_on_integrity_error(func):
  172. """Wraps a database function so that it gets retried on IntegrityError,
  173. with `delete_existing=True` passed in.
  174. Args:
  175. func: function that returns a Deferred and accepts a `delete_existing` arg
  176. """
  177. @wraps(func)
  178. @defer.inlineCallbacks
  179. def f(self, *args, **kwargs):
  180. try:
  181. res = yield func(self, *args, **kwargs)
  182. except self.database_engine.module.IntegrityError:
  183. logger.exception("IntegrityError, retrying.")
  184. res = yield func(self, *args, delete_existing=True, **kwargs)
  185. return res
  186. return f
  187. # inherits from EventFederationStore so that we can call _update_backward_extremities
  188. # and _handle_mult_prev_events (though arguably those could both be moved in here)
  189. class EventsStore(
  190. StateGroupWorkerStore,
  191. EventFederationStore,
  192. EventsWorkerStore,
  193. BackgroundUpdateStore,
  194. ):
  195. def __init__(self, db_conn, hs):
  196. super(EventsStore, self).__init__(db_conn, hs)
  197. self._event_persist_queue = _EventPeristenceQueue()
  198. self._state_resolution_handler = hs.get_state_resolution_handler()
  199. # Collect metrics on the number of forward extremities that exist.
  200. # Counter of number of extremities to count
  201. self._current_forward_extremities_amount = c_counter()
  202. BucketCollector(
  203. "synapse_forward_extremities",
  204. lambda: self._current_forward_extremities_amount,
  205. buckets=[1, 2, 3, 5, 7, 10, 15, 20, 50, 100, 200, 500, "+Inf"],
  206. )
  207. # Read the extrems every 60 minutes
  208. def read_forward_extremities():
  209. # run as a background process to make sure that the database transactions
  210. # have a logcontext to report to
  211. return run_as_background_process(
  212. "read_forward_extremities", self._read_forward_extremities
  213. )
  214. hs.get_clock().looping_call(read_forward_extremities, 60 * 60 * 1000)
  215. @defer.inlineCallbacks
  216. def _read_forward_extremities(self):
  217. def fetch(txn):
  218. txn.execute(
  219. """
  220. select count(*) c from event_forward_extremities
  221. group by room_id
  222. """
  223. )
  224. return txn.fetchall()
  225. res = yield self.runInteraction("read_forward_extremities", fetch)
  226. self._current_forward_extremities_amount = c_counter(list(x[0] for x in res))
  227. @defer.inlineCallbacks
  228. def persist_events(self, events_and_contexts, backfilled=False):
  229. """
  230. Write events to the database
  231. Args:
  232. events_and_contexts: list of tuples of (event, context)
  233. backfilled (bool): Whether the results are retrieved from federation
  234. via backfill or not. Used to determine if they're "new" events
  235. which might update the current state etc.
  236. Returns:
  237. Deferred[int]: the stream ordering of the latest persisted event
  238. """
  239. partitioned = {}
  240. for event, ctx in events_and_contexts:
  241. partitioned.setdefault(event.room_id, []).append((event, ctx))
  242. deferreds = []
  243. for room_id, evs_ctxs in iteritems(partitioned):
  244. d = self._event_persist_queue.add_to_queue(
  245. room_id, evs_ctxs, backfilled=backfilled
  246. )
  247. deferreds.append(d)
  248. for room_id in partitioned:
  249. self._maybe_start_persisting(room_id)
  250. yield make_deferred_yieldable(
  251. defer.gatherResults(deferreds, consumeErrors=True)
  252. )
  253. max_persisted_id = yield self._stream_id_gen.get_current_token()
  254. return max_persisted_id
  255. @defer.inlineCallbacks
  256. @log_function
  257. def persist_event(self, event, context, backfilled=False):
  258. """
  259. Args:
  260. event (EventBase):
  261. context (EventContext):
  262. backfilled (bool):
  263. Returns:
  264. Deferred: resolves to (int, int): the stream ordering of ``event``,
  265. and the stream ordering of the latest persisted event
  266. """
  267. deferred = self._event_persist_queue.add_to_queue(
  268. event.room_id, [(event, context)], backfilled=backfilled
  269. )
  270. self._maybe_start_persisting(event.room_id)
  271. yield make_deferred_yieldable(deferred)
  272. max_persisted_id = yield self._stream_id_gen.get_current_token()
  273. return (event.internal_metadata.stream_ordering, max_persisted_id)
  274. def _maybe_start_persisting(self, room_id):
  275. @defer.inlineCallbacks
  276. def persisting_queue(item):
  277. with Measure(self._clock, "persist_events"):
  278. yield self._persist_events(
  279. item.events_and_contexts, backfilled=item.backfilled
  280. )
  281. self._event_persist_queue.handle_queue(room_id, persisting_queue)
  282. @_retry_on_integrity_error
  283. @defer.inlineCallbacks
  284. def _persist_events(
  285. self, events_and_contexts, backfilled=False, delete_existing=False
  286. ):
  287. """Persist events to db
  288. Args:
  289. events_and_contexts (list[(EventBase, EventContext)]):
  290. backfilled (bool):
  291. delete_existing (bool):
  292. Returns:
  293. Deferred: resolves when the events have been persisted
  294. """
  295. if not events_and_contexts:
  296. return
  297. chunks = [
  298. events_and_contexts[x : x + 100]
  299. for x in range(0, len(events_and_contexts), 100)
  300. ]
  301. for chunk in chunks:
  302. # We can't easily parallelize these since different chunks
  303. # might contain the same event. :(
  304. # NB: Assumes that we are only persisting events for one room
  305. # at a time.
  306. # map room_id->list[event_ids] giving the new forward
  307. # extremities in each room
  308. new_forward_extremeties = {}
  309. # map room_id->(type,state_key)->event_id tracking the full
  310. # state in each room after adding these events.
  311. # This is simply used to prefill the get_current_state_ids
  312. # cache
  313. current_state_for_room = {}
  314. # map room_id->(to_delete, to_insert) where to_delete is a list
  315. # of type/state keys to remove from current state, and to_insert
  316. # is a map (type,key)->event_id giving the state delta in each
  317. # room
  318. state_delta_for_room = {}
  319. if not backfilled:
  320. with Measure(self._clock, "_calculate_state_and_extrem"):
  321. # Work out the new "current state" for each room.
  322. # We do this by working out what the new extremities are and then
  323. # calculating the state from that.
  324. events_by_room = {}
  325. for event, context in chunk:
  326. events_by_room.setdefault(event.room_id, []).append(
  327. (event, context)
  328. )
  329. for room_id, ev_ctx_rm in iteritems(events_by_room):
  330. latest_event_ids = yield self.get_latest_event_ids_in_room(
  331. room_id
  332. )
  333. new_latest_event_ids = yield self._calculate_new_extremities(
  334. room_id, ev_ctx_rm, latest_event_ids
  335. )
  336. latest_event_ids = set(latest_event_ids)
  337. if new_latest_event_ids == latest_event_ids:
  338. # No change in extremities, so no change in state
  339. continue
  340. # there should always be at least one forward extremity.
  341. # (except during the initial persistence of the send_join
  342. # results, in which case there will be no existing
  343. # extremities, so we'll `continue` above and skip this bit.)
  344. assert new_latest_event_ids, "No forward extremities left!"
  345. new_forward_extremeties[room_id] = new_latest_event_ids
  346. len_1 = (
  347. len(latest_event_ids) == 1
  348. and len(new_latest_event_ids) == 1
  349. )
  350. if len_1:
  351. all_single_prev_not_state = all(
  352. len(event.prev_event_ids()) == 1
  353. and not event.is_state()
  354. for event, ctx in ev_ctx_rm
  355. )
  356. # Don't bother calculating state if they're just
  357. # a long chain of single ancestor non-state events.
  358. if all_single_prev_not_state:
  359. continue
  360. state_delta_counter.inc()
  361. if len(new_latest_event_ids) == 1:
  362. state_delta_single_event_counter.inc()
  363. # This is a fairly handwavey check to see if we could
  364. # have guessed what the delta would have been when
  365. # processing one of these events.
  366. # What we're interested in is if the latest extremities
  367. # were the same when we created the event as they are
  368. # now. When this server creates a new event (as opposed
  369. # to receiving it over federation) it will use the
  370. # forward extremities as the prev_events, so we can
  371. # guess this by looking at the prev_events and checking
  372. # if they match the current forward extremities.
  373. for ev, _ in ev_ctx_rm:
  374. prev_event_ids = set(ev.prev_event_ids())
  375. if latest_event_ids == prev_event_ids:
  376. state_delta_reuse_delta_counter.inc()
  377. break
  378. logger.info("Calculating state delta for room %s", room_id)
  379. with Measure(
  380. self._clock, "persist_events.get_new_state_after_events"
  381. ):
  382. res = yield self._get_new_state_after_events(
  383. room_id,
  384. ev_ctx_rm,
  385. latest_event_ids,
  386. new_latest_event_ids,
  387. )
  388. current_state, delta_ids = res
  389. # If either are not None then there has been a change,
  390. # and we need to work out the delta (or use that
  391. # given)
  392. if delta_ids is not None:
  393. # If there is a delta we know that we've
  394. # only added or replaced state, never
  395. # removed keys entirely.
  396. state_delta_for_room[room_id] = ([], delta_ids)
  397. elif current_state is not None:
  398. with Measure(
  399. self._clock, "persist_events.calculate_state_delta"
  400. ):
  401. delta = yield self._calculate_state_delta(
  402. room_id, current_state
  403. )
  404. state_delta_for_room[room_id] = delta
  405. # If we have the current_state then lets prefill
  406. # the cache with it.
  407. if current_state is not None:
  408. current_state_for_room[room_id] = current_state
  409. # We want to calculate the stream orderings as late as possible, as
  410. # we only notify after all events with a lesser stream ordering have
  411. # been persisted. I.e. if we spend 10s inside the with block then
  412. # that will delay all subsequent events from being notified about.
  413. # Hence why we do it down here rather than wrapping the entire
  414. # function.
  415. #
  416. # Its safe to do this after calculating the state deltas etc as we
  417. # only need to protect the *persistence* of the events. This is to
  418. # ensure that queries of the form "fetch events since X" don't
  419. # return events and stream positions after events that are still in
  420. # flight, as otherwise subsequent requests "fetch event since Y"
  421. # will not return those events.
  422. #
  423. # Note: Multiple instances of this function cannot be in flight at
  424. # the same time for the same room.
  425. if backfilled:
  426. stream_ordering_manager = self._backfill_id_gen.get_next_mult(
  427. len(chunk)
  428. )
  429. else:
  430. stream_ordering_manager = self._stream_id_gen.get_next_mult(len(chunk))
  431. with stream_ordering_manager as stream_orderings:
  432. for (event, context), stream in zip(chunk, stream_orderings):
  433. event.internal_metadata.stream_ordering = stream
  434. yield self.runInteraction(
  435. "persist_events",
  436. self._persist_events_txn,
  437. events_and_contexts=chunk,
  438. backfilled=backfilled,
  439. delete_existing=delete_existing,
  440. state_delta_for_room=state_delta_for_room,
  441. new_forward_extremeties=new_forward_extremeties,
  442. )
  443. persist_event_counter.inc(len(chunk))
  444. if not backfilled:
  445. # backfilled events have negative stream orderings, so we don't
  446. # want to set the event_persisted_position to that.
  447. synapse.metrics.event_persisted_position.set(
  448. chunk[-1][0].internal_metadata.stream_ordering
  449. )
  450. for event, context in chunk:
  451. if context.app_service:
  452. origin_type = "local"
  453. origin_entity = context.app_service.id
  454. elif self.hs.is_mine_id(event.sender):
  455. origin_type = "local"
  456. origin_entity = "*client*"
  457. else:
  458. origin_type = "remote"
  459. origin_entity = get_domain_from_id(event.sender)
  460. event_counter.labels(event.type, origin_type, origin_entity).inc()
  461. for room_id, new_state in iteritems(current_state_for_room):
  462. self.get_current_state_ids.prefill((room_id,), new_state)
  463. for room_id, latest_event_ids in iteritems(new_forward_extremeties):
  464. self.get_latest_event_ids_in_room.prefill(
  465. (room_id,), list(latest_event_ids)
  466. )
  467. @defer.inlineCallbacks
  468. def _calculate_new_extremities(self, room_id, event_contexts, latest_event_ids):
  469. """Calculates the new forward extremities for a room given events to
  470. persist.
  471. Assumes that we are only persisting events for one room at a time.
  472. """
  473. # we're only interested in new events which aren't outliers and which aren't
  474. # being rejected.
  475. new_events = [
  476. event
  477. for event, ctx in event_contexts
  478. if not event.internal_metadata.is_outlier()
  479. and not ctx.rejected
  480. and not event.internal_metadata.is_soft_failed()
  481. ]
  482. latest_event_ids = set(latest_event_ids)
  483. # start with the existing forward extremities
  484. result = set(latest_event_ids)
  485. # add all the new events to the list
  486. result.update(event.event_id for event in new_events)
  487. # Now remove all events which are prev_events of any of the new events
  488. result.difference_update(
  489. e_id for event in new_events for e_id in event.prev_event_ids()
  490. )
  491. # Remove any events which are prev_events of any existing events.
  492. existing_prevs = yield self._get_events_which_are_prevs(result)
  493. result.difference_update(existing_prevs)
  494. # Finally handle the case where the new events have soft-failed prev
  495. # events. If they do we need to remove them and their prev events,
  496. # otherwise we end up with dangling extremities.
  497. existing_prevs = yield self._get_prevs_before_rejected(
  498. e_id for event in new_events for e_id in event.prev_event_ids()
  499. )
  500. result.difference_update(existing_prevs)
  501. # We only update metrics for events that change forward extremities
  502. # (e.g. we ignore backfill/outliers/etc)
  503. if result != latest_event_ids:
  504. forward_extremities_counter.observe(len(result))
  505. stale = latest_event_ids & result
  506. stale_forward_extremities_counter.observe(len(stale))
  507. return result
  508. @defer.inlineCallbacks
  509. def _get_events_which_are_prevs(self, event_ids):
  510. """Filter the supplied list of event_ids to get those which are prev_events of
  511. existing (non-outlier/rejected) events.
  512. Args:
  513. event_ids (Iterable[str]): event ids to filter
  514. Returns:
  515. Deferred[List[str]]: filtered event ids
  516. """
  517. results = []
  518. def _get_events_which_are_prevs_txn(txn, batch):
  519. sql = """
  520. SELECT prev_event_id, internal_metadata
  521. FROM event_edges
  522. INNER JOIN events USING (event_id)
  523. LEFT JOIN rejections USING (event_id)
  524. LEFT JOIN event_json USING (event_id)
  525. WHERE
  526. prev_event_id IN (%s)
  527. AND NOT events.outlier
  528. AND rejections.event_id IS NULL
  529. """ % (
  530. ",".join("?" for _ in batch),
  531. )
  532. txn.execute(sql, batch)
  533. results.extend(r[0] for r in txn if not json.loads(r[1]).get("soft_failed"))
  534. for chunk in batch_iter(event_ids, 100):
  535. yield self.runInteraction(
  536. "_get_events_which_are_prevs", _get_events_which_are_prevs_txn, chunk
  537. )
  538. return results
  539. @defer.inlineCallbacks
  540. def _get_prevs_before_rejected(self, event_ids):
  541. """Get soft-failed ancestors to remove from the extremities.
  542. Given a set of events, find all those that have been soft-failed or
  543. rejected. Returns those soft failed/rejected events and their prev
  544. events (whether soft-failed/rejected or not), and recurses up the
  545. prev-event graph until it finds no more soft-failed/rejected events.
  546. This is used to find extremities that are ancestors of new events, but
  547. are separated by soft failed events.
  548. Args:
  549. event_ids (Iterable[str]): Events to find prev events for. Note
  550. that these must have already been persisted.
  551. Returns:
  552. Deferred[set[str]]
  553. """
  554. # The set of event_ids to return. This includes all soft-failed events
  555. # and their prev events.
  556. existing_prevs = set()
  557. def _get_prevs_before_rejected_txn(txn, batch):
  558. to_recursively_check = batch
  559. while to_recursively_check:
  560. sql = """
  561. SELECT
  562. event_id, prev_event_id, internal_metadata,
  563. rejections.event_id IS NOT NULL
  564. FROM event_edges
  565. INNER JOIN events USING (event_id)
  566. LEFT JOIN rejections USING (event_id)
  567. LEFT JOIN event_json USING (event_id)
  568. WHERE
  569. event_id IN (%s)
  570. AND NOT events.outlier
  571. """ % (
  572. ",".join("?" for _ in to_recursively_check),
  573. )
  574. txn.execute(sql, to_recursively_check)
  575. to_recursively_check = []
  576. for event_id, prev_event_id, metadata, rejected in txn:
  577. if prev_event_id in existing_prevs:
  578. continue
  579. soft_failed = json.loads(metadata).get("soft_failed")
  580. if soft_failed or rejected:
  581. to_recursively_check.append(prev_event_id)
  582. existing_prevs.add(prev_event_id)
  583. for chunk in batch_iter(event_ids, 100):
  584. yield self.runInteraction(
  585. "_get_prevs_before_rejected", _get_prevs_before_rejected_txn, chunk
  586. )
  587. return existing_prevs
  588. @defer.inlineCallbacks
  589. def _get_new_state_after_events(
  590. self, room_id, events_context, old_latest_event_ids, new_latest_event_ids
  591. ):
  592. """Calculate the current state dict after adding some new events to
  593. a room
  594. Args:
  595. room_id (str):
  596. room to which the events are being added. Used for logging etc
  597. events_context (list[(EventBase, EventContext)]):
  598. events and contexts which are being added to the room
  599. old_latest_event_ids (iterable[str]):
  600. the old forward extremities for the room.
  601. new_latest_event_ids (iterable[str]):
  602. the new forward extremities for the room.
  603. Returns:
  604. Deferred[tuple[dict[(str,str), str]|None, dict[(str,str), str]|None]]:
  605. Returns a tuple of two state maps, the first being the full new current
  606. state and the second being the delta to the existing current state.
  607. If both are None then there has been no change.
  608. If there has been a change then we only return the delta if its
  609. already been calculated. Conversely if we do know the delta then
  610. the new current state is only returned if we've already calculated
  611. it.
  612. """
  613. # map from state_group to ((type, key) -> event_id) state map
  614. state_groups_map = {}
  615. # Map from (prev state group, new state group) -> delta state dict
  616. state_group_deltas = {}
  617. for ev, ctx in events_context:
  618. if ctx.state_group is None:
  619. # This should only happen for outlier events.
  620. if not ev.internal_metadata.is_outlier():
  621. raise Exception(
  622. "Context for new event %s has no state "
  623. "group" % (ev.event_id,)
  624. )
  625. continue
  626. if ctx.state_group in state_groups_map:
  627. continue
  628. # We're only interested in pulling out state that has already
  629. # been cached in the context. We'll pull stuff out of the DB later
  630. # if necessary.
  631. current_state_ids = ctx.get_cached_current_state_ids()
  632. if current_state_ids is not None:
  633. state_groups_map[ctx.state_group] = current_state_ids
  634. if ctx.prev_group:
  635. state_group_deltas[(ctx.prev_group, ctx.state_group)] = ctx.delta_ids
  636. # We need to map the event_ids to their state groups. First, let's
  637. # check if the event is one we're persisting, in which case we can
  638. # pull the state group from its context.
  639. # Otherwise we need to pull the state group from the database.
  640. # Set of events we need to fetch groups for. (We know none of the old
  641. # extremities are going to be in events_context).
  642. missing_event_ids = set(old_latest_event_ids)
  643. event_id_to_state_group = {}
  644. for event_id in new_latest_event_ids:
  645. # First search in the list of new events we're adding.
  646. for ev, ctx in events_context:
  647. if event_id == ev.event_id and ctx.state_group is not None:
  648. event_id_to_state_group[event_id] = ctx.state_group
  649. break
  650. else:
  651. # If we couldn't find it, then we'll need to pull
  652. # the state from the database
  653. missing_event_ids.add(event_id)
  654. if missing_event_ids:
  655. # Now pull out the state groups for any missing events from DB
  656. event_to_groups = yield self._get_state_group_for_events(missing_event_ids)
  657. event_id_to_state_group.update(event_to_groups)
  658. # State groups of old_latest_event_ids
  659. old_state_groups = set(
  660. event_id_to_state_group[evid] for evid in old_latest_event_ids
  661. )
  662. # State groups of new_latest_event_ids
  663. new_state_groups = set(
  664. event_id_to_state_group[evid] for evid in new_latest_event_ids
  665. )
  666. # If they old and new groups are the same then we don't need to do
  667. # anything.
  668. if old_state_groups == new_state_groups:
  669. return (None, None)
  670. if len(new_state_groups) == 1 and len(old_state_groups) == 1:
  671. # If we're going from one state group to another, lets check if
  672. # we have a delta for that transition. If we do then we can just
  673. # return that.
  674. new_state_group = next(iter(new_state_groups))
  675. old_state_group = next(iter(old_state_groups))
  676. delta_ids = state_group_deltas.get((old_state_group, new_state_group), None)
  677. if delta_ids is not None:
  678. # We have a delta from the existing to new current state,
  679. # so lets just return that. If we happen to already have
  680. # the current state in memory then lets also return that,
  681. # but it doesn't matter if we don't.
  682. new_state = state_groups_map.get(new_state_group)
  683. return (new_state, delta_ids)
  684. # Now that we have calculated new_state_groups we need to get
  685. # their state IDs so we can resolve to a single state set.
  686. missing_state = new_state_groups - set(state_groups_map)
  687. if missing_state:
  688. group_to_state = yield self._get_state_for_groups(missing_state)
  689. state_groups_map.update(group_to_state)
  690. if len(new_state_groups) == 1:
  691. # If there is only one state group, then we know what the current
  692. # state is.
  693. return (state_groups_map[new_state_groups.pop()], None)
  694. # Ok, we need to defer to the state handler to resolve our state sets.
  695. state_groups = {sg: state_groups_map[sg] for sg in new_state_groups}
  696. events_map = {ev.event_id: ev for ev, _ in events_context}
  697. # We need to get the room version, which is in the create event.
  698. # Normally that'd be in the database, but its also possible that we're
  699. # currently trying to persist it.
  700. room_version = None
  701. for ev, _ in events_context:
  702. if ev.type == EventTypes.Create and ev.state_key == "":
  703. room_version = ev.content.get("room_version", "1")
  704. break
  705. if not room_version:
  706. room_version = yield self.get_room_version(room_id)
  707. logger.debug("calling resolve_state_groups from preserve_events")
  708. res = yield self._state_resolution_handler.resolve_state_groups(
  709. room_id,
  710. room_version,
  711. state_groups,
  712. events_map,
  713. state_res_store=StateResolutionStore(self),
  714. )
  715. return (res.state, None)
  716. @defer.inlineCallbacks
  717. def _calculate_state_delta(self, room_id, current_state):
  718. """Calculate the new state deltas for a room.
  719. Assumes that we are only persisting events for one room at a time.
  720. Returns:
  721. tuple[list, dict] (to_delete, to_insert): where to_delete are the
  722. type/state_keys to remove from current_state_events and `to_insert`
  723. are the updates to current_state_events.
  724. """
  725. existing_state = yield self.get_current_state_ids(room_id)
  726. to_delete = [key for key in existing_state if key not in current_state]
  727. to_insert = {
  728. key: ev_id
  729. for key, ev_id in iteritems(current_state)
  730. if ev_id != existing_state.get(key)
  731. }
  732. return (to_delete, to_insert)
  733. @log_function
  734. def _persist_events_txn(
  735. self,
  736. txn,
  737. events_and_contexts,
  738. backfilled,
  739. delete_existing=False,
  740. state_delta_for_room={},
  741. new_forward_extremeties={},
  742. ):
  743. """Insert some number of room events into the necessary database tables.
  744. Rejected events are only inserted into the events table, the events_json table,
  745. and the rejections table. Things reading from those table will need to check
  746. whether the event was rejected.
  747. Args:
  748. txn (twisted.enterprise.adbapi.Connection): db connection
  749. events_and_contexts (list[(EventBase, EventContext)]):
  750. events to persist
  751. backfilled (bool): True if the events were backfilled
  752. delete_existing (bool): True to purge existing table rows for the
  753. events from the database. This is useful when retrying due to
  754. IntegrityError.
  755. state_delta_for_room (dict[str, (list, dict)]):
  756. The current-state delta for each room. For each room, a tuple
  757. (to_delete, to_insert), being a list of type/state keys to be
  758. removed from the current state, and a state set to be added to
  759. the current state.
  760. new_forward_extremeties (dict[str, list[str]]):
  761. The new forward extremities for each room. For each room, a
  762. list of the event ids which are the forward extremities.
  763. """
  764. all_events_and_contexts = events_and_contexts
  765. min_stream_order = events_and_contexts[0][0].internal_metadata.stream_ordering
  766. max_stream_order = events_and_contexts[-1][0].internal_metadata.stream_ordering
  767. self._update_forward_extremities_txn(
  768. txn,
  769. new_forward_extremities=new_forward_extremeties,
  770. max_stream_order=max_stream_order,
  771. )
  772. # Ensure that we don't have the same event twice.
  773. events_and_contexts = self._filter_events_and_contexts_for_duplicates(
  774. events_and_contexts
  775. )
  776. self._update_room_depths_txn(
  777. txn, events_and_contexts=events_and_contexts, backfilled=backfilled
  778. )
  779. # _update_outliers_txn filters out any events which have already been
  780. # persisted, and returns the filtered list.
  781. events_and_contexts = self._update_outliers_txn(
  782. txn, events_and_contexts=events_and_contexts
  783. )
  784. # From this point onwards the events are only events that we haven't
  785. # seen before.
  786. if delete_existing:
  787. # For paranoia reasons, we go and delete all the existing entries
  788. # for these events so we can reinsert them.
  789. # This gets around any problems with some tables already having
  790. # entries.
  791. self._delete_existing_rows_txn(txn, events_and_contexts=events_and_contexts)
  792. self._store_event_txn(txn, events_and_contexts=events_and_contexts)
  793. # Insert into event_to_state_groups.
  794. self._store_event_state_mappings_txn(txn, events_and_contexts)
  795. # We want to store event_auth mappings for rejected events, as they're
  796. # used in state res v2.
  797. # This is only necessary if the rejected event appears in an accepted
  798. # event's auth chain, but its easier for now just to store them (and
  799. # it doesn't take much storage compared to storing the entire event
  800. # anyway).
  801. self._simple_insert_many_txn(
  802. txn,
  803. table="event_auth",
  804. values=[
  805. {
  806. "event_id": event.event_id,
  807. "room_id": event.room_id,
  808. "auth_id": auth_id,
  809. }
  810. for event, _ in events_and_contexts
  811. for auth_id in event.auth_event_ids()
  812. if event.is_state()
  813. ],
  814. )
  815. # _store_rejected_events_txn filters out any events which were
  816. # rejected, and returns the filtered list.
  817. events_and_contexts = self._store_rejected_events_txn(
  818. txn, events_and_contexts=events_and_contexts
  819. )
  820. # From this point onwards the events are only ones that weren't
  821. # rejected.
  822. self._update_metadata_tables_txn(
  823. txn,
  824. events_and_contexts=events_and_contexts,
  825. all_events_and_contexts=all_events_and_contexts,
  826. backfilled=backfilled,
  827. )
  828. # We call this last as it assumes we've inserted the events into
  829. # room_memberships, where applicable.
  830. self._update_current_state_txn(txn, state_delta_for_room, min_stream_order)
  831. def _update_current_state_txn(self, txn, state_delta_by_room, stream_id):
  832. for room_id, current_state_tuple in iteritems(state_delta_by_room):
  833. to_delete, to_insert = current_state_tuple
  834. # First we add entries to the current_state_delta_stream. We
  835. # do this before updating the current_state_events table so
  836. # that we can use it to calculate the `prev_event_id`. (This
  837. # allows us to not have to pull out the existing state
  838. # unnecessarily).
  839. #
  840. # The stream_id for the update is chosen to be the minimum of the stream_ids
  841. # for the batch of the events that we are persisting; that means we do not
  842. # end up in a situation where workers see events before the
  843. # current_state_delta updates.
  844. #
  845. sql = """
  846. INSERT INTO current_state_delta_stream
  847. (stream_id, room_id, type, state_key, event_id, prev_event_id)
  848. SELECT ?, ?, ?, ?, ?, (
  849. SELECT event_id FROM current_state_events
  850. WHERE room_id = ? AND type = ? AND state_key = ?
  851. )
  852. """
  853. txn.executemany(
  854. sql,
  855. (
  856. (
  857. stream_id,
  858. room_id,
  859. etype,
  860. state_key,
  861. None,
  862. room_id,
  863. etype,
  864. state_key,
  865. )
  866. for etype, state_key in to_delete
  867. # We sanity check that we're deleting rather than updating
  868. if (etype, state_key) not in to_insert
  869. ),
  870. )
  871. txn.executemany(
  872. sql,
  873. (
  874. (
  875. stream_id,
  876. room_id,
  877. etype,
  878. state_key,
  879. ev_id,
  880. room_id,
  881. etype,
  882. state_key,
  883. )
  884. for (etype, state_key), ev_id in iteritems(to_insert)
  885. ),
  886. )
  887. # Now we actually update the current_state_events table
  888. txn.executemany(
  889. "DELETE FROM current_state_events"
  890. " WHERE room_id = ? AND type = ? AND state_key = ?",
  891. (
  892. (room_id, etype, state_key)
  893. for etype, state_key in itertools.chain(to_delete, to_insert)
  894. ),
  895. )
  896. # We include the membership in the current state table, hence we do
  897. # a lookup when we insert. This assumes that all events have already
  898. # been inserted into room_memberships.
  899. txn.executemany(
  900. """INSERT INTO current_state_events
  901. (room_id, type, state_key, event_id, membership)
  902. VALUES (?, ?, ?, ?, (SELECT membership FROM room_memberships WHERE event_id = ?))
  903. """,
  904. [
  905. (room_id, key[0], key[1], ev_id, ev_id)
  906. for key, ev_id in iteritems(to_insert)
  907. ],
  908. )
  909. txn.call_after(
  910. self._curr_state_delta_stream_cache.entity_has_changed,
  911. room_id,
  912. stream_id,
  913. )
  914. # Invalidate the various caches
  915. # Figure out the changes of membership to invalidate the
  916. # `get_rooms_for_user` cache.
  917. # We find out which membership events we may have deleted
  918. # and which we have added, then we invlidate the caches for all
  919. # those users.
  920. members_changed = set(
  921. state_key
  922. for ev_type, state_key in itertools.chain(to_delete, to_insert)
  923. if ev_type == EventTypes.Member
  924. )
  925. for member in members_changed:
  926. txn.call_after(
  927. self.get_rooms_for_user_with_stream_ordering.invalidate, (member,)
  928. )
  929. self._invalidate_state_caches_and_stream(txn, room_id, members_changed)
  930. def _update_forward_extremities_txn(
  931. self, txn, new_forward_extremities, max_stream_order
  932. ):
  933. for room_id, new_extrem in iteritems(new_forward_extremities):
  934. self._simple_delete_txn(
  935. txn, table="event_forward_extremities", keyvalues={"room_id": room_id}
  936. )
  937. txn.call_after(self.get_latest_event_ids_in_room.invalidate, (room_id,))
  938. self._simple_insert_many_txn(
  939. txn,
  940. table="event_forward_extremities",
  941. values=[
  942. {"event_id": ev_id, "room_id": room_id}
  943. for room_id, new_extrem in iteritems(new_forward_extremities)
  944. for ev_id in new_extrem
  945. ],
  946. )
  947. # We now insert into stream_ordering_to_exterm a mapping from room_id,
  948. # new stream_ordering to new forward extremeties in the room.
  949. # This allows us to later efficiently look up the forward extremeties
  950. # for a room before a given stream_ordering
  951. self._simple_insert_many_txn(
  952. txn,
  953. table="stream_ordering_to_exterm",
  954. values=[
  955. {
  956. "room_id": room_id,
  957. "event_id": event_id,
  958. "stream_ordering": max_stream_order,
  959. }
  960. for room_id, new_extrem in iteritems(new_forward_extremities)
  961. for event_id in new_extrem
  962. ],
  963. )
  964. @classmethod
  965. def _filter_events_and_contexts_for_duplicates(cls, events_and_contexts):
  966. """Ensure that we don't have the same event twice.
  967. Pick the earliest non-outlier if there is one, else the earliest one.
  968. Args:
  969. events_and_contexts (list[(EventBase, EventContext)]):
  970. Returns:
  971. list[(EventBase, EventContext)]: filtered list
  972. """
  973. new_events_and_contexts = OrderedDict()
  974. for event, context in events_and_contexts:
  975. prev_event_context = new_events_and_contexts.get(event.event_id)
  976. if prev_event_context:
  977. if not event.internal_metadata.is_outlier():
  978. if prev_event_context[0].internal_metadata.is_outlier():
  979. # To ensure correct ordering we pop, as OrderedDict is
  980. # ordered by first insertion.
  981. new_events_and_contexts.pop(event.event_id, None)
  982. new_events_and_contexts[event.event_id] = (event, context)
  983. else:
  984. new_events_and_contexts[event.event_id] = (event, context)
  985. return list(new_events_and_contexts.values())
  986. def _update_room_depths_txn(self, txn, events_and_contexts, backfilled):
  987. """Update min_depth for each room
  988. Args:
  989. txn (twisted.enterprise.adbapi.Connection): db connection
  990. events_and_contexts (list[(EventBase, EventContext)]): events
  991. we are persisting
  992. backfilled (bool): True if the events were backfilled
  993. """
  994. depth_updates = {}
  995. for event, context in events_and_contexts:
  996. # Remove the any existing cache entries for the event_ids
  997. txn.call_after(self._invalidate_get_event_cache, event.event_id)
  998. if not backfilled:
  999. txn.call_after(
  1000. self._events_stream_cache.entity_has_changed,
  1001. event.room_id,
  1002. event.internal_metadata.stream_ordering,
  1003. )
  1004. if not event.internal_metadata.is_outlier() and not context.rejected:
  1005. depth_updates[event.room_id] = max(
  1006. event.depth, depth_updates.get(event.room_id, event.depth)
  1007. )
  1008. for room_id, depth in iteritems(depth_updates):
  1009. self._update_min_depth_for_room_txn(txn, room_id, depth)
  1010. def _update_outliers_txn(self, txn, events_and_contexts):
  1011. """Update any outliers with new event info.
  1012. This turns outliers into ex-outliers (unless the new event was
  1013. rejected).
  1014. Args:
  1015. txn (twisted.enterprise.adbapi.Connection): db connection
  1016. events_and_contexts (list[(EventBase, EventContext)]): events
  1017. we are persisting
  1018. Returns:
  1019. list[(EventBase, EventContext)] new list, without events which
  1020. are already in the events table.
  1021. """
  1022. txn.execute(
  1023. "SELECT event_id, outlier FROM events WHERE event_id in (%s)"
  1024. % (",".join(["?"] * len(events_and_contexts)),),
  1025. [event.event_id for event, _ in events_and_contexts],
  1026. )
  1027. have_persisted = {event_id: outlier for event_id, outlier in txn}
  1028. to_remove = set()
  1029. for event, context in events_and_contexts:
  1030. if event.event_id not in have_persisted:
  1031. continue
  1032. to_remove.add(event)
  1033. if context.rejected:
  1034. # If the event is rejected then we don't care if the event
  1035. # was an outlier or not.
  1036. continue
  1037. outlier_persisted = have_persisted[event.event_id]
  1038. if not event.internal_metadata.is_outlier() and outlier_persisted:
  1039. # We received a copy of an event that we had already stored as
  1040. # an outlier in the database. We now have some state at that
  1041. # so we need to update the state_groups table with that state.
  1042. # insert into event_to_state_groups.
  1043. try:
  1044. self._store_event_state_mappings_txn(txn, ((event, context),))
  1045. except Exception:
  1046. logger.exception("")
  1047. raise
  1048. metadata_json = encode_json(event.internal_metadata.get_dict())
  1049. sql = (
  1050. "UPDATE event_json SET internal_metadata = ?" " WHERE event_id = ?"
  1051. )
  1052. txn.execute(sql, (metadata_json, event.event_id))
  1053. # Add an entry to the ex_outlier_stream table to replicate the
  1054. # change in outlier status to our workers.
  1055. stream_order = event.internal_metadata.stream_ordering
  1056. state_group_id = context.state_group
  1057. self._simple_insert_txn(
  1058. txn,
  1059. table="ex_outlier_stream",
  1060. values={
  1061. "event_stream_ordering": stream_order,
  1062. "event_id": event.event_id,
  1063. "state_group": state_group_id,
  1064. },
  1065. )
  1066. sql = "UPDATE events SET outlier = ?" " WHERE event_id = ?"
  1067. txn.execute(sql, (False, event.event_id))
  1068. # Update the event_backward_extremities table now that this
  1069. # event isn't an outlier any more.
  1070. self._update_backward_extremeties(txn, [event])
  1071. return [ec for ec in events_and_contexts if ec[0] not in to_remove]
  1072. @classmethod
  1073. def _delete_existing_rows_txn(cls, txn, events_and_contexts):
  1074. if not events_and_contexts:
  1075. # nothing to do here
  1076. return
  1077. logger.info("Deleting existing")
  1078. for table in (
  1079. "events",
  1080. "event_auth",
  1081. "event_json",
  1082. "event_edges",
  1083. "event_forward_extremities",
  1084. "event_reference_hashes",
  1085. "event_search",
  1086. "event_to_state_groups",
  1087. "guest_access",
  1088. "history_visibility",
  1089. "local_invites",
  1090. "room_names",
  1091. "state_events",
  1092. "rejections",
  1093. "redactions",
  1094. "room_memberships",
  1095. "topics",
  1096. ):
  1097. txn.executemany(
  1098. "DELETE FROM %s WHERE event_id = ?" % (table,),
  1099. [(ev.event_id,) for ev, _ in events_and_contexts],
  1100. )
  1101. for table in ("event_push_actions",):
  1102. txn.executemany(
  1103. "DELETE FROM %s WHERE room_id = ? AND event_id = ?" % (table,),
  1104. [(ev.room_id, ev.event_id) for ev, _ in events_and_contexts],
  1105. )
  1106. def _store_event_txn(self, txn, events_and_contexts):
  1107. """Insert new events into the event and event_json tables
  1108. Args:
  1109. txn (twisted.enterprise.adbapi.Connection): db connection
  1110. events_and_contexts (list[(EventBase, EventContext)]): events
  1111. we are persisting
  1112. """
  1113. if not events_and_contexts:
  1114. # nothing to do here
  1115. return
  1116. def event_dict(event):
  1117. d = event.get_dict()
  1118. d.pop("redacted", None)
  1119. d.pop("redacted_because", None)
  1120. return d
  1121. self._simple_insert_many_txn(
  1122. txn,
  1123. table="event_json",
  1124. values=[
  1125. {
  1126. "event_id": event.event_id,
  1127. "room_id": event.room_id,
  1128. "internal_metadata": encode_json(
  1129. event.internal_metadata.get_dict()
  1130. ),
  1131. "json": encode_json(event_dict(event)),
  1132. "format_version": event.format_version,
  1133. }
  1134. for event, _ in events_and_contexts
  1135. ],
  1136. )
  1137. self._simple_insert_many_txn(
  1138. txn,
  1139. table="events",
  1140. values=[
  1141. {
  1142. "stream_ordering": event.internal_metadata.stream_ordering,
  1143. "topological_ordering": event.depth,
  1144. "depth": event.depth,
  1145. "event_id": event.event_id,
  1146. "room_id": event.room_id,
  1147. "type": event.type,
  1148. "processed": True,
  1149. "outlier": event.internal_metadata.is_outlier(),
  1150. "origin_server_ts": int(event.origin_server_ts),
  1151. "received_ts": self._clock.time_msec(),
  1152. "sender": event.sender,
  1153. "contains_url": (
  1154. "url" in event.content
  1155. and isinstance(event.content["url"], text_type)
  1156. ),
  1157. }
  1158. for event, _ in events_and_contexts
  1159. ],
  1160. )
  1161. def _store_rejected_events_txn(self, txn, events_and_contexts):
  1162. """Add rows to the 'rejections' table for received events which were
  1163. rejected
  1164. Args:
  1165. txn (twisted.enterprise.adbapi.Connection): db connection
  1166. events_and_contexts (list[(EventBase, EventContext)]): events
  1167. we are persisting
  1168. Returns:
  1169. list[(EventBase, EventContext)] new list, without the rejected
  1170. events.
  1171. """
  1172. # Remove the rejected events from the list now that we've added them
  1173. # to the events table and the events_json table.
  1174. to_remove = set()
  1175. for event, context in events_and_contexts:
  1176. if context.rejected:
  1177. # Insert the event_id into the rejections table
  1178. self._store_rejections_txn(txn, event.event_id, context.rejected)
  1179. to_remove.add(event)
  1180. return [ec for ec in events_and_contexts if ec[0] not in to_remove]
  1181. def _update_metadata_tables_txn(
  1182. self, txn, events_and_contexts, all_events_and_contexts, backfilled
  1183. ):
  1184. """Update all the miscellaneous tables for new events
  1185. Args:
  1186. txn (twisted.enterprise.adbapi.Connection): db connection
  1187. events_and_contexts (list[(EventBase, EventContext)]): events
  1188. we are persisting
  1189. all_events_and_contexts (list[(EventBase, EventContext)]): all
  1190. events that we were going to persist. This includes events
  1191. we've already persisted, etc, that wouldn't appear in
  1192. events_and_context.
  1193. backfilled (bool): True if the events were backfilled
  1194. """
  1195. # Insert all the push actions into the event_push_actions table.
  1196. self._set_push_actions_for_event_and_users_txn(
  1197. txn,
  1198. events_and_contexts=events_and_contexts,
  1199. all_events_and_contexts=all_events_and_contexts,
  1200. )
  1201. if not events_and_contexts:
  1202. # nothing to do here
  1203. return
  1204. for event, context in events_and_contexts:
  1205. if event.type == EventTypes.Redaction and event.redacts is not None:
  1206. # Remove the entries in the event_push_actions table for the
  1207. # redacted event.
  1208. self._remove_push_actions_for_event_id_txn(
  1209. txn, event.room_id, event.redacts
  1210. )
  1211. # Remove from relations table.
  1212. self._handle_redaction(txn, event.redacts)
  1213. # Update the event_forward_extremities, event_backward_extremities and
  1214. # event_edges tables.
  1215. self._handle_mult_prev_events(
  1216. txn, events=[event for event, _ in events_and_contexts]
  1217. )
  1218. for event, _ in events_and_contexts:
  1219. if event.type == EventTypes.Name:
  1220. # Insert into the room_names and event_search tables.
  1221. self._store_room_name_txn(txn, event)
  1222. elif event.type == EventTypes.Topic:
  1223. # Insert into the topics table and event_search table.
  1224. self._store_room_topic_txn(txn, event)
  1225. elif event.type == EventTypes.Message:
  1226. # Insert into the event_search table.
  1227. self._store_room_message_txn(txn, event)
  1228. elif event.type == EventTypes.Redaction:
  1229. # Insert into the redactions table.
  1230. self._store_redaction(txn, event)
  1231. elif event.type == EventTypes.RoomHistoryVisibility:
  1232. # Insert into the event_search table.
  1233. self._store_history_visibility_txn(txn, event)
  1234. elif event.type == EventTypes.GuestAccess:
  1235. # Insert into the event_search table.
  1236. self._store_guest_access_txn(txn, event)
  1237. self._handle_event_relations(txn, event)
  1238. # Insert into the room_memberships table.
  1239. self._store_room_members_txn(
  1240. txn,
  1241. [
  1242. event
  1243. for event, _ in events_and_contexts
  1244. if event.type == EventTypes.Member
  1245. ],
  1246. backfilled=backfilled,
  1247. )
  1248. # Insert event_reference_hashes table.
  1249. self._store_event_reference_hashes_txn(
  1250. txn, [event for event, _ in events_and_contexts]
  1251. )
  1252. state_events_and_contexts = [
  1253. ec for ec in events_and_contexts if ec[0].is_state()
  1254. ]
  1255. state_values = []
  1256. for event, context in state_events_and_contexts:
  1257. vals = {
  1258. "event_id": event.event_id,
  1259. "room_id": event.room_id,
  1260. "type": event.type,
  1261. "state_key": event.state_key,
  1262. }
  1263. # TODO: How does this work with backfilling?
  1264. if hasattr(event, "replaces_state"):
  1265. vals["prev_state"] = event.replaces_state
  1266. state_values.append(vals)
  1267. self._simple_insert_many_txn(txn, table="state_events", values=state_values)
  1268. # Prefill the event cache
  1269. self._add_to_cache(txn, events_and_contexts)
  1270. def _add_to_cache(self, txn, events_and_contexts):
  1271. to_prefill = []
  1272. rows = []
  1273. N = 200
  1274. for i in range(0, len(events_and_contexts), N):
  1275. ev_map = {e[0].event_id: e[0] for e in events_and_contexts[i : i + N]}
  1276. if not ev_map:
  1277. break
  1278. sql = (
  1279. "SELECT "
  1280. " e.event_id as event_id, "
  1281. " r.redacts as redacts,"
  1282. " rej.event_id as rejects "
  1283. " FROM events as e"
  1284. " LEFT JOIN rejections as rej USING (event_id)"
  1285. " LEFT JOIN redactions as r ON e.event_id = r.redacts"
  1286. " WHERE e.event_id IN (%s)"
  1287. ) % (",".join(["?"] * len(ev_map)),)
  1288. txn.execute(sql, list(ev_map))
  1289. rows = self.cursor_to_dict(txn)
  1290. for row in rows:
  1291. event = ev_map[row["event_id"]]
  1292. if not row["rejects"] and not row["redacts"]:
  1293. to_prefill.append(
  1294. _EventCacheEntry(event=event, redacted_event=None)
  1295. )
  1296. def prefill():
  1297. for cache_entry in to_prefill:
  1298. self._get_event_cache.prefill((cache_entry[0].event_id,), cache_entry)
  1299. txn.call_after(prefill)
  1300. def _store_redaction(self, txn, event):
  1301. # invalidate the cache for the redacted event
  1302. txn.call_after(self._invalidate_get_event_cache, event.redacts)
  1303. txn.execute(
  1304. "INSERT INTO redactions (event_id, redacts) VALUES (?,?)",
  1305. (event.event_id, event.redacts),
  1306. )
  1307. @defer.inlineCallbacks
  1308. def count_daily_messages(self):
  1309. """
  1310. Returns an estimate of the number of messages sent in the last day.
  1311. If it has been significantly less or more than one day since the last
  1312. call to this function, it will return None.
  1313. """
  1314. def _count_messages(txn):
  1315. sql = """
  1316. SELECT COALESCE(COUNT(*), 0) FROM events
  1317. WHERE type = 'm.room.message'
  1318. AND stream_ordering > ?
  1319. """
  1320. txn.execute(sql, (self.stream_ordering_day_ago,))
  1321. count, = txn.fetchone()
  1322. return count
  1323. ret = yield self.runInteraction("count_messages", _count_messages)
  1324. return ret
  1325. @defer.inlineCallbacks
  1326. def count_daily_sent_messages(self):
  1327. def _count_messages(txn):
  1328. # This is good enough as if you have silly characters in your own
  1329. # hostname then thats your own fault.
  1330. like_clause = "%:" + self.hs.hostname
  1331. sql = """
  1332. SELECT COALESCE(COUNT(*), 0) FROM events
  1333. WHERE type = 'm.room.message'
  1334. AND sender LIKE ?
  1335. AND stream_ordering > ?
  1336. """
  1337. txn.execute(sql, (like_clause, self.stream_ordering_day_ago))
  1338. count, = txn.fetchone()
  1339. return count
  1340. ret = yield self.runInteraction("count_daily_sent_messages", _count_messages)
  1341. return ret
  1342. @defer.inlineCallbacks
  1343. def count_daily_active_rooms(self):
  1344. def _count(txn):
  1345. sql = """
  1346. SELECT COALESCE(COUNT(DISTINCT room_id), 0) FROM events
  1347. WHERE type = 'm.room.message'
  1348. AND stream_ordering > ?
  1349. """
  1350. txn.execute(sql, (self.stream_ordering_day_ago,))
  1351. count, = txn.fetchone()
  1352. return count
  1353. ret = yield self.runInteraction("count_daily_active_rooms", _count)
  1354. return ret
  1355. def get_current_backfill_token(self):
  1356. """The current minimum token that backfilled events have reached"""
  1357. return -self._backfill_id_gen.get_current_token()
  1358. def get_current_events_token(self):
  1359. """The current maximum token that events have reached"""
  1360. return self._stream_id_gen.get_current_token()
  1361. def get_all_new_forward_event_rows(self, last_id, current_id, limit):
  1362. if last_id == current_id:
  1363. return defer.succeed([])
  1364. def get_all_new_forward_event_rows(txn):
  1365. sql = (
  1366. "SELECT e.stream_ordering, e.event_id, e.room_id, e.type,"
  1367. " state_key, redacts, relates_to_id"
  1368. " FROM events AS e"
  1369. " LEFT JOIN redactions USING (event_id)"
  1370. " LEFT JOIN state_events USING (event_id)"
  1371. " LEFT JOIN event_relations USING (event_id)"
  1372. " WHERE ? < stream_ordering AND stream_ordering <= ?"
  1373. " ORDER BY stream_ordering ASC"
  1374. " LIMIT ?"
  1375. )
  1376. txn.execute(sql, (last_id, current_id, limit))
  1377. new_event_updates = txn.fetchall()
  1378. if len(new_event_updates) == limit:
  1379. upper_bound = new_event_updates[-1][0]
  1380. else:
  1381. upper_bound = current_id
  1382. sql = (
  1383. "SELECT event_stream_ordering, e.event_id, e.room_id, e.type,"
  1384. " state_key, redacts, relates_to_id"
  1385. " FROM events AS e"
  1386. " INNER JOIN ex_outlier_stream USING (event_id)"
  1387. " LEFT JOIN redactions USING (event_id)"
  1388. " LEFT JOIN state_events USING (event_id)"
  1389. " LEFT JOIN event_relations USING (event_id)"
  1390. " WHERE ? < event_stream_ordering"
  1391. " AND event_stream_ordering <= ?"
  1392. " ORDER BY event_stream_ordering DESC"
  1393. )
  1394. txn.execute(sql, (last_id, upper_bound))
  1395. new_event_updates.extend(txn)
  1396. return new_event_updates
  1397. return self.runInteraction(
  1398. "get_all_new_forward_event_rows", get_all_new_forward_event_rows
  1399. )
  1400. def get_all_new_backfill_event_rows(self, last_id, current_id, limit):
  1401. if last_id == current_id:
  1402. return defer.succeed([])
  1403. def get_all_new_backfill_event_rows(txn):
  1404. sql = (
  1405. "SELECT -e.stream_ordering, e.event_id, e.room_id, e.type,"
  1406. " state_key, redacts, relates_to_id"
  1407. " FROM events AS e"
  1408. " LEFT JOIN redactions USING (event_id)"
  1409. " LEFT JOIN state_events USING (event_id)"
  1410. " LEFT JOIN event_relations USING (event_id)"
  1411. " WHERE ? > stream_ordering AND stream_ordering >= ?"
  1412. " ORDER BY stream_ordering ASC"
  1413. " LIMIT ?"
  1414. )
  1415. txn.execute(sql, (-last_id, -current_id, limit))
  1416. new_event_updates = txn.fetchall()
  1417. if len(new_event_updates) == limit:
  1418. upper_bound = new_event_updates[-1][0]
  1419. else:
  1420. upper_bound = current_id
  1421. sql = (
  1422. "SELECT -event_stream_ordering, e.event_id, e.room_id, e.type,"
  1423. " state_key, redacts, relates_to_id"
  1424. " FROM events AS e"
  1425. " INNER JOIN ex_outlier_stream USING (event_id)"
  1426. " LEFT JOIN redactions USING (event_id)"
  1427. " LEFT JOIN state_events USING (event_id)"
  1428. " LEFT JOIN event_relations USING (event_id)"
  1429. " WHERE ? > event_stream_ordering"
  1430. " AND event_stream_ordering >= ?"
  1431. " ORDER BY event_stream_ordering DESC"
  1432. )
  1433. txn.execute(sql, (-last_id, -upper_bound))
  1434. new_event_updates.extend(txn.fetchall())
  1435. return new_event_updates
  1436. return self.runInteraction(
  1437. "get_all_new_backfill_event_rows", get_all_new_backfill_event_rows
  1438. )
  1439. @cached(num_args=5, max_entries=10)
  1440. def get_all_new_events(
  1441. self,
  1442. last_backfill_id,
  1443. last_forward_id,
  1444. current_backfill_id,
  1445. current_forward_id,
  1446. limit,
  1447. ):
  1448. """Get all the new events that have arrived at the server either as
  1449. new events or as backfilled events"""
  1450. have_backfill_events = last_backfill_id != current_backfill_id
  1451. have_forward_events = last_forward_id != current_forward_id
  1452. if not have_backfill_events and not have_forward_events:
  1453. return defer.succeed(AllNewEventsResult([], [], [], [], []))
  1454. def get_all_new_events_txn(txn):
  1455. sql = (
  1456. "SELECT e.stream_ordering, e.event_id, e.room_id, e.type,"
  1457. " state_key, redacts"
  1458. " FROM events AS e"
  1459. " LEFT JOIN redactions USING (event_id)"
  1460. " LEFT JOIN state_events USING (event_id)"
  1461. " WHERE ? < stream_ordering AND stream_ordering <= ?"
  1462. " ORDER BY stream_ordering ASC"
  1463. " LIMIT ?"
  1464. )
  1465. if have_forward_events:
  1466. txn.execute(sql, (last_forward_id, current_forward_id, limit))
  1467. new_forward_events = txn.fetchall()
  1468. if len(new_forward_events) == limit:
  1469. upper_bound = new_forward_events[-1][0]
  1470. else:
  1471. upper_bound = current_forward_id
  1472. sql = (
  1473. "SELECT event_stream_ordering, event_id, state_group"
  1474. " FROM ex_outlier_stream"
  1475. " WHERE ? > event_stream_ordering"
  1476. " AND event_stream_ordering >= ?"
  1477. " ORDER BY event_stream_ordering DESC"
  1478. )
  1479. txn.execute(sql, (last_forward_id, upper_bound))
  1480. forward_ex_outliers = txn.fetchall()
  1481. else:
  1482. new_forward_events = []
  1483. forward_ex_outliers = []
  1484. sql = (
  1485. "SELECT -e.stream_ordering, e.event_id, e.room_id, e.type,"
  1486. " state_key, redacts"
  1487. " FROM events AS e"
  1488. " LEFT JOIN redactions USING (event_id)"
  1489. " LEFT JOIN state_events USING (event_id)"
  1490. " WHERE ? > stream_ordering AND stream_ordering >= ?"
  1491. " ORDER BY stream_ordering DESC"
  1492. " LIMIT ?"
  1493. )
  1494. if have_backfill_events:
  1495. txn.execute(sql, (-last_backfill_id, -current_backfill_id, limit))
  1496. new_backfill_events = txn.fetchall()
  1497. if len(new_backfill_events) == limit:
  1498. upper_bound = new_backfill_events[-1][0]
  1499. else:
  1500. upper_bound = current_backfill_id
  1501. sql = (
  1502. "SELECT -event_stream_ordering, event_id, state_group"
  1503. " FROM ex_outlier_stream"
  1504. " WHERE ? > event_stream_ordering"
  1505. " AND event_stream_ordering >= ?"
  1506. " ORDER BY event_stream_ordering DESC"
  1507. )
  1508. txn.execute(sql, (-last_backfill_id, -upper_bound))
  1509. backward_ex_outliers = txn.fetchall()
  1510. else:
  1511. new_backfill_events = []
  1512. backward_ex_outliers = []
  1513. return AllNewEventsResult(
  1514. new_forward_events,
  1515. new_backfill_events,
  1516. forward_ex_outliers,
  1517. backward_ex_outliers,
  1518. )
  1519. return self.runInteraction("get_all_new_events", get_all_new_events_txn)
  1520. def purge_history(self, room_id, token, delete_local_events):
  1521. """Deletes room history before a certain point
  1522. Args:
  1523. room_id (str):
  1524. token (str): A topological token to delete events before
  1525. delete_local_events (bool):
  1526. if True, we will delete local events as well as remote ones
  1527. (instead of just marking them as outliers and deleting their
  1528. state groups).
  1529. """
  1530. return self.runInteraction(
  1531. "purge_history",
  1532. self._purge_history_txn,
  1533. room_id,
  1534. token,
  1535. delete_local_events,
  1536. )
  1537. def _purge_history_txn(self, txn, room_id, token_str, delete_local_events):
  1538. token = RoomStreamToken.parse(token_str)
  1539. # Tables that should be pruned:
  1540. # event_auth
  1541. # event_backward_extremities
  1542. # event_edges
  1543. # event_forward_extremities
  1544. # event_json
  1545. # event_push_actions
  1546. # event_reference_hashes
  1547. # event_search
  1548. # event_to_state_groups
  1549. # events
  1550. # rejections
  1551. # room_depth
  1552. # state_groups
  1553. # state_groups_state
  1554. # we will build a temporary table listing the events so that we don't
  1555. # have to keep shovelling the list back and forth across the
  1556. # connection. Annoyingly the python sqlite driver commits the
  1557. # transaction on CREATE, so let's do this first.
  1558. #
  1559. # furthermore, we might already have the table from a previous (failed)
  1560. # purge attempt, so let's drop the table first.
  1561. txn.execute("DROP TABLE IF EXISTS events_to_purge")
  1562. txn.execute(
  1563. "CREATE TEMPORARY TABLE events_to_purge ("
  1564. " event_id TEXT NOT NULL,"
  1565. " should_delete BOOLEAN NOT NULL"
  1566. ")"
  1567. )
  1568. # First ensure that we're not about to delete all the forward extremeties
  1569. txn.execute(
  1570. "SELECT e.event_id, e.depth FROM events as e "
  1571. "INNER JOIN event_forward_extremities as f "
  1572. "ON e.event_id = f.event_id "
  1573. "AND e.room_id = f.room_id "
  1574. "WHERE f.room_id = ?",
  1575. (room_id,),
  1576. )
  1577. rows = txn.fetchall()
  1578. max_depth = max(row[1] for row in rows)
  1579. if max_depth < token.topological:
  1580. # We need to ensure we don't delete all the events from the database
  1581. # otherwise we wouldn't be able to send any events (due to not
  1582. # having any backwards extremeties)
  1583. raise SynapseError(
  1584. 400, "topological_ordering is greater than forward extremeties"
  1585. )
  1586. logger.info("[purge] looking for events to delete")
  1587. should_delete_expr = "state_key IS NULL"
  1588. should_delete_params = ()
  1589. if not delete_local_events:
  1590. should_delete_expr += " AND event_id NOT LIKE ?"
  1591. # We include the parameter twice since we use the expression twice
  1592. should_delete_params += ("%:" + self.hs.hostname, "%:" + self.hs.hostname)
  1593. should_delete_params += (room_id, token.topological)
  1594. # Note that we insert events that are outliers and aren't going to be
  1595. # deleted, as nothing will happen to them.
  1596. txn.execute(
  1597. "INSERT INTO events_to_purge"
  1598. " SELECT event_id, %s"
  1599. " FROM events AS e LEFT JOIN state_events USING (event_id)"
  1600. " WHERE (NOT outlier OR (%s)) AND e.room_id = ? AND topological_ordering < ?"
  1601. % (should_delete_expr, should_delete_expr),
  1602. should_delete_params,
  1603. )
  1604. # We create the indices *after* insertion as that's a lot faster.
  1605. # create an index on should_delete because later we'll be looking for
  1606. # the should_delete / shouldn't_delete subsets
  1607. txn.execute(
  1608. "CREATE INDEX events_to_purge_should_delete"
  1609. " ON events_to_purge(should_delete)"
  1610. )
  1611. # We do joins against events_to_purge for e.g. calculating state
  1612. # groups to purge, etc., so lets make an index.
  1613. txn.execute("CREATE INDEX events_to_purge_id" " ON events_to_purge(event_id)")
  1614. txn.execute("SELECT event_id, should_delete FROM events_to_purge")
  1615. event_rows = txn.fetchall()
  1616. logger.info(
  1617. "[purge] found %i events before cutoff, of which %i can be deleted",
  1618. len(event_rows),
  1619. sum(1 for e in event_rows if e[1]),
  1620. )
  1621. logger.info("[purge] Finding new backward extremities")
  1622. # We calculate the new entries for the backward extremeties by finding
  1623. # events to be purged that are pointed to by events we're not going to
  1624. # purge.
  1625. txn.execute(
  1626. "SELECT DISTINCT e.event_id FROM events_to_purge AS e"
  1627. " INNER JOIN event_edges AS ed ON e.event_id = ed.prev_event_id"
  1628. " LEFT JOIN events_to_purge AS ep2 ON ed.event_id = ep2.event_id"
  1629. " WHERE ep2.event_id IS NULL"
  1630. )
  1631. new_backwards_extrems = txn.fetchall()
  1632. logger.info("[purge] replacing backward extremities: %r", new_backwards_extrems)
  1633. txn.execute(
  1634. "DELETE FROM event_backward_extremities WHERE room_id = ?", (room_id,)
  1635. )
  1636. # Update backward extremeties
  1637. txn.executemany(
  1638. "INSERT INTO event_backward_extremities (room_id, event_id)"
  1639. " VALUES (?, ?)",
  1640. [(room_id, event_id) for event_id, in new_backwards_extrems],
  1641. )
  1642. logger.info("[purge] finding redundant state groups")
  1643. # Get all state groups that are referenced by events that are to be
  1644. # deleted. We then go and check if they are referenced by other events
  1645. # or state groups, and if not we delete them.
  1646. txn.execute(
  1647. """
  1648. SELECT DISTINCT state_group FROM events_to_purge
  1649. INNER JOIN event_to_state_groups USING (event_id)
  1650. """
  1651. )
  1652. referenced_state_groups = set(sg for sg, in txn)
  1653. logger.info(
  1654. "[purge] found %i referenced state groups", len(referenced_state_groups)
  1655. )
  1656. logger.info("[purge] finding state groups that can be deleted")
  1657. _ = self._find_unreferenced_groups_during_purge(txn, referenced_state_groups)
  1658. state_groups_to_delete, remaining_state_groups = _
  1659. logger.info(
  1660. "[purge] found %i state groups to delete", len(state_groups_to_delete)
  1661. )
  1662. logger.info(
  1663. "[purge] de-delta-ing %i remaining state groups",
  1664. len(remaining_state_groups),
  1665. )
  1666. # Now we turn the state groups that reference to-be-deleted state
  1667. # groups to non delta versions.
  1668. for sg in remaining_state_groups:
  1669. logger.info("[purge] de-delta-ing remaining state group %s", sg)
  1670. curr_state = self._get_state_groups_from_groups_txn(txn, [sg])
  1671. curr_state = curr_state[sg]
  1672. self._simple_delete_txn(
  1673. txn, table="state_groups_state", keyvalues={"state_group": sg}
  1674. )
  1675. self._simple_delete_txn(
  1676. txn, table="state_group_edges", keyvalues={"state_group": sg}
  1677. )
  1678. self._simple_insert_many_txn(
  1679. txn,
  1680. table="state_groups_state",
  1681. values=[
  1682. {
  1683. "state_group": sg,
  1684. "room_id": room_id,
  1685. "type": key[0],
  1686. "state_key": key[1],
  1687. "event_id": state_id,
  1688. }
  1689. for key, state_id in iteritems(curr_state)
  1690. ],
  1691. )
  1692. logger.info("[purge] removing redundant state groups")
  1693. txn.executemany(
  1694. "DELETE FROM state_groups_state WHERE state_group = ?",
  1695. ((sg,) for sg in state_groups_to_delete),
  1696. )
  1697. txn.executemany(
  1698. "DELETE FROM state_groups WHERE id = ?",
  1699. ((sg,) for sg in state_groups_to_delete),
  1700. )
  1701. logger.info("[purge] removing events from event_to_state_groups")
  1702. txn.execute(
  1703. "DELETE FROM event_to_state_groups "
  1704. "WHERE event_id IN (SELECT event_id from events_to_purge)"
  1705. )
  1706. for event_id, _ in event_rows:
  1707. txn.call_after(self._get_state_group_for_event.invalidate, (event_id,))
  1708. # Delete all remote non-state events
  1709. for table in (
  1710. "events",
  1711. "event_json",
  1712. "event_auth",
  1713. "event_edges",
  1714. "event_forward_extremities",
  1715. "event_reference_hashes",
  1716. "event_search",
  1717. "rejections",
  1718. ):
  1719. logger.info("[purge] removing events from %s", table)
  1720. txn.execute(
  1721. "DELETE FROM %s WHERE event_id IN ("
  1722. " SELECT event_id FROM events_to_purge WHERE should_delete"
  1723. ")" % (table,)
  1724. )
  1725. # event_push_actions lacks an index on event_id, and has one on
  1726. # (room_id, event_id) instead.
  1727. for table in ("event_push_actions",):
  1728. logger.info("[purge] removing events from %s", table)
  1729. txn.execute(
  1730. "DELETE FROM %s WHERE room_id = ? AND event_id IN ("
  1731. " SELECT event_id FROM events_to_purge WHERE should_delete"
  1732. ")" % (table,),
  1733. (room_id,),
  1734. )
  1735. # Mark all state and own events as outliers
  1736. logger.info("[purge] marking remaining events as outliers")
  1737. txn.execute(
  1738. "UPDATE events SET outlier = ?"
  1739. " WHERE event_id IN ("
  1740. " SELECT event_id FROM events_to_purge "
  1741. " WHERE NOT should_delete"
  1742. ")",
  1743. (True,),
  1744. )
  1745. # synapse tries to take out an exclusive lock on room_depth whenever it
  1746. # persists events (because upsert), and once we run this update, we
  1747. # will block that for the rest of our transaction.
  1748. #
  1749. # So, let's stick it at the end so that we don't block event
  1750. # persistence.
  1751. #
  1752. # We do this by calculating the minimum depth of the backwards
  1753. # extremities. However, the events in event_backward_extremities
  1754. # are ones we don't have yet so we need to look at the events that
  1755. # point to it via event_edges table.
  1756. txn.execute(
  1757. """
  1758. SELECT COALESCE(MIN(depth), 0)
  1759. FROM event_backward_extremities AS eb
  1760. INNER JOIN event_edges AS eg ON eg.prev_event_id = eb.event_id
  1761. INNER JOIN events AS e ON e.event_id = eg.event_id
  1762. WHERE eb.room_id = ?
  1763. """,
  1764. (room_id,),
  1765. )
  1766. min_depth, = txn.fetchone()
  1767. logger.info("[purge] updating room_depth to %d", min_depth)
  1768. txn.execute(
  1769. "UPDATE room_depth SET min_depth = ? WHERE room_id = ?",
  1770. (min_depth, room_id),
  1771. )
  1772. # finally, drop the temp table. this will commit the txn in sqlite,
  1773. # so make sure to keep this actually last.
  1774. txn.execute("DROP TABLE events_to_purge")
  1775. logger.info("[purge] done")
  1776. def _find_unreferenced_groups_during_purge(self, txn, state_groups):
  1777. """Used when purging history to figure out which state groups can be
  1778. deleted and which need to be de-delta'ed (due to one of its prev groups
  1779. being scheduled for deletion).
  1780. Args:
  1781. txn
  1782. state_groups (set[int]): Set of state groups referenced by events
  1783. that are going to be deleted.
  1784. Returns:
  1785. tuple[set[int], set[int]]: The set of state groups that can be
  1786. deleted and the set of state groups that need to be de-delta'ed
  1787. """
  1788. # Graph of state group -> previous group
  1789. graph = {}
  1790. # Set of events that we have found to be referenced by events
  1791. referenced_groups = set()
  1792. # Set of state groups we've already seen
  1793. state_groups_seen = set(state_groups)
  1794. # Set of state groups to handle next.
  1795. next_to_search = set(state_groups)
  1796. while next_to_search:
  1797. # We bound size of groups we're looking up at once, to stop the
  1798. # SQL query getting too big
  1799. if len(next_to_search) < 100:
  1800. current_search = next_to_search
  1801. next_to_search = set()
  1802. else:
  1803. current_search = set(itertools.islice(next_to_search, 100))
  1804. next_to_search -= current_search
  1805. # Check if state groups are referenced
  1806. sql = """
  1807. SELECT DISTINCT state_group FROM event_to_state_groups
  1808. LEFT JOIN events_to_purge AS ep USING (event_id)
  1809. WHERE state_group IN (%s) AND ep.event_id IS NULL
  1810. """ % (
  1811. ",".join("?" for _ in current_search),
  1812. )
  1813. txn.execute(sql, list(current_search))
  1814. referenced = set(sg for sg, in txn)
  1815. referenced_groups |= referenced
  1816. # We don't continue iterating up the state group graphs for state
  1817. # groups that are referenced.
  1818. current_search -= referenced
  1819. rows = self._simple_select_many_txn(
  1820. txn,
  1821. table="state_group_edges",
  1822. column="prev_state_group",
  1823. iterable=current_search,
  1824. keyvalues={},
  1825. retcols=("prev_state_group", "state_group"),
  1826. )
  1827. prevs = set(row["state_group"] for row in rows)
  1828. # We don't bother re-handling groups we've already seen
  1829. prevs -= state_groups_seen
  1830. next_to_search |= prevs
  1831. state_groups_seen |= prevs
  1832. for row in rows:
  1833. # Note: Each state group can have at most one prev group
  1834. graph[row["state_group"]] = row["prev_state_group"]
  1835. to_delete = state_groups_seen - referenced_groups
  1836. to_dedelta = set()
  1837. for sg in referenced_groups:
  1838. prev_sg = graph.get(sg)
  1839. if prev_sg and prev_sg in to_delete:
  1840. to_dedelta.add(sg)
  1841. return to_delete, to_dedelta
  1842. @defer.inlineCallbacks
  1843. def is_event_after(self, event_id1, event_id2):
  1844. """Returns True if event_id1 is after event_id2 in the stream
  1845. """
  1846. to_1, so_1 = yield self._get_event_ordering(event_id1)
  1847. to_2, so_2 = yield self._get_event_ordering(event_id2)
  1848. return (to_1, so_1) > (to_2, so_2)
  1849. @cachedInlineCallbacks(max_entries=5000)
  1850. def _get_event_ordering(self, event_id):
  1851. res = yield self._simple_select_one(
  1852. table="events",
  1853. retcols=["topological_ordering", "stream_ordering"],
  1854. keyvalues={"event_id": event_id},
  1855. allow_none=True,
  1856. )
  1857. if not res:
  1858. raise SynapseError(404, "Could not find event %s" % (event_id,))
  1859. return (int(res["topological_ordering"]), int(res["stream_ordering"]))
  1860. def get_all_updated_current_state_deltas(self, from_token, to_token, limit):
  1861. def get_all_updated_current_state_deltas_txn(txn):
  1862. sql = """
  1863. SELECT stream_id, room_id, type, state_key, event_id
  1864. FROM current_state_delta_stream
  1865. WHERE ? < stream_id AND stream_id <= ?
  1866. ORDER BY stream_id ASC LIMIT ?
  1867. """
  1868. txn.execute(sql, (from_token, to_token, limit))
  1869. return txn.fetchall()
  1870. return self.runInteraction(
  1871. "get_all_updated_current_state_deltas",
  1872. get_all_updated_current_state_deltas_txn,
  1873. )
  1874. AllNewEventsResult = namedtuple(
  1875. "AllNewEventsResult",
  1876. [
  1877. "new_forward_events",
  1878. "new_backfill_events",
  1879. "forward_ex_outliers",
  1880. "backward_ex_outliers",
  1881. ],
  1882. )