Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

918 rader
33 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2018 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import heapq
  16. import logging
  17. from collections import ChainMap, defaultdict
  18. from typing import (
  19. TYPE_CHECKING,
  20. Any,
  21. Awaitable,
  22. Callable,
  23. DefaultDict,
  24. Dict,
  25. FrozenSet,
  26. List,
  27. Mapping,
  28. Optional,
  29. Sequence,
  30. Set,
  31. Tuple,
  32. )
  33. import attr
  34. from immutabledict import immutabledict
  35. from prometheus_client import Counter, Histogram
  36. from synapse.api.constants import EventTypes
  37. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, StateResolutionVersions
  38. from synapse.events import EventBase
  39. from synapse.events.snapshot import (
  40. EventContext,
  41. UnpersistedEventContext,
  42. UnpersistedEventContextBase,
  43. )
  44. from synapse.logging.context import ContextResourceUsage
  45. from synapse.logging.opentracing import tag_args, trace
  46. from synapse.replication.http.state import ReplicationUpdateCurrentStateRestServlet
  47. from synapse.state import v1, v2
  48. from synapse.storage.databases.main.events_worker import EventRedactBehaviour
  49. from synapse.types import StateMap, StrCollection
  50. from synapse.types.state import StateFilter
  51. from synapse.util.async_helpers import Linearizer
  52. from synapse.util.caches.expiringcache import ExpiringCache
  53. from synapse.util.metrics import Measure, measure_func
  54. if TYPE_CHECKING:
  55. from synapse.server import HomeServer
  56. from synapse.storage.controllers import StateStorageController
  57. from synapse.storage.databases.main import DataStore
  58. logger = logging.getLogger(__name__)
  59. metrics_logger = logging.getLogger("synapse.state.metrics")
  60. # Metrics for number of state groups involved in a resolution.
  61. state_groups_histogram = Histogram(
  62. "synapse_state_number_state_groups_in_resolution",
  63. "Number of state groups used when performing a state resolution",
  64. buckets=(1, 2, 3, 5, 7, 10, 15, 20, 50, 100, 200, 500, "+Inf"),
  65. )
  66. EVICTION_TIMEOUT_SECONDS = 60 * 60
  67. _NEXT_STATE_ID = 1
  68. POWER_KEY = (EventTypes.PowerLevels, "")
  69. def _gen_state_id() -> str:
  70. global _NEXT_STATE_ID
  71. s = "X%d" % (_NEXT_STATE_ID,)
  72. _NEXT_STATE_ID += 1
  73. return s
  74. class _StateCacheEntry:
  75. __slots__ = ["_state", "state_group", "prev_group", "delta_ids"]
  76. def __init__(
  77. self,
  78. state: Optional[StateMap[str]],
  79. state_group: Optional[int],
  80. prev_group: Optional[int] = None,
  81. delta_ids: Optional[StateMap[str]] = None,
  82. ):
  83. if state is None and state_group is None and prev_group is None:
  84. raise Exception("One of state, state_group or prev_group must be not None")
  85. if prev_group is not None and delta_ids is None:
  86. raise Exception("If prev_group is set so must delta_ids")
  87. # A map from (type, state_key) to event_id.
  88. #
  89. # This can be None if we have a `state_group` (as then we can fetch the
  90. # state from the DB.)
  91. self._state: Optional[StateMap[str]] = (
  92. immutabledict(state) if state is not None else None
  93. )
  94. # the ID of a state group if one and only one is involved.
  95. # otherwise, None otherwise?
  96. self.state_group = state_group
  97. self.prev_group = prev_group
  98. self.delta_ids: Optional[StateMap[str]] = (
  99. immutabledict(delta_ids) if delta_ids is not None else None
  100. )
  101. async def get_state(
  102. self,
  103. state_storage: "StateStorageController",
  104. state_filter: Optional["StateFilter"] = None,
  105. ) -> StateMap[str]:
  106. """Get the state map for this entry, either from the in-memory state or
  107. looking up the state group in the DB.
  108. """
  109. if self._state is not None:
  110. return self._state
  111. if self.state_group is not None:
  112. return await state_storage.get_state_ids_for_group(
  113. self.state_group, state_filter
  114. )
  115. assert self.prev_group is not None and self.delta_ids is not None
  116. prev_state = await state_storage.get_state_ids_for_group(
  117. self.prev_group, state_filter
  118. )
  119. # ChainMap expects MutableMapping, but since we're using it immutably
  120. # its safe to give it immutable maps.
  121. return ChainMap(self.delta_ids, prev_state) # type: ignore[arg-type]
  122. def set_state_group(self, state_group: int) -> None:
  123. """Update the state group assigned to this state (e.g. after we've
  124. persisted it).
  125. Note: this will cause the cache entry to drop any stored state.
  126. """
  127. self.state_group = state_group
  128. # We clear out the state as we know longer need to explicitly keep it in
  129. # the `state_cache` (as the store state group cache will do that).
  130. self._state = None
  131. def __len__(self) -> int:
  132. # The len should be used to estimate how large this cache entry is, for
  133. # cache eviction purposes. This is why it's fine to return 1 if we're
  134. # not storing any state.
  135. length = 0
  136. if self._state:
  137. length += len(self._state)
  138. if self.delta_ids:
  139. length += len(self.delta_ids)
  140. return length or 1 # Make sure its not 0.
  141. class StateHandler:
  142. """Fetches bits of state from the stores, and does state resolution
  143. where necessary
  144. """
  145. def __init__(self, hs: "HomeServer"):
  146. self.clock = hs.get_clock()
  147. self.store = hs.get_datastores().main
  148. self._state_storage_controller = hs.get_storage_controllers().state
  149. self.hs = hs
  150. self._state_resolution_handler = hs.get_state_resolution_handler()
  151. self._storage_controllers = hs.get_storage_controllers()
  152. self._events_shard_config = hs.config.worker.events_shard_config
  153. self._instance_name = hs.get_instance_name()
  154. self._update_current_state_client = (
  155. ReplicationUpdateCurrentStateRestServlet.make_client(hs)
  156. )
  157. async def compute_state_after_events(
  158. self,
  159. room_id: str,
  160. event_ids: StrCollection,
  161. state_filter: Optional[StateFilter] = None,
  162. await_full_state: bool = True,
  163. ) -> StateMap[str]:
  164. """Fetch the state after each of the given event IDs. Resolve them and return.
  165. This is typically used where `event_ids` is a collection of forward extremities
  166. in a room, intended to become the `prev_events` of a new event E. If so, the
  167. return value of this function represents the state before E.
  168. Args:
  169. room_id: the room_id containing the given events.
  170. event_ids: the events whose state should be fetched and resolved.
  171. await_full_state: if `True`, will block if we do not yet have complete state
  172. at these events and `state_filter` is not satisfied by partial state.
  173. Defaults to `True`.
  174. Returns:
  175. the state dict (a mapping from (event_type, state_key) -> event_id) which
  176. holds the resolution of the states after the given event IDs.
  177. """
  178. logger.debug("calling resolve_state_groups from compute_state_after_events")
  179. if (
  180. await_full_state
  181. and state_filter
  182. and not state_filter.must_await_full_state(self.hs.is_mine_id)
  183. ):
  184. await_full_state = False
  185. ret = await self.resolve_state_groups_for_events(
  186. room_id, event_ids, await_full_state
  187. )
  188. return await ret.get_state(self._state_storage_controller, state_filter)
  189. async def get_current_user_ids_in_room(
  190. self, room_id: str, latest_event_ids: StrCollection
  191. ) -> Set[str]:
  192. """
  193. Get the users IDs who are currently in a room.
  194. Note: This is much slower than using the equivalent method
  195. `DataStore.get_users_in_room` or `DataStore.get_users_in_room_with_profiles`,
  196. so this should only be used when wanting the users at a particular point
  197. in the room.
  198. Args:
  199. room_id: The ID of the room.
  200. latest_event_ids: Precomputed list of latest event IDs. Will be computed if None.
  201. Returns:
  202. Set of user IDs in the room.
  203. """
  204. assert latest_event_ids is not None
  205. logger.debug("calling resolve_state_groups from get_current_user_ids_in_room")
  206. entry = await self.resolve_state_groups_for_events(room_id, latest_event_ids)
  207. state = await entry.get_state(self._state_storage_controller, StateFilter.all())
  208. return await self.store.get_joined_user_ids_from_state(room_id, state)
  209. async def get_hosts_in_room_at_events(
  210. self, room_id: str, event_ids: StrCollection
  211. ) -> FrozenSet[str]:
  212. """Get the hosts that were in a room at the given event ids
  213. Args:
  214. room_id:
  215. event_ids:
  216. Returns:
  217. The hosts in the room at the given events
  218. """
  219. entry = await self.resolve_state_groups_for_events(room_id, event_ids)
  220. return await self._state_storage_controller.get_joined_hosts(room_id, entry)
  221. @trace
  222. @tag_args
  223. async def calculate_context_info(
  224. self,
  225. event: EventBase,
  226. state_ids_before_event: Optional[StateMap[str]] = None,
  227. partial_state: Optional[bool] = None,
  228. state_group_before_event: Optional[int] = None,
  229. ) -> UnpersistedEventContextBase:
  230. """
  231. Calulates the contents of an unpersisted event context, other than the current
  232. state group (which is either provided or calculated when the event context is persisted)
  233. state_ids_before_event:
  234. The event ids of the full state before the event if
  235. it can't be calculated from existing events. This is normally
  236. only specified when receiving an event from federation where we
  237. don't have the prev events, e.g. when backfilling or when the event
  238. is being created for batch persisting.
  239. partial_state:
  240. `True` if `state_ids_before_event` is partial and omits non-critical
  241. membership events.
  242. `False` if `state_ids_before_event` is the full state.
  243. `None` when `state_ids_before_event` is not provided. In this case, the
  244. flag will be calculated based on `event`'s prev events.
  245. state_group_before_event:
  246. the current state group at the time of event, if known
  247. Returns:
  248. The event context.
  249. Raises:
  250. RuntimeError if `state_ids_before_event` is not provided and one or more
  251. prev events are missing or outliers.
  252. """
  253. assert not event.internal_metadata.is_outlier()
  254. #
  255. # first of all, figure out the state before the event, unless we
  256. # already have it.
  257. #
  258. if state_ids_before_event:
  259. # if we're given the state before the event, then we use that
  260. state_group_before_event_prev_group = None
  261. deltas_to_state_group_before_event = None
  262. # the partial_state flag must be provided
  263. assert partial_state is not None
  264. else:
  265. # otherwise, we'll need to resolve the state across the prev_events.
  266. # partial_state should not be set explicitly in this case:
  267. # we work it out dynamically
  268. assert partial_state is None
  269. # if any of the prev-events have partial state, so do we.
  270. # (This is slightly racy - the prev-events might get fixed up before we use
  271. # their states - but I don't think that really matters; it just means we
  272. # might redundantly recalculate the state for this event later.)
  273. prev_event_ids = event.prev_event_ids()
  274. incomplete_prev_events = await self.store.get_partial_state_events(
  275. prev_event_ids
  276. )
  277. partial_state = any(incomplete_prev_events.values())
  278. if partial_state:
  279. logger.debug(
  280. "New/incoming event %s refers to prev_events %s with partial state",
  281. event.event_id,
  282. [k for (k, v) in incomplete_prev_events.items() if v],
  283. )
  284. logger.debug("calling resolve_state_groups from compute_event_context")
  285. # we've already taken into account partial state, so no need to wait for
  286. # complete state here.
  287. entry = await self.resolve_state_groups_for_events(
  288. event.room_id,
  289. event.prev_event_ids(),
  290. await_full_state=False,
  291. )
  292. state_group_before_event_prev_group = entry.prev_group
  293. deltas_to_state_group_before_event = entry.delta_ids
  294. state_ids_before_event = None
  295. # We make sure that we have a state group assigned to the state.
  296. if entry.state_group is None:
  297. # store_state_group requires us to have either a previous state group
  298. # (with deltas) or the complete state map. So, if we don't have a
  299. # previous state group, load the complete state map now.
  300. if state_group_before_event_prev_group is None:
  301. state_ids_before_event = await entry.get_state(
  302. self._state_storage_controller, StateFilter.all()
  303. )
  304. state_group_before_event = (
  305. await self._state_storage_controller.store_state_group(
  306. event.event_id,
  307. event.room_id,
  308. prev_group=state_group_before_event_prev_group,
  309. delta_ids=deltas_to_state_group_before_event,
  310. current_state_ids=state_ids_before_event,
  311. )
  312. )
  313. entry.set_state_group(state_group_before_event)
  314. else:
  315. state_group_before_event = entry.state_group
  316. #
  317. # now if it's not a state event, we're done
  318. #
  319. if not event.is_state():
  320. return UnpersistedEventContext(
  321. storage=self._storage_controllers,
  322. state_group_before_event=state_group_before_event,
  323. state_group_after_event=state_group_before_event,
  324. state_delta_due_to_event={},
  325. prev_group_for_state_group_before_event=state_group_before_event_prev_group,
  326. delta_ids_to_state_group_before_event=deltas_to_state_group_before_event,
  327. partial_state=partial_state,
  328. state_map_before_event=state_ids_before_event,
  329. )
  330. #
  331. # otherwise, we'll need to set up creating a new state group for after the event
  332. #
  333. key = (event.type, event.state_key)
  334. if state_ids_before_event is not None:
  335. replaces = state_ids_before_event.get(key)
  336. else:
  337. replaces_state_map = await entry.get_state(
  338. self._state_storage_controller, StateFilter.from_types([key])
  339. )
  340. replaces = replaces_state_map.get(key)
  341. if replaces and replaces != event.event_id:
  342. event.unsigned["replaces_state"] = replaces
  343. delta_ids = {key: event.event_id}
  344. return UnpersistedEventContext(
  345. storage=self._storage_controllers,
  346. state_group_before_event=state_group_before_event,
  347. state_group_after_event=None,
  348. state_delta_due_to_event=delta_ids,
  349. prev_group_for_state_group_before_event=state_group_before_event_prev_group,
  350. delta_ids_to_state_group_before_event=deltas_to_state_group_before_event,
  351. partial_state=partial_state,
  352. state_map_before_event=state_ids_before_event,
  353. )
  354. async def compute_event_context(
  355. self,
  356. event: EventBase,
  357. state_ids_before_event: Optional[StateMap[str]] = None,
  358. partial_state: Optional[bool] = None,
  359. ) -> EventContext:
  360. """Build an EventContext structure for a non-outlier event.
  361. (for an outlier, call EventContext.for_outlier directly)
  362. This works out what the current state should be for the event, and
  363. generates a new state group if necessary.
  364. Args:
  365. event:
  366. state_ids_before_event: The event ids of the state before the event if
  367. it can't be calculated from existing events. This is normally
  368. only specified when receiving an event from federation where we
  369. don't have the prev events, e.g. when backfilling.
  370. partial_state:
  371. `True` if `state_ids_before_event` is partial and omits non-critical
  372. membership events.
  373. `False` if `state_ids_before_event` is the full state.
  374. `None` when `state_ids_before_event` is not provided. In this case, the
  375. flag will be calculated based on `event`'s prev events.
  376. entry:
  377. A state cache entry for the resolved state across the prev events. We may
  378. have already calculated this, so if it's available pass it in
  379. Returns:
  380. The event context.
  381. Raises:
  382. RuntimeError if `state_ids_before_event` is not provided and one or more
  383. prev events are missing or outliers.
  384. """
  385. unpersisted_context = await self.calculate_context_info(
  386. event=event,
  387. state_ids_before_event=state_ids_before_event,
  388. partial_state=partial_state,
  389. )
  390. return await unpersisted_context.persist(event)
  391. @trace
  392. @measure_func()
  393. async def resolve_state_groups_for_events(
  394. self, room_id: str, event_ids: StrCollection, await_full_state: bool = True
  395. ) -> _StateCacheEntry:
  396. """Given a list of event_ids this method fetches the state at each
  397. event, resolves conflicts between them and returns them.
  398. Args:
  399. room_id
  400. event_ids
  401. await_full_state: if true, will block if we do not yet have complete
  402. state at these events.
  403. Returns:
  404. The resolved state
  405. Raises:
  406. RuntimeError if we don't have a state group for one or more of the events
  407. (ie. they are outliers or unknown)
  408. """
  409. logger.debug("resolve_state_groups event_ids %s", event_ids)
  410. state_groups = await self._state_storage_controller.get_state_group_for_events(
  411. event_ids, await_full_state=await_full_state
  412. )
  413. state_group_ids = state_groups.values()
  414. # check if each event has same state group id, if so there's no state to resolve
  415. state_group_ids_set = set(state_group_ids)
  416. if len(state_group_ids_set) == 1:
  417. (state_group_id,) = state_group_ids_set
  418. (
  419. prev_group,
  420. delta_ids,
  421. ) = await self._state_storage_controller.get_state_group_delta(
  422. state_group_id
  423. )
  424. return _StateCacheEntry(
  425. state=None,
  426. state_group=state_group_id,
  427. prev_group=prev_group,
  428. delta_ids=delta_ids,
  429. )
  430. elif len(state_group_ids_set) == 0:
  431. return _StateCacheEntry(state={}, state_group=None)
  432. room_version = await self.store.get_room_version_id(room_id)
  433. state_to_resolve = await self._state_storage_controller.get_state_for_groups(
  434. state_group_ids_set
  435. )
  436. result = await self._state_resolution_handler.resolve_state_groups(
  437. room_id,
  438. room_version,
  439. state_to_resolve,
  440. None,
  441. state_res_store=StateResolutionStore(self.store),
  442. )
  443. return result
  444. async def update_current_state(self, room_id: str) -> None:
  445. """Recalculates the current state for a room, and persists it.
  446. Raises:
  447. SynapseError(502): if all attempts to connect to the event persister worker
  448. fail
  449. """
  450. writer_instance = self._events_shard_config.get_instance(room_id)
  451. if writer_instance != self._instance_name:
  452. await self._update_current_state_client(
  453. instance_name=writer_instance,
  454. room_id=room_id,
  455. )
  456. return
  457. assert self._storage_controllers.persistence is not None
  458. await self._storage_controllers.persistence.update_current_state(room_id)
  459. @attr.s(slots=True, auto_attribs=True)
  460. class _StateResMetrics:
  461. """Keeps track of some usage metrics about state res."""
  462. # System and User CPU time, in seconds
  463. cpu_time: float = 0.0
  464. # time spent on database transactions (excluding scheduling time). This roughly
  465. # corresponds to the amount of work done on the db server, excluding event fetches.
  466. db_time: float = 0.0
  467. # number of events fetched from the db.
  468. db_events: int = 0
  469. _biggest_room_by_cpu_counter = Counter(
  470. "synapse_state_res_cpu_for_biggest_room_seconds",
  471. "CPU time spent performing state resolution for the single most expensive "
  472. "room for state resolution",
  473. )
  474. _biggest_room_by_db_counter = Counter(
  475. "synapse_state_res_db_for_biggest_room_seconds",
  476. "Database time spent performing state resolution for the single most "
  477. "expensive room for state resolution",
  478. )
  479. _cpu_times = Histogram(
  480. "synapse_state_res_cpu_for_all_rooms_seconds",
  481. "CPU time (utime+stime) spent computing a single state resolution",
  482. )
  483. _db_times = Histogram(
  484. "synapse_state_res_db_for_all_rooms_seconds",
  485. "Database time spent computing a single state resolution",
  486. )
  487. class StateResolutionHandler:
  488. """Responsible for doing state conflict resolution.
  489. Note that the storage layer depends on this handler, so all functions must
  490. be storage-independent.
  491. """
  492. def __init__(self, hs: "HomeServer"):
  493. self.clock = hs.get_clock()
  494. self.resolve_linearizer = Linearizer(name="state_resolve_lock")
  495. # dict of set of event_ids -> _StateCacheEntry.
  496. self._state_cache: ExpiringCache[
  497. FrozenSet[int], _StateCacheEntry
  498. ] = ExpiringCache(
  499. cache_name="state_cache",
  500. clock=self.clock,
  501. max_len=100000,
  502. expiry_ms=EVICTION_TIMEOUT_SECONDS * 1000,
  503. iterable=True,
  504. reset_expiry_on_get=True,
  505. )
  506. #
  507. # stuff for tracking time spent on state-res by room
  508. #
  509. # tracks the amount of work done on state res per room
  510. self._state_res_metrics: DefaultDict[str, _StateResMetrics] = defaultdict(
  511. _StateResMetrics
  512. )
  513. self.clock.looping_call(self._report_metrics, 120 * 1000)
  514. async def resolve_state_groups(
  515. self,
  516. room_id: str,
  517. room_version: str,
  518. state_groups_ids: Mapping[int, StateMap[str]],
  519. event_map: Optional[Dict[str, EventBase]],
  520. state_res_store: "StateResolutionStore",
  521. ) -> _StateCacheEntry:
  522. """Resolves conflicts between a set of state groups
  523. Always generates a new state group (unless we hit the cache), so should
  524. not be called for a single state group
  525. Args:
  526. room_id: room we are resolving for (used for logging and sanity checks)
  527. room_version: version of the room
  528. state_groups_ids:
  529. A map from state group id to the state in that state group
  530. (where 'state' is a map from state key to event id)
  531. event_map:
  532. a dict from event_id to event, for any events that we happen to
  533. have in flight (eg, those currently being persisted). This will be
  534. used as a starting point for finding the state we need; any missing
  535. events will be requested via state_res_store.
  536. If None, all events will be fetched via state_res_store.
  537. state_res_store
  538. Returns:
  539. The resolved state
  540. """
  541. group_names = frozenset(state_groups_ids.keys())
  542. async with self.resolve_linearizer.queue(group_names):
  543. cache = self._state_cache.get(group_names, None)
  544. if cache:
  545. return cache
  546. logger.info(
  547. "Resolving state for %s with groups %s",
  548. room_id,
  549. list(group_names),
  550. )
  551. state_groups_histogram.observe(len(state_groups_ids))
  552. new_state = await self.resolve_events_with_store(
  553. room_id,
  554. room_version,
  555. list(state_groups_ids.values()),
  556. event_map=event_map,
  557. state_res_store=state_res_store,
  558. )
  559. # if the new state matches any of the input state groups, we can
  560. # use that state group again. Otherwise we will generate a state_id
  561. # which will be used as a cache key for future resolutions, but
  562. # not get persisted.
  563. with Measure(self.clock, "state.create_group_ids"):
  564. cache = _make_state_cache_entry(new_state, state_groups_ids)
  565. self._state_cache[group_names] = cache
  566. return cache
  567. async def resolve_events_with_store(
  568. self,
  569. room_id: str,
  570. room_version: str,
  571. state_sets: Sequence[StateMap[str]],
  572. event_map: Optional[Dict[str, EventBase]],
  573. state_res_store: "StateResolutionStore",
  574. ) -> StateMap[str]:
  575. """
  576. Args:
  577. room_id: the room we are working in
  578. room_version: Version of the room
  579. state_sets: List of dicts of (type, state_key) -> event_id,
  580. which are the different state groups to resolve.
  581. event_map:
  582. a dict from event_id to event, for any events that we happen to
  583. have in flight (eg, those currently being persisted). This will be
  584. used as a starting point for finding the state we need; any missing
  585. events will be requested via state_map_factory.
  586. If None, all events will be fetched via state_res_store.
  587. state_res_store: a place to fetch events from
  588. Returns:
  589. a map from (type, state_key) to event_id.
  590. """
  591. try:
  592. with Measure(self.clock, "state._resolve_events") as m:
  593. room_version_obj = KNOWN_ROOM_VERSIONS[room_version]
  594. if room_version_obj.state_res == StateResolutionVersions.V1:
  595. return await v1.resolve_events_with_store(
  596. room_id,
  597. room_version_obj,
  598. state_sets,
  599. event_map,
  600. state_res_store.get_events,
  601. )
  602. else:
  603. return await v2.resolve_events_with_store(
  604. self.clock,
  605. room_id,
  606. room_version_obj,
  607. state_sets,
  608. event_map,
  609. state_res_store,
  610. )
  611. finally:
  612. self._record_state_res_metrics(room_id, m.get_resource_usage())
  613. def _record_state_res_metrics(
  614. self, room_id: str, rusage: ContextResourceUsage
  615. ) -> None:
  616. room_metrics = self._state_res_metrics[room_id]
  617. room_metrics.cpu_time += rusage.ru_utime + rusage.ru_stime
  618. room_metrics.db_time += rusage.db_txn_duration_sec
  619. room_metrics.db_events += rusage.evt_db_fetch_count
  620. _cpu_times.observe(rusage.ru_utime + rusage.ru_stime)
  621. _db_times.observe(rusage.db_txn_duration_sec)
  622. def _report_metrics(self) -> None:
  623. if not self._state_res_metrics:
  624. # no state res has happened since the last iteration: don't bother logging.
  625. return
  626. self._report_biggest(
  627. lambda i: i.cpu_time,
  628. "CPU time",
  629. _biggest_room_by_cpu_counter,
  630. )
  631. self._report_biggest(
  632. lambda i: i.db_time,
  633. "DB time",
  634. _biggest_room_by_db_counter,
  635. )
  636. self._state_res_metrics.clear()
  637. def _report_biggest(
  638. self,
  639. extract_key: Callable[[_StateResMetrics], Any],
  640. metric_name: str,
  641. prometheus_counter_metric: Counter,
  642. ) -> None:
  643. """Report metrics on the biggest rooms for state res
  644. Args:
  645. extract_key: a callable which, given a _StateResMetrics, extracts a single
  646. metric to sort by.
  647. metric_name: the name of the metric we have extracted, for the log line
  648. prometheus_counter_metric: a prometheus metric recording the sum of the
  649. the extracted metric
  650. """
  651. n_to_log = 10
  652. if not metrics_logger.isEnabledFor(logging.DEBUG):
  653. # only need the most expensive if we don't have debug logging, which
  654. # allows nlargest() to degrade to max()
  655. n_to_log = 1
  656. items = self._state_res_metrics.items()
  657. # log the N biggest rooms
  658. biggest: List[Tuple[str, _StateResMetrics]] = heapq.nlargest(
  659. n_to_log, items, key=lambda i: extract_key(i[1])
  660. )
  661. metrics_logger.debug(
  662. "%i biggest rooms for state-res by %s: %s",
  663. len(biggest),
  664. metric_name,
  665. ["%s (%gs)" % (r, extract_key(m)) for (r, m) in biggest],
  666. )
  667. # report info on the single biggest to prometheus
  668. _, biggest_metrics = biggest[0]
  669. prometheus_counter_metric.inc(extract_key(biggest_metrics))
  670. def _make_state_cache_entry(
  671. new_state: StateMap[str], state_groups_ids: Mapping[int, StateMap[str]]
  672. ) -> _StateCacheEntry:
  673. """Given a resolved state, and a set of input state groups, pick one to base
  674. a new state group on (if any), and return an appropriately-constructed
  675. _StateCacheEntry.
  676. Args:
  677. new_state: resolved state map (mapping from (type, state_key) to event_id)
  678. state_groups_ids:
  679. map from state group id to the state in that state group (where
  680. 'state' is a map from state key to event id)
  681. Returns:
  682. The cache entry.
  683. """
  684. # if the new state matches any of the input state groups, we can
  685. # use that state group again. Otherwise we will generate a state_id
  686. # which will be used as a cache key for future resolutions, but
  687. # not get persisted.
  688. # first look for exact matches
  689. new_state_event_ids = set(new_state.values())
  690. for sg, state in state_groups_ids.items():
  691. if len(new_state_event_ids) != len(state):
  692. continue
  693. old_state_event_ids = set(state.values())
  694. if new_state_event_ids == old_state_event_ids:
  695. # got an exact match.
  696. return _StateCacheEntry(state=None, state_group=sg)
  697. # TODO: We want to create a state group for this set of events, to
  698. # increase cache hits, but we need to make sure that it doesn't
  699. # end up as a prev_group without being added to the database
  700. # failing that, look for the closest match.
  701. prev_group = None
  702. delta_ids: Optional[StateMap[str]] = None
  703. for old_group, old_state in state_groups_ids.items():
  704. if old_state.keys() - new_state.keys():
  705. # Currently we don't support deltas that remove keys from the state
  706. # map, so we have to ignore this group as a candidate to base the
  707. # new group on.
  708. continue
  709. n_delta_ids = {k: v for k, v in new_state.items() if old_state.get(k) != v}
  710. if not delta_ids or len(n_delta_ids) < len(delta_ids):
  711. prev_group = old_group
  712. delta_ids = n_delta_ids
  713. if prev_group is not None:
  714. # If we have a prev group and deltas then we can drop the new state from
  715. # the cache (to reduce memory usage).
  716. return _StateCacheEntry(
  717. state=None, state_group=None, prev_group=prev_group, delta_ids=delta_ids
  718. )
  719. else:
  720. return _StateCacheEntry(state=new_state, state_group=None)
  721. @attr.s(slots=True, auto_attribs=True)
  722. class StateResolutionStore:
  723. """Interface that allows state resolution algorithms to access the database
  724. in well defined way.
  725. """
  726. store: "DataStore"
  727. def get_events(
  728. self, event_ids: StrCollection, allow_rejected: bool = False
  729. ) -> Awaitable[Dict[str, EventBase]]:
  730. """Get events from the database
  731. Args:
  732. event_ids: The event_ids of the events to fetch
  733. allow_rejected: If True return rejected events.
  734. Returns:
  735. An awaitable which resolves to a dict from event_id to event.
  736. """
  737. return self.store.get_events(
  738. event_ids,
  739. redact_behaviour=EventRedactBehaviour.as_is,
  740. get_prev_content=False,
  741. allow_rejected=allow_rejected,
  742. )
  743. def get_auth_chain_difference(
  744. self, room_id: str, state_sets: List[Set[str]]
  745. ) -> Awaitable[Set[str]]:
  746. """Given sets of state events figure out the auth chain difference (as
  747. per state res v2 algorithm).
  748. This equivalent to fetching the full auth chain for each set of state
  749. and returning the events that don't appear in each and every auth
  750. chain.
  751. Returns:
  752. An awaitable that resolves to a set of event IDs.
  753. """
  754. return self.store.get_auth_chain_difference(room_id, state_sets)