state.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket 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. from twisted.internet import defer
  16. from synapse import event_auth
  17. from synapse.util.logutils import log_function
  18. from synapse.util.caches.expiringcache import ExpiringCache
  19. from synapse.util.metrics import Measure
  20. from synapse.api.constants import EventTypes
  21. from synapse.api.errors import AuthError
  22. from synapse.events.snapshot import EventContext
  23. from synapse.util.async import Linearizer
  24. from synapse.util.caches import CACHE_SIZE_FACTOR
  25. from collections import namedtuple
  26. from frozendict import frozendict
  27. import logging
  28. import hashlib
  29. from six import iteritems, itervalues
  30. logger = logging.getLogger(__name__)
  31. KeyStateTuple = namedtuple("KeyStateTuple", ("context", "type", "state_key"))
  32. SIZE_OF_CACHE = int(100000 * CACHE_SIZE_FACTOR)
  33. EVICTION_TIMEOUT_SECONDS = 60 * 60
  34. _NEXT_STATE_ID = 1
  35. POWER_KEY = (EventTypes.PowerLevels, "")
  36. def _gen_state_id():
  37. global _NEXT_STATE_ID
  38. s = "X%d" % (_NEXT_STATE_ID,)
  39. _NEXT_STATE_ID += 1
  40. return s
  41. class _StateCacheEntry(object):
  42. __slots__ = ["state", "state_group", "state_id", "prev_group", "delta_ids"]
  43. def __init__(self, state, state_group, prev_group=None, delta_ids=None):
  44. # dict[(str, str), str] map from (type, state_key) to event_id
  45. self.state = frozendict(state)
  46. # the ID of a state group if one and only one is involved.
  47. # otherwise, None otherwise?
  48. self.state_group = state_group
  49. self.prev_group = prev_group
  50. self.delta_ids = frozendict(delta_ids) if delta_ids is not None else None
  51. # The `state_id` is a unique ID we generate that can be used as ID for
  52. # this collection of state. Usually this would be the same as the
  53. # state group, but on worker instances we can't generate a new state
  54. # group each time we resolve state, so we generate a separate one that
  55. # isn't persisted and is used solely for caches.
  56. # `state_id` is either a state_group (and so an int) or a string. This
  57. # ensures we don't accidentally persist a state_id as a stateg_group
  58. if state_group:
  59. self.state_id = state_group
  60. else:
  61. self.state_id = _gen_state_id()
  62. def __len__(self):
  63. return len(self.state)
  64. class StateHandler(object):
  65. """Fetches bits of state from the stores, and does state resolution
  66. where necessary
  67. """
  68. def __init__(self, hs):
  69. self.clock = hs.get_clock()
  70. self.store = hs.get_datastore()
  71. self.hs = hs
  72. self._state_resolution_handler = hs.get_state_resolution_handler()
  73. def start_caching(self):
  74. # TODO: remove this shim
  75. self._state_resolution_handler.start_caching()
  76. @defer.inlineCallbacks
  77. def get_current_state(self, room_id, event_type=None, state_key="",
  78. latest_event_ids=None):
  79. """ Retrieves the current state for the room. This is done by
  80. calling `get_latest_events_in_room` to get the leading edges of the
  81. event graph and then resolving any of the state conflicts.
  82. This is equivalent to getting the state of an event that were to send
  83. next before receiving any new events.
  84. If `event_type` is specified, then the method returns only the one
  85. event (or None) with that `event_type` and `state_key`.
  86. Returns:
  87. map from (type, state_key) to event
  88. """
  89. if not latest_event_ids:
  90. latest_event_ids = yield self.store.get_latest_event_ids_in_room(room_id)
  91. logger.debug("calling resolve_state_groups from get_current_state")
  92. ret = yield self.resolve_state_groups_for_events(room_id, latest_event_ids)
  93. state = ret.state
  94. if event_type:
  95. event_id = state.get((event_type, state_key))
  96. event = None
  97. if event_id:
  98. event = yield self.store.get_event(event_id, allow_none=True)
  99. defer.returnValue(event)
  100. return
  101. state_map = yield self.store.get_events(list(state.values()),
  102. get_prev_content=False)
  103. state = {
  104. key: state_map[e_id] for key, e_id in iteritems(state) if e_id in state_map
  105. }
  106. defer.returnValue(state)
  107. @defer.inlineCallbacks
  108. def get_current_state_ids(self, room_id, latest_event_ids=None):
  109. """Get the current state, or the state at a set of events, for a room
  110. Args:
  111. room_id (str):
  112. latest_event_ids (iterable[str]|None): if given, the forward
  113. extremities to resolve. If None, we look them up from the
  114. database (via a cache)
  115. Returns:
  116. Deferred[dict[(str, str), str)]]: the state dict, mapping from
  117. (event_type, state_key) -> event_id
  118. """
  119. if not latest_event_ids:
  120. latest_event_ids = yield self.store.get_latest_event_ids_in_room(room_id)
  121. logger.debug("calling resolve_state_groups from get_current_state_ids")
  122. ret = yield self.resolve_state_groups_for_events(room_id, latest_event_ids)
  123. state = ret.state
  124. defer.returnValue(state)
  125. @defer.inlineCallbacks
  126. def get_current_user_in_room(self, room_id, latest_event_ids=None):
  127. if not latest_event_ids:
  128. latest_event_ids = yield self.store.get_latest_event_ids_in_room(room_id)
  129. logger.debug("calling resolve_state_groups from get_current_user_in_room")
  130. entry = yield self.resolve_state_groups_for_events(room_id, latest_event_ids)
  131. joined_users = yield self.store.get_joined_users_from_state(room_id, entry)
  132. defer.returnValue(joined_users)
  133. @defer.inlineCallbacks
  134. def get_current_hosts_in_room(self, room_id, latest_event_ids=None):
  135. if not latest_event_ids:
  136. latest_event_ids = yield self.store.get_latest_event_ids_in_room(room_id)
  137. logger.debug("calling resolve_state_groups from get_current_hosts_in_room")
  138. entry = yield self.resolve_state_groups_for_events(room_id, latest_event_ids)
  139. joined_hosts = yield self.store.get_joined_hosts(room_id, entry)
  140. defer.returnValue(joined_hosts)
  141. @defer.inlineCallbacks
  142. def compute_event_context(self, event, old_state=None):
  143. """Build an EventContext structure for the event.
  144. This works out what the current state should be for the event, and
  145. generates a new state group if necessary.
  146. Args:
  147. event (synapse.events.EventBase):
  148. old_state (dict|None): The state at the event if it can't be
  149. calculated from existing events. This is normally only specified
  150. when receiving an event from federation where we don't have the
  151. prev events for, e.g. when backfilling.
  152. Returns:
  153. synapse.events.snapshot.EventContext:
  154. """
  155. if event.internal_metadata.is_outlier():
  156. # If this is an outlier, then we know it shouldn't have any current
  157. # state. Certainly store.get_current_state won't return any, and
  158. # persisting the event won't store the state group.
  159. context = EventContext()
  160. if old_state:
  161. context.prev_state_ids = {
  162. (s.type, s.state_key): s.event_id for s in old_state
  163. }
  164. if event.is_state():
  165. context.current_state_ids = dict(context.prev_state_ids)
  166. key = (event.type, event.state_key)
  167. context.current_state_ids[key] = event.event_id
  168. else:
  169. context.current_state_ids = context.prev_state_ids
  170. else:
  171. context.current_state_ids = {}
  172. context.prev_state_ids = {}
  173. context.prev_state_events = []
  174. # We don't store state for outliers, so we don't generate a state
  175. # froup for it.
  176. context.state_group = None
  177. defer.returnValue(context)
  178. if old_state:
  179. # We already have the state, so we don't need to calculate it.
  180. # Let's just correctly fill out the context and create a
  181. # new state group for it.
  182. context = EventContext()
  183. context.prev_state_ids = {
  184. (s.type, s.state_key): s.event_id for s in old_state
  185. }
  186. if event.is_state():
  187. key = (event.type, event.state_key)
  188. if key in context.prev_state_ids:
  189. replaces = context.prev_state_ids[key]
  190. if replaces != event.event_id: # Paranoia check
  191. event.unsigned["replaces_state"] = replaces
  192. context.current_state_ids = dict(context.prev_state_ids)
  193. context.current_state_ids[key] = event.event_id
  194. else:
  195. context.current_state_ids = context.prev_state_ids
  196. context.state_group = yield self.store.store_state_group(
  197. event.event_id,
  198. event.room_id,
  199. prev_group=None,
  200. delta_ids=None,
  201. current_state_ids=context.current_state_ids,
  202. )
  203. context.prev_state_events = []
  204. defer.returnValue(context)
  205. logger.debug("calling resolve_state_groups from compute_event_context")
  206. entry = yield self.resolve_state_groups_for_events(
  207. event.room_id, [e for e, _ in event.prev_events],
  208. )
  209. curr_state = entry.state
  210. context = EventContext()
  211. context.prev_state_ids = curr_state
  212. if event.is_state():
  213. # If this is a state event then we need to create a new state
  214. # group for the state after this event.
  215. key = (event.type, event.state_key)
  216. if key in context.prev_state_ids:
  217. replaces = context.prev_state_ids[key]
  218. event.unsigned["replaces_state"] = replaces
  219. context.current_state_ids = dict(context.prev_state_ids)
  220. context.current_state_ids[key] = event.event_id
  221. if entry.state_group:
  222. # If the state at the event has a state group assigned then
  223. # we can use that as the prev group
  224. context.prev_group = entry.state_group
  225. context.delta_ids = {
  226. key: event.event_id
  227. }
  228. elif entry.prev_group:
  229. # If the state at the event only has a prev group, then we can
  230. # use that as a prev group too.
  231. context.prev_group = entry.prev_group
  232. context.delta_ids = dict(entry.delta_ids)
  233. context.delta_ids[key] = event.event_id
  234. context.state_group = yield self.store.store_state_group(
  235. event.event_id,
  236. event.room_id,
  237. prev_group=context.prev_group,
  238. delta_ids=context.delta_ids,
  239. current_state_ids=context.current_state_ids,
  240. )
  241. else:
  242. context.current_state_ids = context.prev_state_ids
  243. context.prev_group = entry.prev_group
  244. context.delta_ids = entry.delta_ids
  245. if entry.state_group is None:
  246. entry.state_group = yield self.store.store_state_group(
  247. event.event_id,
  248. event.room_id,
  249. prev_group=entry.prev_group,
  250. delta_ids=entry.delta_ids,
  251. current_state_ids=context.current_state_ids,
  252. )
  253. entry.state_id = entry.state_group
  254. context.state_group = entry.state_group
  255. context.prev_state_events = []
  256. defer.returnValue(context)
  257. @defer.inlineCallbacks
  258. def resolve_state_groups_for_events(self, room_id, event_ids):
  259. """ Given a list of event_ids this method fetches the state at each
  260. event, resolves conflicts between them and returns them.
  261. Args:
  262. room_id (str):
  263. event_ids (list[str]):
  264. Returns:
  265. Deferred[_StateCacheEntry]: resolved state
  266. """
  267. logger.debug("resolve_state_groups event_ids %s", event_ids)
  268. # map from state group id to the state in that state group (where
  269. # 'state' is a map from state key to event id)
  270. # dict[int, dict[(str, str), str]]
  271. state_groups_ids = yield self.store.get_state_groups_ids(
  272. room_id, event_ids
  273. )
  274. if len(state_groups_ids) == 1:
  275. name, state_list = list(state_groups_ids.items()).pop()
  276. prev_group, delta_ids = yield self.store.get_state_group_delta(name)
  277. defer.returnValue(_StateCacheEntry(
  278. state=state_list,
  279. state_group=name,
  280. prev_group=prev_group,
  281. delta_ids=delta_ids,
  282. ))
  283. result = yield self._state_resolution_handler.resolve_state_groups(
  284. room_id, state_groups_ids, None, self._state_map_factory,
  285. )
  286. defer.returnValue(result)
  287. def _state_map_factory(self, ev_ids):
  288. return self.store.get_events(
  289. ev_ids, get_prev_content=False, check_redacted=False,
  290. )
  291. def resolve_events(self, state_sets, event):
  292. logger.info(
  293. "Resolving state for %s with %d groups", event.room_id, len(state_sets)
  294. )
  295. state_set_ids = [{
  296. (ev.type, ev.state_key): ev.event_id
  297. for ev in st
  298. } for st in state_sets]
  299. state_map = {
  300. ev.event_id: ev
  301. for st in state_sets
  302. for ev in st
  303. }
  304. with Measure(self.clock, "state._resolve_events"):
  305. new_state = resolve_events_with_state_map(state_set_ids, state_map)
  306. new_state = {
  307. key: state_map[ev_id] for key, ev_id in iteritems(new_state)
  308. }
  309. return new_state
  310. class StateResolutionHandler(object):
  311. """Responsible for doing state conflict resolution.
  312. Note that the storage layer depends on this handler, so all functions must
  313. be storage-independent.
  314. """
  315. def __init__(self, hs):
  316. self.clock = hs.get_clock()
  317. # dict of set of event_ids -> _StateCacheEntry.
  318. self._state_cache = None
  319. self.resolve_linearizer = Linearizer(name="state_resolve_lock")
  320. def start_caching(self):
  321. logger.debug("start_caching")
  322. self._state_cache = ExpiringCache(
  323. cache_name="state_cache",
  324. clock=self.clock,
  325. max_len=SIZE_OF_CACHE,
  326. expiry_ms=EVICTION_TIMEOUT_SECONDS * 1000,
  327. iterable=True,
  328. reset_expiry_on_get=True,
  329. )
  330. self._state_cache.start()
  331. @defer.inlineCallbacks
  332. @log_function
  333. def resolve_state_groups(
  334. self, room_id, state_groups_ids, event_map, state_map_factory,
  335. ):
  336. """Resolves conflicts between a set of state groups
  337. Always generates a new state group (unless we hit the cache), so should
  338. not be called for a single state group
  339. Args:
  340. room_id (str): room we are resolving for (used for logging)
  341. state_groups_ids (dict[int, dict[(str, str), str]]):
  342. map from state group id to the state in that state group
  343. (where 'state' is a map from state key to event id)
  344. event_map(dict[str,FrozenEvent]|None):
  345. a dict from event_id to event, for any events that we happen to
  346. have in flight (eg, those currently being persisted). This will be
  347. used as a starting point fof finding the state we need; any missing
  348. events will be requested via state_map_factory.
  349. If None, all events will be fetched via state_map_factory.
  350. Returns:
  351. Deferred[_StateCacheEntry]: resolved state
  352. """
  353. logger.debug(
  354. "resolve_state_groups state_groups %s",
  355. state_groups_ids.keys()
  356. )
  357. group_names = frozenset(state_groups_ids.keys())
  358. with (yield self.resolve_linearizer.queue(group_names)):
  359. if self._state_cache is not None:
  360. cache = self._state_cache.get(group_names, None)
  361. if cache:
  362. defer.returnValue(cache)
  363. logger.info(
  364. "Resolving state for %s with %d groups", room_id, len(state_groups_ids)
  365. )
  366. # build a map from state key to the event_ids which set that state.
  367. # dict[(str, str), set[str])
  368. state = {}
  369. for st in itervalues(state_groups_ids):
  370. for key, e_id in iteritems(st):
  371. state.setdefault(key, set()).add(e_id)
  372. # build a map from state key to the event_ids which set that state,
  373. # including only those where there are state keys in conflict.
  374. conflicted_state = {
  375. k: list(v)
  376. for k, v in iteritems(state)
  377. if len(v) > 1
  378. }
  379. if conflicted_state:
  380. logger.info("Resolving conflicted state for %r", room_id)
  381. with Measure(self.clock, "state._resolve_events"):
  382. new_state = yield resolve_events_with_factory(
  383. list(state_groups_ids.values()),
  384. event_map=event_map,
  385. state_map_factory=state_map_factory,
  386. )
  387. else:
  388. new_state = {
  389. key: e_ids.pop() for key, e_ids in iteritems(state)
  390. }
  391. with Measure(self.clock, "state.create_group_ids"):
  392. # if the new state matches any of the input state groups, we can
  393. # use that state group again. Otherwise we will generate a state_id
  394. # which will be used as a cache key for future resolutions, but
  395. # not get persisted.
  396. state_group = None
  397. new_state_event_ids = frozenset(itervalues(new_state))
  398. for sg, events in iteritems(state_groups_ids):
  399. if new_state_event_ids == frozenset(e_id for e_id in events):
  400. state_group = sg
  401. break
  402. # TODO: We want to create a state group for this set of events, to
  403. # increase cache hits, but we need to make sure that it doesn't
  404. # end up as a prev_group without being added to the database
  405. prev_group = None
  406. delta_ids = None
  407. for old_group, old_ids in iteritems(state_groups_ids):
  408. if not set(new_state) - set(old_ids):
  409. n_delta_ids = {
  410. k: v
  411. for k, v in iteritems(new_state)
  412. if old_ids.get(k) != v
  413. }
  414. if not delta_ids or len(n_delta_ids) < len(delta_ids):
  415. prev_group = old_group
  416. delta_ids = n_delta_ids
  417. cache = _StateCacheEntry(
  418. state=new_state,
  419. state_group=state_group,
  420. prev_group=prev_group,
  421. delta_ids=delta_ids,
  422. )
  423. if self._state_cache is not None:
  424. self._state_cache[group_names] = cache
  425. defer.returnValue(cache)
  426. def _ordered_events(events):
  427. def key_func(e):
  428. return -int(e.depth), hashlib.sha1(e.event_id.encode()).hexdigest()
  429. return sorted(events, key=key_func)
  430. def resolve_events_with_state_map(state_sets, state_map):
  431. """
  432. Args:
  433. state_sets(list): List of dicts of (type, state_key) -> event_id,
  434. which are the different state groups to resolve.
  435. state_map(dict): a dict from event_id to event, for all events in
  436. state_sets.
  437. Returns
  438. dict[(str, str), str]:
  439. a map from (type, state_key) to event_id.
  440. """
  441. if len(state_sets) == 1:
  442. return state_sets[0]
  443. unconflicted_state, conflicted_state = _seperate(
  444. state_sets,
  445. )
  446. auth_events = _create_auth_events_from_maps(
  447. unconflicted_state, conflicted_state, state_map
  448. )
  449. return _resolve_with_state(
  450. unconflicted_state, conflicted_state, auth_events, state_map
  451. )
  452. def _seperate(state_sets):
  453. """Takes the state_sets and figures out which keys are conflicted and
  454. which aren't. i.e., which have multiple different event_ids associated
  455. with them in different state sets.
  456. Args:
  457. state_sets(list[dict[(str, str), str]]):
  458. List of dicts of (type, state_key) -> event_id, which are the
  459. different state groups to resolve.
  460. Returns:
  461. (dict[(str, str), str], dict[(str, str), set[str]]):
  462. A tuple of (unconflicted_state, conflicted_state), where:
  463. unconflicted_state is a dict mapping (type, state_key)->event_id
  464. for unconflicted state keys.
  465. conflicted_state is a dict mapping (type, state_key) to a set of
  466. event ids for conflicted state keys.
  467. """
  468. unconflicted_state = dict(state_sets[0])
  469. conflicted_state = {}
  470. for state_set in state_sets[1:]:
  471. for key, value in iteritems(state_set):
  472. # Check if there is an unconflicted entry for the state key.
  473. unconflicted_value = unconflicted_state.get(key)
  474. if unconflicted_value is None:
  475. # There isn't an unconflicted entry so check if there is a
  476. # conflicted entry.
  477. ls = conflicted_state.get(key)
  478. if ls is None:
  479. # There wasn't a conflicted entry so haven't seen this key before.
  480. # Therefore it isn't conflicted yet.
  481. unconflicted_state[key] = value
  482. else:
  483. # This key is already conflicted, add our value to the conflict set.
  484. ls.add(value)
  485. elif unconflicted_value != value:
  486. # If the unconflicted value is not the same as our value then we
  487. # have a new conflict. So move the key from the unconflicted_state
  488. # to the conflicted state.
  489. conflicted_state[key] = {value, unconflicted_value}
  490. unconflicted_state.pop(key, None)
  491. return unconflicted_state, conflicted_state
  492. @defer.inlineCallbacks
  493. def resolve_events_with_factory(state_sets, event_map, state_map_factory):
  494. """
  495. Args:
  496. state_sets(list): List of dicts of (type, state_key) -> event_id,
  497. which are the different state groups to resolve.
  498. event_map(dict[str,FrozenEvent]|None):
  499. a dict from event_id to event, for any events that we happen to
  500. have in flight (eg, those currently being persisted). This will be
  501. used as a starting point fof finding the state we need; any missing
  502. events will be requested via state_map_factory.
  503. If None, all events will be fetched via state_map_factory.
  504. state_map_factory(func): will be called
  505. with a list of event_ids that are needed, and should return with
  506. a Deferred of dict of event_id to event.
  507. Returns
  508. Deferred[dict[(str, str), str]]:
  509. a map from (type, state_key) to event_id.
  510. """
  511. if len(state_sets) == 1:
  512. defer.returnValue(state_sets[0])
  513. unconflicted_state, conflicted_state = _seperate(
  514. state_sets,
  515. )
  516. needed_events = set(
  517. event_id
  518. for event_ids in itervalues(conflicted_state)
  519. for event_id in event_ids
  520. )
  521. if event_map is not None:
  522. needed_events -= set(event_map.iterkeys())
  523. logger.info("Asking for %d conflicted events", len(needed_events))
  524. # dict[str, FrozenEvent]: a map from state event id to event. Only includes
  525. # the state events which are in conflict (and those in event_map)
  526. state_map = yield state_map_factory(needed_events)
  527. if event_map is not None:
  528. state_map.update(event_map)
  529. # get the ids of the auth events which allow us to authenticate the
  530. # conflicted state, picking only from the unconflicting state.
  531. #
  532. # dict[(str, str), str]: a map from state key to event id
  533. auth_events = _create_auth_events_from_maps(
  534. unconflicted_state, conflicted_state, state_map
  535. )
  536. new_needed_events = set(itervalues(auth_events))
  537. new_needed_events -= needed_events
  538. if event_map is not None:
  539. new_needed_events -= set(event_map.iterkeys())
  540. logger.info("Asking for %d auth events", len(new_needed_events))
  541. state_map_new = yield state_map_factory(new_needed_events)
  542. state_map.update(state_map_new)
  543. defer.returnValue(_resolve_with_state(
  544. unconflicted_state, conflicted_state, auth_events, state_map
  545. ))
  546. def _create_auth_events_from_maps(unconflicted_state, conflicted_state, state_map):
  547. auth_events = {}
  548. for event_ids in itervalues(conflicted_state):
  549. for event_id in event_ids:
  550. if event_id in state_map:
  551. keys = event_auth.auth_types_for_event(state_map[event_id])
  552. for key in keys:
  553. if key not in auth_events:
  554. event_id = unconflicted_state.get(key, None)
  555. if event_id:
  556. auth_events[key] = event_id
  557. return auth_events
  558. def _resolve_with_state(unconflicted_state_ids, conflicted_state_ds, auth_event_ids,
  559. state_map):
  560. conflicted_state = {}
  561. for key, event_ids in iteritems(conflicted_state_ds):
  562. events = [state_map[ev_id] for ev_id in event_ids if ev_id in state_map]
  563. if len(events) > 1:
  564. conflicted_state[key] = events
  565. elif len(events) == 1:
  566. unconflicted_state_ids[key] = events[0].event_id
  567. auth_events = {
  568. key: state_map[ev_id]
  569. for key, ev_id in iteritems(auth_event_ids)
  570. if ev_id in state_map
  571. }
  572. try:
  573. resolved_state = _resolve_state_events(
  574. conflicted_state, auth_events
  575. )
  576. except Exception:
  577. logger.exception("Failed to resolve state")
  578. raise
  579. new_state = unconflicted_state_ids
  580. for key, event in iteritems(resolved_state):
  581. new_state[key] = event.event_id
  582. return new_state
  583. def _resolve_state_events(conflicted_state, auth_events):
  584. """ This is where we actually decide which of the conflicted state to
  585. use.
  586. We resolve conflicts in the following order:
  587. 1. power levels
  588. 2. join rules
  589. 3. memberships
  590. 4. other events.
  591. """
  592. resolved_state = {}
  593. if POWER_KEY in conflicted_state:
  594. events = conflicted_state[POWER_KEY]
  595. logger.debug("Resolving conflicted power levels %r", events)
  596. resolved_state[POWER_KEY] = _resolve_auth_events(
  597. events, auth_events)
  598. auth_events.update(resolved_state)
  599. for key, events in iteritems(conflicted_state):
  600. if key[0] == EventTypes.JoinRules:
  601. logger.debug("Resolving conflicted join rules %r", events)
  602. resolved_state[key] = _resolve_auth_events(
  603. events,
  604. auth_events
  605. )
  606. auth_events.update(resolved_state)
  607. for key, events in iteritems(conflicted_state):
  608. if key[0] == EventTypes.Member:
  609. logger.debug("Resolving conflicted member lists %r", events)
  610. resolved_state[key] = _resolve_auth_events(
  611. events,
  612. auth_events
  613. )
  614. auth_events.update(resolved_state)
  615. for key, events in iteritems(conflicted_state):
  616. if key not in resolved_state:
  617. logger.debug("Resolving conflicted state %r:%r", key, events)
  618. resolved_state[key] = _resolve_normal_events(
  619. events, auth_events
  620. )
  621. return resolved_state
  622. def _resolve_auth_events(events, auth_events):
  623. reverse = [i for i in reversed(_ordered_events(events))]
  624. auth_keys = set(
  625. key
  626. for event in events
  627. for key in event_auth.auth_types_for_event(event)
  628. )
  629. new_auth_events = {}
  630. for key in auth_keys:
  631. auth_event = auth_events.get(key, None)
  632. if auth_event:
  633. new_auth_events[key] = auth_event
  634. auth_events = new_auth_events
  635. prev_event = reverse[0]
  636. for event in reverse[1:]:
  637. auth_events[(prev_event.type, prev_event.state_key)] = prev_event
  638. try:
  639. # The signatures have already been checked at this point
  640. event_auth.check(event, auth_events, do_sig_check=False, do_size_check=False)
  641. prev_event = event
  642. except AuthError:
  643. return prev_event
  644. return event
  645. def _resolve_normal_events(events, auth_events):
  646. for event in _ordered_events(events):
  647. try:
  648. # The signatures have already been checked at this point
  649. event_auth.check(event, auth_events, do_sig_check=False, do_size_check=False)
  650. return event
  651. except AuthError:
  652. pass
  653. # Use the last event (the one with the least depth) if they all fail
  654. # the auth check.
  655. return event