You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

2723 lines
112 KiB

  1. # Copyright 2015-2021 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import itertools
  15. import logging
  16. from typing import (
  17. TYPE_CHECKING,
  18. AbstractSet,
  19. Any,
  20. Dict,
  21. FrozenSet,
  22. List,
  23. Mapping,
  24. Optional,
  25. Sequence,
  26. Set,
  27. Tuple,
  28. )
  29. import attr
  30. from prometheus_client import Counter
  31. from synapse.api.constants import (
  32. AccountDataTypes,
  33. EventContentFields,
  34. EventTypes,
  35. Membership,
  36. )
  37. from synapse.api.filtering import FilterCollection
  38. from synapse.api.presence import UserPresenceState
  39. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
  40. from synapse.events import EventBase
  41. from synapse.handlers.relations import BundledAggregations
  42. from synapse.logging import issue9533_logger
  43. from synapse.logging.context import current_context
  44. from synapse.logging.opentracing import (
  45. SynapseTags,
  46. log_kv,
  47. set_tag,
  48. start_active_span,
  49. trace,
  50. )
  51. from synapse.push.clientformat import format_push_rules_for_user
  52. from synapse.storage.databases.main.event_push_actions import RoomNotifCounts
  53. from synapse.storage.databases.main.roommember import extract_heroes_from_room_summary
  54. from synapse.storage.roommember import MemberSummary
  55. from synapse.types import (
  56. DeviceListUpdates,
  57. JsonDict,
  58. MutableStateMap,
  59. Requester,
  60. RoomStreamToken,
  61. StateMap,
  62. StrCollection,
  63. StreamKeyType,
  64. StreamToken,
  65. UserID,
  66. )
  67. from synapse.types.state import StateFilter
  68. from synapse.util.async_helpers import concurrently_execute
  69. from synapse.util.caches.expiringcache import ExpiringCache
  70. from synapse.util.caches.lrucache import LruCache
  71. from synapse.util.caches.response_cache import ResponseCache, ResponseCacheContext
  72. from synapse.util.metrics import Measure, measure_func
  73. from synapse.visibility import filter_events_for_client
  74. if TYPE_CHECKING:
  75. from synapse.server import HomeServer
  76. logger = logging.getLogger(__name__)
  77. # Counts the number of times we returned a non-empty sync. `type` is one of
  78. # "initial_sync", "full_state_sync" or "incremental_sync", `lazy_loaded` is
  79. # "true" or "false" depending on if the request asked for lazy loaded members or
  80. # not.
  81. non_empty_sync_counter = Counter(
  82. "synapse_handlers_sync_nonempty_total",
  83. "Count of non empty sync responses. type is initial_sync/full_state_sync"
  84. "/incremental_sync. lazy_loaded indicates if lazy loaded members were "
  85. "enabled for that request.",
  86. ["type", "lazy_loaded"],
  87. )
  88. # Store the cache that tracks which lazy-loaded members have been sent to a given
  89. # client for no more than 30 minutes.
  90. LAZY_LOADED_MEMBERS_CACHE_MAX_AGE = 30 * 60 * 1000
  91. # Remember the last 100 members we sent to a client for the purposes of
  92. # avoiding redundantly sending the same lazy-loaded members to the client
  93. LAZY_LOADED_MEMBERS_CACHE_MAX_SIZE = 100
  94. SyncRequestKey = Tuple[Any, ...]
  95. @attr.s(slots=True, frozen=True, auto_attribs=True)
  96. class SyncConfig:
  97. user: UserID
  98. filter_collection: FilterCollection
  99. is_guest: bool
  100. request_key: SyncRequestKey
  101. device_id: Optional[str]
  102. @attr.s(slots=True, frozen=True, auto_attribs=True)
  103. class TimelineBatch:
  104. prev_batch: StreamToken
  105. events: Sequence[EventBase]
  106. limited: bool
  107. # A mapping of event ID to the bundled aggregations for the above events.
  108. # This is only calculated if limited is true.
  109. bundled_aggregations: Optional[Dict[str, BundledAggregations]] = None
  110. def __bool__(self) -> bool:
  111. """Make the result appear empty if there are no updates. This is used
  112. to tell if room needs to be part of the sync result.
  113. """
  114. return bool(self.events)
  115. # We can't freeze this class, because we need to update it after it's instantiated to
  116. # update its unread count. This is because we calculate the unread count for a room only
  117. # if there are updates for it, which we check after the instance has been created.
  118. # This should not be a big deal because we update the notification counts afterwards as
  119. # well anyway.
  120. @attr.s(slots=True, auto_attribs=True)
  121. class JoinedSyncResult:
  122. room_id: str
  123. timeline: TimelineBatch
  124. state: StateMap[EventBase]
  125. ephemeral: List[JsonDict]
  126. account_data: List[JsonDict]
  127. unread_notifications: JsonDict
  128. unread_thread_notifications: JsonDict
  129. summary: Optional[JsonDict]
  130. unread_count: int
  131. def __bool__(self) -> bool:
  132. """Make the result appear empty if there are no updates. This is used
  133. to tell if room needs to be part of the sync result.
  134. """
  135. return bool(
  136. self.timeline
  137. or self.state
  138. or self.ephemeral
  139. or self.account_data
  140. # nb the notification count does not, er, count: if there's nothing
  141. # else in the result, we don't need to send it.
  142. )
  143. @attr.s(slots=True, frozen=True, auto_attribs=True)
  144. class ArchivedSyncResult:
  145. room_id: str
  146. timeline: TimelineBatch
  147. state: StateMap[EventBase]
  148. account_data: List[JsonDict]
  149. def __bool__(self) -> bool:
  150. """Make the result appear empty if there are no updates. This is used
  151. to tell if room needs to be part of the sync result.
  152. """
  153. return bool(self.timeline or self.state or self.account_data)
  154. @attr.s(slots=True, frozen=True, auto_attribs=True)
  155. class InvitedSyncResult:
  156. room_id: str
  157. invite: EventBase
  158. def __bool__(self) -> bool:
  159. """Invited rooms should always be reported to the client"""
  160. return True
  161. @attr.s(slots=True, frozen=True, auto_attribs=True)
  162. class KnockedSyncResult:
  163. room_id: str
  164. knock: EventBase
  165. def __bool__(self) -> bool:
  166. """Knocked rooms should always be reported to the client"""
  167. return True
  168. @attr.s(slots=True, auto_attribs=True)
  169. class _RoomChanges:
  170. """The set of room entries to include in the sync, plus the set of joined
  171. and left room IDs since last sync.
  172. """
  173. room_entries: List["RoomSyncResultBuilder"]
  174. invited: List[InvitedSyncResult]
  175. knocked: List[KnockedSyncResult]
  176. newly_joined_rooms: List[str]
  177. newly_left_rooms: List[str]
  178. @attr.s(slots=True, frozen=True, auto_attribs=True)
  179. class SyncResult:
  180. """
  181. Attributes:
  182. next_batch: Token for the next sync
  183. presence: List of presence events for the user.
  184. account_data: List of account_data events for the user.
  185. joined: JoinedSyncResult for each joined room.
  186. invited: InvitedSyncResult for each invited room.
  187. knocked: KnockedSyncResult for each knocked on room.
  188. archived: ArchivedSyncResult for each archived room.
  189. to_device: List of direct messages for the device.
  190. device_lists: List of user_ids whose devices have changed
  191. device_one_time_keys_count: Dict of algorithm to count for one time keys
  192. for this device
  193. device_unused_fallback_key_types: List of key types that have an unused fallback
  194. key
  195. """
  196. next_batch: StreamToken
  197. presence: List[UserPresenceState]
  198. account_data: List[JsonDict]
  199. joined: List[JoinedSyncResult]
  200. invited: List[InvitedSyncResult]
  201. knocked: List[KnockedSyncResult]
  202. archived: List[ArchivedSyncResult]
  203. to_device: List[JsonDict]
  204. device_lists: DeviceListUpdates
  205. device_one_time_keys_count: JsonDict
  206. device_unused_fallback_key_types: List[str]
  207. def __bool__(self) -> bool:
  208. """Make the result appear empty if there are no updates. This is used
  209. to tell if the notifier needs to wait for more events when polling for
  210. events.
  211. """
  212. return bool(
  213. self.presence
  214. or self.joined
  215. or self.invited
  216. or self.knocked
  217. or self.archived
  218. or self.account_data
  219. or self.to_device
  220. or self.device_lists
  221. )
  222. class SyncHandler:
  223. def __init__(self, hs: "HomeServer"):
  224. self.hs_config = hs.config
  225. self.store = hs.get_datastores().main
  226. self.notifier = hs.get_notifier()
  227. self.presence_handler = hs.get_presence_handler()
  228. self._relations_handler = hs.get_relations_handler()
  229. self.event_sources = hs.get_event_sources()
  230. self.clock = hs.get_clock()
  231. self.state = hs.get_state_handler()
  232. self.auth_blocking = hs.get_auth_blocking()
  233. self._storage_controllers = hs.get_storage_controllers()
  234. self._state_storage_controller = self._storage_controllers.state
  235. self._device_handler = hs.get_device_handler()
  236. self.should_calculate_push_rules = hs.config.push.enable_push
  237. # TODO: flush cache entries on subsequent sync request.
  238. # Once we get the next /sync request (ie, one with the same access token
  239. # that sets 'since' to 'next_batch'), we know that device won't need a
  240. # cached result any more, and we could flush the entry from the cache to save
  241. # memory.
  242. self.response_cache: ResponseCache[SyncRequestKey] = ResponseCache(
  243. hs.get_clock(),
  244. "sync",
  245. timeout_ms=hs.config.caches.sync_response_cache_duration,
  246. )
  247. # ExpiringCache((User, Device)) -> LruCache(user_id => event_id)
  248. self.lazy_loaded_members_cache: ExpiringCache[
  249. Tuple[str, Optional[str]], LruCache[str, str]
  250. ] = ExpiringCache(
  251. "lazy_loaded_members_cache",
  252. self.clock,
  253. max_len=0,
  254. expiry_ms=LAZY_LOADED_MEMBERS_CACHE_MAX_AGE,
  255. )
  256. self.rooms_to_exclude_globally = hs.config.server.rooms_to_exclude_from_sync
  257. async def wait_for_sync_for_user(
  258. self,
  259. requester: Requester,
  260. sync_config: SyncConfig,
  261. since_token: Optional[StreamToken] = None,
  262. timeout: int = 0,
  263. full_state: bool = False,
  264. ) -> SyncResult:
  265. """Get the sync for a client if we have new data for it now. Otherwise
  266. wait for new data to arrive on the server. If the timeout expires, then
  267. return an empty sync result.
  268. """
  269. # If the user is not part of the mau group, then check that limits have
  270. # not been exceeded (if not part of the group by this point, almost certain
  271. # auth_blocking will occur)
  272. user_id = sync_config.user.to_string()
  273. await self.auth_blocking.check_auth_blocking(requester=requester)
  274. res = await self.response_cache.wrap(
  275. sync_config.request_key,
  276. self._wait_for_sync_for_user,
  277. sync_config,
  278. since_token,
  279. timeout,
  280. full_state,
  281. cache_context=True,
  282. )
  283. logger.debug("Returning sync response for %s", user_id)
  284. return res
  285. async def _wait_for_sync_for_user(
  286. self,
  287. sync_config: SyncConfig,
  288. since_token: Optional[StreamToken],
  289. timeout: int,
  290. full_state: bool,
  291. cache_context: ResponseCacheContext[SyncRequestKey],
  292. ) -> SyncResult:
  293. """The start of the machinery that produces a /sync response.
  294. See https://spec.matrix.org/v1.1/client-server-api/#syncing for full details.
  295. This method does high-level bookkeeping:
  296. - tracking the kind of sync in the logging context
  297. - deleting any to_device messages whose delivery has been acknowledged.
  298. - deciding if we should dispatch an instant or delayed response
  299. - marking the sync as being lazily loaded, if appropriate
  300. Computing the body of the response begins in the next method,
  301. `current_sync_for_user`.
  302. """
  303. if since_token is None:
  304. sync_type = "initial_sync"
  305. elif full_state:
  306. sync_type = "full_state_sync"
  307. else:
  308. sync_type = "incremental_sync"
  309. context = current_context()
  310. if context:
  311. context.tag = sync_type
  312. # if we have a since token, delete any to-device messages before that token
  313. # (since we now know that the device has received them)
  314. if since_token is not None:
  315. since_stream_id = since_token.to_device_key
  316. deleted = await self.store.delete_messages_for_device(
  317. sync_config.user.to_string(), sync_config.device_id, since_stream_id
  318. )
  319. logger.debug(
  320. "Deleted %d to-device messages up to %d", deleted, since_stream_id
  321. )
  322. if timeout == 0 or since_token is None or full_state:
  323. # we are going to return immediately, so don't bother calling
  324. # notifier.wait_for_events.
  325. result: SyncResult = await self.current_sync_for_user(
  326. sync_config, since_token, full_state=full_state
  327. )
  328. else:
  329. # Otherwise, we wait for something to happen and report it to the user.
  330. async def current_sync_callback(
  331. before_token: StreamToken, after_token: StreamToken
  332. ) -> SyncResult:
  333. return await self.current_sync_for_user(sync_config, since_token)
  334. result = await self.notifier.wait_for_events(
  335. sync_config.user.to_string(),
  336. timeout,
  337. current_sync_callback,
  338. from_token=since_token,
  339. )
  340. # if nothing has happened in any of the users' rooms since /sync was called,
  341. # the resultant next_batch will be the same as since_token (since the result
  342. # is generated when wait_for_events is first called, and not regenerated
  343. # when wait_for_events times out).
  344. #
  345. # If that happens, we mustn't cache it, so that when the client comes back
  346. # with the same cache token, we don't immediately return the same empty
  347. # result, causing a tightloop. (#8518)
  348. if result.next_batch == since_token:
  349. cache_context.should_cache = False
  350. if result:
  351. if sync_config.filter_collection.lazy_load_members():
  352. lazy_loaded = "true"
  353. else:
  354. lazy_loaded = "false"
  355. non_empty_sync_counter.labels(sync_type, lazy_loaded).inc()
  356. return result
  357. async def current_sync_for_user(
  358. self,
  359. sync_config: SyncConfig,
  360. since_token: Optional[StreamToken] = None,
  361. full_state: bool = False,
  362. ) -> SyncResult:
  363. """Generates the response body of a sync result, represented as a SyncResult.
  364. This is a wrapper around `generate_sync_result` which starts an open tracing
  365. span to track the sync. See `generate_sync_result` for the next part of your
  366. indoctrination.
  367. """
  368. with start_active_span("sync.current_sync_for_user"):
  369. log_kv({"since_token": since_token})
  370. sync_result = await self.generate_sync_result(
  371. sync_config, since_token, full_state
  372. )
  373. set_tag(SynapseTags.SYNC_RESULT, bool(sync_result))
  374. return sync_result
  375. async def push_rules_for_user(self, user: UserID) -> Dict[str, Dict[str, list]]:
  376. user_id = user.to_string()
  377. rules_raw = await self.store.get_push_rules_for_user(user_id)
  378. rules = format_push_rules_for_user(user, rules_raw)
  379. return rules
  380. async def ephemeral_by_room(
  381. self,
  382. sync_result_builder: "SyncResultBuilder",
  383. now_token: StreamToken,
  384. since_token: Optional[StreamToken] = None,
  385. ) -> Tuple[StreamToken, Dict[str, List[JsonDict]]]:
  386. """Get the ephemeral events for each room the user is in
  387. Args:
  388. sync_result_builder
  389. now_token: Where the server is currently up to.
  390. since_token: Where the server was when the client
  391. last synced.
  392. Returns:
  393. A tuple of the now StreamToken, updated to reflect the which typing
  394. events are included, and a dict mapping from room_id to a list of
  395. typing events for that room.
  396. """
  397. sync_config = sync_result_builder.sync_config
  398. with Measure(self.clock, "ephemeral_by_room"):
  399. typing_key = since_token.typing_key if since_token else 0
  400. room_ids = sync_result_builder.joined_room_ids
  401. typing_source = self.event_sources.sources.typing
  402. typing, typing_key = await typing_source.get_new_events(
  403. user=sync_config.user,
  404. from_key=typing_key,
  405. limit=sync_config.filter_collection.ephemeral_limit(),
  406. room_ids=room_ids,
  407. is_guest=sync_config.is_guest,
  408. )
  409. now_token = now_token.copy_and_replace(StreamKeyType.TYPING, typing_key)
  410. ephemeral_by_room: JsonDict = {}
  411. for event in typing:
  412. # we want to exclude the room_id from the event, but modifying the
  413. # result returned by the event source is poor form (it might cache
  414. # the object)
  415. room_id = event["room_id"]
  416. event_copy = {k: v for (k, v) in event.items() if k != "room_id"}
  417. ephemeral_by_room.setdefault(room_id, []).append(event_copy)
  418. receipt_key = since_token.receipt_key if since_token else 0
  419. receipt_source = self.event_sources.sources.receipt
  420. receipts, receipt_key = await receipt_source.get_new_events(
  421. user=sync_config.user,
  422. from_key=receipt_key,
  423. limit=sync_config.filter_collection.ephemeral_limit(),
  424. room_ids=room_ids,
  425. is_guest=sync_config.is_guest,
  426. )
  427. now_token = now_token.copy_and_replace(StreamKeyType.RECEIPT, receipt_key)
  428. for event in receipts:
  429. room_id = event["room_id"]
  430. # exclude room id, as above
  431. event_copy = {k: v for (k, v) in event.items() if k != "room_id"}
  432. ephemeral_by_room.setdefault(room_id, []).append(event_copy)
  433. return now_token, ephemeral_by_room
  434. async def _load_filtered_recents(
  435. self,
  436. room_id: str,
  437. sync_config: SyncConfig,
  438. now_token: StreamToken,
  439. since_token: Optional[StreamToken] = None,
  440. potential_recents: Optional[List[EventBase]] = None,
  441. newly_joined_room: bool = False,
  442. ) -> TimelineBatch:
  443. with Measure(self.clock, "load_filtered_recents"):
  444. timeline_limit = sync_config.filter_collection.timeline_limit()
  445. block_all_timeline = (
  446. sync_config.filter_collection.blocks_all_room_timeline()
  447. )
  448. if (
  449. potential_recents is None
  450. or newly_joined_room
  451. or timeline_limit < len(potential_recents)
  452. ):
  453. limited = True
  454. else:
  455. limited = False
  456. log_kv({"limited": limited})
  457. if potential_recents:
  458. recents = await sync_config.filter_collection.filter_room_timeline(
  459. potential_recents
  460. )
  461. log_kv({"recents_after_sync_filtering": len(recents)})
  462. # We check if there are any state events, if there are then we pass
  463. # all current state events to the filter_events function. This is to
  464. # ensure that we always include current state in the timeline
  465. current_state_ids: FrozenSet[str] = frozenset()
  466. if any(e.is_state() for e in recents):
  467. # FIXME(faster_joins): We use the partial state here as
  468. # we don't want to block `/sync` on finishing a lazy join.
  469. # Which should be fine once
  470. # https://github.com/matrix-org/synapse/issues/12989 is resolved,
  471. # since we shouldn't reach here anymore?
  472. # Note that we use the current state as a whitelist for filtering
  473. # `recents`, so partial state is only a problem when a membership
  474. # event turns up in `recents` but has not made it into the current
  475. # state.
  476. current_state_ids_map = (
  477. await self.store.get_partial_current_state_ids(room_id)
  478. )
  479. current_state_ids = frozenset(current_state_ids_map.values())
  480. recents = await filter_events_for_client(
  481. self._storage_controllers,
  482. sync_config.user.to_string(),
  483. recents,
  484. always_include_ids=current_state_ids,
  485. )
  486. log_kv({"recents_after_visibility_filtering": len(recents)})
  487. else:
  488. recents = []
  489. if not limited or block_all_timeline:
  490. prev_batch_token = now_token
  491. if recents:
  492. room_key = recents[0].internal_metadata.before
  493. prev_batch_token = now_token.copy_and_replace(
  494. StreamKeyType.ROOM, room_key
  495. )
  496. return TimelineBatch(
  497. events=recents, prev_batch=prev_batch_token, limited=False
  498. )
  499. filtering_factor = 2
  500. load_limit = max(timeline_limit * filtering_factor, 10)
  501. max_repeat = 5 # Only try a few times per room, otherwise
  502. room_key = now_token.room_key
  503. end_key = room_key
  504. since_key = None
  505. if since_token and not newly_joined_room:
  506. since_key = since_token.room_key
  507. while limited and len(recents) < timeline_limit and max_repeat:
  508. # If we have a since_key then we are trying to get any events
  509. # that have happened since `since_key` up to `end_key`, so we
  510. # can just use `get_room_events_stream_for_room`.
  511. # Otherwise, we want to return the last N events in the room
  512. # in topological ordering.
  513. if since_key:
  514. events, end_key = await self.store.get_room_events_stream_for_room(
  515. room_id,
  516. limit=load_limit + 1,
  517. from_key=since_key,
  518. to_key=end_key,
  519. )
  520. else:
  521. events, end_key = await self.store.get_recent_events_for_room(
  522. room_id, limit=load_limit + 1, end_token=end_key
  523. )
  524. log_kv({"loaded_recents": len(events)})
  525. loaded_recents = (
  526. await sync_config.filter_collection.filter_room_timeline(events)
  527. )
  528. log_kv({"loaded_recents_after_sync_filtering": len(loaded_recents)})
  529. # We check if there are any state events, if there are then we pass
  530. # all current state events to the filter_events function. This is to
  531. # ensure that we always include current state in the timeline
  532. current_state_ids = frozenset()
  533. if any(e.is_state() for e in loaded_recents):
  534. # FIXME(faster_joins): We use the partial state here as
  535. # we don't want to block `/sync` on finishing a lazy join.
  536. # Which should be fine once
  537. # https://github.com/matrix-org/synapse/issues/12989 is resolved,
  538. # since we shouldn't reach here anymore?
  539. # Note that we use the current state as a whitelist for filtering
  540. # `loaded_recents`, so partial state is only a problem when a
  541. # membership event turns up in `loaded_recents` but has not made it
  542. # into the current state.
  543. current_state_ids_map = (
  544. await self.store.get_partial_current_state_ids(room_id)
  545. )
  546. current_state_ids = frozenset(current_state_ids_map.values())
  547. loaded_recents = await filter_events_for_client(
  548. self._storage_controllers,
  549. sync_config.user.to_string(),
  550. loaded_recents,
  551. always_include_ids=current_state_ids,
  552. )
  553. log_kv({"loaded_recents_after_client_filtering": len(loaded_recents)})
  554. loaded_recents.extend(recents)
  555. recents = loaded_recents
  556. if len(events) <= load_limit:
  557. limited = False
  558. break
  559. max_repeat -= 1
  560. if len(recents) > timeline_limit:
  561. limited = True
  562. recents = recents[-timeline_limit:]
  563. room_key = recents[0].internal_metadata.before
  564. prev_batch_token = now_token.copy_and_replace(StreamKeyType.ROOM, room_key)
  565. # Don't bother to bundle aggregations if the timeline is unlimited,
  566. # as clients will have all the necessary information.
  567. bundled_aggregations = None
  568. if limited or newly_joined_room:
  569. bundled_aggregations = (
  570. await self._relations_handler.get_bundled_aggregations(
  571. recents, sync_config.user.to_string()
  572. )
  573. )
  574. return TimelineBatch(
  575. events=recents,
  576. prev_batch=prev_batch_token,
  577. limited=limited or newly_joined_room,
  578. bundled_aggregations=bundled_aggregations,
  579. )
  580. async def get_state_after_event(
  581. self,
  582. event_id: str,
  583. state_filter: Optional[StateFilter] = None,
  584. await_full_state: bool = True,
  585. ) -> StateMap[str]:
  586. """
  587. Get the room state after the given event
  588. Args:
  589. event_id: event of interest
  590. state_filter: The state filter used to fetch state from the database.
  591. await_full_state: if `True`, will block if we do not yet have complete state
  592. at the event and `state_filter` is not satisfied by partial state.
  593. Defaults to `True`.
  594. """
  595. state_ids = await self._state_storage_controller.get_state_ids_for_event(
  596. event_id,
  597. state_filter=state_filter or StateFilter.all(),
  598. await_full_state=await_full_state,
  599. )
  600. # using get_metadata_for_events here (instead of get_event) sidesteps an issue
  601. # with redactions: if `event_id` is a redaction event, and we don't have the
  602. # original (possibly because it got purged), get_event will refuse to return
  603. # the redaction event, which isn't terribly helpful here.
  604. #
  605. # (To be fair, in that case we could assume it's *not* a state event, and
  606. # therefore we don't need to worry about it. But still, it seems cleaner just
  607. # to pull the metadata.)
  608. m = (await self.store.get_metadata_for_events([event_id]))[event_id]
  609. if m.state_key is not None and m.rejection_reason is None:
  610. state_ids = dict(state_ids)
  611. state_ids[(m.event_type, m.state_key)] = event_id
  612. return state_ids
  613. async def get_state_at(
  614. self,
  615. room_id: str,
  616. stream_position: StreamToken,
  617. state_filter: Optional[StateFilter] = None,
  618. await_full_state: bool = True,
  619. ) -> StateMap[str]:
  620. """Get the room state at a particular stream position
  621. Args:
  622. room_id: room for which to get state
  623. stream_position: point at which to get state
  624. state_filter: The state filter used to fetch state from the database.
  625. await_full_state: if `True`, will block if we do not yet have complete state
  626. at the last event in the room before `stream_position` and
  627. `state_filter` is not satisfied by partial state. Defaults to `True`.
  628. """
  629. # FIXME: This gets the state at the latest event before the stream ordering,
  630. # which might not be the same as the "current state" of the room at the time
  631. # of the stream token if there were multiple forward extremities at the time.
  632. last_event_id = await self.store.get_last_event_in_room_before_stream_ordering(
  633. room_id,
  634. end_token=stream_position.room_key,
  635. )
  636. if last_event_id:
  637. state = await self.get_state_after_event(
  638. last_event_id,
  639. state_filter=state_filter or StateFilter.all(),
  640. await_full_state=await_full_state,
  641. )
  642. else:
  643. # no events in this room - so presumably no state
  644. state = {}
  645. # (erikj) This should be rarely hit, but we've had some reports that
  646. # we get more state down gappy syncs than we should, so let's add
  647. # some logging.
  648. logger.info(
  649. "Failed to find any events in room %s at %s",
  650. room_id,
  651. stream_position.room_key,
  652. )
  653. return state
  654. async def compute_summary(
  655. self,
  656. room_id: str,
  657. sync_config: SyncConfig,
  658. batch: TimelineBatch,
  659. state: MutableStateMap[EventBase],
  660. now_token: StreamToken,
  661. ) -> Optional[JsonDict]:
  662. """Works out a room summary block for this room, summarising the number
  663. of joined members in the room, and providing the 'hero' members if the
  664. room has no name so clients can consistently name rooms. Also adds
  665. state events to 'state' if needed to describe the heroes.
  666. Args
  667. room_id
  668. sync_config
  669. batch: The timeline batch for the room that will be sent to the user.
  670. state: State as returned by compute_state_delta
  671. now_token: Token of the end of the current batch.
  672. """
  673. # FIXME: we could/should get this from room_stats when matthew/stats lands
  674. # FIXME: this promulgates https://github.com/matrix-org/synapse/issues/3305
  675. last_events, _ = await self.store.get_recent_event_ids_for_room(
  676. room_id, end_token=now_token.room_key, limit=1
  677. )
  678. if not last_events:
  679. return None
  680. last_event = last_events[-1]
  681. state_ids = await self._state_storage_controller.get_state_ids_for_event(
  682. last_event.event_id,
  683. state_filter=StateFilter.from_types(
  684. [(EventTypes.Name, ""), (EventTypes.CanonicalAlias, "")]
  685. ),
  686. )
  687. # this is heavily cached, thus: fast.
  688. details = await self.store.get_room_summary(room_id)
  689. name_id = state_ids.get((EventTypes.Name, ""))
  690. canonical_alias_id = state_ids.get((EventTypes.CanonicalAlias, ""))
  691. summary: JsonDict = {}
  692. empty_ms = MemberSummary([], 0)
  693. # TODO: only send these when they change.
  694. summary["m.joined_member_count"] = details.get(Membership.JOIN, empty_ms).count
  695. summary["m.invited_member_count"] = details.get(
  696. Membership.INVITE, empty_ms
  697. ).count
  698. # if the room has a name or canonical_alias set, we can skip
  699. # calculating heroes. Empty strings are falsey, so we check
  700. # for the "name" value and default to an empty string.
  701. if name_id:
  702. name = await self.store.get_event(name_id, allow_none=True)
  703. if name and name.content.get("name"):
  704. return summary
  705. if canonical_alias_id:
  706. canonical_alias = await self.store.get_event(
  707. canonical_alias_id, allow_none=True
  708. )
  709. if canonical_alias and canonical_alias.content.get("alias"):
  710. return summary
  711. # FIXME: only build up a member_ids list for our heroes
  712. member_ids = {}
  713. for membership in (
  714. Membership.JOIN,
  715. Membership.INVITE,
  716. Membership.LEAVE,
  717. Membership.BAN,
  718. ):
  719. for user_id, event_id in details.get(membership, empty_ms).members:
  720. member_ids[user_id] = event_id
  721. me = sync_config.user.to_string()
  722. summary["m.heroes"] = extract_heroes_from_room_summary(details, me)
  723. if not sync_config.filter_collection.lazy_load_members():
  724. return summary
  725. # ensure we send membership events for heroes if needed
  726. cache_key = (sync_config.user.to_string(), sync_config.device_id)
  727. cache = self.get_lazy_loaded_members_cache(cache_key)
  728. # track which members the client should already know about via LL:
  729. # Ones which are already in state...
  730. existing_members = {
  731. user_id for (typ, user_id) in state.keys() if typ == EventTypes.Member
  732. }
  733. # ...or ones which are in the timeline...
  734. for ev in batch.events:
  735. if ev.type == EventTypes.Member:
  736. existing_members.add(ev.state_key)
  737. # ...and then ensure any missing ones get included in state.
  738. missing_hero_event_ids = [
  739. member_ids[hero_id]
  740. for hero_id in summary["m.heroes"]
  741. if (
  742. cache.get(hero_id) != member_ids[hero_id]
  743. and hero_id not in existing_members
  744. )
  745. ]
  746. missing_hero_state = await self.store.get_events(missing_hero_event_ids)
  747. for s in missing_hero_state.values():
  748. cache.set(s.state_key, s.event_id)
  749. state[(EventTypes.Member, s.state_key)] = s
  750. return summary
  751. def get_lazy_loaded_members_cache(
  752. self, cache_key: Tuple[str, Optional[str]]
  753. ) -> LruCache[str, str]:
  754. cache: Optional[LruCache[str, str]] = self.lazy_loaded_members_cache.get(
  755. cache_key
  756. )
  757. if cache is None:
  758. logger.debug("creating LruCache for %r", cache_key)
  759. cache = LruCache(LAZY_LOADED_MEMBERS_CACHE_MAX_SIZE)
  760. self.lazy_loaded_members_cache[cache_key] = cache
  761. else:
  762. logger.debug("found LruCache for %r", cache_key)
  763. return cache
  764. async def compute_state_delta(
  765. self,
  766. room_id: str,
  767. batch: TimelineBatch,
  768. sync_config: SyncConfig,
  769. since_token: Optional[StreamToken],
  770. now_token: StreamToken,
  771. full_state: bool,
  772. ) -> MutableStateMap[EventBase]:
  773. """Works out the difference in state between the end of the previous sync and
  774. the start of the timeline.
  775. Args:
  776. room_id:
  777. batch: The timeline batch for the room that will be sent to the user.
  778. sync_config:
  779. since_token: Token of the end of the previous batch. May be `None`.
  780. now_token: Token of the end of the current batch.
  781. full_state: Whether to force returning the full state.
  782. `lazy_load_members` still applies when `full_state` is `True`.
  783. Returns:
  784. The state to return in the sync response for the room.
  785. Clients will overlay this onto the state at the end of the previous sync to
  786. arrive at the state at the start of the timeline.
  787. Clients will then overlay state events in the timeline to arrive at the
  788. state at the end of the timeline, in preparation for the next sync.
  789. """
  790. # TODO(mjark) Check if the state events were received by the server
  791. # after the previous sync, since we need to include those state
  792. # updates even if they occurred logically before the previous event.
  793. # TODO(mjark) Check for new redactions in the state events.
  794. with Measure(self.clock, "compute_state_delta"):
  795. # The memberships needed for events in the timeline.
  796. # Only calculated when `lazy_load_members` is on.
  797. members_to_fetch: Optional[Set[str]] = None
  798. # A dictionary mapping user IDs to the first event in the timeline sent by
  799. # them. Only calculated when `lazy_load_members` is on.
  800. first_event_by_sender_map: Optional[Dict[str, EventBase]] = None
  801. # The contribution to the room state from state events in the timeline.
  802. # Only contains the last event for any given state key.
  803. timeline_state: StateMap[str]
  804. lazy_load_members = sync_config.filter_collection.lazy_load_members()
  805. include_redundant_members = (
  806. sync_config.filter_collection.include_redundant_members()
  807. )
  808. if lazy_load_members:
  809. # We only request state for the members needed to display the
  810. # timeline:
  811. timeline_state = {}
  812. members_to_fetch = set()
  813. first_event_by_sender_map = {}
  814. for event in batch.events:
  815. # Build the map from user IDs to the first timeline event they sent.
  816. if event.sender not in first_event_by_sender_map:
  817. first_event_by_sender_map[event.sender] = event
  818. # We need the event's sender, unless their membership was in a
  819. # previous timeline event.
  820. if (EventTypes.Member, event.sender) not in timeline_state:
  821. members_to_fetch.add(event.sender)
  822. # FIXME: we also care about invite targets etc.
  823. if event.is_state():
  824. timeline_state[(event.type, event.state_key)] = event.event_id
  825. if full_state:
  826. # always make sure we LL ourselves so we know we're in the room
  827. # (if we are) to fix https://github.com/vector-im/riot-web/issues/7209
  828. # We only need apply this on full state syncs given we disabled
  829. # LL for incr syncs in #3840.
  830. members_to_fetch.add(sync_config.user.to_string())
  831. state_filter = StateFilter.from_lazy_load_member_list(members_to_fetch)
  832. # We are happy to use partial state to compute the `/sync` response.
  833. # Since partial state may not include the lazy-loaded memberships we
  834. # require, we fix up the state response afterwards with memberships from
  835. # auth events.
  836. await_full_state = False
  837. else:
  838. timeline_state = {
  839. (event.type, event.state_key): event.event_id
  840. for event in batch.events
  841. if event.is_state()
  842. }
  843. state_filter = StateFilter.all()
  844. await_full_state = True
  845. # Now calculate the state to return in the sync response for the room.
  846. # This is more or less the change in state between the end of the previous
  847. # sync's timeline and the start of the current sync's timeline.
  848. # See the docstring above for details.
  849. state_ids: StateMap[str]
  850. if full_state:
  851. if batch:
  852. state_at_timeline_end = (
  853. await self._state_storage_controller.get_state_ids_for_event(
  854. batch.events[-1].event_id,
  855. state_filter=state_filter,
  856. await_full_state=await_full_state,
  857. )
  858. )
  859. state_at_timeline_start = (
  860. await self._state_storage_controller.get_state_ids_for_event(
  861. batch.events[0].event_id,
  862. state_filter=state_filter,
  863. await_full_state=await_full_state,
  864. )
  865. )
  866. else:
  867. state_at_timeline_end = await self.get_state_at(
  868. room_id,
  869. stream_position=now_token,
  870. state_filter=state_filter,
  871. await_full_state=await_full_state,
  872. )
  873. state_at_timeline_start = state_at_timeline_end
  874. state_ids = _calculate_state(
  875. timeline_contains=timeline_state,
  876. timeline_start=state_at_timeline_start,
  877. timeline_end=state_at_timeline_end,
  878. previous_timeline_end={},
  879. lazy_load_members=lazy_load_members,
  880. )
  881. elif batch.limited:
  882. if batch:
  883. state_at_timeline_start = (
  884. await self._state_storage_controller.get_state_ids_for_event(
  885. batch.events[0].event_id,
  886. state_filter=state_filter,
  887. await_full_state=await_full_state,
  888. )
  889. )
  890. else:
  891. # We can get here if the user has ignored the senders of all
  892. # the recent events.
  893. state_at_timeline_start = await self.get_state_at(
  894. room_id,
  895. stream_position=now_token,
  896. state_filter=state_filter,
  897. await_full_state=await_full_state,
  898. )
  899. # for now, we disable LL for gappy syncs - see
  900. # https://github.com/vector-im/riot-web/issues/7211#issuecomment-419976346
  901. # N.B. this slows down incr syncs as we are now processing way
  902. # more state in the server than if we were LLing.
  903. #
  904. # We still have to filter timeline_start to LL entries (above) in order
  905. # for _calculate_state's LL logic to work, as we have to include LL
  906. # members for timeline senders in case they weren't loaded in the initial
  907. # sync. We do this by (counterintuitively) by filtering timeline_start
  908. # members to just be ones which were timeline senders, which then ensures
  909. # all of the rest get included in the state block (if we need to know
  910. # about them).
  911. state_filter = StateFilter.all()
  912. # If this is an initial sync then full_state should be set, and
  913. # that case is handled above. We assert here to ensure that this
  914. # is indeed the case.
  915. assert since_token is not None
  916. state_at_previous_sync = await self.get_state_at(
  917. room_id,
  918. stream_position=since_token,
  919. state_filter=state_filter,
  920. await_full_state=await_full_state,
  921. )
  922. if batch:
  923. state_at_timeline_end = (
  924. await self._state_storage_controller.get_state_ids_for_event(
  925. batch.events[-1].event_id,
  926. state_filter=state_filter,
  927. await_full_state=await_full_state,
  928. )
  929. )
  930. else:
  931. # We can get here if the user has ignored the senders of all
  932. # the recent events.
  933. state_at_timeline_end = await self.get_state_at(
  934. room_id,
  935. stream_position=now_token,
  936. state_filter=state_filter,
  937. await_full_state=await_full_state,
  938. )
  939. state_ids = _calculate_state(
  940. timeline_contains=timeline_state,
  941. timeline_start=state_at_timeline_start,
  942. timeline_end=state_at_timeline_end,
  943. previous_timeline_end=state_at_previous_sync,
  944. # we have to include LL members in case LL initial sync missed them
  945. lazy_load_members=lazy_load_members,
  946. )
  947. else:
  948. state_ids = {}
  949. if lazy_load_members:
  950. if members_to_fetch and batch.events:
  951. # We're returning an incremental sync, with no
  952. # "gap" since the previous sync, so normally there would be
  953. # no state to return.
  954. # But we're lazy-loading, so the client might need some more
  955. # member events to understand the events in this timeline.
  956. # So we fish out all the member events corresponding to the
  957. # timeline here, and then dedupe any redundant ones below.
  958. state_ids = await self._state_storage_controller.get_state_ids_for_event(
  959. batch.events[0].event_id,
  960. # we only want members!
  961. state_filter=StateFilter.from_types(
  962. (EventTypes.Member, member)
  963. for member in members_to_fetch
  964. ),
  965. await_full_state=False,
  966. )
  967. # If we only have partial state for the room, `state_ids` may be missing the
  968. # memberships we wanted. We attempt to find some by digging through the auth
  969. # events of timeline events.
  970. if lazy_load_members and await self.store.is_partial_state_room(room_id):
  971. assert members_to_fetch is not None
  972. assert first_event_by_sender_map is not None
  973. additional_state_ids = (
  974. await self._find_missing_partial_state_memberships(
  975. room_id, members_to_fetch, first_event_by_sender_map, state_ids
  976. )
  977. )
  978. state_ids = {**state_ids, **additional_state_ids}
  979. # At this point, if `lazy_load_members` is enabled, `state_ids` includes
  980. # the memberships of all event senders in the timeline. This is because we
  981. # may not have sent the memberships in a previous sync.
  982. # When `include_redundant_members` is on, we send all the lazy-loaded
  983. # memberships of event senders. Otherwise we make an effort to limit the set
  984. # of memberships we send to those that we have not already sent to this client.
  985. if lazy_load_members and not include_redundant_members:
  986. cache_key = (sync_config.user.to_string(), sync_config.device_id)
  987. cache = self.get_lazy_loaded_members_cache(cache_key)
  988. # if it's a new sync sequence, then assume the client has had
  989. # amnesia and doesn't want any recent lazy-loaded members
  990. # de-duplicated.
  991. if since_token is None:
  992. logger.debug("clearing LruCache for %r", cache_key)
  993. cache.clear()
  994. else:
  995. # only send members which aren't in our LruCache (either
  996. # because they're new to this client or have been pushed out
  997. # of the cache)
  998. logger.debug("filtering state from %r...", state_ids)
  999. state_ids = {
  1000. t: event_id
  1001. for t, event_id in state_ids.items()
  1002. if cache.get(t[1]) != event_id
  1003. }
  1004. logger.debug("...to %r", state_ids)
  1005. # add any member IDs we are about to send into our LruCache
  1006. for t, event_id in itertools.chain(
  1007. state_ids.items(), timeline_state.items()
  1008. ):
  1009. if t[0] == EventTypes.Member:
  1010. cache.set(t[1], event_id)
  1011. state: Dict[str, EventBase] = {}
  1012. if state_ids:
  1013. state = await self.store.get_events(list(state_ids.values()))
  1014. return {
  1015. (e.type, e.state_key): e
  1016. for e in await sync_config.filter_collection.filter_room_state(
  1017. list(state.values())
  1018. )
  1019. if e.type != EventTypes.Aliases # until MSC2261 or alternative solution
  1020. }
  1021. async def _find_missing_partial_state_memberships(
  1022. self,
  1023. room_id: str,
  1024. members_to_fetch: StrCollection,
  1025. events_with_membership_auth: Mapping[str, EventBase],
  1026. found_state_ids: StateMap[str],
  1027. ) -> StateMap[str]:
  1028. """Finds missing memberships from a set of auth events and returns them as a
  1029. state map.
  1030. Args:
  1031. room_id: The partial state room to find the remaining memberships for.
  1032. members_to_fetch: The memberships to find.
  1033. events_with_membership_auth: A mapping from user IDs to events whose auth
  1034. events would contain their prior membership, if one exists.
  1035. Note that join events will not cite a prior membership if a user has
  1036. never been in a room before.
  1037. found_state_ids: A dict from (type, state_key) -> state_event_id, containing
  1038. memberships that have been previously found. Entries in
  1039. `members_to_fetch` that have a membership in `found_state_ids` are
  1040. ignored.
  1041. Returns:
  1042. A dict from ("m.room.member", state_key) -> state_event_id, containing the
  1043. memberships missing from `found_state_ids`.
  1044. When `events_with_membership_auth` contains a join event for a given user
  1045. which does not cite a prior membership, no membership is returned for that
  1046. user.
  1047. Raises:
  1048. KeyError: if `events_with_membership_auth` does not have an entry for a
  1049. missing membership. Memberships in `found_state_ids` do not need an
  1050. entry in `events_with_membership_auth`.
  1051. """
  1052. additional_state_ids: MutableStateMap[str] = {}
  1053. # Tracks the missing members for logging purposes.
  1054. missing_members = set()
  1055. # Identify memberships missing from `found_state_ids` and pick out the auth
  1056. # events in which to look for them.
  1057. auth_event_ids: Set[str] = set()
  1058. for member in members_to_fetch:
  1059. if (EventTypes.Member, member) in found_state_ids:
  1060. continue
  1061. event_with_membership_auth = events_with_membership_auth[member]
  1062. is_join = (
  1063. event_with_membership_auth.is_state()
  1064. and event_with_membership_auth.type == EventTypes.Member
  1065. and event_with_membership_auth.state_key == member
  1066. and event_with_membership_auth.content.get("membership")
  1067. == Membership.JOIN
  1068. )
  1069. if not is_join:
  1070. # The event must include the desired membership as an auth event, unless
  1071. # it's the first join event for a given user.
  1072. missing_members.add(member)
  1073. auth_event_ids.update(event_with_membership_auth.auth_event_ids())
  1074. auth_events = await self.store.get_events(auth_event_ids)
  1075. # Run through the missing memberships once more, picking out the memberships
  1076. # from the pile of auth events we have just fetched.
  1077. for member in members_to_fetch:
  1078. if (EventTypes.Member, member) in found_state_ids:
  1079. continue
  1080. event_with_membership_auth = events_with_membership_auth[member]
  1081. # Dig through the auth events to find the desired membership.
  1082. for auth_event_id in event_with_membership_auth.auth_event_ids():
  1083. # We only store events once we have all their auth events,
  1084. # so the auth event must be in the pile we have just
  1085. # fetched.
  1086. auth_event = auth_events[auth_event_id]
  1087. if (
  1088. auth_event.type == EventTypes.Member
  1089. and auth_event.state_key == member
  1090. ):
  1091. missing_members.discard(member)
  1092. additional_state_ids[
  1093. (EventTypes.Member, member)
  1094. ] = auth_event.event_id
  1095. break
  1096. if missing_members:
  1097. # There really shouldn't be any missing memberships now. Either:
  1098. # * we couldn't find an auth event, which shouldn't happen because we do
  1099. # not persist events with persisting their auth events first, or
  1100. # * the set of auth events did not contain a membership we wanted, which
  1101. # means our caller didn't compute the events in `members_to_fetch`
  1102. # correctly, or we somehow accepted an event whose auth events were
  1103. # dodgy.
  1104. logger.error(
  1105. "Failed to find memberships for %s in partial state room "
  1106. "%s in the auth events of %s.",
  1107. missing_members,
  1108. room_id,
  1109. [
  1110. events_with_membership_auth[member].event_id
  1111. for member in missing_members
  1112. ],
  1113. )
  1114. return additional_state_ids
  1115. async def unread_notifs_for_room_id(
  1116. self, room_id: str, sync_config: SyncConfig
  1117. ) -> RoomNotifCounts:
  1118. if not self.should_calculate_push_rules:
  1119. # If push rules have been universally disabled then we know we won't
  1120. # have any unread counts in the DB, so we may as well skip asking
  1121. # the DB.
  1122. return RoomNotifCounts.empty()
  1123. with Measure(self.clock, "unread_notifs_for_room_id"):
  1124. return await self.store.get_unread_event_push_actions_by_room_for_user(
  1125. room_id,
  1126. sync_config.user.to_string(),
  1127. )
  1128. async def generate_sync_result(
  1129. self,
  1130. sync_config: SyncConfig,
  1131. since_token: Optional[StreamToken] = None,
  1132. full_state: bool = False,
  1133. ) -> SyncResult:
  1134. """Generates the response body of a sync result.
  1135. This is represented by a `SyncResult` struct, which is built from small pieces
  1136. using a `SyncResultBuilder`. See also
  1137. https://spec.matrix.org/v1.1/client-server-api/#get_matrixclientv3sync
  1138. the `sync_result_builder` is passed as a mutable ("inout") parameter to various
  1139. helper functions. These retrieve and process the data which forms the sync body,
  1140. often writing to the `sync_result_builder` to store their output.
  1141. At the end, we transfer data from the `sync_result_builder` to a new `SyncResult`
  1142. instance to signify that the sync calculation is complete.
  1143. """
  1144. user_id = sync_config.user.to_string()
  1145. app_service = self.store.get_app_service_by_user_id(user_id)
  1146. if app_service:
  1147. # We no longer support AS users using /sync directly.
  1148. # See https://github.com/matrix-org/matrix-doc/issues/1144
  1149. raise NotImplementedError()
  1150. # Note: we get the users room list *before* we get the current token, this
  1151. # avoids checking back in history if rooms are joined after the token is fetched.
  1152. token_before_rooms = self.event_sources.get_current_token()
  1153. mutable_joined_room_ids = set(await self.store.get_rooms_for_user(user_id))
  1154. # NB: The now_token gets changed by some of the generate_sync_* methods,
  1155. # this is due to some of the underlying streams not supporting the ability
  1156. # to query up to a given point.
  1157. # Always use the `now_token` in `SyncResultBuilder`
  1158. now_token = self.event_sources.get_current_token()
  1159. log_kv({"now_token": now_token})
  1160. # Since we fetched the users room list before the token, there's a small window
  1161. # during which membership events may have been persisted, so we fetch these now
  1162. # and modify the joined room list for any changes between the get_rooms_for_user
  1163. # call and the get_current_token call.
  1164. membership_change_events = []
  1165. if since_token:
  1166. membership_change_events = await self.store.get_membership_changes_for_user(
  1167. user_id,
  1168. since_token.room_key,
  1169. now_token.room_key,
  1170. self.rooms_to_exclude_globally,
  1171. )
  1172. mem_last_change_by_room_id: Dict[str, EventBase] = {}
  1173. for event in membership_change_events:
  1174. mem_last_change_by_room_id[event.room_id] = event
  1175. # For the latest membership event in each room found, add/remove the room ID
  1176. # from the joined room list accordingly. In this case we only care if the
  1177. # latest change is JOIN.
  1178. for room_id, event in mem_last_change_by_room_id.items():
  1179. assert event.internal_metadata.stream_ordering
  1180. if (
  1181. event.internal_metadata.stream_ordering
  1182. < token_before_rooms.room_key.stream
  1183. ):
  1184. continue
  1185. logger.info(
  1186. "User membership change between getting rooms and current token: %s %s %s",
  1187. user_id,
  1188. event.membership,
  1189. room_id,
  1190. )
  1191. # User joined a room - we have to then check the room state to ensure we
  1192. # respect any bans if there's a race between the join and ban events.
  1193. if event.membership == Membership.JOIN:
  1194. user_ids_in_room = await self.store.get_users_in_room(room_id)
  1195. if user_id in user_ids_in_room:
  1196. mutable_joined_room_ids.add(room_id)
  1197. # The user left the room, or left and was re-invited but not joined yet
  1198. else:
  1199. mutable_joined_room_ids.discard(room_id)
  1200. # Tweak the set of rooms to return to the client for eager (non-lazy) syncs.
  1201. mutable_rooms_to_exclude = set(self.rooms_to_exclude_globally)
  1202. if not sync_config.filter_collection.lazy_load_members():
  1203. # Non-lazy syncs should never include partially stated rooms.
  1204. # Exclude all partially stated rooms from this sync.
  1205. results = await self.store.is_partial_state_room_batched(
  1206. mutable_joined_room_ids
  1207. )
  1208. mutable_rooms_to_exclude.update(
  1209. room_id
  1210. for room_id, is_partial_state in results.items()
  1211. if is_partial_state
  1212. )
  1213. membership_change_events = [
  1214. event
  1215. for event in membership_change_events
  1216. if not results.get(event.room_id, False)
  1217. ]
  1218. # Incremental eager syncs should additionally include rooms that
  1219. # - we are joined to
  1220. # - are full-stated
  1221. # - became fully-stated at some point during the sync period
  1222. # (These rooms will have been omitted during a previous eager sync.)
  1223. forced_newly_joined_room_ids: Set[str] = set()
  1224. if since_token and not sync_config.filter_collection.lazy_load_members():
  1225. un_partial_stated_rooms = (
  1226. await self.store.get_un_partial_stated_rooms_between(
  1227. since_token.un_partial_stated_rooms_key,
  1228. now_token.un_partial_stated_rooms_key,
  1229. mutable_joined_room_ids,
  1230. )
  1231. )
  1232. results = await self.store.is_partial_state_room_batched(
  1233. un_partial_stated_rooms
  1234. )
  1235. forced_newly_joined_room_ids.update(
  1236. room_id
  1237. for room_id, is_partial_state in results.items()
  1238. if not is_partial_state
  1239. )
  1240. # Now we have our list of joined room IDs, exclude as configured and freeze
  1241. joined_room_ids = frozenset(
  1242. (
  1243. room_id
  1244. for room_id in mutable_joined_room_ids
  1245. if room_id not in mutable_rooms_to_exclude
  1246. )
  1247. )
  1248. logger.debug(
  1249. "Calculating sync response for %r between %s and %s",
  1250. sync_config.user,
  1251. since_token,
  1252. now_token,
  1253. )
  1254. sync_result_builder = SyncResultBuilder(
  1255. sync_config,
  1256. full_state,
  1257. since_token=since_token,
  1258. now_token=now_token,
  1259. joined_room_ids=joined_room_ids,
  1260. excluded_room_ids=frozenset(mutable_rooms_to_exclude),
  1261. forced_newly_joined_room_ids=frozenset(forced_newly_joined_room_ids),
  1262. membership_change_events=membership_change_events,
  1263. )
  1264. logger.debug("Fetching account data")
  1265. # Global account data is included if it is not filtered out.
  1266. if not sync_config.filter_collection.blocks_all_global_account_data():
  1267. await self._generate_sync_entry_for_account_data(sync_result_builder)
  1268. # Presence data is included if the server has it enabled and not filtered out.
  1269. include_presence_data = bool(
  1270. self.hs_config.server.use_presence
  1271. and not sync_config.filter_collection.blocks_all_presence()
  1272. )
  1273. # Device list updates are sent if a since token is provided.
  1274. include_device_list_updates = bool(since_token and since_token.device_list_key)
  1275. # If we do not care about the rooms or things which depend on the room
  1276. # data (namely presence and device list updates), then we can skip
  1277. # this process completely.
  1278. device_lists = DeviceListUpdates()
  1279. if (
  1280. not sync_result_builder.sync_config.filter_collection.blocks_all_rooms()
  1281. or include_presence_data
  1282. or include_device_list_updates
  1283. ):
  1284. logger.debug("Fetching room data")
  1285. # Note that _generate_sync_entry_for_rooms sets sync_result_builder.joined, which
  1286. # is used in calculate_user_changes below.
  1287. (
  1288. newly_joined_rooms,
  1289. newly_left_rooms,
  1290. ) = await self._generate_sync_entry_for_rooms(sync_result_builder)
  1291. # Work out which users have joined or left rooms we're in. We use this
  1292. # to build the presence and device_list parts of the sync response in
  1293. # `_generate_sync_entry_for_presence` and
  1294. # `_generate_sync_entry_for_device_list` respectively.
  1295. if include_presence_data or include_device_list_updates:
  1296. # This uses the sync_result_builder.joined which is set in
  1297. # `_generate_sync_entry_for_rooms`, if that didn't find any joined
  1298. # rooms for some reason it is a no-op.
  1299. (
  1300. newly_joined_or_invited_or_knocked_users,
  1301. newly_left_users,
  1302. ) = sync_result_builder.calculate_user_changes()
  1303. if include_presence_data:
  1304. logger.debug("Fetching presence data")
  1305. await self._generate_sync_entry_for_presence(
  1306. sync_result_builder,
  1307. newly_joined_rooms,
  1308. newly_joined_or_invited_or_knocked_users,
  1309. )
  1310. if include_device_list_updates:
  1311. device_lists = await self._generate_sync_entry_for_device_list(
  1312. sync_result_builder,
  1313. newly_joined_rooms=newly_joined_rooms,
  1314. newly_joined_or_invited_or_knocked_users=newly_joined_or_invited_or_knocked_users,
  1315. newly_left_rooms=newly_left_rooms,
  1316. newly_left_users=newly_left_users,
  1317. )
  1318. logger.debug("Fetching to-device data")
  1319. await self._generate_sync_entry_for_to_device(sync_result_builder)
  1320. logger.debug("Fetching OTK data")
  1321. device_id = sync_config.device_id
  1322. one_time_keys_count: JsonDict = {}
  1323. unused_fallback_key_types: List[str] = []
  1324. if device_id:
  1325. # TODO: We should have a way to let clients differentiate between the states of:
  1326. # * no change in OTK count since the provided since token
  1327. # * the server has zero OTKs left for this device
  1328. # Spec issue: https://github.com/matrix-org/matrix-doc/issues/3298
  1329. one_time_keys_count = await self.store.count_e2e_one_time_keys(
  1330. user_id, device_id
  1331. )
  1332. unused_fallback_key_types = list(
  1333. await self.store.get_e2e_unused_fallback_key_types(user_id, device_id)
  1334. )
  1335. num_events = 0
  1336. # debug for https://github.com/matrix-org/synapse/issues/9424
  1337. for joined_room in sync_result_builder.joined:
  1338. num_events += len(joined_room.timeline.events)
  1339. log_kv(
  1340. {
  1341. "joined_rooms_in_result": len(sync_result_builder.joined),
  1342. "events_in_result": num_events,
  1343. }
  1344. )
  1345. logger.debug("Sync response calculation complete")
  1346. return SyncResult(
  1347. presence=sync_result_builder.presence,
  1348. account_data=sync_result_builder.account_data,
  1349. joined=sync_result_builder.joined,
  1350. invited=sync_result_builder.invited,
  1351. knocked=sync_result_builder.knocked,
  1352. archived=sync_result_builder.archived,
  1353. to_device=sync_result_builder.to_device,
  1354. device_lists=device_lists,
  1355. device_one_time_keys_count=one_time_keys_count,
  1356. device_unused_fallback_key_types=unused_fallback_key_types,
  1357. next_batch=sync_result_builder.now_token,
  1358. )
  1359. @measure_func("_generate_sync_entry_for_device_list")
  1360. async def _generate_sync_entry_for_device_list(
  1361. self,
  1362. sync_result_builder: "SyncResultBuilder",
  1363. newly_joined_rooms: AbstractSet[str],
  1364. newly_joined_or_invited_or_knocked_users: AbstractSet[str],
  1365. newly_left_rooms: AbstractSet[str],
  1366. newly_left_users: AbstractSet[str],
  1367. ) -> DeviceListUpdates:
  1368. """Generate the DeviceListUpdates section of sync
  1369. Args:
  1370. sync_result_builder
  1371. newly_joined_rooms: Set of rooms user has joined since previous sync
  1372. newly_joined_or_invited_or_knocked_users: Set of users that have joined,
  1373. been invited to a room or are knocking on a room since
  1374. previous sync.
  1375. newly_left_rooms: Set of rooms user has left since previous sync
  1376. newly_left_users: Set of users that have left a room we're in since
  1377. previous sync
  1378. """
  1379. user_id = sync_result_builder.sync_config.user.to_string()
  1380. since_token = sync_result_builder.since_token
  1381. assert since_token is not None
  1382. # Take a copy since these fields will be mutated later.
  1383. newly_joined_or_invited_or_knocked_users = set(
  1384. newly_joined_or_invited_or_knocked_users
  1385. )
  1386. newly_left_users = set(newly_left_users)
  1387. # We want to figure out what user IDs the client should refetch
  1388. # device keys for, and which users we aren't going to track changes
  1389. # for anymore.
  1390. #
  1391. # For the first step we check:
  1392. # a. if any users we share a room with have updated their devices,
  1393. # and
  1394. # b. we also check if we've joined any new rooms, or if a user has
  1395. # joined a room we're in.
  1396. #
  1397. # For the second step we just find any users we no longer share a
  1398. # room with by looking at all users that have left a room plus users
  1399. # that were in a room we've left.
  1400. users_that_have_changed = set()
  1401. joined_rooms = sync_result_builder.joined_room_ids
  1402. # Step 1a, check for changes in devices of users we share a room
  1403. # with
  1404. #
  1405. # We do this in two different ways depending on what we have cached.
  1406. # If we already have a list of all the user that have changed since
  1407. # the last sync then it's likely more efficient to compare the rooms
  1408. # they're in with the rooms the syncing user is in.
  1409. #
  1410. # If we don't have that info cached then we get all the users that
  1411. # share a room with our user and check if those users have changed.
  1412. cache_result = self.store.get_cached_device_list_changes(
  1413. since_token.device_list_key
  1414. )
  1415. if cache_result.hit:
  1416. changed_users = cache_result.entities
  1417. result = await self.store.get_rooms_for_users(changed_users)
  1418. for changed_user_id, entries in result.items():
  1419. # Check if the changed user shares any rooms with the user,
  1420. # or if the changed user is the syncing user (as we always
  1421. # want to include device list updates of their own devices).
  1422. if user_id == changed_user_id or any(
  1423. rid in joined_rooms for rid in entries
  1424. ):
  1425. users_that_have_changed.add(changed_user_id)
  1426. else:
  1427. users_that_have_changed = (
  1428. await self._device_handler.get_device_changes_in_shared_rooms(
  1429. user_id,
  1430. sync_result_builder.joined_room_ids,
  1431. from_token=since_token,
  1432. )
  1433. )
  1434. # Step 1b, check for newly joined rooms
  1435. for room_id in newly_joined_rooms:
  1436. joined_users = await self.store.get_users_in_room(room_id)
  1437. newly_joined_or_invited_or_knocked_users.update(joined_users)
  1438. # TODO: Check that these users are actually new, i.e. either they
  1439. # weren't in the previous sync *or* they left and rejoined.
  1440. users_that_have_changed.update(newly_joined_or_invited_or_knocked_users)
  1441. user_signatures_changed = await self.store.get_users_whose_signatures_changed(
  1442. user_id, since_token.device_list_key
  1443. )
  1444. users_that_have_changed.update(user_signatures_changed)
  1445. # Now find users that we no longer track
  1446. for room_id in newly_left_rooms:
  1447. left_users = await self.store.get_users_in_room(room_id)
  1448. newly_left_users.update(left_users)
  1449. # Remove any users that we still share a room with.
  1450. left_users_rooms = await self.store.get_rooms_for_users(newly_left_users)
  1451. for user_id, entries in left_users_rooms.items():
  1452. if any(rid in joined_rooms for rid in entries):
  1453. newly_left_users.discard(user_id)
  1454. return DeviceListUpdates(changed=users_that_have_changed, left=newly_left_users)
  1455. @trace
  1456. async def _generate_sync_entry_for_to_device(
  1457. self, sync_result_builder: "SyncResultBuilder"
  1458. ) -> None:
  1459. """Generates the portion of the sync response. Populates
  1460. `sync_result_builder` with the result.
  1461. """
  1462. user_id = sync_result_builder.sync_config.user.to_string()
  1463. device_id = sync_result_builder.sync_config.device_id
  1464. now_token = sync_result_builder.now_token
  1465. since_stream_id = 0
  1466. if sync_result_builder.since_token is not None:
  1467. since_stream_id = int(sync_result_builder.since_token.to_device_key)
  1468. if device_id is not None and since_stream_id != int(now_token.to_device_key):
  1469. messages, stream_id = await self.store.get_messages_for_device(
  1470. user_id, device_id, since_stream_id, now_token.to_device_key
  1471. )
  1472. for message in messages:
  1473. log_kv(
  1474. {
  1475. "event": "to_device_message",
  1476. "sender": message["sender"],
  1477. "type": message["type"],
  1478. EventContentFields.TO_DEVICE_MSGID: message["content"].get(
  1479. EventContentFields.TO_DEVICE_MSGID
  1480. ),
  1481. }
  1482. )
  1483. if messages and issue9533_logger.isEnabledFor(logging.DEBUG):
  1484. issue9533_logger.debug(
  1485. "Returning to-device messages with stream_ids (%d, %d]; now: %d;"
  1486. " msgids: %s",
  1487. since_stream_id,
  1488. stream_id,
  1489. now_token.to_device_key,
  1490. [
  1491. message["content"].get(EventContentFields.TO_DEVICE_MSGID)
  1492. for message in messages
  1493. ],
  1494. )
  1495. sync_result_builder.now_token = now_token.copy_and_replace(
  1496. StreamKeyType.TO_DEVICE, stream_id
  1497. )
  1498. sync_result_builder.to_device = messages
  1499. else:
  1500. sync_result_builder.to_device = []
  1501. async def _generate_sync_entry_for_account_data(
  1502. self, sync_result_builder: "SyncResultBuilder"
  1503. ) -> None:
  1504. """Generates the global account data portion of the sync response.
  1505. Account data (called "Client Config" in the spec) can be set either globally
  1506. or for a specific room. Account data consists of a list of events which
  1507. accumulate state, much like a room.
  1508. This function retrieves global account data and writes it to the given
  1509. `sync_result_builder`. See `_generate_sync_entry_for_rooms` for handling
  1510. of per-room account data.
  1511. Args:
  1512. sync_result_builder
  1513. """
  1514. sync_config = sync_result_builder.sync_config
  1515. user_id = sync_result_builder.sync_config.user.to_string()
  1516. since_token = sync_result_builder.since_token
  1517. if since_token and not sync_result_builder.full_state:
  1518. global_account_data = (
  1519. await self.store.get_updated_global_account_data_for_user(
  1520. user_id, since_token.account_data_key
  1521. )
  1522. )
  1523. push_rules_changed = await self.store.have_push_rules_changed_for_user(
  1524. user_id, int(since_token.push_rules_key)
  1525. )
  1526. if push_rules_changed:
  1527. global_account_data = dict(global_account_data)
  1528. global_account_data["m.push_rules"] = await self.push_rules_for_user(
  1529. sync_config.user
  1530. )
  1531. else:
  1532. all_global_account_data = await self.store.get_global_account_data_for_user(
  1533. user_id
  1534. )
  1535. global_account_data = dict(all_global_account_data)
  1536. global_account_data["m.push_rules"] = await self.push_rules_for_user(
  1537. sync_config.user
  1538. )
  1539. account_data_for_user = (
  1540. await sync_config.filter_collection.filter_global_account_data(
  1541. [
  1542. {"type": account_data_type, "content": content}
  1543. for account_data_type, content in global_account_data.items()
  1544. ]
  1545. )
  1546. )
  1547. sync_result_builder.account_data = account_data_for_user
  1548. async def _generate_sync_entry_for_presence(
  1549. self,
  1550. sync_result_builder: "SyncResultBuilder",
  1551. newly_joined_rooms: AbstractSet[str],
  1552. newly_joined_or_invited_users: AbstractSet[str],
  1553. ) -> None:
  1554. """Generates the presence portion of the sync response. Populates the
  1555. `sync_result_builder` with the result.
  1556. Args:
  1557. sync_result_builder
  1558. newly_joined_rooms: Set of rooms that the user has joined since
  1559. the last sync (or empty if an initial sync)
  1560. newly_joined_or_invited_users: Set of users that have joined or
  1561. been invited to rooms since the last sync (or empty if an
  1562. initial sync)
  1563. """
  1564. now_token = sync_result_builder.now_token
  1565. sync_config = sync_result_builder.sync_config
  1566. user = sync_result_builder.sync_config.user
  1567. presence_source = self.event_sources.sources.presence
  1568. since_token = sync_result_builder.since_token
  1569. presence_key = None
  1570. include_offline = False
  1571. if since_token and not sync_result_builder.full_state:
  1572. presence_key = since_token.presence_key
  1573. include_offline = True
  1574. presence, presence_key = await presence_source.get_new_events(
  1575. user=user,
  1576. from_key=presence_key,
  1577. is_guest=sync_config.is_guest,
  1578. include_offline=include_offline,
  1579. )
  1580. assert presence_key
  1581. sync_result_builder.now_token = now_token.copy_and_replace(
  1582. StreamKeyType.PRESENCE, presence_key
  1583. )
  1584. extra_users_ids = set(newly_joined_or_invited_users)
  1585. for room_id in newly_joined_rooms:
  1586. users = await self.store.get_users_in_room(room_id)
  1587. extra_users_ids.update(users)
  1588. extra_users_ids.discard(user.to_string())
  1589. if extra_users_ids:
  1590. states = await self.presence_handler.get_states(extra_users_ids)
  1591. presence.extend(states)
  1592. # Deduplicate the presence entries so that there's at most one per user
  1593. presence = list({p.user_id: p for p in presence}.values())
  1594. presence = await sync_config.filter_collection.filter_presence(presence)
  1595. sync_result_builder.presence = presence
  1596. async def _generate_sync_entry_for_rooms(
  1597. self, sync_result_builder: "SyncResultBuilder"
  1598. ) -> Tuple[AbstractSet[str], AbstractSet[str]]:
  1599. """Generates the rooms portion of the sync response. Populates the
  1600. `sync_result_builder` with the result.
  1601. In the response that reaches the client, rooms are divided into four categories:
  1602. `invite`, `join`, `knock`, `leave`. These aren't the same as the four sets of
  1603. room ids returned by this function.
  1604. Args:
  1605. sync_result_builder
  1606. Returns:
  1607. Returns a 2-tuple describing rooms the user has joined or left.
  1608. Its entries are:
  1609. - newly_joined_rooms
  1610. - newly_left_rooms
  1611. """
  1612. since_token = sync_result_builder.since_token
  1613. user_id = sync_result_builder.sync_config.user.to_string()
  1614. blocks_all_rooms = (
  1615. sync_result_builder.sync_config.filter_collection.blocks_all_rooms()
  1616. )
  1617. # 0. Start by fetching room account data (if required).
  1618. if (
  1619. blocks_all_rooms
  1620. or sync_result_builder.sync_config.filter_collection.blocks_all_room_account_data()
  1621. ):
  1622. account_data_by_room: Mapping[str, Mapping[str, JsonDict]] = {}
  1623. elif since_token and not sync_result_builder.full_state:
  1624. account_data_by_room = (
  1625. await self.store.get_updated_room_account_data_for_user(
  1626. user_id, since_token.account_data_key
  1627. )
  1628. )
  1629. else:
  1630. account_data_by_room = await self.store.get_room_account_data_for_user(
  1631. user_id
  1632. )
  1633. # 1. Start by fetching all ephemeral events in rooms we've joined (if required).
  1634. block_all_room_ephemeral = (
  1635. blocks_all_rooms
  1636. or sync_result_builder.sync_config.filter_collection.blocks_all_room_ephemeral()
  1637. )
  1638. if block_all_room_ephemeral:
  1639. ephemeral_by_room: Dict[str, List[JsonDict]] = {}
  1640. else:
  1641. now_token, ephemeral_by_room = await self.ephemeral_by_room(
  1642. sync_result_builder,
  1643. now_token=sync_result_builder.now_token,
  1644. since_token=sync_result_builder.since_token,
  1645. )
  1646. sync_result_builder.now_token = now_token
  1647. # 2. We check up front if anything has changed, if it hasn't then there is
  1648. # no point in going further.
  1649. if not sync_result_builder.full_state:
  1650. if since_token and not ephemeral_by_room and not account_data_by_room:
  1651. have_changed = await self._have_rooms_changed(sync_result_builder)
  1652. log_kv({"rooms_have_changed": have_changed})
  1653. if not have_changed:
  1654. tags_by_room = await self.store.get_updated_tags(
  1655. user_id, since_token.account_data_key
  1656. )
  1657. if not tags_by_room:
  1658. logger.debug("no-oping sync")
  1659. return set(), set()
  1660. # 3. Work out which rooms need reporting in the sync response.
  1661. ignored_users = await self.store.ignored_users(user_id)
  1662. if since_token:
  1663. room_changes = await self._get_room_changes_for_incremental_sync(
  1664. sync_result_builder, ignored_users
  1665. )
  1666. tags_by_room = await self.store.get_updated_tags(
  1667. user_id, since_token.account_data_key
  1668. )
  1669. else:
  1670. room_changes = await self._get_room_changes_for_initial_sync(
  1671. sync_result_builder, ignored_users
  1672. )
  1673. tags_by_room = await self.store.get_tags_for_user(user_id)
  1674. log_kv({"rooms_changed": len(room_changes.room_entries)})
  1675. room_entries = room_changes.room_entries
  1676. invited = room_changes.invited
  1677. knocked = room_changes.knocked
  1678. newly_joined_rooms = room_changes.newly_joined_rooms
  1679. newly_left_rooms = room_changes.newly_left_rooms
  1680. # 4. We need to apply further processing to `room_entries` (rooms considered
  1681. # joined or archived).
  1682. async def handle_room_entries(room_entry: "RoomSyncResultBuilder") -> None:
  1683. logger.debug("Generating room entry for %s", room_entry.room_id)
  1684. # Note that this mutates sync_result_builder.{joined,archived}.
  1685. await self._generate_room_entry(
  1686. sync_result_builder,
  1687. room_entry,
  1688. ephemeral=ephemeral_by_room.get(room_entry.room_id, []),
  1689. tags=tags_by_room.get(room_entry.room_id),
  1690. account_data=account_data_by_room.get(room_entry.room_id, {}),
  1691. always_include=sync_result_builder.full_state,
  1692. )
  1693. logger.debug("Generated room entry for %s", room_entry.room_id)
  1694. with start_active_span("sync.generate_room_entries"):
  1695. await concurrently_execute(handle_room_entries, room_entries, 10)
  1696. sync_result_builder.invited.extend(invited)
  1697. sync_result_builder.knocked.extend(knocked)
  1698. return set(newly_joined_rooms), set(newly_left_rooms)
  1699. async def _have_rooms_changed(
  1700. self, sync_result_builder: "SyncResultBuilder"
  1701. ) -> bool:
  1702. """Returns whether there may be any new events that should be sent down
  1703. the sync. Returns True if there are.
  1704. Does not modify the `sync_result_builder`.
  1705. """
  1706. since_token = sync_result_builder.since_token
  1707. membership_change_events = sync_result_builder.membership_change_events
  1708. assert since_token
  1709. if membership_change_events or sync_result_builder.forced_newly_joined_room_ids:
  1710. return True
  1711. stream_id = since_token.room_key.stream
  1712. for room_id in sync_result_builder.joined_room_ids:
  1713. if self.store.has_room_changed_since(room_id, stream_id):
  1714. return True
  1715. return False
  1716. async def _get_room_changes_for_incremental_sync(
  1717. self,
  1718. sync_result_builder: "SyncResultBuilder",
  1719. ignored_users: FrozenSet[str],
  1720. ) -> _RoomChanges:
  1721. """Determine the changes in rooms to report to the user.
  1722. This function is a first pass at generating the rooms part of the sync response.
  1723. It determines which rooms have changed during the sync period, and categorises
  1724. them into four buckets: "knock", "invite", "join" and "leave". It also excludes
  1725. from that list any room that appears in the list of rooms to exclude from sync
  1726. results in the server configuration.
  1727. 1. Finds all membership changes for the user in the sync period (from
  1728. `since_token` up to `now_token`).
  1729. 2. Uses those to place the room in one of the four categories above.
  1730. 3. Builds a `_RoomChanges` struct to record this, and return that struct.
  1731. For rooms classified as "knock", "invite" or "leave", we just need to report
  1732. a single membership event in the eventual /sync response. For "join" we need
  1733. to fetch additional non-membership events, e.g. messages in the room. That is
  1734. more complicated, so instead we report an intermediary `RoomSyncResultBuilder`
  1735. struct, and leave the additional work to `_generate_room_entry`.
  1736. The sync_result_builder is not modified by this function.
  1737. """
  1738. user_id = sync_result_builder.sync_config.user.to_string()
  1739. since_token = sync_result_builder.since_token
  1740. now_token = sync_result_builder.now_token
  1741. sync_config = sync_result_builder.sync_config
  1742. membership_change_events = sync_result_builder.membership_change_events
  1743. assert since_token
  1744. mem_change_events_by_room_id: Dict[str, List[EventBase]] = {}
  1745. for event in membership_change_events:
  1746. mem_change_events_by_room_id.setdefault(event.room_id, []).append(event)
  1747. newly_joined_rooms: List[str] = list(
  1748. sync_result_builder.forced_newly_joined_room_ids
  1749. )
  1750. newly_left_rooms: List[str] = []
  1751. room_entries: List[RoomSyncResultBuilder] = []
  1752. invited: List[InvitedSyncResult] = []
  1753. knocked: List[KnockedSyncResult] = []
  1754. for room_id, events in mem_change_events_by_room_id.items():
  1755. # The body of this loop will add this room to at least one of the five lists
  1756. # above. Things get messy if you've e.g. joined, left, joined then left the
  1757. # room all in the same sync period.
  1758. logger.debug(
  1759. "Membership changes in %s: [%s]",
  1760. room_id,
  1761. ", ".join("%s (%s)" % (e.event_id, e.membership) for e in events),
  1762. )
  1763. non_joins = [e for e in events if e.membership != Membership.JOIN]
  1764. has_join = len(non_joins) != len(events)
  1765. # We want to figure out if we joined the room at some point since
  1766. # the last sync (even if we have since left). This is to make sure
  1767. # we do send down the room, and with full state, where necessary
  1768. old_state_ids = None
  1769. if room_id in sync_result_builder.joined_room_ids and non_joins:
  1770. # Always include if the user (re)joined the room, especially
  1771. # important so that device list changes are calculated correctly.
  1772. # If there are non-join member events, but we are still in the room,
  1773. # then the user must have left and joined
  1774. newly_joined_rooms.append(room_id)
  1775. # User is in the room so we don't need to do the invite/leave checks
  1776. continue
  1777. if room_id in sync_result_builder.joined_room_ids or has_join:
  1778. old_state_ids = await self.get_state_at(
  1779. room_id,
  1780. since_token,
  1781. state_filter=StateFilter.from_types([(EventTypes.Member, user_id)]),
  1782. )
  1783. old_mem_ev_id = old_state_ids.get((EventTypes.Member, user_id), None)
  1784. old_mem_ev = None
  1785. if old_mem_ev_id:
  1786. old_mem_ev = await self.store.get_event(
  1787. old_mem_ev_id, allow_none=True
  1788. )
  1789. if not old_mem_ev or old_mem_ev.membership != Membership.JOIN:
  1790. newly_joined_rooms.append(room_id)
  1791. # If user is in the room then we don't need to do the invite/leave checks
  1792. if room_id in sync_result_builder.joined_room_ids:
  1793. continue
  1794. if not non_joins:
  1795. continue
  1796. last_non_join = non_joins[-1]
  1797. # Check if we have left the room. This can either be because we were
  1798. # joined before *or* that we since joined and then left.
  1799. if events[-1].membership != Membership.JOIN:
  1800. if has_join:
  1801. newly_left_rooms.append(room_id)
  1802. else:
  1803. if not old_state_ids:
  1804. old_state_ids = await self.get_state_at(
  1805. room_id,
  1806. since_token,
  1807. state_filter=StateFilter.from_types(
  1808. [(EventTypes.Member, user_id)]
  1809. ),
  1810. )
  1811. old_mem_ev_id = old_state_ids.get(
  1812. (EventTypes.Member, user_id), None
  1813. )
  1814. old_mem_ev = None
  1815. if old_mem_ev_id:
  1816. old_mem_ev = await self.store.get_event(
  1817. old_mem_ev_id, allow_none=True
  1818. )
  1819. if old_mem_ev and old_mem_ev.membership == Membership.JOIN:
  1820. newly_left_rooms.append(room_id)
  1821. # Only bother if we're still currently invited
  1822. should_invite = last_non_join.membership == Membership.INVITE
  1823. if should_invite:
  1824. if last_non_join.sender not in ignored_users:
  1825. invite_room_sync = InvitedSyncResult(room_id, invite=last_non_join)
  1826. if invite_room_sync:
  1827. invited.append(invite_room_sync)
  1828. # Only bother if our latest membership in the room is knock (and we haven't
  1829. # been accepted/rejected in the meantime).
  1830. should_knock = last_non_join.membership == Membership.KNOCK
  1831. if should_knock:
  1832. knock_room_sync = KnockedSyncResult(room_id, knock=last_non_join)
  1833. if knock_room_sync:
  1834. knocked.append(knock_room_sync)
  1835. # Always include leave/ban events. Just take the last one.
  1836. # TODO: How do we handle ban -> leave in same batch?
  1837. leave_events = [
  1838. e
  1839. for e in non_joins
  1840. if e.membership in (Membership.LEAVE, Membership.BAN)
  1841. ]
  1842. if leave_events:
  1843. leave_event = leave_events[-1]
  1844. leave_position = await self.store.get_position_for_event(
  1845. leave_event.event_id
  1846. )
  1847. # If the leave event happened before the since token then we
  1848. # bail.
  1849. if since_token and not leave_position.persisted_after(
  1850. since_token.room_key
  1851. ):
  1852. continue
  1853. # We can safely convert the position of the leave event into a
  1854. # stream token as it'll only be used in the context of this
  1855. # room. (c.f. the docstring of `to_room_stream_token`).
  1856. leave_token = since_token.copy_and_replace(
  1857. StreamKeyType.ROOM, leave_position.to_room_stream_token()
  1858. )
  1859. # If this is an out of band message, like a remote invite
  1860. # rejection, we include it in the recents batch. Otherwise, we
  1861. # let _load_filtered_recents handle fetching the correct
  1862. # batches.
  1863. #
  1864. # This is all screaming out for a refactor, as the logic here is
  1865. # subtle and the moving parts numerous.
  1866. if leave_event.internal_metadata.is_out_of_band_membership():
  1867. batch_events: Optional[List[EventBase]] = [leave_event]
  1868. else:
  1869. batch_events = None
  1870. room_entries.append(
  1871. RoomSyncResultBuilder(
  1872. room_id=room_id,
  1873. rtype="archived",
  1874. events=batch_events,
  1875. newly_joined=room_id in newly_joined_rooms,
  1876. full_state=False,
  1877. since_token=since_token,
  1878. upto_token=leave_token,
  1879. out_of_band=leave_event.internal_metadata.is_out_of_band_membership(),
  1880. )
  1881. )
  1882. timeline_limit = sync_config.filter_collection.timeline_limit()
  1883. # Get all events since the `from_key` in rooms we're currently joined to.
  1884. # If there are too many, we get the most recent events only. This leaves
  1885. # a "gap" in the timeline, as described by the spec for /sync.
  1886. room_to_events = await self.store.get_room_events_stream_for_rooms(
  1887. room_ids=sync_result_builder.joined_room_ids,
  1888. from_key=since_token.room_key,
  1889. to_key=now_token.room_key,
  1890. limit=timeline_limit + 1,
  1891. )
  1892. # We loop through all room ids, even if there are no new events, in case
  1893. # there are non room events that we need to notify about.
  1894. for room_id in sync_result_builder.joined_room_ids:
  1895. room_entry = room_to_events.get(room_id, None)
  1896. newly_joined = room_id in newly_joined_rooms
  1897. if room_entry:
  1898. events, start_key = room_entry
  1899. prev_batch_token = now_token.copy_and_replace(
  1900. StreamKeyType.ROOM, start_key
  1901. )
  1902. entry = RoomSyncResultBuilder(
  1903. room_id=room_id,
  1904. rtype="joined",
  1905. events=events,
  1906. newly_joined=newly_joined,
  1907. full_state=False,
  1908. since_token=None if newly_joined else since_token,
  1909. upto_token=prev_batch_token,
  1910. )
  1911. else:
  1912. entry = RoomSyncResultBuilder(
  1913. room_id=room_id,
  1914. rtype="joined",
  1915. events=[],
  1916. newly_joined=newly_joined,
  1917. full_state=False,
  1918. since_token=since_token,
  1919. upto_token=since_token,
  1920. )
  1921. room_entries.append(entry)
  1922. return _RoomChanges(
  1923. room_entries,
  1924. invited,
  1925. knocked,
  1926. newly_joined_rooms,
  1927. newly_left_rooms,
  1928. )
  1929. async def _get_room_changes_for_initial_sync(
  1930. self,
  1931. sync_result_builder: "SyncResultBuilder",
  1932. ignored_users: FrozenSet[str],
  1933. ) -> _RoomChanges:
  1934. """Returns entries for all rooms for the user.
  1935. Like `_get_rooms_changed`, but assumes the `since_token` is `None`.
  1936. This function does not modify the sync_result_builder.
  1937. Args:
  1938. sync_result_builder
  1939. ignored_users: Set of users ignored by user.
  1940. ignored_rooms: List of rooms to ignore.
  1941. """
  1942. user_id = sync_result_builder.sync_config.user.to_string()
  1943. since_token = sync_result_builder.since_token
  1944. now_token = sync_result_builder.now_token
  1945. sync_config = sync_result_builder.sync_config
  1946. room_list = await self.store.get_rooms_for_local_user_where_membership_is(
  1947. user_id=user_id,
  1948. membership_list=Membership.LIST,
  1949. excluded_rooms=sync_result_builder.excluded_room_ids,
  1950. )
  1951. room_entries = []
  1952. invited = []
  1953. knocked = []
  1954. for event in room_list:
  1955. if event.room_version_id not in KNOWN_ROOM_VERSIONS:
  1956. continue
  1957. if event.membership == Membership.JOIN:
  1958. room_entries.append(
  1959. RoomSyncResultBuilder(
  1960. room_id=event.room_id,
  1961. rtype="joined",
  1962. events=None,
  1963. newly_joined=False,
  1964. full_state=True,
  1965. since_token=since_token,
  1966. upto_token=now_token,
  1967. )
  1968. )
  1969. elif event.membership == Membership.INVITE:
  1970. if event.sender in ignored_users:
  1971. continue
  1972. invite = await self.store.get_event(event.event_id)
  1973. invited.append(InvitedSyncResult(room_id=event.room_id, invite=invite))
  1974. elif event.membership == Membership.KNOCK:
  1975. knock = await self.store.get_event(event.event_id)
  1976. knocked.append(KnockedSyncResult(room_id=event.room_id, knock=knock))
  1977. elif event.membership in (Membership.LEAVE, Membership.BAN):
  1978. # Always send down rooms we were banned from or kicked from.
  1979. if not sync_config.filter_collection.include_leave:
  1980. if event.membership == Membership.LEAVE:
  1981. if user_id == event.sender:
  1982. continue
  1983. leave_token = now_token.copy_and_replace(
  1984. StreamKeyType.ROOM, RoomStreamToken(None, event.stream_ordering)
  1985. )
  1986. room_entries.append(
  1987. RoomSyncResultBuilder(
  1988. room_id=event.room_id,
  1989. rtype="archived",
  1990. events=None,
  1991. newly_joined=False,
  1992. full_state=True,
  1993. since_token=since_token,
  1994. upto_token=leave_token,
  1995. )
  1996. )
  1997. return _RoomChanges(room_entries, invited, knocked, [], [])
  1998. async def _generate_room_entry(
  1999. self,
  2000. sync_result_builder: "SyncResultBuilder",
  2001. room_builder: "RoomSyncResultBuilder",
  2002. ephemeral: List[JsonDict],
  2003. tags: Optional[Mapping[str, Mapping[str, Any]]],
  2004. account_data: Mapping[str, JsonDict],
  2005. always_include: bool = False,
  2006. ) -> None:
  2007. """Populates the `joined` and `archived` section of `sync_result_builder`
  2008. based on the `room_builder`.
  2009. Ideally, we want to report all events whose stream ordering `s` lies in the
  2010. range `since_token < s <= now_token`, where the two tokens are read from the
  2011. sync_result_builder.
  2012. If there are too many events in that range to report, things get complicated.
  2013. In this situation we return a truncated list of the most recent events, and
  2014. indicate in the response that there is a "gap" of omitted events. Lots of this
  2015. is handled in `_load_filtered_recents`, but some of is handled in this method.
  2016. Additionally:
  2017. - we include a "state_delta", to describe the changes in state over the gap,
  2018. - we include all membership events applying to the user making the request,
  2019. even those in the gap.
  2020. See the spec for the rationale:
  2021. https://spec.matrix.org/v1.1/client-server-api/#syncing
  2022. Args:
  2023. sync_result_builder
  2024. room_builder
  2025. ephemeral: List of new ephemeral events for room
  2026. tags: List of *all* tags for room, or None if there has been
  2027. no change.
  2028. account_data: List of new account data for room
  2029. always_include: Always include this room in the sync response,
  2030. even if empty.
  2031. """
  2032. newly_joined = room_builder.newly_joined
  2033. full_state = (
  2034. room_builder.full_state or newly_joined or sync_result_builder.full_state
  2035. )
  2036. events = room_builder.events
  2037. # We want to shortcut out as early as possible.
  2038. if not (always_include or account_data or ephemeral or full_state):
  2039. if events == [] and tags is None:
  2040. return
  2041. now_token = sync_result_builder.now_token
  2042. sync_config = sync_result_builder.sync_config
  2043. room_id = room_builder.room_id
  2044. since_token = room_builder.since_token
  2045. upto_token = room_builder.upto_token
  2046. with start_active_span("sync.generate_room_entry"):
  2047. set_tag("room_id", room_id)
  2048. log_kv({"events": len(events or ())})
  2049. log_kv(
  2050. {
  2051. "since_token": since_token,
  2052. "upto_token": upto_token,
  2053. }
  2054. )
  2055. batch = await self._load_filtered_recents(
  2056. room_id,
  2057. sync_config,
  2058. now_token=upto_token,
  2059. since_token=since_token,
  2060. potential_recents=events,
  2061. newly_joined_room=newly_joined,
  2062. )
  2063. log_kv(
  2064. {
  2065. "batch_events": len(batch.events),
  2066. "prev_batch": batch.prev_batch,
  2067. "batch_limited": batch.limited,
  2068. }
  2069. )
  2070. # Note: `batch` can be both empty and limited here in the case where
  2071. # `_load_filtered_recents` can't find any events the user should see
  2072. # (e.g. due to having ignored the sender of the last 50 events).
  2073. # When we join the room (or the client requests full_state), we should
  2074. # send down any existing tags. Usually the user won't have tags in a
  2075. # newly joined room, unless either a) they've joined before or b) the
  2076. # tag was added by synapse e.g. for server notice rooms.
  2077. if full_state:
  2078. user_id = sync_result_builder.sync_config.user.to_string()
  2079. tags = await self.store.get_tags_for_room(user_id, room_id)
  2080. # If there aren't any tags, don't send the empty tags list down
  2081. # sync
  2082. if not tags:
  2083. tags = None
  2084. account_data_events = []
  2085. if tags is not None:
  2086. account_data_events.append(
  2087. {"type": AccountDataTypes.TAG, "content": {"tags": tags}}
  2088. )
  2089. for account_data_type, content in account_data.items():
  2090. account_data_events.append(
  2091. {"type": account_data_type, "content": content}
  2092. )
  2093. account_data_events = (
  2094. await sync_config.filter_collection.filter_room_account_data(
  2095. account_data_events
  2096. )
  2097. )
  2098. ephemeral = await sync_config.filter_collection.filter_room_ephemeral(
  2099. ephemeral
  2100. )
  2101. if not (
  2102. always_include
  2103. or batch
  2104. or account_data_events
  2105. or ephemeral
  2106. or full_state
  2107. ):
  2108. return
  2109. if not room_builder.out_of_band:
  2110. state = await self.compute_state_delta(
  2111. room_id,
  2112. batch,
  2113. sync_config,
  2114. since_token,
  2115. now_token,
  2116. full_state=full_state,
  2117. )
  2118. else:
  2119. # An out of band room won't have any state changes.
  2120. state = {}
  2121. summary: Optional[JsonDict] = {}
  2122. # we include a summary in room responses when we're lazy loading
  2123. # members (as the client otherwise doesn't have enough info to form
  2124. # the name itself).
  2125. if (
  2126. not room_builder.out_of_band
  2127. and sync_config.filter_collection.lazy_load_members()
  2128. and (
  2129. # we recalculate the summary:
  2130. # if there are membership changes in the timeline, or
  2131. # if membership has changed during a gappy sync, or
  2132. # if this is an initial sync.
  2133. any(ev.type == EventTypes.Member for ev in batch.events)
  2134. or (
  2135. # XXX: this may include false positives in the form of LL
  2136. # members which have snuck into state
  2137. batch.limited
  2138. and any(t == EventTypes.Member for (t, k) in state)
  2139. )
  2140. or since_token is None
  2141. )
  2142. ):
  2143. summary = await self.compute_summary(
  2144. room_id, sync_config, batch, state, now_token
  2145. )
  2146. if room_builder.rtype == "joined":
  2147. unread_notifications: Dict[str, int] = {}
  2148. room_sync = JoinedSyncResult(
  2149. room_id=room_id,
  2150. timeline=batch,
  2151. state=state,
  2152. ephemeral=ephemeral,
  2153. account_data=account_data_events,
  2154. unread_notifications=unread_notifications,
  2155. unread_thread_notifications={},
  2156. summary=summary,
  2157. unread_count=0,
  2158. )
  2159. if room_sync or always_include:
  2160. notifs = await self.unread_notifs_for_room_id(room_id, sync_config)
  2161. # Notifications for the main timeline.
  2162. notify_count = notifs.main_timeline.notify_count
  2163. highlight_count = notifs.main_timeline.highlight_count
  2164. unread_count = notifs.main_timeline.unread_count
  2165. # Check the sync configuration.
  2166. if sync_config.filter_collection.unread_thread_notifications():
  2167. # And add info for each thread.
  2168. room_sync.unread_thread_notifications = {
  2169. thread_id: {
  2170. "notification_count": thread_notifs.notify_count,
  2171. "highlight_count": thread_notifs.highlight_count,
  2172. }
  2173. for thread_id, thread_notifs in notifs.threads.items()
  2174. if thread_id is not None
  2175. }
  2176. else:
  2177. # Combine the unread counts for all threads and main timeline.
  2178. for thread_notifs in notifs.threads.values():
  2179. notify_count += thread_notifs.notify_count
  2180. highlight_count += thread_notifs.highlight_count
  2181. unread_count += thread_notifs.unread_count
  2182. unread_notifications["notification_count"] = notify_count
  2183. unread_notifications["highlight_count"] = highlight_count
  2184. room_sync.unread_count = unread_count
  2185. sync_result_builder.joined.append(room_sync)
  2186. if batch.limited and since_token:
  2187. user_id = sync_result_builder.sync_config.user.to_string()
  2188. logger.debug(
  2189. "Incremental gappy sync of %s for user %s with %d state events"
  2190. % (room_id, user_id, len(state))
  2191. )
  2192. elif room_builder.rtype == "archived":
  2193. archived_room_sync = ArchivedSyncResult(
  2194. room_id=room_id,
  2195. timeline=batch,
  2196. state=state,
  2197. account_data=account_data_events,
  2198. )
  2199. if archived_room_sync or always_include:
  2200. sync_result_builder.archived.append(archived_room_sync)
  2201. else:
  2202. raise Exception("Unrecognized rtype: %r", room_builder.rtype)
  2203. def _action_has_highlight(actions: List[JsonDict]) -> bool:
  2204. for action in actions:
  2205. try:
  2206. if action.get("set_tweak", None) == "highlight":
  2207. return action.get("value", True)
  2208. except AttributeError:
  2209. pass
  2210. return False
  2211. def _calculate_state(
  2212. timeline_contains: StateMap[str],
  2213. timeline_start: StateMap[str],
  2214. timeline_end: StateMap[str],
  2215. previous_timeline_end: StateMap[str],
  2216. lazy_load_members: bool,
  2217. ) -> StateMap[str]:
  2218. """Works out what state to include in a sync response.
  2219. Args:
  2220. timeline_contains: state in the timeline
  2221. timeline_start: state at the start of the timeline
  2222. timeline_end: state at the end of the timeline
  2223. previous_timeline_end: state at the end of the previous sync (or empty dict
  2224. if this is an initial sync)
  2225. lazy_load_members: whether to return members from timeline_start
  2226. or not. assumes that timeline_start has already been filtered to
  2227. include only the members the client needs to know about.
  2228. """
  2229. event_id_to_state_key = {
  2230. event_id: state_key
  2231. for state_key, event_id in itertools.chain(
  2232. timeline_contains.items(),
  2233. timeline_start.items(),
  2234. timeline_end.items(),
  2235. previous_timeline_end.items(),
  2236. )
  2237. }
  2238. timeline_end_ids = set(timeline_end.values())
  2239. timeline_start_ids = set(timeline_start.values())
  2240. previous_timeline_end_ids = set(previous_timeline_end.values())
  2241. timeline_contains_ids = set(timeline_contains.values())
  2242. # If we are lazyloading room members, we explicitly add the membership events
  2243. # for the senders in the timeline into the state block returned by /sync,
  2244. # as we may not have sent them to the client before. We find these membership
  2245. # events by filtering them out of timeline_start, which has already been filtered
  2246. # to only include membership events for the senders in the timeline.
  2247. # In practice, we can do this by removing them from the previous_timeline_end_ids
  2248. # list, which is the list of relevant state we know we have already sent to the
  2249. # client.
  2250. # see https://github.com/matrix-org/synapse/pull/2970/files/efcdacad7d1b7f52f879179701c7e0d9b763511f#r204732809
  2251. if lazy_load_members:
  2252. previous_timeline_end_ids.difference_update(
  2253. e for t, e in timeline_start.items() if t[0] == EventTypes.Member
  2254. )
  2255. state_ids = (
  2256. (timeline_end_ids | timeline_start_ids)
  2257. - previous_timeline_end_ids
  2258. - timeline_contains_ids
  2259. )
  2260. return {event_id_to_state_key[e]: e for e in state_ids}
  2261. @attr.s(slots=True, auto_attribs=True)
  2262. class SyncResultBuilder:
  2263. """Used to help build up a new SyncResult for a user
  2264. Attributes:
  2265. sync_config
  2266. full_state: The full_state flag as specified by user
  2267. since_token: The token supplied by user, or None.
  2268. now_token: The token to sync up to.
  2269. joined_room_ids: List of rooms the user is joined to
  2270. excluded_room_ids: Set of room ids we should omit from the /sync response.
  2271. forced_newly_joined_room_ids:
  2272. Rooms that should be presented in the /sync response as if they were
  2273. newly joined during the sync period, even if that's not the case.
  2274. (This is useful if the room was previously excluded from a /sync response,
  2275. and now the client should be made aware of it.)
  2276. Only used by incremental syncs.
  2277. # The following mirror the fields in a sync response
  2278. presence
  2279. account_data
  2280. joined
  2281. invited
  2282. knocked
  2283. archived
  2284. to_device
  2285. """
  2286. sync_config: SyncConfig
  2287. full_state: bool
  2288. since_token: Optional[StreamToken]
  2289. now_token: StreamToken
  2290. joined_room_ids: FrozenSet[str]
  2291. excluded_room_ids: FrozenSet[str]
  2292. forced_newly_joined_room_ids: FrozenSet[str]
  2293. membership_change_events: List[EventBase]
  2294. presence: List[UserPresenceState] = attr.Factory(list)
  2295. account_data: List[JsonDict] = attr.Factory(list)
  2296. joined: List[JoinedSyncResult] = attr.Factory(list)
  2297. invited: List[InvitedSyncResult] = attr.Factory(list)
  2298. knocked: List[KnockedSyncResult] = attr.Factory(list)
  2299. archived: List[ArchivedSyncResult] = attr.Factory(list)
  2300. to_device: List[JsonDict] = attr.Factory(list)
  2301. def calculate_user_changes(self) -> Tuple[AbstractSet[str], AbstractSet[str]]:
  2302. """Work out which other users have joined or left rooms we are joined to.
  2303. This data only is only useful for an incremental sync.
  2304. The SyncResultBuilder is not modified by this function.
  2305. """
  2306. newly_joined_or_invited_or_knocked_users = set()
  2307. newly_left_users = set()
  2308. if self.since_token:
  2309. for joined_sync in self.joined:
  2310. it = itertools.chain(
  2311. joined_sync.timeline.events, joined_sync.state.values()
  2312. )
  2313. for event in it:
  2314. if event.type == EventTypes.Member:
  2315. if (
  2316. event.membership == Membership.JOIN
  2317. or event.membership == Membership.INVITE
  2318. or event.membership == Membership.KNOCK
  2319. ):
  2320. newly_joined_or_invited_or_knocked_users.add(
  2321. event.state_key
  2322. )
  2323. else:
  2324. prev_content = event.unsigned.get("prev_content", {})
  2325. prev_membership = prev_content.get("membership", None)
  2326. if prev_membership == Membership.JOIN:
  2327. newly_left_users.add(event.state_key)
  2328. newly_left_users -= newly_joined_or_invited_or_knocked_users
  2329. return newly_joined_or_invited_or_knocked_users, newly_left_users
  2330. @attr.s(slots=True, auto_attribs=True)
  2331. class RoomSyncResultBuilder:
  2332. """Stores information needed to create either a `JoinedSyncResult` or
  2333. `ArchivedSyncResult`.
  2334. Attributes:
  2335. room_id
  2336. rtype: One of `"joined"` or `"archived"`
  2337. events: List of events to include in the room (more events may be added
  2338. when generating result).
  2339. newly_joined: If the user has newly joined the room
  2340. full_state: Whether the full state should be sent in result
  2341. since_token: Earliest point to return events from, or None
  2342. upto_token: Latest point to return events from.
  2343. out_of_band: whether the events in the room are "out of band" events
  2344. and the server isn't in the room.
  2345. """
  2346. room_id: str
  2347. rtype: str
  2348. events: Optional[List[EventBase]]
  2349. newly_joined: bool
  2350. full_state: bool
  2351. since_token: Optional[StreamToken]
  2352. upto_token: StreamToken
  2353. out_of_band: bool = False