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.
 
 
 
 
 
 

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