persist_events.py 32 KB

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