25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

208 lines
7.7 KiB

  1. # Copyright 2018 New Vector 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 typing import TYPE_CHECKING, List, Tuple
  16. from synapse.api.constants import (
  17. EventTypes,
  18. LimitBlockingTypes,
  19. ServerNoticeLimitReached,
  20. ServerNoticeMsgType,
  21. )
  22. from synapse.api.errors import AuthError, ResourceLimitError, SynapseError
  23. if TYPE_CHECKING:
  24. from synapse.server import HomeServer
  25. logger = logging.getLogger(__name__)
  26. class ResourceLimitsServerNotices:
  27. """Keeps track of whether the server has reached it's resource limit and
  28. ensures that the client is kept up to date.
  29. """
  30. def __init__(self, hs: "HomeServer"):
  31. self._server_notices_manager = hs.get_server_notices_manager()
  32. self._store = hs.get_datastores().main
  33. self._storage_controllers = hs.get_storage_controllers()
  34. self._auth_blocking = hs.get_auth_blocking()
  35. self._config = hs.config
  36. self._resouce_limited = False
  37. self._account_data_handler = hs.get_account_data_handler()
  38. self._message_handler = hs.get_message_handler()
  39. self._state = hs.get_state_handler()
  40. self._notifier = hs.get_notifier()
  41. self._enabled = (
  42. hs.config.server.limit_usage_by_mau
  43. and self._server_notices_manager.is_enabled()
  44. and not hs.config.server.hs_disabled
  45. )
  46. async def maybe_send_server_notice_to_user(self, user_id: str) -> None:
  47. """Check if we need to send a notice to this user, this will be true in
  48. two cases.
  49. 1. The server has reached its limit does not reflect this
  50. 2. The room state indicates that the server has reached its limit when
  51. actually the server is fine
  52. Args:
  53. user_id: user to check
  54. """
  55. if not self._enabled:
  56. return
  57. timestamp = await self._store.user_last_seen_monthly_active(user_id)
  58. if timestamp is None:
  59. # This user will be blocked from receiving the notice anyway.
  60. # In practice, not sure we can ever get here
  61. return
  62. # Check if there's a server notice room for this user.
  63. room_id = await self._server_notices_manager.maybe_get_notice_room_for_user(
  64. user_id
  65. )
  66. if room_id is not None:
  67. # Determine current state of room
  68. currently_blocked, ref_events = await self._is_room_currently_blocked(
  69. room_id
  70. )
  71. else:
  72. currently_blocked = False
  73. ref_events = []
  74. limit_msg = None
  75. limit_type = None
  76. try:
  77. # Normally should always pass in user_id to check_auth_blocking
  78. # if you have it, but in this case are checking what would happen
  79. # to other users if they were to arrive.
  80. await self._auth_blocking.check_auth_blocking()
  81. except ResourceLimitError as e:
  82. limit_msg = e.msg
  83. limit_type = e.limit_type
  84. try:
  85. if (
  86. limit_type == LimitBlockingTypes.MONTHLY_ACTIVE_USER
  87. and not self._config.server.mau_limit_alerting
  88. ):
  89. # We have hit the MAU limit, but MAU alerting is disabled:
  90. # reset room if necessary and return
  91. if currently_blocked:
  92. await self._remove_limit_block_notification(user_id, ref_events)
  93. return
  94. if currently_blocked and not limit_msg:
  95. # Room is notifying of a block, when it ought not to be.
  96. await self._remove_limit_block_notification(user_id, ref_events)
  97. elif not currently_blocked and limit_msg:
  98. # Room is not notifying of a block, when it ought to be.
  99. await self._apply_limit_block_notification(
  100. user_id, limit_msg, limit_type # type: ignore
  101. )
  102. except SynapseError as e:
  103. logger.error("Error sending resource limits server notice: %s", e)
  104. async def _remove_limit_block_notification(
  105. self, user_id: str, ref_events: List[str]
  106. ) -> None:
  107. """Utility method to remove limit block notifications from the server
  108. notices room.
  109. Args:
  110. user_id: user to notify
  111. ref_events: The event_ids of pinned events that are unrelated to
  112. limit blocking and need to be preserved.
  113. """
  114. content = {"pinned": ref_events}
  115. await self._server_notices_manager.send_notice(
  116. user_id, content, EventTypes.Pinned, ""
  117. )
  118. async def _apply_limit_block_notification(
  119. self, user_id: str, event_body: str, event_limit_type: str
  120. ) -> None:
  121. """Utility method to apply limit block notifications in the server
  122. notices room.
  123. Args:
  124. user_id: user to notify
  125. event_body: The human readable text that describes the block.
  126. event_limit_type: Specifies the type of block e.g. monthly active user
  127. limit has been exceeded.
  128. """
  129. content = {
  130. "body": event_body,
  131. "msgtype": ServerNoticeMsgType,
  132. "server_notice_type": ServerNoticeLimitReached,
  133. "admin_contact": self._config.server.admin_contact,
  134. "limit_type": event_limit_type,
  135. }
  136. event = await self._server_notices_manager.send_notice(
  137. user_id, content, EventTypes.Message
  138. )
  139. content = {"pinned": [event.event_id]}
  140. await self._server_notices_manager.send_notice(
  141. user_id, content, EventTypes.Pinned, ""
  142. )
  143. async def _is_room_currently_blocked(self, room_id: str) -> Tuple[bool, List[str]]:
  144. """
  145. Determines if the room is currently blocked
  146. Args:
  147. room_id: The room id of the server notices room
  148. Returns:
  149. Tuple of:
  150. Is the room currently blocked
  151. The list of pinned event IDs that are unrelated to limit blocking
  152. This list can be used as a convenience in the case where the block
  153. is to be lifted and the remaining pinned event references need to be
  154. preserved
  155. """
  156. currently_blocked = False
  157. pinned_state_event = None
  158. try:
  159. pinned_state_event = (
  160. await self._storage_controllers.state.get_current_state_event(
  161. room_id, event_type=EventTypes.Pinned, state_key=""
  162. )
  163. )
  164. except AuthError:
  165. # The user has yet to join the server notices room
  166. pass
  167. referenced_events: List[str] = []
  168. if pinned_state_event is not None:
  169. referenced_events = list(pinned_state_event.content.get("pinned", []))
  170. events = await self._store.get_events(referenced_events)
  171. for event_id, event in events.items():
  172. if event.type != EventTypes.Message:
  173. continue
  174. if event.content.get("msgtype") == ServerNoticeMsgType:
  175. currently_blocked = True
  176. # remove event in case we need to disable blocking later on.
  177. if event_id in referenced_events:
  178. referenced_events.remove(event.event_id)
  179. return currently_blocked, referenced_events