persist_events.py 45 KB

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