persist_events.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2018-2019 New Vector Ltd
  3. # Copyright 2019 The Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import itertools
  17. import logging
  18. from collections import deque
  19. from typing import (
  20. TYPE_CHECKING,
  21. Any,
  22. Awaitable,
  23. Callable,
  24. Collection,
  25. Deque,
  26. Dict,
  27. Generic,
  28. Iterable,
  29. List,
  30. Optional,
  31. Set,
  32. Tuple,
  33. TypeVar,
  34. )
  35. import attr
  36. from prometheus_client import Counter, Histogram
  37. from twisted.internet import defer
  38. from synapse.api.constants import EventTypes, Membership
  39. from synapse.events import EventBase
  40. from synapse.events.snapshot import EventContext
  41. from synapse.logging import opentracing
  42. from synapse.logging.context import PreserveLoggingContext, make_deferred_yieldable
  43. from synapse.metrics.background_process_metrics import run_as_background_process
  44. from synapse.storage.databases import Databases
  45. from synapse.storage.databases.main.events import DeltaState
  46. from synapse.storage.databases.main.events_worker import EventRedactBehaviour
  47. from synapse.types import (
  48. PersistedEventPosition,
  49. RoomStreamToken,
  50. StateMap,
  51. get_domain_from_id,
  52. )
  53. from synapse.util.async_helpers import ObservableDeferred, yieldable_gather_results
  54. from synapse.util.metrics import Measure
  55. if TYPE_CHECKING:
  56. from synapse.server import HomeServer
  57. logger = logging.getLogger(__name__)
  58. # The number of times we are recalculating the current state
  59. state_delta_counter = Counter("synapse_storage_events_state_delta", "")
  60. # The number of times we are recalculating state when there is only a
  61. # single forward extremity
  62. state_delta_single_event_counter = Counter(
  63. "synapse_storage_events_state_delta_single_event", ""
  64. )
  65. # The number of times we are reculating state when we could have resonably
  66. # calculated the delta when we calculated the state for an event we were
  67. # persisting.
  68. state_delta_reuse_delta_counter = Counter(
  69. "synapse_storage_events_state_delta_reuse_delta", ""
  70. )
  71. # The number of forward extremities for each new event.
  72. forward_extremities_counter = Histogram(
  73. "synapse_storage_events_forward_extremities_persisted",
  74. "Number of forward extremities for each new event",
  75. buckets=(1, 2, 3, 5, 7, 10, 15, 20, 50, 100, 200, 500, "+Inf"),
  76. )
  77. # The number of stale forward extremities for each new event. Stale extremities
  78. # are those that were in the previous set of extremities as well as the new.
  79. stale_forward_extremities_counter = Histogram(
  80. "synapse_storage_events_stale_forward_extremities_persisted",
  81. "Number of unchanged forward extremities for each new event",
  82. buckets=(0, 1, 2, 3, 5, 7, 10, 15, 20, 50, 100, 200, 500, "+Inf"),
  83. )
  84. state_resolutions_during_persistence = Counter(
  85. "synapse_storage_events_state_resolutions_during_persistence",
  86. "Number of times we had to do state res to calculate new current state",
  87. )
  88. potential_times_prune_extremities = Counter(
  89. "synapse_storage_events_potential_times_prune_extremities",
  90. "Number of times we might be able to prune extremities",
  91. )
  92. times_pruned_extremities = Counter(
  93. "synapse_storage_events_times_pruned_extremities",
  94. "Number of times we were actually be able to prune extremities",
  95. )
  96. @attr.s(auto_attribs=True, slots=True)
  97. class _EventPersistQueueItem:
  98. events_and_contexts: List[Tuple[EventBase, EventContext]]
  99. backfilled: bool
  100. deferred: ObservableDeferred
  101. parent_opentracing_span_contexts: List = attr.ib(factory=list)
  102. """A list of opentracing spans waiting for this batch"""
  103. opentracing_span_context: Any = None
  104. """The opentracing span under which the persistence actually happened"""
  105. _PersistResult = TypeVar("_PersistResult")
  106. class _EventPeristenceQueue(Generic[_PersistResult]):
  107. """Queues up events so that they can be persisted in bulk with only one
  108. concurrent transaction per room.
  109. """
  110. def __init__(
  111. self,
  112. per_item_callback: Callable[
  113. [List[Tuple[EventBase, EventContext]], bool],
  114. Awaitable[_PersistResult],
  115. ],
  116. ):
  117. """Create a new event persistence queue
  118. The per_item_callback will be called for each item added via add_to_queue,
  119. and its result will be returned via the Deferreds returned from add_to_queue.
  120. """
  121. self._event_persist_queues: Dict[str, Deque[_EventPersistQueueItem]] = {}
  122. self._currently_persisting_rooms: Set[str] = set()
  123. self._per_item_callback = per_item_callback
  124. async def add_to_queue(
  125. self,
  126. room_id: str,
  127. events_and_contexts: Iterable[Tuple[EventBase, EventContext]],
  128. backfilled: bool,
  129. ) -> _PersistResult:
  130. """Add events to the queue, with the given persist_event options.
  131. If we are not already processing events in this room, starts off a background
  132. process to to so, calling the per_item_callback for each item.
  133. Args:
  134. room_id (str):
  135. events_and_contexts (list[(EventBase, EventContext)]):
  136. backfilled (bool):
  137. Returns:
  138. the result returned by the `_per_item_callback` passed to
  139. `__init__`.
  140. """
  141. queue = self._event_persist_queues.setdefault(room_id, deque())
  142. # if the last item in the queue has the same `backfilled` setting,
  143. # we can just add these new events to that item.
  144. if queue and queue[-1].backfilled == backfilled:
  145. end_item = queue[-1]
  146. else:
  147. # need to make a new queue item
  148. deferred: ObservableDeferred[_PersistResult] = ObservableDeferred(
  149. defer.Deferred(), consumeErrors=True
  150. )
  151. end_item = _EventPersistQueueItem(
  152. events_and_contexts=[],
  153. backfilled=backfilled,
  154. deferred=deferred,
  155. )
  156. queue.append(end_item)
  157. # add our events to the queue item
  158. end_item.events_and_contexts.extend(events_and_contexts)
  159. # also add our active opentracing span to the item so that we get a link back
  160. span = opentracing.active_span()
  161. if span:
  162. end_item.parent_opentracing_span_contexts.append(span.context)
  163. # start a processor for the queue, if there isn't one already
  164. self._handle_queue(room_id)
  165. # wait for the queue item to complete
  166. res = await make_deferred_yieldable(end_item.deferred.observe())
  167. # add another opentracing span which links to the persist trace.
  168. with opentracing.start_active_span_follows_from(
  169. "persist_event_batch_complete", (end_item.opentracing_span_context,)
  170. ):
  171. pass
  172. return res
  173. def _handle_queue(self, room_id):
  174. """Attempts to handle the queue for a room if not already being handled.
  175. The queue's callback will be invoked with for each item in the queue,
  176. of type _EventPersistQueueItem. The per_item_callback will continuously
  177. be called with new items, unless the queue becomes empty. The return
  178. value of the function will be given to the deferreds waiting on the item,
  179. exceptions will be passed to the deferreds as well.
  180. This function should therefore be called whenever anything is added
  181. to the queue.
  182. If another callback is currently handling the queue then it will not be
  183. invoked.
  184. """
  185. if room_id in self._currently_persisting_rooms:
  186. return
  187. self._currently_persisting_rooms.add(room_id)
  188. async def handle_queue_loop():
  189. try:
  190. queue = self._get_drainining_queue(room_id)
  191. for item in queue:
  192. try:
  193. with opentracing.start_active_span_follows_from(
  194. "persist_event_batch",
  195. item.parent_opentracing_span_contexts,
  196. inherit_force_tracing=True,
  197. ) as scope:
  198. if scope:
  199. item.opentracing_span_context = scope.span.context
  200. ret = await self._per_item_callback(
  201. item.events_and_contexts, item.backfilled
  202. )
  203. except Exception:
  204. with PreserveLoggingContext():
  205. item.deferred.errback()
  206. else:
  207. with PreserveLoggingContext():
  208. item.deferred.callback(ret)
  209. finally:
  210. queue = self._event_persist_queues.pop(room_id, None)
  211. if queue:
  212. self._event_persist_queues[room_id] = queue
  213. self._currently_persisting_rooms.discard(room_id)
  214. # set handle_queue_loop off in the background
  215. run_as_background_process("persist_events", handle_queue_loop)
  216. def _get_drainining_queue(self, room_id):
  217. queue = self._event_persist_queues.setdefault(room_id, deque())
  218. try:
  219. while True:
  220. yield queue.popleft()
  221. except IndexError:
  222. # Queue has been drained.
  223. pass
  224. class EventsPersistenceStorage:
  225. """High level interface for handling persisting newly received events.
  226. Takes care of batching up events by room, and calculating the necessary
  227. current state and forward extremity changes.
  228. """
  229. def __init__(self, hs: "HomeServer", stores: Databases):
  230. # We ultimately want to split out the state store from the main store,
  231. # so we use separate variables here even though they point to the same
  232. # store for now.
  233. self.main_store = stores.main
  234. self.state_store = stores.state
  235. assert stores.persist_events
  236. self.persist_events_store = stores.persist_events
  237. self._clock = hs.get_clock()
  238. self._instance_name = hs.get_instance_name()
  239. self.is_mine_id = hs.is_mine_id
  240. self._event_persist_queue = _EventPeristenceQueue(self._persist_event_batch)
  241. self._state_resolution_handler = hs.get_state_resolution_handler()
  242. @opentracing.trace
  243. async def persist_events(
  244. self,
  245. events_and_contexts: Iterable[Tuple[EventBase, EventContext]],
  246. backfilled: bool = False,
  247. ) -> Tuple[List[EventBase], RoomStreamToken]:
  248. """
  249. Write events to the database
  250. Args:
  251. events_and_contexts: list of tuples of (event, context)
  252. backfilled: Whether the results are retrieved from federation
  253. via backfill or not. Used to determine if they're "new" events
  254. which might update the current state etc.
  255. Returns:
  256. List of events persisted, the current position room stream position.
  257. The list of events persisted may not be the same as those passed in
  258. if they were deduplicated due to an event already existing that
  259. matched the transcation ID; the existing event is returned in such
  260. a case.
  261. """
  262. partitioned: Dict[str, List[Tuple[EventBase, EventContext]]] = {}
  263. for event, ctx in events_and_contexts:
  264. partitioned.setdefault(event.room_id, []).append((event, ctx))
  265. async def enqueue(item):
  266. room_id, evs_ctxs = item
  267. return await self._event_persist_queue.add_to_queue(
  268. room_id, evs_ctxs, backfilled=backfilled
  269. )
  270. ret_vals = await yieldable_gather_results(enqueue, partitioned.items())
  271. # Each call to add_to_queue returns a map from event ID to existing event ID if
  272. # the event was deduplicated. (The dict may also include other entries if
  273. # the event was persisted in a batch with other events).
  274. #
  275. # Since we use `yieldable_gather_results` we need to merge the returned list
  276. # of dicts into one.
  277. replaced_events: Dict[str, str] = {}
  278. for d in ret_vals:
  279. replaced_events.update(d)
  280. events = []
  281. for event, _ in events_and_contexts:
  282. existing_event_id = replaced_events.get(event.event_id)
  283. if existing_event_id:
  284. events.append(await self.main_store.get_event(existing_event_id))
  285. else:
  286. events.append(event)
  287. return (
  288. events,
  289. self.main_store.get_room_max_token(),
  290. )
  291. @opentracing.trace
  292. async def persist_event(
  293. self, event: EventBase, context: EventContext, backfilled: bool = False
  294. ) -> Tuple[EventBase, PersistedEventPosition, RoomStreamToken]:
  295. """
  296. Returns:
  297. The event, stream ordering of `event`, and the stream ordering of the
  298. latest persisted event. The returned event may not match the given
  299. event if it was deduplicated due to an existing event matching the
  300. transaction ID.
  301. """
  302. # add_to_queue returns a map from event ID to existing event ID if the
  303. # event was deduplicated. (The dict may also include other entries if
  304. # the event was persisted in a batch with other events.)
  305. replaced_events = await self._event_persist_queue.add_to_queue(
  306. event.room_id, [(event, context)], backfilled=backfilled
  307. )
  308. replaced_event = replaced_events.get(event.event_id)
  309. if replaced_event:
  310. event = await self.main_store.get_event(replaced_event)
  311. event_stream_id = event.internal_metadata.stream_ordering
  312. # stream ordering should have been assigned by now
  313. assert event_stream_id
  314. pos = PersistedEventPosition(self._instance_name, event_stream_id)
  315. return event, pos, self.main_store.get_room_max_token()
  316. async def _persist_event_batch(
  317. self,
  318. events_and_contexts: List[Tuple[EventBase, EventContext]],
  319. backfilled: bool = False,
  320. ) -> Dict[str, str]:
  321. """Callback for the _event_persist_queue
  322. Calculates the change to current state and forward extremities, and
  323. persists the given events and with those updates.
  324. Returns:
  325. A dictionary of event ID to event ID we didn't persist as we already
  326. had another event persisted with the same TXN ID.
  327. """
  328. replaced_events: Dict[str, str] = {}
  329. if not events_and_contexts:
  330. return replaced_events
  331. # Check if any of the events have a transaction ID that has already been
  332. # persisted, and if so we don't persist it again.
  333. #
  334. # We should have checked this a long time before we get here, but it's
  335. # possible that different send event requests race in such a way that
  336. # they both pass the earlier checks. Checking here isn't racey as we can
  337. # have only one `_persist_events` per room being called at a time.
  338. replaced_events = await self.main_store.get_already_persisted_events(
  339. (event for event, _ in events_and_contexts)
  340. )
  341. if replaced_events:
  342. events_and_contexts = [
  343. (e, ctx)
  344. for e, ctx in events_and_contexts
  345. if e.event_id not in replaced_events
  346. ]
  347. if not events_and_contexts:
  348. return replaced_events
  349. chunks = [
  350. events_and_contexts[x : x + 100]
  351. for x in range(0, len(events_and_contexts), 100)
  352. ]
  353. for chunk in chunks:
  354. # We can't easily parallelize these since different chunks
  355. # might contain the same event. :(
  356. # NB: Assumes that we are only persisting events for one room
  357. # at a time.
  358. # map room_id->set[event_ids] giving the new forward
  359. # extremities in each room
  360. new_forward_extremities: Dict[str, Set[str]] = {}
  361. # map room_id->(type,state_key)->event_id tracking the full
  362. # state in each room after adding these events.
  363. # This is simply used to prefill the get_current_state_ids
  364. # cache
  365. current_state_for_room: Dict[str, StateMap[str]] = {}
  366. # map room_id->(to_delete, to_insert) where to_delete is a list
  367. # of type/state keys to remove from current state, and to_insert
  368. # is a map (type,key)->event_id giving the state delta in each
  369. # room
  370. state_delta_for_room: Dict[str, DeltaState] = {}
  371. # Set of remote users which were in rooms the server has left. We
  372. # should check if we still share any rooms and if not we mark their
  373. # device lists as stale.
  374. potentially_left_users: Set[str] = set()
  375. if not backfilled:
  376. with Measure(self._clock, "_calculate_state_and_extrem"):
  377. # Work out the new "current state" for each room.
  378. # We do this by working out what the new extremities are and then
  379. # calculating the state from that.
  380. events_by_room: Dict[str, List[Tuple[EventBase, EventContext]]] = {}
  381. for event, context in chunk:
  382. events_by_room.setdefault(event.room_id, []).append(
  383. (event, context)
  384. )
  385. for room_id, ev_ctx_rm in events_by_room.items():
  386. latest_event_ids = set(
  387. await self.main_store.get_latest_event_ids_in_room(room_id)
  388. )
  389. new_latest_event_ids = await self._calculate_new_extremities(
  390. room_id, ev_ctx_rm, latest_event_ids
  391. )
  392. if new_latest_event_ids == latest_event_ids:
  393. # No change in extremities, so no change in state
  394. continue
  395. # there should always be at least one forward extremity.
  396. # (except during the initial persistence of the send_join
  397. # results, in which case there will be no existing
  398. # extremities, so we'll `continue` above and skip this bit.)
  399. assert new_latest_event_ids, "No forward extremities left!"
  400. new_forward_extremities[room_id] = new_latest_event_ids
  401. len_1 = (
  402. len(latest_event_ids) == 1
  403. and len(new_latest_event_ids) == 1
  404. )
  405. if len_1:
  406. all_single_prev_not_state = all(
  407. len(event.prev_event_ids()) == 1
  408. and not event.is_state()
  409. for event, ctx in ev_ctx_rm
  410. )
  411. # Don't bother calculating state if they're just
  412. # a long chain of single ancestor non-state events.
  413. if all_single_prev_not_state:
  414. continue
  415. state_delta_counter.inc()
  416. if len(new_latest_event_ids) == 1:
  417. state_delta_single_event_counter.inc()
  418. # This is a fairly handwavey check to see if we could
  419. # have guessed what the delta would have been when
  420. # processing one of these events.
  421. # What we're interested in is if the latest extremities
  422. # were the same when we created the event as they are
  423. # now. When this server creates a new event (as opposed
  424. # to receiving it over federation) it will use the
  425. # forward extremities as the prev_events, so we can
  426. # guess this by looking at the prev_events and checking
  427. # if they match the current forward extremities.
  428. for ev, _ in ev_ctx_rm:
  429. prev_event_ids = set(ev.prev_event_ids())
  430. if latest_event_ids == prev_event_ids:
  431. state_delta_reuse_delta_counter.inc()
  432. break
  433. logger.debug("Calculating state delta for room %s", room_id)
  434. with Measure(
  435. self._clock, "persist_events.get_new_state_after_events"
  436. ):
  437. res = await self._get_new_state_after_events(
  438. room_id,
  439. ev_ctx_rm,
  440. latest_event_ids,
  441. new_latest_event_ids,
  442. )
  443. current_state, delta_ids, new_latest_event_ids = res
  444. # there should always be at least one forward extremity.
  445. # (except during the initial persistence of the send_join
  446. # results, in which case there will be no existing
  447. # extremities, so we'll `continue` above and skip this bit.)
  448. assert new_latest_event_ids, "No forward extremities left!"
  449. new_forward_extremities[room_id] = new_latest_event_ids
  450. # If either are not None then there has been a change,
  451. # and we need to work out the delta (or use that
  452. # given)
  453. delta = None
  454. if delta_ids is not None:
  455. # If there is a delta we know that we've
  456. # only added or replaced state, never
  457. # removed keys entirely.
  458. delta = DeltaState([], delta_ids)
  459. elif current_state is not None:
  460. with Measure(
  461. self._clock, "persist_events.calculate_state_delta"
  462. ):
  463. delta = await self._calculate_state_delta(
  464. room_id, current_state
  465. )
  466. if delta:
  467. # If we have a change of state then lets check
  468. # whether we're actually still a member of the room,
  469. # or if our last user left. If we're no longer in
  470. # the room then we delete the current state and
  471. # extremities.
  472. is_still_joined = await self._is_server_still_joined(
  473. room_id,
  474. ev_ctx_rm,
  475. delta,
  476. current_state,
  477. potentially_left_users,
  478. )
  479. if not is_still_joined:
  480. logger.info("Server no longer in room %s", room_id)
  481. latest_event_ids = set()
  482. current_state = {}
  483. delta.no_longer_in_room = True
  484. state_delta_for_room[room_id] = delta
  485. # If we have the current_state then lets prefill
  486. # the cache with it.
  487. if current_state is not None:
  488. current_state_for_room[room_id] = current_state
  489. await self.persist_events_store._persist_events_and_state_updates(
  490. chunk,
  491. current_state_for_room=current_state_for_room,
  492. state_delta_for_room=state_delta_for_room,
  493. new_forward_extremities=new_forward_extremities,
  494. use_negative_stream_ordering=backfilled,
  495. inhibit_local_membership_updates=backfilled,
  496. )
  497. await self._handle_potentially_left_users(potentially_left_users)
  498. return replaced_events
  499. async def _calculate_new_extremities(
  500. self,
  501. room_id: str,
  502. event_contexts: List[Tuple[EventBase, EventContext]],
  503. latest_event_ids: Collection[str],
  504. ) -> Set[str]:
  505. """Calculates the new forward extremities for a room given events to
  506. persist.
  507. Assumes that we are only persisting events for one room at a time.
  508. """
  509. # we're only interested in new events which aren't outliers and which aren't
  510. # being rejected.
  511. new_events = [
  512. event
  513. for event, ctx in event_contexts
  514. if not event.internal_metadata.is_outlier()
  515. and not ctx.rejected
  516. and not event.internal_metadata.is_soft_failed()
  517. ]
  518. latest_event_ids = set(latest_event_ids)
  519. # start with the existing forward extremities
  520. result = set(latest_event_ids)
  521. # add all the new events to the list
  522. result.update(event.event_id for event in new_events)
  523. # Now remove all events which are prev_events of any of the new events
  524. result.difference_update(
  525. e_id for event in new_events for e_id in event.prev_event_ids()
  526. )
  527. # Remove any events which are prev_events of any existing events.
  528. existing_prevs: Collection[
  529. str
  530. ] = await self.persist_events_store._get_events_which_are_prevs(result)
  531. result.difference_update(existing_prevs)
  532. # Finally handle the case where the new events have soft-failed prev
  533. # events. If they do we need to remove them and their prev events,
  534. # otherwise we end up with dangling extremities.
  535. existing_prevs = await self.persist_events_store._get_prevs_before_rejected(
  536. e_id for event in new_events for e_id in event.prev_event_ids()
  537. )
  538. result.difference_update(existing_prevs)
  539. # We only update metrics for events that change forward extremities
  540. # (e.g. we ignore backfill/outliers/etc)
  541. if result != latest_event_ids:
  542. forward_extremities_counter.observe(len(result))
  543. stale = latest_event_ids & result
  544. stale_forward_extremities_counter.observe(len(stale))
  545. return result
  546. async def _get_new_state_after_events(
  547. self,
  548. room_id: str,
  549. events_context: List[Tuple[EventBase, EventContext]],
  550. old_latest_event_ids: Set[str],
  551. new_latest_event_ids: Set[str],
  552. ) -> Tuple[Optional[StateMap[str]], Optional[StateMap[str]], Set[str]]:
  553. """Calculate the current state dict after adding some new events to
  554. a room
  555. Args:
  556. room_id:
  557. room to which the events are being added. Used for logging etc
  558. events_context:
  559. events and contexts which are being added to the room
  560. old_latest_event_ids:
  561. the old forward extremities for the room.
  562. new_latest_event_ids :
  563. the new forward extremities for the room.
  564. Returns:
  565. Returns a tuple of two state maps and a set of new forward
  566. extremities.
  567. The first state map is the full new current state and the second
  568. is the delta to the existing current state. If both are None then
  569. there has been no change.
  570. The function may prune some old entries from the set of new
  571. forward extremities if it's safe to do so.
  572. If there has been a change then we only return the delta if its
  573. already been calculated. Conversely if we do know the delta then
  574. the new current state is only returned if we've already calculated
  575. it.
  576. """
  577. # map from state_group to ((type, key) -> event_id) state map
  578. state_groups_map = {}
  579. # Map from (prev state group, new state group) -> delta state dict
  580. state_group_deltas = {}
  581. for ev, ctx in events_context:
  582. if ctx.state_group is None:
  583. # This should only happen for outlier events.
  584. if not ev.internal_metadata.is_outlier():
  585. raise Exception(
  586. "Context for new event %s has no state "
  587. "group" % (ev.event_id,)
  588. )
  589. continue
  590. if ctx.state_group in state_groups_map:
  591. continue
  592. # We're only interested in pulling out state that has already
  593. # been cached in the context. We'll pull stuff out of the DB later
  594. # if necessary.
  595. current_state_ids = ctx.get_cached_current_state_ids()
  596. if current_state_ids is not None:
  597. state_groups_map[ctx.state_group] = current_state_ids
  598. if ctx.prev_group:
  599. state_group_deltas[(ctx.prev_group, ctx.state_group)] = ctx.delta_ids
  600. # We need to map the event_ids to their state groups. First, let's
  601. # check if the event is one we're persisting, in which case we can
  602. # pull the state group from its context.
  603. # Otherwise we need to pull the state group from the database.
  604. # Set of events we need to fetch groups for. (We know none of the old
  605. # extremities are going to be in events_context).
  606. missing_event_ids = set(old_latest_event_ids)
  607. event_id_to_state_group = {}
  608. for event_id in new_latest_event_ids:
  609. # First search in the list of new events we're adding.
  610. for ev, ctx in events_context:
  611. if event_id == ev.event_id and ctx.state_group is not None:
  612. event_id_to_state_group[event_id] = ctx.state_group
  613. break
  614. else:
  615. # If we couldn't find it, then we'll need to pull
  616. # the state from the database
  617. missing_event_ids.add(event_id)
  618. if missing_event_ids:
  619. # Now pull out the state groups for any missing events from DB
  620. event_to_groups = await self.main_store._get_state_group_for_events(
  621. missing_event_ids
  622. )
  623. event_id_to_state_group.update(event_to_groups)
  624. # State groups of old_latest_event_ids
  625. old_state_groups = {
  626. event_id_to_state_group[evid] for evid in old_latest_event_ids
  627. }
  628. # State groups of new_latest_event_ids
  629. new_state_groups = {
  630. event_id_to_state_group[evid] for evid in new_latest_event_ids
  631. }
  632. # If they old and new groups are the same then we don't need to do
  633. # anything.
  634. if old_state_groups == new_state_groups:
  635. return None, None, new_latest_event_ids
  636. if len(new_state_groups) == 1 and len(old_state_groups) == 1:
  637. # If we're going from one state group to another, lets check if
  638. # we have a delta for that transition. If we do then we can just
  639. # return that.
  640. new_state_group = next(iter(new_state_groups))
  641. old_state_group = next(iter(old_state_groups))
  642. delta_ids = state_group_deltas.get((old_state_group, new_state_group), None)
  643. if delta_ids is not None:
  644. # We have a delta from the existing to new current state,
  645. # so lets just return that. If we happen to already have
  646. # the current state in memory then lets also return that,
  647. # but it doesn't matter if we don't.
  648. new_state = state_groups_map.get(new_state_group)
  649. return new_state, delta_ids, new_latest_event_ids
  650. # Now that we have calculated new_state_groups we need to get
  651. # their state IDs so we can resolve to a single state set.
  652. missing_state = new_state_groups - set(state_groups_map)
  653. if missing_state:
  654. group_to_state = await self.state_store._get_state_for_groups(missing_state)
  655. state_groups_map.update(group_to_state)
  656. if len(new_state_groups) == 1:
  657. # If there is only one state group, then we know what the current
  658. # state is.
  659. return state_groups_map[new_state_groups.pop()], None, new_latest_event_ids
  660. # Ok, we need to defer to the state handler to resolve our state sets.
  661. state_groups = {sg: state_groups_map[sg] for sg in new_state_groups}
  662. events_map = {ev.event_id: ev for ev, _ in events_context}
  663. # We need to get the room version, which is in the create event.
  664. # Normally that'd be in the database, but its also possible that we're
  665. # currently trying to persist it.
  666. room_version = None
  667. for ev, _ in events_context:
  668. if ev.type == EventTypes.Create and ev.state_key == "":
  669. room_version = ev.content.get("room_version", "1")
  670. break
  671. if not room_version:
  672. room_version = await self.main_store.get_room_version_id(room_id)
  673. logger.debug("calling resolve_state_groups from preserve_events")
  674. # Avoid a circular import.
  675. from synapse.state import StateResolutionStore
  676. res = await self._state_resolution_handler.resolve_state_groups(
  677. room_id,
  678. room_version,
  679. state_groups,
  680. events_map,
  681. state_res_store=StateResolutionStore(self.main_store),
  682. )
  683. state_resolutions_during_persistence.inc()
  684. # If the returned state matches the state group of one of the new
  685. # forward extremities then we check if we are able to prune some state
  686. # extremities.
  687. if res.state_group and res.state_group in new_state_groups:
  688. new_latest_event_ids = await self._prune_extremities(
  689. room_id,
  690. new_latest_event_ids,
  691. res.state_group,
  692. event_id_to_state_group,
  693. events_context,
  694. )
  695. return res.state, None, new_latest_event_ids
  696. async def _prune_extremities(
  697. self,
  698. room_id: str,
  699. new_latest_event_ids: Set[str],
  700. resolved_state_group: int,
  701. event_id_to_state_group: Dict[str, int],
  702. events_context: List[Tuple[EventBase, EventContext]],
  703. ) -> Set[str]:
  704. """See if we can prune any of the extremities after calculating the
  705. resolved state.
  706. """
  707. potential_times_prune_extremities.inc()
  708. # We keep all the extremities that have the same state group, and
  709. # see if we can drop the others.
  710. new_new_extrems = {
  711. e
  712. for e in new_latest_event_ids
  713. if event_id_to_state_group[e] == resolved_state_group
  714. }
  715. dropped_extrems = set(new_latest_event_ids) - new_new_extrems
  716. logger.debug("Might drop extremities: %s", dropped_extrems)
  717. # We only drop events from the extremities list if:
  718. # 1. we're not currently persisting them;
  719. # 2. they're not our own events (or are dummy events); and
  720. # 3. they're either:
  721. # 1. over N hours old and more than N events ago (we use depth to
  722. # calculate); or
  723. # 2. we are persisting an event from the same domain and more than
  724. # M events ago.
  725. #
  726. # The idea is that we don't want to drop events that are "legitimate"
  727. # extremities (that we would want to include as prev events), only
  728. # "stuck" extremities that are e.g. due to a gap in the graph.
  729. #
  730. # Note that we either drop all of them or none of them. If we only drop
  731. # some of the events we don't know if state res would come to the same
  732. # conclusion.
  733. for ev, _ in events_context:
  734. if ev.event_id in dropped_extrems:
  735. logger.debug(
  736. "Not dropping extremities: %s is being persisted", ev.event_id
  737. )
  738. return new_latest_event_ids
  739. dropped_events = await self.main_store.get_events(
  740. dropped_extrems,
  741. allow_rejected=True,
  742. redact_behaviour=EventRedactBehaviour.AS_IS,
  743. )
  744. new_senders = {get_domain_from_id(e.sender) for e, _ in events_context}
  745. one_day_ago = self._clock.time_msec() - 24 * 60 * 60 * 1000
  746. current_depth = max(e.depth for e, _ in events_context)
  747. for event in dropped_events.values():
  748. # If the event is a local dummy event then we should check it
  749. # doesn't reference any local events, as we want to reference those
  750. # if we send any new events.
  751. #
  752. # Note we do this recursively to handle the case where a dummy event
  753. # references a dummy event that only references remote events.
  754. #
  755. # Ideally we'd figure out a way of still being able to drop old
  756. # dummy events that reference local events, but this is good enough
  757. # as a first cut.
  758. events_to_check: Collection[EventBase] = [event]
  759. while events_to_check:
  760. new_events: Set[str] = set()
  761. for event_to_check in events_to_check:
  762. if self.is_mine_id(event_to_check.sender):
  763. if event_to_check.type != EventTypes.Dummy:
  764. logger.debug("Not dropping own event")
  765. return new_latest_event_ids
  766. new_events.update(event_to_check.prev_event_ids())
  767. prev_events = await self.main_store.get_events(
  768. new_events,
  769. allow_rejected=True,
  770. redact_behaviour=EventRedactBehaviour.AS_IS,
  771. )
  772. events_to_check = prev_events.values()
  773. if (
  774. event.origin_server_ts < one_day_ago
  775. and event.depth < current_depth - 100
  776. ):
  777. continue
  778. # We can be less conservative about dropping extremities from the
  779. # same domain, though we do want to wait a little bit (otherwise
  780. # we'll immediately remove all extremities from a given server).
  781. if (
  782. get_domain_from_id(event.sender) in new_senders
  783. and event.depth < current_depth - 20
  784. ):
  785. continue
  786. logger.debug(
  787. "Not dropping as too new and not in new_senders: %s",
  788. new_senders,
  789. )
  790. return new_latest_event_ids
  791. times_pruned_extremities.inc()
  792. logger.info(
  793. "Pruning forward extremities in room %s: from %s -> %s",
  794. room_id,
  795. new_latest_event_ids,
  796. new_new_extrems,
  797. )
  798. return new_new_extrems
  799. async def _calculate_state_delta(
  800. self, room_id: str, current_state: StateMap[str]
  801. ) -> DeltaState:
  802. """Calculate the new state deltas for a room.
  803. Assumes that we are only persisting events for one room at a time.
  804. """
  805. existing_state = await self.main_store.get_current_state_ids(room_id)
  806. to_delete = [key for key in existing_state if key not in current_state]
  807. to_insert = {
  808. key: ev_id
  809. for key, ev_id in current_state.items()
  810. if ev_id != existing_state.get(key)
  811. }
  812. return DeltaState(to_delete=to_delete, to_insert=to_insert)
  813. async def _is_server_still_joined(
  814. self,
  815. room_id: str,
  816. ev_ctx_rm: List[Tuple[EventBase, EventContext]],
  817. delta: DeltaState,
  818. current_state: Optional[StateMap[str]],
  819. potentially_left_users: Set[str],
  820. ) -> bool:
  821. """Check if the server will still be joined after the given events have
  822. been persised.
  823. Args:
  824. room_id
  825. ev_ctx_rm
  826. delta: The delta of current state between what is in the database
  827. and what the new current state will be.
  828. current_state: The new current state if it already been calculated,
  829. otherwise None.
  830. potentially_left_users: If the server has left the room, then joined
  831. remote users will be added to this set to indicate that the
  832. server may no longer be sharing a room with them.
  833. """
  834. if not any(
  835. self.is_mine_id(state_key)
  836. for typ, state_key in itertools.chain(delta.to_delete, delta.to_insert)
  837. if typ == EventTypes.Member
  838. ):
  839. # There have been no changes to membership of our users, so nothing
  840. # has changed and we assume we're still in the room.
  841. return True
  842. # Check if any of the given events are a local join that appear in the
  843. # current state
  844. events_to_check = [] # Event IDs that aren't an event we're persisting
  845. for (typ, state_key), event_id in delta.to_insert.items():
  846. if typ != EventTypes.Member or not self.is_mine_id(state_key):
  847. continue
  848. for event, _ in ev_ctx_rm:
  849. if event_id == event.event_id:
  850. if event.membership == Membership.JOIN:
  851. return True
  852. # The event is not in `ev_ctx_rm`, so we need to pull it out of
  853. # the DB.
  854. events_to_check.append(event_id)
  855. # Check if any of the changes that we don't have events for are joins.
  856. if events_to_check:
  857. rows = await self.main_store.get_membership_from_event_ids(events_to_check)
  858. is_still_joined = any(row["membership"] == Membership.JOIN for row in rows)
  859. if is_still_joined:
  860. return True
  861. # None of the new state events are local joins, so we check the database
  862. # to see if there are any other local users in the room. We ignore users
  863. # whose state has changed as we've already their new state above.
  864. users_to_ignore = [
  865. state_key
  866. for typ, state_key in itertools.chain(delta.to_insert, delta.to_delete)
  867. if typ == EventTypes.Member and self.is_mine_id(state_key)
  868. ]
  869. if await self.main_store.is_local_host_in_room_ignoring_users(
  870. room_id, users_to_ignore
  871. ):
  872. return True
  873. # The server will leave the room, so we go and find out which remote
  874. # users will still be joined when we leave.
  875. if current_state is None:
  876. current_state = await self.main_store.get_current_state_ids(room_id)
  877. current_state = dict(current_state)
  878. for key in delta.to_delete:
  879. current_state.pop(key, None)
  880. current_state.update(delta.to_insert)
  881. remote_event_ids = [
  882. event_id
  883. for (
  884. typ,
  885. state_key,
  886. ), event_id in current_state.items()
  887. if typ == EventTypes.Member and not self.is_mine_id(state_key)
  888. ]
  889. rows = await self.main_store.get_membership_from_event_ids(remote_event_ids)
  890. potentially_left_users.update(
  891. row["user_id"] for row in rows if row["membership"] == Membership.JOIN
  892. )
  893. return False
  894. async def _handle_potentially_left_users(self, user_ids: Set[str]):
  895. """Given a set of remote users check if the server still shares a room with
  896. them. If not then mark those users' device cache as stale.
  897. """
  898. if not user_ids:
  899. return
  900. joined_users = await self.main_store.get_users_server_still_shares_room_with(
  901. user_ids
  902. )
  903. left_users = user_ids - joined_users
  904. for user_id in left_users:
  905. await self.main_store.mark_remote_user_device_list_as_unsubscribed(user_id)