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.
 
 
 
 
 
 

755 lines
31 KiB

  1. # Copyright 2017 Vector Creations Ltd
  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 logging
  15. from http import HTTPStatus
  16. from typing import TYPE_CHECKING, List, Optional, Set, Tuple
  17. from twisted.internet.interfaces import IDelayedCall
  18. import synapse.metrics
  19. from synapse.api.constants import EventTypes, HistoryVisibility, JoinRules, Membership
  20. from synapse.api.errors import Codes, SynapseError
  21. from synapse.handlers.state_deltas import MatchChange, StateDeltasHandler
  22. from synapse.metrics.background_process_metrics import run_as_background_process
  23. from synapse.storage.databases.main.state_deltas import StateDelta
  24. from synapse.storage.databases.main.user_directory import SearchResult
  25. from synapse.storage.roommember import ProfileInfo
  26. from synapse.types import UserID
  27. from synapse.util.metrics import Measure
  28. from synapse.util.retryutils import NotRetryingDestination
  29. from synapse.util.stringutils import non_null_str_or_none
  30. if TYPE_CHECKING:
  31. from synapse.server import HomeServer
  32. logger = logging.getLogger(__name__)
  33. # Don't refresh a stale user directory entry, using a Federation /profile request,
  34. # for 60 seconds. This gives time for other state events to arrive (which will
  35. # then be coalesced such that only one /profile request is made).
  36. USER_DIRECTORY_STALE_REFRESH_TIME_MS = 60 * 1000
  37. # Maximum number of remote servers that we will attempt to refresh profiles for
  38. # in one go.
  39. MAX_SERVERS_TO_REFRESH_PROFILES_FOR_IN_ONE_GO = 5
  40. # As long as we have servers to refresh (without backoff), keep adding more
  41. # every 15 seconds.
  42. INTERVAL_TO_ADD_MORE_SERVERS_TO_REFRESH_PROFILES = 15
  43. def calculate_time_of_next_retry(now_ts: int, retry_count: int) -> int:
  44. """
  45. Calculates the time of a next retry given `now_ts` in ms and the number
  46. of failures encountered thus far.
  47. Currently the sequence goes:
  48. 1 min, 5 min, 25 min, 2 hour, 10 hour, 52 hour, 10 day, 7.75 week
  49. """
  50. return now_ts + 60_000 * (5 ** min(retry_count, 7))
  51. class UserDirectoryHandler(StateDeltasHandler):
  52. """Handles queries and updates for the user_directory.
  53. N.B.: ASSUMES IT IS THE ONLY THING THAT MODIFIES THE USER DIRECTORY
  54. When a local user searches the user_directory, we report two kinds of users:
  55. - users this server can see are joined to a world_readable or publicly
  56. joinable room, and
  57. - users belonging to a private room shared by that local user.
  58. The two cases are tracked separately in the `users_in_public_rooms` and
  59. `users_who_share_private_rooms` tables. Both kinds of users have their
  60. username and avatar tracked in a `user_directory` table.
  61. This handler has three responsibilities:
  62. 1. Forwarding requests to `/user_directory/search` to the UserDirectoryStore.
  63. 2. Providing hooks for the application to call when local users are added,
  64. removed, or have their profile changed.
  65. 3. Listening for room state changes that indicate remote users have
  66. joined or left a room, or that their profile has changed.
  67. """
  68. def __init__(self, hs: "HomeServer"):
  69. super().__init__(hs)
  70. self.store = hs.get_datastores().main
  71. self._storage_controllers = hs.get_storage_controllers()
  72. self.server_name = hs.hostname
  73. self.clock = hs.get_clock()
  74. self.notifier = hs.get_notifier()
  75. self.is_mine_id = hs.is_mine_id
  76. self.update_user_directory = hs.config.worker.should_update_user_directory
  77. self.search_all_users = hs.config.userdirectory.user_directory_search_all_users
  78. self.show_locked_users = hs.config.userdirectory.show_locked_users
  79. self._spam_checker_module_callbacks = hs.get_module_api_callbacks().spam_checker
  80. self._hs = hs
  81. # The current position in the current_state_delta stream
  82. self.pos: Optional[int] = None
  83. # Guard to ensure we only process deltas one at a time
  84. self._is_processing = False
  85. # Guard to ensure we only have one process for refreshing remote profiles
  86. self._is_refreshing_remote_profiles = False
  87. # Handle to cancel the `call_later` of `kick_off_remote_profile_refresh_process`
  88. self._refresh_remote_profiles_call_later: Optional[IDelayedCall] = None
  89. # Guard to ensure we only have one process for refreshing remote profiles
  90. # for the given servers.
  91. # Set of server names.
  92. self._is_refreshing_remote_profiles_for_servers: Set[str] = set()
  93. if self.update_user_directory:
  94. self.notifier.add_replication_callback(self.notify_new_event)
  95. # We kick this off so that we don't have to wait for a change before
  96. # we start populating the user directory
  97. self.clock.call_later(0, self.notify_new_event)
  98. # Kick off the profile refresh process on startup
  99. self._refresh_remote_profiles_call_later = self.clock.call_later(
  100. 10, self.kick_off_remote_profile_refresh_process
  101. )
  102. async def search_users(
  103. self, user_id: str, search_term: str, limit: int
  104. ) -> SearchResult:
  105. """Searches for users in directory
  106. Returns:
  107. dict of the form::
  108. {
  109. "limited": <bool>, # whether there were more results or not
  110. "results": [ # Ordered by best match first
  111. {
  112. "user_id": <user_id>,
  113. "display_name": <display_name>,
  114. "avatar_url": <avatar_url>
  115. }
  116. ]
  117. }
  118. """
  119. results = await self.store.search_user_dir(
  120. user_id, search_term, limit, self.show_locked_users
  121. )
  122. # Remove any spammy users from the results.
  123. non_spammy_users = []
  124. for user in results["results"]:
  125. if not await self._spam_checker_module_callbacks.check_username_for_spam(
  126. user
  127. ):
  128. non_spammy_users.append(user)
  129. results["results"] = non_spammy_users
  130. return results
  131. def notify_new_event(self) -> None:
  132. """Called when there may be more deltas to process"""
  133. if not self.update_user_directory:
  134. return
  135. if self._is_processing:
  136. return
  137. async def process() -> None:
  138. try:
  139. await self._unsafe_process()
  140. finally:
  141. self._is_processing = False
  142. self._is_processing = True
  143. run_as_background_process("user_directory.notify_new_event", process)
  144. async def handle_local_profile_change(
  145. self, user_id: str, profile: ProfileInfo
  146. ) -> None:
  147. """Called to update index of our local user profiles when they change
  148. irrespective of any rooms the user may be in.
  149. """
  150. # FIXME(https://github.com/matrix-org/synapse/issues/3714): We should
  151. # probably do this in the same worker as all the other changes.
  152. if await self.store.should_include_local_user_in_dir(user_id):
  153. await self.store.update_profile_in_user_dir(
  154. user_id, profile.display_name, profile.avatar_url
  155. )
  156. async def handle_local_user_deactivated(self, user_id: str) -> None:
  157. """Called when a user ID is deactivated"""
  158. # FIXME(https://github.com/matrix-org/synapse/issues/3714): We should
  159. # probably do this in the same worker as all the other changes.
  160. await self.store.remove_from_user_dir(user_id)
  161. async def _unsafe_process(self) -> None:
  162. # If self.pos is None then means we haven't fetched it from DB
  163. if self.pos is None:
  164. self.pos = await self.store.get_user_directory_stream_pos()
  165. # If still None then the initial background update hasn't happened yet.
  166. if self.pos is None:
  167. return None
  168. room_max_stream_ordering = self.store.get_room_max_stream_ordering()
  169. if self.pos > room_max_stream_ordering:
  170. # apparently, we've processed more events than exist in the database!
  171. # this can happen if events are removed with history purge or similar.
  172. logger.warning(
  173. "Event stream ordering appears to have gone backwards (%i -> %i): "
  174. "rewinding user directory processor",
  175. self.pos,
  176. room_max_stream_ordering,
  177. )
  178. self.pos = room_max_stream_ordering
  179. # Loop round handling deltas until we're up to date
  180. while True:
  181. with Measure(self.clock, "user_dir_delta"):
  182. room_max_stream_ordering = self.store.get_room_max_stream_ordering()
  183. if self.pos == room_max_stream_ordering:
  184. return
  185. logger.debug(
  186. "Processing user stats %s->%s", self.pos, room_max_stream_ordering
  187. )
  188. (
  189. max_pos,
  190. deltas,
  191. ) = await self._storage_controllers.state.get_current_state_deltas(
  192. self.pos, room_max_stream_ordering
  193. )
  194. logger.debug("Handling %d state deltas", len(deltas))
  195. await self._handle_deltas(deltas)
  196. self.pos = max_pos
  197. # Expose current event processing position to prometheus
  198. synapse.metrics.event_processing_positions.labels("user_dir").set(
  199. max_pos
  200. )
  201. await self.store.update_user_directory_stream_pos(max_pos)
  202. async def _handle_deltas(self, deltas: List[StateDelta]) -> None:
  203. """Called with the state deltas to process"""
  204. for delta in deltas:
  205. logger.debug(
  206. "Handling: %r %r, %s", delta.event_type, delta.state_key, delta.event_id
  207. )
  208. # For join rule and visibility changes we need to check if the room
  209. # may have become public or not and add/remove the users in said room
  210. if delta.event_type in (
  211. EventTypes.RoomHistoryVisibility,
  212. EventTypes.JoinRules,
  213. ):
  214. await self._handle_room_publicity_change(
  215. delta.room_id, delta.prev_event_id, delta.event_id, delta.event_type
  216. )
  217. elif delta.event_type == EventTypes.Member:
  218. await self._handle_room_membership_event(
  219. delta.room_id,
  220. delta.prev_event_id,
  221. delta.event_id,
  222. delta.state_key,
  223. )
  224. else:
  225. logger.debug("Ignoring irrelevant type: %r", delta.event_type)
  226. async def _handle_room_publicity_change(
  227. self,
  228. room_id: str,
  229. prev_event_id: Optional[str],
  230. event_id: Optional[str],
  231. typ: str,
  232. ) -> None:
  233. """Handle a room having potentially changed from/to world_readable/publicly
  234. joinable.
  235. Args:
  236. room_id: The ID of the room which changed.
  237. prev_event_id: The previous event before the state change
  238. event_id: The new event after the state change
  239. typ: Type of the event
  240. """
  241. logger.debug("Handling change for %s: %s", typ, room_id)
  242. if typ == EventTypes.RoomHistoryVisibility:
  243. publicness = await self._get_key_change(
  244. prev_event_id,
  245. event_id,
  246. key_name="history_visibility",
  247. public_value=HistoryVisibility.WORLD_READABLE,
  248. )
  249. elif typ == EventTypes.JoinRules:
  250. publicness = await self._get_key_change(
  251. prev_event_id,
  252. event_id,
  253. key_name="join_rule",
  254. public_value=JoinRules.PUBLIC,
  255. )
  256. else:
  257. raise Exception("Invalid event type")
  258. if publicness is MatchChange.no_change:
  259. logger.debug("No change")
  260. return
  261. # There's been a change to or from being world readable.
  262. is_public = await self.store.is_room_world_readable_or_publicly_joinable(
  263. room_id
  264. )
  265. logger.debug("Publicness change: %r, is_public: %r", publicness, is_public)
  266. if publicness is MatchChange.now_true and not is_public:
  267. # If we became world readable but room isn't currently public then
  268. # we ignore the change
  269. return
  270. elif publicness is MatchChange.now_false and is_public:
  271. # If we stopped being world readable but are still public,
  272. # ignore the change
  273. return
  274. users_in_room = await self.store.get_users_in_room(room_id)
  275. # Remove every user from the sharing tables for that room.
  276. for user_id in users_in_room:
  277. await self.store.remove_user_who_share_room(user_id, room_id)
  278. # Then, re-add all remote users and some local users to the tables.
  279. # NOTE: this is not the most efficient method, as _track_user_joined_room sets
  280. # up local_user -> other_user and other_user_whos_local -> local_user,
  281. # which when ran over an entire room, will result in the same values
  282. # being added multiple times. The batching upserts shouldn't make this
  283. # too bad, though.
  284. for user_id in users_in_room:
  285. if not self.is_mine_id(
  286. user_id
  287. ) or await self.store.should_include_local_user_in_dir(user_id):
  288. await self._track_user_joined_room(room_id, user_id)
  289. async def _handle_room_membership_event(
  290. self,
  291. room_id: str,
  292. prev_event_id: Optional[str],
  293. event_id: Optional[str],
  294. state_key: str,
  295. ) -> None:
  296. """Process a single room membershp event.
  297. We have to do two things:
  298. 1. Update the room-sharing tables.
  299. This applies to remote users and non-excluded local users.
  300. 2. Update the user_directory and user_directory_search tables.
  301. This applies to remote users only, because we only become aware of
  302. the (and any profile changes) by listening to these events.
  303. The rest of the application knows exactly when local users are
  304. created or their profile changed---it will directly call methods
  305. on this class.
  306. """
  307. joined = await self._get_key_change(
  308. prev_event_id,
  309. event_id,
  310. key_name="membership",
  311. public_value=Membership.JOIN,
  312. )
  313. # Both cases ignore excluded local users, so start by discarding them.
  314. is_remote = not self.is_mine_id(state_key)
  315. if not is_remote and not await self.store.should_include_local_user_in_dir(
  316. state_key
  317. ):
  318. return
  319. if joined is MatchChange.now_false:
  320. # Need to check if the server left the room entirely, if so
  321. # we might need to remove all the users in that room
  322. is_in_room = await self.store.is_host_joined(room_id, self.server_name)
  323. if not is_in_room:
  324. logger.debug("Server left room: %r", room_id)
  325. # Fetch all the users that we marked as being in user
  326. # directory due to being in the room and then check if
  327. # need to remove those users or not
  328. user_ids = await self.store.get_users_in_dir_due_to_room(room_id)
  329. for user_id in user_ids:
  330. await self._handle_remove_user(room_id, user_id)
  331. else:
  332. logger.debug("Server is still in room: %r", room_id)
  333. await self._handle_remove_user(room_id, state_key)
  334. elif joined is MatchChange.no_change:
  335. # Handle any profile changes for remote users.
  336. # (For local users the rest of the application calls
  337. # `handle_local_profile_change`.)
  338. # Only process if there is an event_id.
  339. if is_remote and event_id is not None:
  340. await self._handle_possible_remote_profile_change(
  341. state_key, room_id, prev_event_id, event_id
  342. )
  343. elif joined is MatchChange.now_true: # The user joined
  344. # This may be the first time we've seen a remote user. If
  345. # so, ensure we have a directory entry for them. (For local users,
  346. # the rest of the application calls `handle_local_profile_change`.)
  347. # Only process if there is an event_id.
  348. if is_remote and event_id is not None:
  349. await self._handle_possible_remote_profile_change(
  350. state_key, room_id, None, event_id
  351. )
  352. await self._track_user_joined_room(room_id, state_key)
  353. async def _track_user_joined_room(self, room_id: str, joining_user_id: str) -> None:
  354. """Someone's just joined a room. Update `users_in_public_rooms` or
  355. `users_who_share_private_rooms` as appropriate.
  356. The caller is responsible for ensuring that the given user should be
  357. included in the user directory.
  358. """
  359. is_public = await self.store.is_room_world_readable_or_publicly_joinable(
  360. room_id
  361. )
  362. if is_public:
  363. await self.store.add_users_in_public_rooms(room_id, (joining_user_id,))
  364. else:
  365. users_in_room = await self.store.get_users_in_room(room_id)
  366. other_users_in_room = [
  367. other
  368. for other in users_in_room
  369. if other != joining_user_id
  370. and (
  371. # We can't apply any special rules to remote users so
  372. # they're always included
  373. not self.is_mine_id(other)
  374. # Check the special rules whether the local user should be
  375. # included in the user directory
  376. or await self.store.should_include_local_user_in_dir(other)
  377. )
  378. ]
  379. updates_to_users_who_share_rooms: Set[Tuple[str, str]] = set()
  380. # First, if the joining user is our local user then we need an
  381. # update for every other user in the room.
  382. if self.is_mine_id(joining_user_id):
  383. for other_user_id in other_users_in_room:
  384. updates_to_users_who_share_rooms.add(
  385. (joining_user_id, other_user_id)
  386. )
  387. # Next, we need an update for every other local user in the room
  388. # that they now share a room with the joining user.
  389. for other_user_id in other_users_in_room:
  390. if self.is_mine_id(other_user_id):
  391. updates_to_users_who_share_rooms.add(
  392. (other_user_id, joining_user_id)
  393. )
  394. if updates_to_users_who_share_rooms:
  395. await self.store.add_users_who_share_private_room(
  396. room_id, updates_to_users_who_share_rooms
  397. )
  398. async def _handle_remove_user(self, room_id: str, user_id: str) -> None:
  399. """Called when when someone leaves a room. The user may be local or remote.
  400. (If the person who left was the last local user in this room, the server
  401. is no longer in the room. We call this function to forget that the remaining
  402. remote users are in the room, even though they haven't left. So the name is
  403. a little misleading!)
  404. Args:
  405. room_id: The room ID that user left or stopped being public that
  406. user_id
  407. """
  408. logger.debug("Removing user %r from room %r", user_id, room_id)
  409. # Remove user from sharing tables
  410. await self.store.remove_user_who_share_room(user_id, room_id)
  411. # Additionally, if they're a remote user and we're no longer joined
  412. # to any rooms they're in, remove them from the user directory.
  413. if not self.is_mine_id(user_id):
  414. rooms_user_is_in = await self.store.get_user_dir_rooms_user_is_in(user_id)
  415. if len(rooms_user_is_in) == 0:
  416. logger.debug("Removing user %r from directory", user_id)
  417. await self.store.remove_from_user_dir(user_id)
  418. async def _handle_possible_remote_profile_change(
  419. self,
  420. user_id: str,
  421. room_id: str,
  422. prev_event_id: Optional[str],
  423. event_id: str,
  424. ) -> None:
  425. """Check member event changes for any profile changes and update the
  426. database if there are. This is intended for remote users only. The caller
  427. is responsible for checking that the given user is remote.
  428. """
  429. if not prev_event_id:
  430. # If we don't have an older event to fall back on, just fetch the same
  431. # event itself.
  432. prev_event_id = event_id
  433. prev_event = await self.store.get_event(prev_event_id, allow_none=True)
  434. event = await self.store.get_event(event_id, allow_none=True)
  435. if not prev_event or not event:
  436. return
  437. if event.membership != Membership.JOIN:
  438. return
  439. is_public = await self.store.is_room_world_readable_or_publicly_joinable(
  440. room_id
  441. )
  442. if not is_public:
  443. # Don't collect user profiles from private rooms as they are not guaranteed
  444. # to be the same as the user's global profile.
  445. now_ts = self.clock.time_msec()
  446. await self.store.set_remote_user_profile_in_user_dir_stale(
  447. user_id,
  448. next_try_at_ms=now_ts + USER_DIRECTORY_STALE_REFRESH_TIME_MS,
  449. retry_counter=0,
  450. )
  451. # Schedule a wake-up to refresh the user directory for this server.
  452. # We intentionally wake up this server directly because we don't want
  453. # other servers ahead of it in the queue to get in the way of updating
  454. # the profile if the server only just sent us an event.
  455. self.clock.call_later(
  456. USER_DIRECTORY_STALE_REFRESH_TIME_MS // 1000 + 1,
  457. self.kick_off_remote_profile_refresh_process_for_remote_server,
  458. UserID.from_string(user_id).domain,
  459. )
  460. # Schedule a wake-up to handle any backoffs that may occur in the future.
  461. self.clock.call_later(
  462. 2 * USER_DIRECTORY_STALE_REFRESH_TIME_MS // 1000 + 1,
  463. self.kick_off_remote_profile_refresh_process,
  464. )
  465. return
  466. prev_name = prev_event.content.get("displayname")
  467. new_name = event.content.get("displayname")
  468. # If the new name is an unexpected form, replace with None.
  469. if not isinstance(new_name, str):
  470. new_name = None
  471. prev_avatar = prev_event.content.get("avatar_url")
  472. new_avatar = event.content.get("avatar_url")
  473. # If the new avatar is an unexpected form, replace with None.
  474. if not isinstance(new_avatar, str):
  475. new_avatar = None
  476. if (
  477. prev_name != new_name
  478. or prev_avatar != new_avatar
  479. or prev_event_id == event_id
  480. ):
  481. # Only update if something has changed, or we didn't have a previous event
  482. # in the first place.
  483. await self.store.update_profile_in_user_dir(user_id, new_name, new_avatar)
  484. def kick_off_remote_profile_refresh_process(self) -> None:
  485. """Called when there may be remote users with stale profiles to be refreshed"""
  486. if not self.update_user_directory:
  487. return
  488. if self._is_refreshing_remote_profiles:
  489. return
  490. if self._refresh_remote_profiles_call_later:
  491. if self._refresh_remote_profiles_call_later.active():
  492. self._refresh_remote_profiles_call_later.cancel()
  493. self._refresh_remote_profiles_call_later = None
  494. async def process() -> None:
  495. try:
  496. await self._unsafe_refresh_remote_profiles()
  497. finally:
  498. self._is_refreshing_remote_profiles = False
  499. self._is_refreshing_remote_profiles = True
  500. run_as_background_process("user_directory.refresh_remote_profiles", process)
  501. async def _unsafe_refresh_remote_profiles(self) -> None:
  502. limit = MAX_SERVERS_TO_REFRESH_PROFILES_FOR_IN_ONE_GO - len(
  503. self._is_refreshing_remote_profiles_for_servers
  504. )
  505. if limit <= 0:
  506. # nothing to do: already refreshing the maximum number of servers
  507. # at once.
  508. # Come back later.
  509. self._refresh_remote_profiles_call_later = self.clock.call_later(
  510. INTERVAL_TO_ADD_MORE_SERVERS_TO_REFRESH_PROFILES,
  511. self.kick_off_remote_profile_refresh_process,
  512. )
  513. return
  514. servers_to_refresh = (
  515. await self.store.get_remote_servers_with_profiles_to_refresh(
  516. now_ts=self.clock.time_msec(), limit=limit
  517. )
  518. )
  519. if not servers_to_refresh:
  520. # Do we have any backing-off servers that we should try again
  521. # for eventually?
  522. # By setting `now` is a point in the far future, we can ask for
  523. # which server/user is next to be refreshed, even though it is
  524. # not actually refreshable *now*.
  525. end_of_time = 1 << 62
  526. backing_off_servers = (
  527. await self.store.get_remote_servers_with_profiles_to_refresh(
  528. now_ts=end_of_time, limit=1
  529. )
  530. )
  531. if backing_off_servers:
  532. # Find out when the next user is refreshable and schedule a
  533. # refresh then.
  534. backing_off_server_name = backing_off_servers[0]
  535. users = await self.store.get_remote_users_to_refresh_on_server(
  536. backing_off_server_name, now_ts=end_of_time, limit=1
  537. )
  538. if not users:
  539. return
  540. _, _, next_try_at_ts = users[0]
  541. self._refresh_remote_profiles_call_later = self.clock.call_later(
  542. ((next_try_at_ts - self.clock.time_msec()) // 1000) + 2,
  543. self.kick_off_remote_profile_refresh_process,
  544. )
  545. return
  546. for server_to_refresh in servers_to_refresh:
  547. self.kick_off_remote_profile_refresh_process_for_remote_server(
  548. server_to_refresh
  549. )
  550. self._refresh_remote_profiles_call_later = self.clock.call_later(
  551. INTERVAL_TO_ADD_MORE_SERVERS_TO_REFRESH_PROFILES,
  552. self.kick_off_remote_profile_refresh_process,
  553. )
  554. def kick_off_remote_profile_refresh_process_for_remote_server(
  555. self, server_name: str
  556. ) -> None:
  557. """Called when there may be remote users with stale profiles to be refreshed
  558. on the given server."""
  559. if not self.update_user_directory:
  560. return
  561. if server_name in self._is_refreshing_remote_profiles_for_servers:
  562. return
  563. async def process() -> None:
  564. try:
  565. await self._unsafe_refresh_remote_profiles_for_remote_server(
  566. server_name
  567. )
  568. finally:
  569. self._is_refreshing_remote_profiles_for_servers.remove(server_name)
  570. self._is_refreshing_remote_profiles_for_servers.add(server_name)
  571. run_as_background_process(
  572. "user_directory.refresh_remote_profiles_for_remote_server", process
  573. )
  574. async def _unsafe_refresh_remote_profiles_for_remote_server(
  575. self, server_name: str
  576. ) -> None:
  577. logger.info("Refreshing profiles in user directory for %s", server_name)
  578. while True:
  579. # Get a handful of users to process.
  580. next_batch = await self.store.get_remote_users_to_refresh_on_server(
  581. server_name, now_ts=self.clock.time_msec(), limit=10
  582. )
  583. if not next_batch:
  584. # Finished for now
  585. return
  586. for user_id, retry_counter, _ in next_batch:
  587. # Request the profile of the user.
  588. try:
  589. profile = await self._hs.get_profile_handler().get_profile(
  590. user_id, ignore_backoff=False
  591. )
  592. except NotRetryingDestination as e:
  593. logger.info(
  594. "Failed to refresh profile for %r because the destination is undergoing backoff",
  595. user_id,
  596. )
  597. # As a special-case, we back off until the destination is no longer
  598. # backed off from.
  599. await self.store.set_remote_user_profile_in_user_dir_stale(
  600. user_id,
  601. e.retry_last_ts + e.retry_interval,
  602. retry_counter=retry_counter + 1,
  603. )
  604. continue
  605. except SynapseError as e:
  606. if e.code == HTTPStatus.NOT_FOUND and e.errcode == Codes.NOT_FOUND:
  607. # The profile doesn't exist.
  608. # TODO Does this mean we should clear it from our user
  609. # directory?
  610. await self.store.clear_remote_user_profile_in_user_dir_stale(
  611. user_id
  612. )
  613. logger.warning(
  614. "Refresh of remote profile %r: not found (%r)",
  615. user_id,
  616. e.msg,
  617. )
  618. continue
  619. logger.warning(
  620. "Failed to refresh profile for %r because %r", user_id, e
  621. )
  622. await self.store.set_remote_user_profile_in_user_dir_stale(
  623. user_id,
  624. calculate_time_of_next_retry(
  625. self.clock.time_msec(), retry_counter + 1
  626. ),
  627. retry_counter=retry_counter + 1,
  628. )
  629. continue
  630. except Exception:
  631. logger.error(
  632. "Failed to refresh profile for %r due to unhandled exception",
  633. user_id,
  634. exc_info=True,
  635. )
  636. await self.store.set_remote_user_profile_in_user_dir_stale(
  637. user_id,
  638. calculate_time_of_next_retry(
  639. self.clock.time_msec(), retry_counter + 1
  640. ),
  641. retry_counter=retry_counter + 1,
  642. )
  643. continue
  644. await self.store.update_profile_in_user_dir(
  645. user_id,
  646. display_name=non_null_str_or_none(profile.get("displayname")),
  647. avatar_url=non_null_str_or_none(profile.get("avatar_url")),
  648. )