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.
 
 
 
 
 
 

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