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