選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

170 行
6.2 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2017-2018 New Vector Ltd
  3. # Copyright 2019 The Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. from abc import ABCMeta
  18. from typing import TYPE_CHECKING, Any, Collection, Dict, Iterable, Optional, Union
  19. from synapse.storage.database import make_in_list_sql_clause # noqa: F401; noqa: F401
  20. from synapse.storage.database import DatabasePool, LoggingDatabaseConnection
  21. from synapse.types import get_domain_from_id
  22. from synapse.util import json_decoder
  23. from synapse.util.caches.descriptors import CachedFunction
  24. if TYPE_CHECKING:
  25. from synapse.server import HomeServer
  26. logger = logging.getLogger(__name__)
  27. # some of our subclasses have abstract methods, so we use the ABCMeta metaclass.
  28. class SQLBaseStore(metaclass=ABCMeta):
  29. """Base class for data stores that holds helper functions.
  30. Note that multiple instances of this class will exist as there will be one
  31. per data store (and not one per physical database).
  32. """
  33. def __init__(
  34. self,
  35. database: DatabasePool,
  36. db_conn: LoggingDatabaseConnection,
  37. hs: "HomeServer",
  38. ):
  39. self.hs = hs
  40. self._clock = hs.get_clock()
  41. self.database_engine = database.engine
  42. self.db_pool = database
  43. self.external_cached_functions: Dict[str, CachedFunction] = {}
  44. def process_replication_rows(
  45. self,
  46. stream_name: str,
  47. instance_name: str,
  48. token: int,
  49. rows: Iterable[Any],
  50. ) -> None:
  51. pass
  52. def _invalidate_state_caches(
  53. self, room_id: str, members_changed: Collection[str]
  54. ) -> None:
  55. """Invalidates caches that are based on the current state, but does
  56. not stream invalidations down replication.
  57. Args:
  58. room_id: Room where state changed
  59. members_changed: The user_ids of members that have changed
  60. """
  61. # If there were any membership changes, purge the appropriate caches.
  62. for host in {get_domain_from_id(u) for u in members_changed}:
  63. self._attempt_to_invalidate_cache("is_host_joined", (room_id, host))
  64. if members_changed:
  65. self._attempt_to_invalidate_cache("get_users_in_room", (room_id,))
  66. self._attempt_to_invalidate_cache("get_current_hosts_in_room", (room_id,))
  67. self._attempt_to_invalidate_cache(
  68. "get_users_in_room_with_profiles", (room_id,)
  69. )
  70. self._attempt_to_invalidate_cache(
  71. "get_number_joined_users_in_room", (room_id,)
  72. )
  73. self._attempt_to_invalidate_cache("get_local_users_in_room", (room_id,))
  74. # There's no easy way of invalidating this cache for just the users
  75. # that have changed, so we just clear the entire thing.
  76. self._attempt_to_invalidate_cache("does_pair_of_users_share_a_room", None)
  77. for user_id in members_changed:
  78. self._attempt_to_invalidate_cache(
  79. "get_user_in_room_with_profile", (room_id, user_id)
  80. )
  81. self._attempt_to_invalidate_cache(
  82. "get_rooms_for_user_with_stream_ordering", (user_id,)
  83. )
  84. # Purge other caches based on room state.
  85. self._attempt_to_invalidate_cache("get_room_summary", (room_id,))
  86. self._attempt_to_invalidate_cache("get_partial_current_state_ids", (room_id,))
  87. def _attempt_to_invalidate_cache(
  88. self, cache_name: str, key: Optional[Collection[Any]]
  89. ) -> bool:
  90. """Attempts to invalidate the cache of the given name, ignoring if the
  91. cache doesn't exist. Mainly used for invalidating caches on workers,
  92. where they may not have the cache.
  93. Note that this function does not invalidate any remote caches, only the
  94. local in-memory ones. Any remote invalidation must be performed before
  95. calling this.
  96. Args:
  97. cache_name
  98. key: Entry to invalidate. If None then invalidates the entire
  99. cache.
  100. """
  101. try:
  102. cache = getattr(self, cache_name)
  103. except AttributeError:
  104. # Check if an externally defined module cache has been registered
  105. cache = self.external_cached_functions.get(cache_name)
  106. if not cache:
  107. # We probably haven't pulled in the cache in this worker,
  108. # which is fine.
  109. return False
  110. if key is None:
  111. cache.invalidate_all()
  112. else:
  113. # Prefer any local-only invalidation method. Invalidating any non-local
  114. # cache must be be done before this.
  115. invalidate_method = getattr(cache, "invalidate_local", cache.invalidate)
  116. invalidate_method(tuple(key))
  117. return True
  118. def register_external_cached_function(
  119. self, cache_name: str, func: CachedFunction
  120. ) -> None:
  121. self.external_cached_functions[cache_name] = func
  122. def db_to_json(db_content: Union[memoryview, bytes, bytearray, str]) -> Any:
  123. """
  124. Take some data from a database row and return a JSON-decoded object.
  125. Args:
  126. db_content: The JSON-encoded contents from the database.
  127. Returns:
  128. The object decoded from JSON.
  129. """
  130. # psycopg2 on Python 3 returns memoryview objects, which we need to
  131. # cast to bytes to decode
  132. if isinstance(db_content, memoryview):
  133. db_content = db_content.tobytes()
  134. # Decode it to a Unicode string before feeding it to the JSON decoder, since
  135. # it only supports handling strings
  136. if isinstance(db_content, (bytes, bytearray)):
  137. db_content = db_content.decode("utf8")
  138. try:
  139. return json_decoder.decode(db_content)
  140. except Exception:
  141. logging.warning("Tried to decode '%r' as JSON and failed", db_content)
  142. raise