@@ -1854,13 +1854,38 @@ async def _generate_sync_entry_for_device_list(
18541854
18551855 # Step 1a, check for changes in devices of users we share a room
18561856 # with
1857- users_that_have_changed = (
1858- await self ._device_handler .get_device_changes_in_shared_rooms (
1859- user_id ,
1860- sync_result_builder .joined_room_ids ,
1861- from_token = since_token ,
1862- )
1857+ #
1858+ # We do this in two different ways depending on what we have cached.
1859+ # If we already have a list of all the user that have changed since
1860+ # the last sync then it's likely more efficient to compare the rooms
1861+ # they're in with the rooms the syncing user is in.
1862+ #
1863+ # If we don't have that info cached then we get all the users that
1864+ # share a room with our user and check if those users have changed.
1865+ cache_result = self .store .get_cached_device_list_changes (
1866+ since_token .device_list_key
18631867 )
1868+ if cache_result .hit :
1869+ changed_users = cache_result .entities
1870+
1871+ result = await self .store .get_rooms_for_users (changed_users )
1872+
1873+ for changed_user_id , entries in result .items ():
1874+ # Check if the changed user shares any rooms with the user,
1875+ # or if the changed user is the syncing user (as we always
1876+ # want to include device list updates of their own devices).
1877+ if user_id == changed_user_id or any (
1878+ rid in joined_rooms for rid in entries
1879+ ):
1880+ users_that_have_changed .add (changed_user_id )
1881+ else :
1882+ users_that_have_changed = (
1883+ await self ._device_handler .get_device_changes_in_shared_rooms (
1884+ user_id ,
1885+ sync_result_builder .joined_room_ids ,
1886+ from_token = since_token ,
1887+ )
1888+ )
18641889
18651890 # Step 1b, check for newly joined rooms
18661891 for room_id in newly_joined_rooms :
0 commit comments