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.
 
 
 
 
 
 

143 lines
5.0 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, 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. if TYPE_CHECKING:
  24. from synapse.server import HomeServer
  25. logger = logging.getLogger(__name__)
  26. # some of our subclasses have abstract methods, so we use the ABCMeta metaclass.
  27. class SQLBaseStore(metaclass=ABCMeta):
  28. """Base class for data stores that holds helper functions.
  29. Note that multiple instances of this class will exist as there will be one
  30. per data store (and not one per physical database).
  31. """
  32. def __init__(
  33. self,
  34. database: DatabasePool,
  35. db_conn: LoggingDatabaseConnection,
  36. hs: "HomeServer",
  37. ):
  38. self.hs = hs
  39. self._clock = hs.get_clock()
  40. self.database_engine = database.engine
  41. self.db_pool = database
  42. def process_replication_rows(
  43. self,
  44. stream_name: str,
  45. instance_name: str,
  46. token: int,
  47. rows: Iterable[Any],
  48. ) -> None:
  49. pass
  50. def _invalidate_state_caches(
  51. self, room_id: str, members_changed: Collection[str]
  52. ) -> None:
  53. """Invalidates caches that are based on the current state, but does
  54. not stream invalidations down replication.
  55. Args:
  56. room_id: Room where state changed
  57. members_changed: The user_ids of members that have changed
  58. """
  59. # If there were any membership changes, purge the appropriate caches.
  60. for host in {get_domain_from_id(u) for u in members_changed}:
  61. self._attempt_to_invalidate_cache("is_host_joined", (room_id, host))
  62. if members_changed:
  63. self._attempt_to_invalidate_cache("get_users_in_room", (room_id,))
  64. self._attempt_to_invalidate_cache("get_current_hosts_in_room", (room_id,))
  65. self._attempt_to_invalidate_cache(
  66. "get_users_in_room_with_profiles", (room_id,)
  67. )
  68. self._attempt_to_invalidate_cache(
  69. "get_number_joined_users_in_room", (room_id,)
  70. )
  71. self._attempt_to_invalidate_cache("get_local_users_in_room", (room_id,))
  72. for user_id in members_changed:
  73. self._attempt_to_invalidate_cache(
  74. "get_user_in_room_with_profile", (room_id, user_id)
  75. )
  76. # Purge other caches based on room state.
  77. self._attempt_to_invalidate_cache("get_room_summary", (room_id,))
  78. self._attempt_to_invalidate_cache("get_partial_current_state_ids", (room_id,))
  79. def _attempt_to_invalidate_cache(
  80. self, cache_name: str, key: Optional[Collection[Any]]
  81. ) -> None:
  82. """Attempts to invalidate the cache of the given name, ignoring if the
  83. cache doesn't exist. Mainly used for invalidating caches on workers,
  84. where they may not have the cache.
  85. Args:
  86. cache_name
  87. key: Entry to invalidate. If None then invalidates the entire
  88. cache.
  89. """
  90. try:
  91. cache = getattr(self, cache_name)
  92. except AttributeError:
  93. # We probably haven't pulled in the cache in this worker,
  94. # which is fine.
  95. return
  96. if key is None:
  97. cache.invalidate_all()
  98. else:
  99. cache.invalidate(tuple(key))
  100. def db_to_json(db_content: Union[memoryview, bytes, bytearray, str]) -> Any:
  101. """
  102. Take some data from a database row and return a JSON-decoded object.
  103. Args:
  104. db_content: The JSON-encoded contents from the database.
  105. Returns:
  106. The object decoded from JSON.
  107. """
  108. # psycopg2 on Python 3 returns memoryview objects, which we need to
  109. # cast to bytes to decode
  110. if isinstance(db_content, memoryview):
  111. db_content = db_content.tobytes()
  112. # Decode it to a Unicode string before feeding it to the JSON decoder, since
  113. # it only supports handling strings
  114. if isinstance(db_content, (bytes, bytearray)):
  115. db_content = db_content.decode("utf8")
  116. try:
  117. return json_decoder.decode(db_content)
  118. except Exception:
  119. logging.warning("Tried to decode '%r' as JSON and failed", db_content)
  120. raise