async def _calculate_current_state(self, room_id: str) -> StateMap[str]: """Calculate the current state of a room, based on the forward extremities Args: room_id: room for which to calculate current state Returns: map from (type, state_key) to event id for the current state in the room """ latest_event_ids = await self.main_store.get_latest_event_ids_in_room( room_id) state_groups = set( (await self.main_store._get_state_group_for_events(latest_event_ids) ).values()) state_maps_by_state_group = await self.state_store._get_state_for_groups( state_groups) if len(state_groups) == 1: # If there is only one state group, then we know what the current # state is. return state_maps_by_state_group[state_groups.pop()] # Ok, we need to defer to the state handler to resolve our state sets. logger.debug("calling resolve_state_groups from preserve_events") # Avoid a circular import. from synapse.state import StateResolutionStore room_version = await self.main_store.get_room_version_id(room_id) res = await self._state_resolution_handler.resolve_state_groups( room_id, room_version, state_maps_by_state_group, event_map=None, state_res_store=StateResolutionStore(self.main_store), ) return res.state
async def _get_new_state_after_events( self, room_id: str, events_context: List[Tuple[FrozenEvent, EventContext]], old_latest_event_ids: Iterable[str], new_latest_event_ids: Iterable[str], ) -> Tuple[Optional[StateMap[str]], Optional[StateMap[str]]]: """Calculate the current state dict after adding some new events to a room Args: room_id (str): room to which the events are being added. Used for logging etc events_context (list[(EventBase, EventContext)]): events and contexts which are being added to the room old_latest_event_ids (iterable[str]): the old forward extremities for the room. new_latest_event_ids (iterable[str]): the new forward extremities for the room. Returns: Returns a tuple of two state maps, the first being the full new current state and the second being the delta to the existing current state. If both are None then there has been no change. If there has been a change then we only return the delta if its already been calculated. Conversely if we do know the delta then the new current state is only returned if we've already calculated it. """ # map from state_group to ((type, key) -> event_id) state map state_groups_map = {} # Map from (prev state group, new state group) -> delta state dict state_group_deltas = {} for ev, ctx in events_context: if ctx.state_group is None: # This should only happen for outlier events. if not ev.internal_metadata.is_outlier(): raise Exception("Context for new event %s has no state " "group" % (ev.event_id, )) continue if ctx.state_group in state_groups_map: continue # We're only interested in pulling out state that has already # been cached in the context. We'll pull stuff out of the DB later # if necessary. current_state_ids = ctx.get_cached_current_state_ids() if current_state_ids is not None: state_groups_map[ctx.state_group] = current_state_ids if ctx.prev_group: state_group_deltas[(ctx.prev_group, ctx.state_group)] = ctx.delta_ids # We need to map the event_ids to their state groups. First, let's # check if the event is one we're persisting, in which case we can # pull the state group from its context. # Otherwise we need to pull the state group from the database. # Set of events we need to fetch groups for. (We know none of the old # extremities are going to be in events_context). missing_event_ids = set(old_latest_event_ids) event_id_to_state_group = {} for event_id in new_latest_event_ids: # First search in the list of new events we're adding. for ev, ctx in events_context: if event_id == ev.event_id and ctx.state_group is not None: event_id_to_state_group[event_id] = ctx.state_group break else: # If we couldn't find it, then we'll need to pull # the state from the database missing_event_ids.add(event_id) if missing_event_ids: # Now pull out the state groups for any missing events from DB event_to_groups = await self.main_store._get_state_group_for_events( missing_event_ids) event_id_to_state_group.update(event_to_groups) # State groups of old_latest_event_ids old_state_groups = set(event_id_to_state_group[evid] for evid in old_latest_event_ids) # State groups of new_latest_event_ids new_state_groups = set(event_id_to_state_group[evid] for evid in new_latest_event_ids) # If they old and new groups are the same then we don't need to do # anything. if old_state_groups == new_state_groups: return None, None if len(new_state_groups) == 1 and len(old_state_groups) == 1: # If we're going from one state group to another, lets check if # we have a delta for that transition. If we do then we can just # return that. new_state_group = next(iter(new_state_groups)) old_state_group = next(iter(old_state_groups)) delta_ids = state_group_deltas.get( (old_state_group, new_state_group), None) if delta_ids is not None: # We have a delta from the existing to new current state, # so lets just return that. If we happen to already have # the current state in memory then lets also return that, # but it doesn't matter if we don't. new_state = state_groups_map.get(new_state_group) return new_state, delta_ids # Now that we have calculated new_state_groups we need to get # their state IDs so we can resolve to a single state set. missing_state = new_state_groups - set(state_groups_map) if missing_state: group_to_state = await self.state_store._get_state_for_groups( missing_state) state_groups_map.update(group_to_state) if len(new_state_groups) == 1: # If there is only one state group, then we know what the current # state is. return state_groups_map[new_state_groups.pop()], None # Ok, we need to defer to the state handler to resolve our state sets. state_groups = {sg: state_groups_map[sg] for sg in new_state_groups} events_map = {ev.event_id: ev for ev, _ in events_context} # We need to get the room version, which is in the create event. # Normally that'd be in the database, but its also possible that we're # currently trying to persist it. room_version = None for ev, _ in events_context: if ev.type == EventTypes.Create and ev.state_key == "": room_version = ev.content.get("room_version", "1") break if not room_version: room_version = await self.main_store.get_room_version_id(room_id) logger.debug("calling resolve_state_groups from preserve_events") res = await self._state_resolution_handler.resolve_state_groups( room_id, room_version, state_groups, events_map, state_res_store=StateResolutionStore(self.main_store), ) return res.state, None