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.
 
 
 
 
 
 

916 lines
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. Collection,
  24. DefaultDict,
  25. Dict,
  26. FrozenSet,
  27. List,
  28. Mapping,
  29. Optional,
  30. Sequence,
  31. Set,
  32. Tuple,
  33. )
  34. import attr
  35. from immutabledict import immutabledict
  36. from prometheus_client import Counter, Histogram
  37. from synapse.api.constants import EventTypes
  38. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, StateResolutionVersions
  39. from synapse.events import EventBase
  40. from synapse.events.snapshot import (
  41. EventContext,
  42. UnpersistedEventContext,
  43. UnpersistedEventContextBase,
  44. )
  45. from synapse.logging.context import ContextResourceUsage
  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
  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: Collection[str],
  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: Collection[str]
  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: Collection[str]
  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. state = await entry.get_state(self._state_storage_controller, StateFilter.all())
  221. return await self.store.get_joined_hosts(room_id, state, entry)
  222. async def calculate_context_info(
  223. self,
  224. event: EventBase,
  225. state_ids_before_event: Optional[StateMap[str]] = None,
  226. partial_state: Optional[bool] = None,
  227. state_group_before_event: Optional[int] = None,
  228. ) -> UnpersistedEventContextBase:
  229. """
  230. Calulates the contents of an unpersisted event context, other than the current
  231. state group (which is either provided or calculated when the event context is persisted)
  232. state_ids_before_event:
  233. The event ids of the full state before the event if
  234. it can't be calculated from existing events. This is normally
  235. only specified when receiving an event from federation where we
  236. don't have the prev events, e.g. when backfilling or when the event
  237. is being created for batch persisting.
  238. partial_state:
  239. `True` if `state_ids_before_event` is partial and omits non-critical
  240. membership events.
  241. `False` if `state_ids_before_event` is the full state.
  242. `None` when `state_ids_before_event` is not provided. In this case, the
  243. flag will be calculated based on `event`'s prev events.
  244. state_group_before_event:
  245. the current state group at the time of event, if known
  246. Returns:
  247. The event context.
  248. Raises:
  249. RuntimeError if `state_ids_before_event` is not provided and one or more
  250. prev events are missing or outliers.
  251. """
  252. assert not event.internal_metadata.is_outlier()
  253. #
  254. # first of all, figure out the state before the event, unless we
  255. # already have it.
  256. #
  257. if state_ids_before_event:
  258. # if we're given the state before the event, then we use that
  259. state_group_before_event_prev_group = None
  260. deltas_to_state_group_before_event = None
  261. # the partial_state flag must be provided
  262. assert partial_state is not None
  263. else:
  264. # otherwise, we'll need to resolve the state across the prev_events.
  265. # partial_state should not be set explicitly in this case:
  266. # we work it out dynamically
  267. assert partial_state is None
  268. # if any of the prev-events have partial state, so do we.
  269. # (This is slightly racy - the prev-events might get fixed up before we use
  270. # their states - but I don't think that really matters; it just means we
  271. # might redundantly recalculate the state for this event later.)
  272. prev_event_ids = event.prev_event_ids()
  273. incomplete_prev_events = await self.store.get_partial_state_events(
  274. prev_event_ids
  275. )
  276. partial_state = any(incomplete_prev_events.values())
  277. if partial_state:
  278. logger.debug(
  279. "New/incoming event %s refers to prev_events %s with partial state",
  280. event.event_id,
  281. [k for (k, v) in incomplete_prev_events.items() if v],
  282. )
  283. logger.debug("calling resolve_state_groups from compute_event_context")
  284. # we've already taken into account partial state, so no need to wait for
  285. # complete state here.
  286. entry = await self.resolve_state_groups_for_events(
  287. event.room_id,
  288. event.prev_event_ids(),
  289. await_full_state=False,
  290. )
  291. state_group_before_event_prev_group = entry.prev_group
  292. deltas_to_state_group_before_event = entry.delta_ids
  293. state_ids_before_event = None
  294. # We make sure that we have a state group assigned to the state.
  295. if entry.state_group is None:
  296. # store_state_group requires us to have either a previous state group
  297. # (with deltas) or the complete state map. So, if we don't have a
  298. # previous state group, load the complete state map now.
  299. if state_group_before_event_prev_group is None:
  300. state_ids_before_event = await entry.get_state(
  301. self._state_storage_controller, StateFilter.all()
  302. )
  303. state_group_before_event = (
  304. await self._state_storage_controller.store_state_group(
  305. event.event_id,
  306. event.room_id,
  307. prev_group=state_group_before_event_prev_group,
  308. delta_ids=deltas_to_state_group_before_event,
  309. current_state_ids=state_ids_before_event,
  310. )
  311. )
  312. entry.set_state_group(state_group_before_event)
  313. else:
  314. state_group_before_event = entry.state_group
  315. #
  316. # now if it's not a state event, we're done
  317. #
  318. if not event.is_state():
  319. return UnpersistedEventContext(
  320. storage=self._storage_controllers,
  321. state_group_before_event=state_group_before_event,
  322. state_group_after_event=state_group_before_event,
  323. state_delta_due_to_event={},
  324. prev_group_for_state_group_before_event=state_group_before_event_prev_group,
  325. delta_ids_to_state_group_before_event=deltas_to_state_group_before_event,
  326. partial_state=partial_state,
  327. state_map_before_event=state_ids_before_event,
  328. )
  329. #
  330. # otherwise, we'll need to set up creating a new state group for after the event
  331. #
  332. key = (event.type, event.state_key)
  333. if state_ids_before_event is not None:
  334. replaces = state_ids_before_event.get(key)
  335. else:
  336. replaces_state_map = await entry.get_state(
  337. self._state_storage_controller, StateFilter.from_types([key])
  338. )
  339. replaces = replaces_state_map.get(key)
  340. if replaces and replaces != event.event_id:
  341. event.unsigned["replaces_state"] = replaces
  342. delta_ids = {key: event.event_id}
  343. return UnpersistedEventContext(
  344. storage=self._storage_controllers,
  345. state_group_before_event=state_group_before_event,
  346. state_group_after_event=None,
  347. state_delta_due_to_event=delta_ids,
  348. prev_group_for_state_group_before_event=state_group_before_event_prev_group,
  349. delta_ids_to_state_group_before_event=deltas_to_state_group_before_event,
  350. partial_state=partial_state,
  351. state_map_before_event=state_ids_before_event,
  352. )
  353. async def compute_event_context(
  354. self,
  355. event: EventBase,
  356. state_ids_before_event: Optional[StateMap[str]] = None,
  357. partial_state: Optional[bool] = None,
  358. ) -> EventContext:
  359. """Build an EventContext structure for a non-outlier event.
  360. (for an outlier, call EventContext.for_outlier directly)
  361. This works out what the current state should be for the event, and
  362. generates a new state group if necessary.
  363. Args:
  364. event:
  365. state_ids_before_event: The event ids of the state before the event if
  366. it can't be calculated from existing events. This is normally
  367. only specified when receiving an event from federation where we
  368. don't have the prev events, e.g. when backfilling.
  369. partial_state:
  370. `True` if `state_ids_before_event` is partial and omits non-critical
  371. membership events.
  372. `False` if `state_ids_before_event` is the full state.
  373. `None` when `state_ids_before_event` is not provided. In this case, the
  374. flag will be calculated based on `event`'s prev events.
  375. entry:
  376. A state cache entry for the resolved state across the prev events. We may
  377. have already calculated this, so if it's available pass it in
  378. Returns:
  379. The event context.
  380. Raises:
  381. RuntimeError if `state_ids_before_event` is not provided and one or more
  382. prev events are missing or outliers.
  383. """
  384. unpersisted_context = await self.calculate_context_info(
  385. event=event,
  386. state_ids_before_event=state_ids_before_event,
  387. partial_state=partial_state,
  388. )
  389. return await unpersisted_context.persist(event)
  390. @measure_func()
  391. async def resolve_state_groups_for_events(
  392. self, room_id: str, event_ids: Collection[str], await_full_state: bool = True
  393. ) -> _StateCacheEntry:
  394. """Given a list of event_ids this method fetches the state at each
  395. event, resolves conflicts between them and returns them.
  396. Args:
  397. room_id
  398. event_ids
  399. await_full_state: if true, will block if we do not yet have complete
  400. state at these events.
  401. Returns:
  402. The resolved state
  403. Raises:
  404. RuntimeError if we don't have a state group for one or more of the events
  405. (ie. they are outliers or unknown)
  406. """
  407. logger.debug("resolve_state_groups event_ids %s", event_ids)
  408. state_groups = await self._state_storage_controller.get_state_group_for_events(
  409. event_ids, await_full_state=await_full_state
  410. )
  411. state_group_ids = state_groups.values()
  412. # check if each event has same state group id, if so there's no state to resolve
  413. state_group_ids_set = set(state_group_ids)
  414. if len(state_group_ids_set) == 1:
  415. (state_group_id,) = state_group_ids_set
  416. (
  417. prev_group,
  418. delta_ids,
  419. ) = await self._state_storage_controller.get_state_group_delta(
  420. state_group_id
  421. )
  422. return _StateCacheEntry(
  423. state=None,
  424. state_group=state_group_id,
  425. prev_group=prev_group,
  426. delta_ids=delta_ids,
  427. )
  428. elif len(state_group_ids_set) == 0:
  429. return _StateCacheEntry(state={}, state_group=None)
  430. room_version = await self.store.get_room_version_id(room_id)
  431. state_to_resolve = await self._state_storage_controller.get_state_for_groups(
  432. state_group_ids_set
  433. )
  434. result = await self._state_resolution_handler.resolve_state_groups(
  435. room_id,
  436. room_version,
  437. state_to_resolve,
  438. None,
  439. state_res_store=StateResolutionStore(self.store),
  440. )
  441. return result
  442. async def update_current_state(self, room_id: str) -> None:
  443. """Recalculates the current state for a room, and persists it.
  444. Raises:
  445. SynapseError(502): if all attempts to connect to the event persister worker
  446. fail
  447. """
  448. writer_instance = self._events_shard_config.get_instance(room_id)
  449. if writer_instance != self._instance_name:
  450. await self._update_current_state_client(
  451. instance_name=writer_instance,
  452. room_id=room_id,
  453. )
  454. return
  455. assert self._storage_controllers.persistence is not None
  456. await self._storage_controllers.persistence.update_current_state(room_id)
  457. @attr.s(slots=True, auto_attribs=True)
  458. class _StateResMetrics:
  459. """Keeps track of some usage metrics about state res."""
  460. # System and User CPU time, in seconds
  461. cpu_time: float = 0.0
  462. # time spent on database transactions (excluding scheduling time). This roughly
  463. # corresponds to the amount of work done on the db server, excluding event fetches.
  464. db_time: float = 0.0
  465. # number of events fetched from the db.
  466. db_events: int = 0
  467. _biggest_room_by_cpu_counter = Counter(
  468. "synapse_state_res_cpu_for_biggest_room_seconds",
  469. "CPU time spent performing state resolution for the single most expensive "
  470. "room for state resolution",
  471. )
  472. _biggest_room_by_db_counter = Counter(
  473. "synapse_state_res_db_for_biggest_room_seconds",
  474. "Database time spent performing state resolution for the single most "
  475. "expensive room for state resolution",
  476. )
  477. _cpu_times = Histogram(
  478. "synapse_state_res_cpu_for_all_rooms_seconds",
  479. "CPU time (utime+stime) spent computing a single state resolution",
  480. )
  481. _db_times = Histogram(
  482. "synapse_state_res_db_for_all_rooms_seconds",
  483. "Database time spent computing a single state resolution",
  484. )
  485. class StateResolutionHandler:
  486. """Responsible for doing state conflict resolution.
  487. Note that the storage layer depends on this handler, so all functions must
  488. be storage-independent.
  489. """
  490. def __init__(self, hs: "HomeServer"):
  491. self.clock = hs.get_clock()
  492. self.resolve_linearizer = Linearizer(name="state_resolve_lock")
  493. # dict of set of event_ids -> _StateCacheEntry.
  494. self._state_cache: ExpiringCache[
  495. FrozenSet[int], _StateCacheEntry
  496. ] = ExpiringCache(
  497. cache_name="state_cache",
  498. clock=self.clock,
  499. max_len=100000,
  500. expiry_ms=EVICTION_TIMEOUT_SECONDS * 1000,
  501. iterable=True,
  502. reset_expiry_on_get=True,
  503. )
  504. #
  505. # stuff for tracking time spent on state-res by room
  506. #
  507. # tracks the amount of work done on state res per room
  508. self._state_res_metrics: DefaultDict[str, _StateResMetrics] = defaultdict(
  509. _StateResMetrics
  510. )
  511. self.clock.looping_call(self._report_metrics, 120 * 1000)
  512. async def resolve_state_groups(
  513. self,
  514. room_id: str,
  515. room_version: str,
  516. state_groups_ids: Mapping[int, StateMap[str]],
  517. event_map: Optional[Dict[str, EventBase]],
  518. state_res_store: "StateResolutionStore",
  519. ) -> _StateCacheEntry:
  520. """Resolves conflicts between a set of state groups
  521. Always generates a new state group (unless we hit the cache), so should
  522. not be called for a single state group
  523. Args:
  524. room_id: room we are resolving for (used for logging and sanity checks)
  525. room_version: version of the room
  526. state_groups_ids:
  527. A map from state group id to the state in that state group
  528. (where 'state' is a map from state key to event id)
  529. event_map:
  530. a dict from event_id to event, for any events that we happen to
  531. have in flight (eg, those currently being persisted). This will be
  532. used as a starting point for finding the state we need; any missing
  533. events will be requested via state_res_store.
  534. If None, all events will be fetched via state_res_store.
  535. state_res_store
  536. Returns:
  537. The resolved state
  538. """
  539. group_names = frozenset(state_groups_ids.keys())
  540. async with self.resolve_linearizer.queue(group_names):
  541. cache = self._state_cache.get(group_names, None)
  542. if cache:
  543. return cache
  544. logger.info(
  545. "Resolving state for %s with groups %s",
  546. room_id,
  547. list(group_names),
  548. )
  549. state_groups_histogram.observe(len(state_groups_ids))
  550. new_state = await self.resolve_events_with_store(
  551. room_id,
  552. room_version,
  553. list(state_groups_ids.values()),
  554. event_map=event_map,
  555. state_res_store=state_res_store,
  556. )
  557. # if the new state matches any of the input state groups, we can
  558. # use that state group again. Otherwise we will generate a state_id
  559. # which will be used as a cache key for future resolutions, but
  560. # not get persisted.
  561. with Measure(self.clock, "state.create_group_ids"):
  562. cache = _make_state_cache_entry(new_state, state_groups_ids)
  563. self._state_cache[group_names] = cache
  564. return cache
  565. async def resolve_events_with_store(
  566. self,
  567. room_id: str,
  568. room_version: str,
  569. state_sets: Sequence[StateMap[str]],
  570. event_map: Optional[Dict[str, EventBase]],
  571. state_res_store: "StateResolutionStore",
  572. ) -> StateMap[str]:
  573. """
  574. Args:
  575. room_id: the room we are working in
  576. room_version: Version of the room
  577. state_sets: List of dicts of (type, state_key) -> event_id,
  578. which are the different state groups to resolve.
  579. event_map:
  580. a dict from event_id to event, for any events that we happen to
  581. have in flight (eg, those currently being persisted). This will be
  582. used as a starting point for finding the state we need; any missing
  583. events will be requested via state_map_factory.
  584. If None, all events will be fetched via state_res_store.
  585. state_res_store: a place to fetch events from
  586. Returns:
  587. a map from (type, state_key) to event_id.
  588. """
  589. try:
  590. with Measure(self.clock, "state._resolve_events") as m:
  591. room_version_obj = KNOWN_ROOM_VERSIONS[room_version]
  592. if room_version_obj.state_res == StateResolutionVersions.V1:
  593. return await v1.resolve_events_with_store(
  594. room_id,
  595. room_version_obj,
  596. state_sets,
  597. event_map,
  598. state_res_store.get_events,
  599. )
  600. else:
  601. return await v2.resolve_events_with_store(
  602. self.clock,
  603. room_id,
  604. room_version_obj,
  605. state_sets,
  606. event_map,
  607. state_res_store,
  608. )
  609. finally:
  610. self._record_state_res_metrics(room_id, m.get_resource_usage())
  611. def _record_state_res_metrics(
  612. self, room_id: str, rusage: ContextResourceUsage
  613. ) -> None:
  614. room_metrics = self._state_res_metrics[room_id]
  615. room_metrics.cpu_time += rusage.ru_utime + rusage.ru_stime
  616. room_metrics.db_time += rusage.db_txn_duration_sec
  617. room_metrics.db_events += rusage.evt_db_fetch_count
  618. _cpu_times.observe(rusage.ru_utime + rusage.ru_stime)
  619. _db_times.observe(rusage.db_txn_duration_sec)
  620. def _report_metrics(self) -> None:
  621. if not self._state_res_metrics:
  622. # no state res has happened since the last iteration: don't bother logging.
  623. return
  624. self._report_biggest(
  625. lambda i: i.cpu_time,
  626. "CPU time",
  627. _biggest_room_by_cpu_counter,
  628. )
  629. self._report_biggest(
  630. lambda i: i.db_time,
  631. "DB time",
  632. _biggest_room_by_db_counter,
  633. )
  634. self._state_res_metrics.clear()
  635. def _report_biggest(
  636. self,
  637. extract_key: Callable[[_StateResMetrics], Any],
  638. metric_name: str,
  639. prometheus_counter_metric: Counter,
  640. ) -> None:
  641. """Report metrics on the biggest rooms for state res
  642. Args:
  643. extract_key: a callable which, given a _StateResMetrics, extracts a single
  644. metric to sort by.
  645. metric_name: the name of the metric we have extracted, for the log line
  646. prometheus_counter_metric: a prometheus metric recording the sum of the
  647. the extracted metric
  648. """
  649. n_to_log = 10
  650. if not metrics_logger.isEnabledFor(logging.DEBUG):
  651. # only need the most expensive if we don't have debug logging, which
  652. # allows nlargest() to degrade to max()
  653. n_to_log = 1
  654. items = self._state_res_metrics.items()
  655. # log the N biggest rooms
  656. biggest: List[Tuple[str, _StateResMetrics]] = heapq.nlargest(
  657. n_to_log, items, key=lambda i: extract_key(i[1])
  658. )
  659. metrics_logger.debug(
  660. "%i biggest rooms for state-res by %s: %s",
  661. len(biggest),
  662. metric_name,
  663. ["%s (%gs)" % (r, extract_key(m)) for (r, m) in biggest],
  664. )
  665. # report info on the single biggest to prometheus
  666. _, biggest_metrics = biggest[0]
  667. prometheus_counter_metric.inc(extract_key(biggest_metrics))
  668. def _make_state_cache_entry(
  669. new_state: StateMap[str], state_groups_ids: Mapping[int, StateMap[str]]
  670. ) -> _StateCacheEntry:
  671. """Given a resolved state, and a set of input state groups, pick one to base
  672. a new state group on (if any), and return an appropriately-constructed
  673. _StateCacheEntry.
  674. Args:
  675. new_state: resolved state map (mapping from (type, state_key) to event_id)
  676. state_groups_ids:
  677. map from state group id to the state in that state group (where
  678. 'state' is a map from state key to event id)
  679. Returns:
  680. The cache entry.
  681. """
  682. # if the new state matches any of the input state groups, we can
  683. # use that state group again. Otherwise we will generate a state_id
  684. # which will be used as a cache key for future resolutions, but
  685. # not get persisted.
  686. # first look for exact matches
  687. new_state_event_ids = set(new_state.values())
  688. for sg, state in state_groups_ids.items():
  689. if len(new_state_event_ids) != len(state):
  690. continue
  691. old_state_event_ids = set(state.values())
  692. if new_state_event_ids == old_state_event_ids:
  693. # got an exact match.
  694. return _StateCacheEntry(state=None, state_group=sg)
  695. # TODO: We want to create a state group for this set of events, to
  696. # increase cache hits, but we need to make sure that it doesn't
  697. # end up as a prev_group without being added to the database
  698. # failing that, look for the closest match.
  699. prev_group = None
  700. delta_ids: Optional[StateMap[str]] = None
  701. for old_group, old_state in state_groups_ids.items():
  702. if old_state.keys() - new_state.keys():
  703. # Currently we don't support deltas that remove keys from the state
  704. # map, so we have to ignore this group as a candidate to base the
  705. # new group on.
  706. continue
  707. n_delta_ids = {k: v for k, v in new_state.items() if old_state.get(k) != v}
  708. if not delta_ids or len(n_delta_ids) < len(delta_ids):
  709. prev_group = old_group
  710. delta_ids = n_delta_ids
  711. if prev_group is not None:
  712. # If we have a prev group and deltas then we can drop the new state from
  713. # the cache (to reduce memory usage).
  714. return _StateCacheEntry(
  715. state=None, state_group=None, prev_group=prev_group, delta_ids=delta_ids
  716. )
  717. else:
  718. return _StateCacheEntry(state=new_state, state_group=None)
  719. @attr.s(slots=True, auto_attribs=True)
  720. class StateResolutionStore:
  721. """Interface that allows state resolution algorithms to access the database
  722. in well defined way.
  723. """
  724. store: "DataStore"
  725. def get_events(
  726. self, event_ids: Collection[str], allow_rejected: bool = False
  727. ) -> Awaitable[Dict[str, EventBase]]:
  728. """Get events from the database
  729. Args:
  730. event_ids: The event_ids of the events to fetch
  731. allow_rejected: If True return rejected events.
  732. Returns:
  733. An awaitable which resolves to a dict from event_id to event.
  734. """
  735. return self.store.get_events(
  736. event_ids,
  737. redact_behaviour=EventRedactBehaviour.as_is,
  738. get_prev_content=False,
  739. allow_rejected=allow_rejected,
  740. )
  741. def get_auth_chain_difference(
  742. self, room_id: str, state_sets: List[Set[str]]
  743. ) -> Awaitable[Set[str]]:
  744. """Given sets of state events figure out the auth chain difference (as
  745. per state res v2 algorithm).
  746. This equivalent to fetching the full auth chain for each set of state
  747. and returning the events that don't appear in each and every auth
  748. chain.
  749. Returns:
  750. An awaitable that resolves to a set of event IDs.
  751. """
  752. return self.store.get_auth_chain_difference(room_id, state_sets)