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.
 
 
 
 
 
 

242 line
8.8 KiB

  1. # Copyright 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 logging
  15. from typing import (
  16. TYPE_CHECKING,
  17. Any,
  18. Awaitable,
  19. Callable,
  20. Dict,
  21. Iterable,
  22. List,
  23. Optional,
  24. Set,
  25. TypeVar,
  26. Union,
  27. )
  28. from typing_extensions import ParamSpec
  29. from twisted.internet.defer import CancelledError
  30. from synapse.api.presence import UserPresenceState
  31. from synapse.util.async_helpers import delay_cancellation, maybe_awaitable
  32. if TYPE_CHECKING:
  33. from synapse.server import HomeServer
  34. GET_USERS_FOR_STATES_CALLBACK = Callable[
  35. [Iterable[UserPresenceState]], Awaitable[Dict[str, Set[UserPresenceState]]]
  36. ]
  37. # This must either return a set of strings or the constant PresenceRouter.ALL_USERS.
  38. GET_INTERESTED_USERS_CALLBACK = Callable[[str], Awaitable[Union[Set[str], str]]]
  39. logger = logging.getLogger(__name__)
  40. P = ParamSpec("P")
  41. R = TypeVar("R")
  42. def load_legacy_presence_router(hs: "HomeServer") -> None:
  43. """Wrapper that loads a presence router module configured using the old
  44. configuration, and registers the hooks they implement.
  45. """
  46. if hs.config.server.presence_router_module_class is None:
  47. return
  48. module = hs.config.server.presence_router_module_class
  49. config = hs.config.server.presence_router_config
  50. api = hs.get_module_api()
  51. presence_router = module(config=config, module_api=api)
  52. # The known hooks. If a module implements a method which name appears in this set,
  53. # we'll want to register it.
  54. presence_router_methods = {
  55. "get_users_for_states",
  56. "get_interested_users",
  57. }
  58. # All methods that the module provides should be async, but this wasn't enforced
  59. # in the old module system, so we wrap them if needed
  60. def async_wrapper(
  61. f: Optional[Callable[P, R]]
  62. ) -> Optional[Callable[P, Awaitable[R]]]:
  63. # f might be None if the callback isn't implemented by the module. In this
  64. # case we don't want to register a callback at all so we return None.
  65. if f is None:
  66. return None
  67. def run(*args: P.args, **kwargs: P.kwargs) -> Awaitable[R]:
  68. # Assertion required because mypy can't prove we won't change `f`
  69. # back to `None`. See
  70. # https://mypy.readthedocs.io/en/latest/common_issues.html#narrowing-and-inner-functions
  71. assert f is not None
  72. return maybe_awaitable(f(*args, **kwargs))
  73. return run
  74. # Register the hooks through the module API.
  75. hooks: Dict[str, Optional[Callable[..., Any]]] = {
  76. hook: async_wrapper(getattr(presence_router, hook, None))
  77. for hook in presence_router_methods
  78. }
  79. api.register_presence_router_callbacks(**hooks)
  80. class PresenceRouter:
  81. """
  82. A module that the homeserver will call upon to help route user presence updates to
  83. additional destinations.
  84. """
  85. ALL_USERS = "ALL"
  86. def __init__(self, hs: "HomeServer"):
  87. # Initially there are no callbacks
  88. self._get_users_for_states_callbacks: List[GET_USERS_FOR_STATES_CALLBACK] = []
  89. self._get_interested_users_callbacks: List[GET_INTERESTED_USERS_CALLBACK] = []
  90. def register_presence_router_callbacks(
  91. self,
  92. get_users_for_states: Optional[GET_USERS_FOR_STATES_CALLBACK] = None,
  93. get_interested_users: Optional[GET_INTERESTED_USERS_CALLBACK] = None,
  94. ) -> None:
  95. # PresenceRouter modules are required to implement both of these methods
  96. # or neither of them as they are assumed to act in a complementary manner
  97. paired_methods = [get_users_for_states, get_interested_users]
  98. if paired_methods.count(None) == 1:
  99. raise RuntimeError(
  100. "PresenceRouter modules must register neither or both of the paired callbacks: "
  101. "[get_users_for_states, get_interested_users]"
  102. )
  103. # Append the methods provided to the lists of callbacks
  104. if get_users_for_states is not None:
  105. self._get_users_for_states_callbacks.append(get_users_for_states)
  106. if get_interested_users is not None:
  107. self._get_interested_users_callbacks.append(get_interested_users)
  108. async def get_users_for_states(
  109. self,
  110. state_updates: Iterable[UserPresenceState],
  111. ) -> Dict[str, Set[UserPresenceState]]:
  112. """
  113. Given an iterable of user presence updates, determine where each one
  114. needs to go.
  115. Args:
  116. state_updates: An iterable of user presence state updates.
  117. Returns:
  118. A dictionary of user_id -> set of UserPresenceState, indicating which
  119. presence updates each user should receive.
  120. """
  121. # Bail out early if we don't have any callbacks to run.
  122. if len(self._get_users_for_states_callbacks) == 0:
  123. # Don't include any extra destinations for presence updates
  124. return {}
  125. users_for_states: Dict[str, Set[UserPresenceState]] = {}
  126. # run all the callbacks for get_users_for_states and combine the results
  127. for callback in self._get_users_for_states_callbacks:
  128. try:
  129. # Note: result is an object here, because we don't trust modules to
  130. # return the types they're supposed to.
  131. result: object = await delay_cancellation(callback(state_updates))
  132. except CancelledError:
  133. raise
  134. except Exception as e:
  135. logger.warning("Failed to run module API callback %s: %s", callback, e)
  136. continue
  137. if not isinstance(result, Dict):
  138. logger.warning(
  139. "Wrong type returned by module API callback %s: %s, expected Dict",
  140. callback,
  141. result,
  142. )
  143. continue
  144. for key, new_entries in result.items():
  145. if not isinstance(new_entries, Set):
  146. logger.warning(
  147. "Wrong type returned by module API callback %s: %s, expected Set",
  148. callback,
  149. new_entries,
  150. )
  151. break
  152. users_for_states.setdefault(key, set()).update(new_entries)
  153. return users_for_states
  154. async def get_interested_users(self, user_id: str) -> Union[Set[str], str]:
  155. """
  156. Retrieve a list of users that `user_id` is interested in receiving the
  157. presence of. This will be in addition to those they share a room with.
  158. Optionally, the object PresenceRouter.ALL_USERS can be returned to indicate
  159. that this user should receive all incoming local and remote presence updates.
  160. Note that this method will only be called for local users, but can return users
  161. that are local or remote.
  162. Args:
  163. user_id: A user requesting presence updates.
  164. Returns:
  165. A set of user IDs to return presence updates for, or ALL_USERS to return all
  166. known updates.
  167. """
  168. # Bail out early if we don't have any callbacks to run.
  169. if len(self._get_interested_users_callbacks) == 0:
  170. # Don't report any additional interested users
  171. return set()
  172. interested_users = set()
  173. # run all the callbacks for get_interested_users and combine the results
  174. for callback in self._get_interested_users_callbacks:
  175. try:
  176. result = await delay_cancellation(callback(user_id))
  177. except CancelledError:
  178. raise
  179. except Exception as e:
  180. logger.warning("Failed to run module API callback %s: %s", callback, e)
  181. continue
  182. # If one of the callbacks returns ALL_USERS then we can stop calling all
  183. # of the other callbacks, since the set of interested_users is already as
  184. # large as it can possibly be
  185. if result == PresenceRouter.ALL_USERS:
  186. return PresenceRouter.ALL_USERS
  187. if not isinstance(result, Set):
  188. logger.warning(
  189. "Wrong type returned by module API callback %s: %s, expected set",
  190. callback,
  191. result,
  192. )
  193. continue
  194. # Add the new interested users to the set
  195. interested_users.update(result)
  196. return interested_users