persist_events.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2018-2019 New Vector Ltd
  4. # Copyright 2019 The Matrix.org Foundation C.I.C.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import itertools
  18. import logging
  19. from collections import deque, namedtuple
  20. from typing import Iterable, List, Optional, Set, Tuple
  21. from six import iteritems
  22. from six.moves import range
  23. import attr
  24. from prometheus_client import Counter, Histogram
  25. from twisted.internet import defer
  26. from synapse.api.constants import EventTypes, Membership
  27. from synapse.events import FrozenEvent
  28. from synapse.events.snapshot import EventContext
  29. from synapse.logging.context import PreserveLoggingContext, make_deferred_yieldable
  30. from synapse.metrics.background_process_metrics import run_as_background_process
  31. from synapse.state import StateResolutionStore
  32. from synapse.storage.data_stores import DataStores
  33. from synapse.types import StateMap
  34. from synapse.util.async_helpers import ObservableDeferred
  35. from synapse.util.metrics import Measure
  36. logger = logging.getLogger(__name__)
  37. # The number of times we are recalculating the current state
  38. state_delta_counter = Counter("synapse_storage_events_state_delta", "")
  39. # The number of times we are recalculating state when there is only a
  40. # single forward extremity
  41. state_delta_single_event_counter = Counter(
  42. "synapse_storage_events_state_delta_single_event", ""
  43. )
  44. # The number of times we are reculating state when we could have resonably
  45. # calculated the delta when we calculated the state for an event we were
  46. # persisting.
  47. state_delta_reuse_delta_counter = Counter(
  48. "synapse_storage_events_state_delta_reuse_delta", ""
  49. )
  50. # The number of forward extremities for each new event.
  51. forward_extremities_counter = Histogram(
  52. "synapse_storage_events_forward_extremities_persisted",
  53. "Number of forward extremities for each new event",
  54. buckets=(1, 2, 3, 5, 7, 10, 15, 20, 50, 100, 200, 500, "+Inf"),
  55. )
  56. # The number of stale forward extremities for each new event. Stale extremities
  57. # are those that were in the previous set of extremities as well as the new.
  58. stale_forward_extremities_counter = Histogram(
  59. "synapse_storage_events_stale_forward_extremities_persisted",
  60. "Number of unchanged forward extremities for each new event",
  61. buckets=(0, 1, 2, 3, 5, 7, 10, 15, 20, 50, 100, 200, 500, "+Inf"),
  62. )
  63. @attr.s(slots=True)
  64. class DeltaState:
  65. """Deltas to use to update the `current_state_events` table.
  66. Attributes:
  67. to_delete: List of type/state_keys to delete from current state
  68. to_insert: Map of state to upsert into current state
  69. no_longer_in_room: The server is not longer in the room, so the room
  70. should e.g. be removed from `current_state_events` table.
  71. """
  72. to_delete = attr.ib(type=List[Tuple[str, str]])
  73. to_insert = attr.ib(type=StateMap[str])
  74. no_longer_in_room = attr.ib(type=bool, default=False)
  75. class _EventPeristenceQueue(object):
  76. """Queues up events so that they can be persisted in bulk with only one
  77. concurrent transaction per room.
  78. """
  79. _EventPersistQueueItem = namedtuple(
  80. "_EventPersistQueueItem", ("events_and_contexts", "backfilled", "deferred")
  81. )
  82. def __init__(self):
  83. self._event_persist_queues = {}
  84. self._currently_persisting_rooms = set()
  85. def add_to_queue(self, room_id, events_and_contexts, backfilled):
  86. """Add events to the queue, with the given persist_event options.
  87. NB: due to the normal usage pattern of this method, it does *not*
  88. follow the synapse logcontext rules, and leaves the logcontext in
  89. place whether or not the returned deferred is ready.
  90. Args:
  91. room_id (str):
  92. events_and_contexts (list[(EventBase, EventContext)]):
  93. backfilled (bool):
  94. Returns:
  95. defer.Deferred: a deferred which will resolve once the events are
  96. persisted. Runs its callbacks *without* a logcontext.
  97. """
  98. queue = self._event_persist_queues.setdefault(room_id, deque())
  99. if queue:
  100. # if the last item in the queue has the same `backfilled` setting,
  101. # we can just add these new events to that item.
  102. end_item = queue[-1]
  103. if end_item.backfilled == backfilled:
  104. end_item.events_and_contexts.extend(events_and_contexts)
  105. return end_item.deferred.observe()
  106. deferred = ObservableDeferred(defer.Deferred(), consumeErrors=True)
  107. queue.append(
  108. self._EventPersistQueueItem(
  109. events_and_contexts=events_and_contexts,
  110. backfilled=backfilled,
  111. deferred=deferred,
  112. )
  113. )
  114. return deferred.observe()
  115. def handle_queue(self, room_id, per_item_callback):
  116. """Attempts to handle the queue for a room if not already being handled.
  117. The given callback will be invoked with for each item in the queue,
  118. of type _EventPersistQueueItem. The per_item_callback will continuously
  119. be called with new items, unless the queue becomnes empty. The return
  120. value of the function will be given to the deferreds waiting on the item,
  121. exceptions will be passed to the deferreds as well.
  122. This function should therefore be called whenever anything is added
  123. to the queue.
  124. If another callback is currently handling the queue then it will not be
  125. invoked.
  126. """
  127. if room_id in self._currently_persisting_rooms:
  128. return
  129. self._currently_persisting_rooms.add(room_id)
  130. async def handle_queue_loop():
  131. try:
  132. queue = self._get_drainining_queue(room_id)
  133. for item in queue:
  134. try:
  135. ret = await per_item_callback(item)
  136. except Exception:
  137. with PreserveLoggingContext():
  138. item.deferred.errback()
  139. else:
  140. with PreserveLoggingContext():
  141. item.deferred.callback(ret)
  142. finally:
  143. queue = self._event_persist_queues.pop(room_id, None)
  144. if queue:
  145. self._event_persist_queues[room_id] = queue
  146. self._currently_persisting_rooms.discard(room_id)
  147. # set handle_queue_loop off in the background
  148. run_as_background_process("persist_events", handle_queue_loop)
  149. def _get_drainining_queue(self, room_id):
  150. queue = self._event_persist_queues.setdefault(room_id, deque())
  151. try:
  152. while True:
  153. yield queue.popleft()
  154. except IndexError:
  155. # Queue has been drained.
  156. pass
  157. class EventsPersistenceStorage(object):
  158. """High level interface for handling persisting newly received events.
  159. Takes care of batching up events by room, and calculating the necessary
  160. current state and forward extremity changes.
  161. """
  162. def __init__(self, hs, stores: DataStores):
  163. # We ultimately want to split out the state store from the main store,
  164. # so we use separate variables here even though they point to the same
  165. # store for now.
  166. self.main_store = stores.main
  167. self.state_store = stores.state
  168. self._clock = hs.get_clock()
  169. self.is_mine_id = hs.is_mine_id
  170. self._event_persist_queue = _EventPeristenceQueue()
  171. self._state_resolution_handler = hs.get_state_resolution_handler()
  172. @defer.inlineCallbacks
  173. def persist_events(
  174. self,
  175. events_and_contexts: List[Tuple[FrozenEvent, EventContext]],
  176. backfilled: bool = False,
  177. ):
  178. """
  179. Write events to the database
  180. Args:
  181. events_and_contexts: list of tuples of (event, context)
  182. backfilled: Whether the results are retrieved from federation
  183. via backfill or not. Used to determine if they're "new" events
  184. which might update the current state etc.
  185. Returns:
  186. Deferred[int]: the stream ordering of the latest persisted event
  187. """
  188. partitioned = {}
  189. for event, ctx in events_and_contexts:
  190. partitioned.setdefault(event.room_id, []).append((event, ctx))
  191. deferreds = []
  192. for room_id, evs_ctxs in iteritems(partitioned):
  193. d = self._event_persist_queue.add_to_queue(
  194. room_id, evs_ctxs, backfilled=backfilled
  195. )
  196. deferreds.append(d)
  197. for room_id in partitioned:
  198. self._maybe_start_persisting(room_id)
  199. yield make_deferred_yieldable(
  200. defer.gatherResults(deferreds, consumeErrors=True)
  201. )
  202. max_persisted_id = yield self.main_store.get_current_events_token()
  203. return max_persisted_id
  204. @defer.inlineCallbacks
  205. def persist_event(
  206. self, event: FrozenEvent, context: EventContext, backfilled: bool = False
  207. ):
  208. """
  209. Returns:
  210. Deferred[Tuple[int, int]]: the stream ordering of ``event``,
  211. and the stream ordering of the latest persisted event
  212. """
  213. deferred = self._event_persist_queue.add_to_queue(
  214. event.room_id, [(event, context)], backfilled=backfilled
  215. )
  216. self._maybe_start_persisting(event.room_id)
  217. yield make_deferred_yieldable(deferred)
  218. max_persisted_id = yield self.main_store.get_current_events_token()
  219. return (event.internal_metadata.stream_ordering, max_persisted_id)
  220. def _maybe_start_persisting(self, room_id: str):
  221. async def persisting_queue(item):
  222. with Measure(self._clock, "persist_events"):
  223. await self._persist_events(
  224. item.events_and_contexts, backfilled=item.backfilled
  225. )
  226. self._event_persist_queue.handle_queue(room_id, persisting_queue)
  227. async def _persist_events(
  228. self,
  229. events_and_contexts: List[Tuple[FrozenEvent, EventContext]],
  230. backfilled: bool = False,
  231. ):
  232. """Calculates the change to current state and forward extremities, and
  233. persists the given events and with those updates.
  234. """
  235. if not events_and_contexts:
  236. return
  237. chunks = [
  238. events_and_contexts[x : x + 100]
  239. for x in range(0, len(events_and_contexts), 100)
  240. ]
  241. for chunk in chunks:
  242. # We can't easily parallelize these since different chunks
  243. # might contain the same event. :(
  244. # NB: Assumes that we are only persisting events for one room
  245. # at a time.
  246. # map room_id->list[event_ids] giving the new forward
  247. # extremities in each room
  248. new_forward_extremeties = {}
  249. # map room_id->(type,state_key)->event_id tracking the full
  250. # state in each room after adding these events.
  251. # This is simply used to prefill the get_current_state_ids
  252. # cache
  253. current_state_for_room = {}
  254. # map room_id->(to_delete, to_insert) where to_delete is a list
  255. # of type/state keys to remove from current state, and to_insert
  256. # is a map (type,key)->event_id giving the state delta in each
  257. # room
  258. state_delta_for_room = {}
  259. # Set of remote users which were in rooms the server has left. We
  260. # should check if we still share any rooms and if not we mark their
  261. # device lists as stale.
  262. potentially_left_users = set() # type: Set[str]
  263. if not backfilled:
  264. with Measure(self._clock, "_calculate_state_and_extrem"):
  265. # Work out the new "current state" for each room.
  266. # We do this by working out what the new extremities are and then
  267. # calculating the state from that.
  268. events_by_room = {}
  269. for event, context in chunk:
  270. events_by_room.setdefault(event.room_id, []).append(
  271. (event, context)
  272. )
  273. for room_id, ev_ctx_rm in iteritems(events_by_room):
  274. latest_event_ids = await self.main_store.get_latest_event_ids_in_room(
  275. room_id
  276. )
  277. new_latest_event_ids = await self._calculate_new_extremities(
  278. room_id, ev_ctx_rm, latest_event_ids
  279. )
  280. latest_event_ids = set(latest_event_ids)
  281. if new_latest_event_ids == latest_event_ids:
  282. # No change in extremities, so no change in state
  283. continue
  284. # there should always be at least one forward extremity.
  285. # (except during the initial persistence of the send_join
  286. # results, in which case there will be no existing
  287. # extremities, so we'll `continue` above and skip this bit.)
  288. assert new_latest_event_ids, "No forward extremities left!"
  289. new_forward_extremeties[room_id] = new_latest_event_ids
  290. len_1 = (
  291. len(latest_event_ids) == 1
  292. and len(new_latest_event_ids) == 1
  293. )
  294. if len_1:
  295. all_single_prev_not_state = all(
  296. len(event.prev_event_ids()) == 1
  297. and not event.is_state()
  298. for event, ctx in ev_ctx_rm
  299. )
  300. # Don't bother calculating state if they're just
  301. # a long chain of single ancestor non-state events.
  302. if all_single_prev_not_state:
  303. continue
  304. state_delta_counter.inc()
  305. if len(new_latest_event_ids) == 1:
  306. state_delta_single_event_counter.inc()
  307. # This is a fairly handwavey check to see if we could
  308. # have guessed what the delta would have been when
  309. # processing one of these events.
  310. # What we're interested in is if the latest extremities
  311. # were the same when we created the event as they are
  312. # now. When this server creates a new event (as opposed
  313. # to receiving it over federation) it will use the
  314. # forward extremities as the prev_events, so we can
  315. # guess this by looking at the prev_events and checking
  316. # if they match the current forward extremities.
  317. for ev, _ in ev_ctx_rm:
  318. prev_event_ids = set(ev.prev_event_ids())
  319. if latest_event_ids == prev_event_ids:
  320. state_delta_reuse_delta_counter.inc()
  321. break
  322. logger.info("Calculating state delta for room %s", room_id)
  323. with Measure(
  324. self._clock, "persist_events.get_new_state_after_events"
  325. ):
  326. res = await self._get_new_state_after_events(
  327. room_id,
  328. ev_ctx_rm,
  329. latest_event_ids,
  330. new_latest_event_ids,
  331. )
  332. current_state, delta_ids = res
  333. # If either are not None then there has been a change,
  334. # and we need to work out the delta (or use that
  335. # given)
  336. delta = None
  337. if delta_ids is not None:
  338. # If there is a delta we know that we've
  339. # only added or replaced state, never
  340. # removed keys entirely.
  341. delta = DeltaState([], delta_ids)
  342. elif current_state is not None:
  343. with Measure(
  344. self._clock, "persist_events.calculate_state_delta"
  345. ):
  346. delta = await self._calculate_state_delta(
  347. room_id, current_state
  348. )
  349. if delta:
  350. # If we have a change of state then lets check
  351. # whether we're actually still a member of the room,
  352. # or if our last user left. If we're no longer in
  353. # the room then we delete the current state and
  354. # extremities.
  355. is_still_joined = await self._is_server_still_joined(
  356. room_id,
  357. ev_ctx_rm,
  358. delta,
  359. current_state,
  360. potentially_left_users,
  361. )
  362. if not is_still_joined:
  363. logger.info("Server no longer in room %s", room_id)
  364. latest_event_ids = []
  365. current_state = {}
  366. delta.no_longer_in_room = True
  367. state_delta_for_room[room_id] = delta
  368. # If we have the current_state then lets prefill
  369. # the cache with it.
  370. if current_state is not None:
  371. current_state_for_room[room_id] = current_state
  372. await self.main_store._persist_events_and_state_updates(
  373. chunk,
  374. current_state_for_room=current_state_for_room,
  375. state_delta_for_room=state_delta_for_room,
  376. new_forward_extremeties=new_forward_extremeties,
  377. backfilled=backfilled,
  378. )
  379. await self._handle_potentially_left_users(potentially_left_users)
  380. async def _calculate_new_extremities(
  381. self,
  382. room_id: str,
  383. event_contexts: List[Tuple[FrozenEvent, EventContext]],
  384. latest_event_ids: List[str],
  385. ):
  386. """Calculates the new forward extremities for a room given events to
  387. persist.
  388. Assumes that we are only persisting events for one room at a time.
  389. """
  390. # we're only interested in new events which aren't outliers and which aren't
  391. # being rejected.
  392. new_events = [
  393. event
  394. for event, ctx in event_contexts
  395. if not event.internal_metadata.is_outlier()
  396. and not ctx.rejected
  397. and not event.internal_metadata.is_soft_failed()
  398. ]
  399. latest_event_ids = set(latest_event_ids)
  400. # start with the existing forward extremities
  401. result = set(latest_event_ids)
  402. # add all the new events to the list
  403. result.update(event.event_id for event in new_events)
  404. # Now remove all events which are prev_events of any of the new events
  405. result.difference_update(
  406. e_id for event in new_events for e_id in event.prev_event_ids()
  407. )
  408. # Remove any events which are prev_events of any existing events.
  409. existing_prevs = await self.main_store._get_events_which_are_prevs(result)
  410. result.difference_update(existing_prevs)
  411. # Finally handle the case where the new events have soft-failed prev
  412. # events. If they do we need to remove them and their prev events,
  413. # otherwise we end up with dangling extremities.
  414. existing_prevs = await self.main_store._get_prevs_before_rejected(
  415. e_id for event in new_events for e_id in event.prev_event_ids()
  416. )
  417. result.difference_update(existing_prevs)
  418. # We only update metrics for events that change forward extremities
  419. # (e.g. we ignore backfill/outliers/etc)
  420. if result != latest_event_ids:
  421. forward_extremities_counter.observe(len(result))
  422. stale = latest_event_ids & result
  423. stale_forward_extremities_counter.observe(len(stale))
  424. return result
  425. async def _get_new_state_after_events(
  426. self,
  427. room_id: str,
  428. events_context: List[Tuple[FrozenEvent, EventContext]],
  429. old_latest_event_ids: Iterable[str],
  430. new_latest_event_ids: Iterable[str],
  431. ) -> Tuple[Optional[StateMap[str]], Optional[StateMap[str]]]:
  432. """Calculate the current state dict after adding some new events to
  433. a room
  434. Args:
  435. room_id (str):
  436. room to which the events are being added. Used for logging etc
  437. events_context (list[(EventBase, EventContext)]):
  438. events and contexts which are being added to the room
  439. old_latest_event_ids (iterable[str]):
  440. the old forward extremities for the room.
  441. new_latest_event_ids (iterable[str]):
  442. the new forward extremities for the room.
  443. Returns:
  444. Returns a tuple of two state maps, the first being the full new current
  445. state and the second being the delta to the existing current state.
  446. If both are None then there has been no change.
  447. If there has been a change then we only return the delta if its
  448. already been calculated. Conversely if we do know the delta then
  449. the new current state is only returned if we've already calculated
  450. it.
  451. """
  452. # map from state_group to ((type, key) -> event_id) state map
  453. state_groups_map = {}
  454. # Map from (prev state group, new state group) -> delta state dict
  455. state_group_deltas = {}
  456. for ev, ctx in events_context:
  457. if ctx.state_group is None:
  458. # This should only happen for outlier events.
  459. if not ev.internal_metadata.is_outlier():
  460. raise Exception(
  461. "Context for new event %s has no state "
  462. "group" % (ev.event_id,)
  463. )
  464. continue
  465. if ctx.state_group in state_groups_map:
  466. continue
  467. # We're only interested in pulling out state that has already
  468. # been cached in the context. We'll pull stuff out of the DB later
  469. # if necessary.
  470. current_state_ids = ctx.get_cached_current_state_ids()
  471. if current_state_ids is not None:
  472. state_groups_map[ctx.state_group] = current_state_ids
  473. if ctx.prev_group:
  474. state_group_deltas[(ctx.prev_group, ctx.state_group)] = ctx.delta_ids
  475. # We need to map the event_ids to their state groups. First, let's
  476. # check if the event is one we're persisting, in which case we can
  477. # pull the state group from its context.
  478. # Otherwise we need to pull the state group from the database.
  479. # Set of events we need to fetch groups for. (We know none of the old
  480. # extremities are going to be in events_context).
  481. missing_event_ids = set(old_latest_event_ids)
  482. event_id_to_state_group = {}
  483. for event_id in new_latest_event_ids:
  484. # First search in the list of new events we're adding.
  485. for ev, ctx in events_context:
  486. if event_id == ev.event_id and ctx.state_group is not None:
  487. event_id_to_state_group[event_id] = ctx.state_group
  488. break
  489. else:
  490. # If we couldn't find it, then we'll need to pull
  491. # the state from the database
  492. missing_event_ids.add(event_id)
  493. if missing_event_ids:
  494. # Now pull out the state groups for any missing events from DB
  495. event_to_groups = await self.main_store._get_state_group_for_events(
  496. missing_event_ids
  497. )
  498. event_id_to_state_group.update(event_to_groups)
  499. # State groups of old_latest_event_ids
  500. old_state_groups = set(
  501. event_id_to_state_group[evid] for evid in old_latest_event_ids
  502. )
  503. # State groups of new_latest_event_ids
  504. new_state_groups = set(
  505. event_id_to_state_group[evid] for evid in new_latest_event_ids
  506. )
  507. # If they old and new groups are the same then we don't need to do
  508. # anything.
  509. if old_state_groups == new_state_groups:
  510. return None, None
  511. if len(new_state_groups) == 1 and len(old_state_groups) == 1:
  512. # If we're going from one state group to another, lets check if
  513. # we have a delta for that transition. If we do then we can just
  514. # return that.
  515. new_state_group = next(iter(new_state_groups))
  516. old_state_group = next(iter(old_state_groups))
  517. delta_ids = state_group_deltas.get((old_state_group, new_state_group), None)
  518. if delta_ids is not None:
  519. # We have a delta from the existing to new current state,
  520. # so lets just return that. If we happen to already have
  521. # the current state in memory then lets also return that,
  522. # but it doesn't matter if we don't.
  523. new_state = state_groups_map.get(new_state_group)
  524. return new_state, delta_ids
  525. # Now that we have calculated new_state_groups we need to get
  526. # their state IDs so we can resolve to a single state set.
  527. missing_state = new_state_groups - set(state_groups_map)
  528. if missing_state:
  529. group_to_state = await self.state_store._get_state_for_groups(missing_state)
  530. state_groups_map.update(group_to_state)
  531. if len(new_state_groups) == 1:
  532. # If there is only one state group, then we know what the current
  533. # state is.
  534. return state_groups_map[new_state_groups.pop()], None
  535. # Ok, we need to defer to the state handler to resolve our state sets.
  536. state_groups = {sg: state_groups_map[sg] for sg in new_state_groups}
  537. events_map = {ev.event_id: ev for ev, _ in events_context}
  538. # We need to get the room version, which is in the create event.
  539. # Normally that'd be in the database, but its also possible that we're
  540. # currently trying to persist it.
  541. room_version = None
  542. for ev, _ in events_context:
  543. if ev.type == EventTypes.Create and ev.state_key == "":
  544. room_version = ev.content.get("room_version", "1")
  545. break
  546. if not room_version:
  547. room_version = await self.main_store.get_room_version_id(room_id)
  548. logger.debug("calling resolve_state_groups from preserve_events")
  549. res = await self._state_resolution_handler.resolve_state_groups(
  550. room_id,
  551. room_version,
  552. state_groups,
  553. events_map,
  554. state_res_store=StateResolutionStore(self.main_store),
  555. )
  556. return res.state, None
  557. async def _calculate_state_delta(
  558. self, room_id: str, current_state: StateMap[str]
  559. ) -> DeltaState:
  560. """Calculate the new state deltas for a room.
  561. Assumes that we are only persisting events for one room at a time.
  562. """
  563. existing_state = await self.main_store.get_current_state_ids(room_id)
  564. to_delete = [key for key in existing_state if key not in current_state]
  565. to_insert = {
  566. key: ev_id
  567. for key, ev_id in iteritems(current_state)
  568. if ev_id != existing_state.get(key)
  569. }
  570. return DeltaState(to_delete=to_delete, to_insert=to_insert)
  571. async def _is_server_still_joined(
  572. self,
  573. room_id: str,
  574. ev_ctx_rm: List[Tuple[FrozenEvent, EventContext]],
  575. delta: DeltaState,
  576. current_state: Optional[StateMap[str]],
  577. potentially_left_users: Set[str],
  578. ) -> bool:
  579. """Check if the server will still be joined after the given events have
  580. been persised.
  581. Args:
  582. room_id
  583. ev_ctx_rm
  584. delta: The delta of current state between what is in the database
  585. and what the new current state will be.
  586. current_state: The new current state if it already been calculated,
  587. otherwise None.
  588. potentially_left_users: If the server has left the room, then joined
  589. remote users will be added to this set to indicate that the
  590. server may no longer be sharing a room with them.
  591. """
  592. if not any(
  593. self.is_mine_id(state_key)
  594. for typ, state_key in itertools.chain(delta.to_delete, delta.to_insert)
  595. if typ == EventTypes.Member
  596. ):
  597. # There have been no changes to membership of our users, so nothing
  598. # has changed and we assume we're still in the room.
  599. return True
  600. # Check if any of the given events are a local join that appear in the
  601. # current state
  602. for (typ, state_key), event_id in delta.to_insert.items():
  603. if typ != EventTypes.Member or not self.is_mine_id(state_key):
  604. continue
  605. for event, _ in ev_ctx_rm:
  606. if event_id == event.event_id:
  607. if event.membership == Membership.JOIN:
  608. return True
  609. # There's been a change of membership but we don't have a local join
  610. # event in the new events, so we need to check the full state.
  611. if current_state is None:
  612. current_state = await self.main_store.get_current_state_ids(room_id)
  613. current_state = dict(current_state)
  614. for key in delta.to_delete:
  615. current_state.pop(key, None)
  616. current_state.update(delta.to_insert)
  617. event_ids = [
  618. event_id
  619. for (typ, state_key,), event_id in current_state.items()
  620. if typ == EventTypes.Member and self.is_mine_id(state_key)
  621. ]
  622. rows = await self.main_store.get_membership_from_event_ids(event_ids)
  623. is_still_joined = any(row["membership"] == Membership.JOIN for row in rows)
  624. if is_still_joined:
  625. return True
  626. # The server will leave the room, so we go and find out which remote
  627. # users will still be joined when we leave.
  628. remote_event_ids = [
  629. event_id
  630. for (typ, state_key,), event_id in current_state.items()
  631. if typ == EventTypes.Member and not self.is_mine_id(state_key)
  632. ]
  633. rows = await self.main_store.get_membership_from_event_ids(remote_event_ids)
  634. potentially_left_users.update(
  635. row["user_id"] for row in rows if row["membership"] == Membership.JOIN
  636. )
  637. return False
  638. async def _handle_potentially_left_users(self, user_ids: Set[str]):
  639. """Given a set of remote users check if the server still shares a room with
  640. them. If not then mark those users' device cache as stale.
  641. """
  642. if not user_ids:
  643. return
  644. joined_users = await self.main_store.get_users_server_still_shares_room_with(
  645. user_ids
  646. )
  647. left_users = user_ids - joined_users
  648. for user_id in left_users:
  649. await self.main_store.mark_remote_user_device_list_as_unsubscribed(user_id)