_base.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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( # noqa: B027 (no-op by design)
  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. self._attempt_to_invalidate_cache("get_rooms_for_user", (user_id,))
  85. # Purge other caches based on room state.
  86. self._attempt_to_invalidate_cache("get_room_summary", (room_id,))
  87. self._attempt_to_invalidate_cache("get_partial_current_state_ids", (room_id,))
  88. def _attempt_to_invalidate_cache(
  89. self, cache_name: str, key: Optional[Collection[Any]]
  90. ) -> bool:
  91. """Attempts to invalidate the cache of the given name, ignoring if the
  92. cache doesn't exist. Mainly used for invalidating caches on workers,
  93. where they may not have the cache.
  94. Note that this function does not invalidate any remote caches, only the
  95. local in-memory ones. Any remote invalidation must be performed before
  96. calling this.
  97. Args:
  98. cache_name
  99. key: Entry to invalidate. If None then invalidates the entire
  100. cache.
  101. """
  102. try:
  103. cache = getattr(self, cache_name)
  104. except AttributeError:
  105. # Check if an externally defined module cache has been registered
  106. cache = self.external_cached_functions.get(cache_name)
  107. if not cache:
  108. # We probably haven't pulled in the cache in this worker,
  109. # which is fine.
  110. return False
  111. if key is None:
  112. cache.invalidate_all()
  113. else:
  114. # Prefer any local-only invalidation method. Invalidating any non-local
  115. # cache must be be done before this.
  116. invalidate_method = getattr(cache, "invalidate_local", cache.invalidate)
  117. invalidate_method(tuple(key))
  118. return True
  119. def register_external_cached_function(
  120. self, cache_name: str, func: CachedFunction
  121. ) -> None:
  122. self.external_cached_functions[cache_name] = func
  123. def db_to_json(db_content: Union[memoryview, bytes, bytearray, str]) -> Any:
  124. """
  125. Take some data from a database row and return a JSON-decoded object.
  126. Args:
  127. db_content: The JSON-encoded contents from the database.
  128. Returns:
  129. The object decoded from JSON.
  130. """
  131. # psycopg2 on Python 3 returns memoryview objects, which we need to
  132. # cast to bytes to decode
  133. if isinstance(db_content, memoryview):
  134. db_content = db_content.tobytes()
  135. # Decode it to a Unicode string before feeding it to the JSON decoder, since
  136. # it only supports handling strings
  137. if isinstance(db_content, (bytes, bytearray)):
  138. db_content = db_content.decode("utf8")
  139. try:
  140. return json_decoder.decode(db_content)
  141. except Exception:
  142. logging.warning("Tried to decode '%r' as JSON and failed", db_content)
  143. raise