You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1173 lines
46 KiB

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