Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

136 righe
5.2 KiB

  1. # Copyright 2018 Vector Creations 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 Any, Dict, List, Tuple
  16. from synapse.storage._base import SQLBaseStore
  17. from synapse.storage.database import LoggingTransaction
  18. from synapse.util.caches.stream_change_cache import StreamChangeCache
  19. logger = logging.getLogger(__name__)
  20. class StateDeltasStore(SQLBaseStore):
  21. # This class must be mixed in with a child class which provides the following
  22. # attribute. TODO: can we get static analysis to enforce this?
  23. _curr_state_delta_stream_cache: StreamChangeCache
  24. async def get_partial_current_state_deltas(
  25. self, prev_stream_id: int, max_stream_id: int
  26. ) -> Tuple[int, List[Dict[str, Any]]]:
  27. """Fetch a list of room state changes since the given stream id
  28. Each entry in the result contains the following fields:
  29. - stream_id (int)
  30. - room_id (str)
  31. - type (str): event type
  32. - state_key (str):
  33. - event_id (str|None): new event_id for this state key. None if the
  34. state has been deleted.
  35. - prev_event_id (str|None): previous event_id for this state key. None
  36. if it's new state.
  37. This may be the partial state if we're lazy joining the room.
  38. Args:
  39. prev_stream_id: point to get changes since (exclusive)
  40. max_stream_id: the point that we know has been correctly persisted
  41. - ie, an upper limit to return changes from.
  42. Returns:
  43. A tuple consisting of:
  44. - the stream id which these results go up to
  45. - list of current_state_delta_stream rows. If it is empty, we are
  46. up to date.
  47. """
  48. prev_stream_id = int(prev_stream_id)
  49. # check we're not going backwards
  50. assert (
  51. prev_stream_id <= max_stream_id
  52. ), f"New stream id {max_stream_id} is smaller than prev stream id {prev_stream_id}"
  53. if not self._curr_state_delta_stream_cache.has_any_entity_changed(
  54. prev_stream_id
  55. ):
  56. # if the CSDs haven't changed between prev_stream_id and now, we
  57. # know for certain that they haven't changed between prev_stream_id and
  58. # max_stream_id.
  59. return max_stream_id, []
  60. def get_current_state_deltas_txn(
  61. txn: LoggingTransaction,
  62. ) -> Tuple[int, List[Dict[str, Any]]]:
  63. # First we calculate the max stream id that will give us less than
  64. # N results.
  65. # We arbitrarily limit to 100 stream_id entries to ensure we don't
  66. # select toooo many.
  67. sql = """
  68. SELECT stream_id, count(*)
  69. FROM current_state_delta_stream
  70. WHERE stream_id > ? AND stream_id <= ?
  71. GROUP BY stream_id
  72. ORDER BY stream_id ASC
  73. LIMIT 100
  74. """
  75. txn.execute(sql, (prev_stream_id, max_stream_id))
  76. total = 0
  77. for stream_id, count in txn:
  78. total += count
  79. if total > 100:
  80. # We arbitrarily limit to 100 entries to ensure we don't
  81. # select toooo many.
  82. logger.debug(
  83. "Clipping current_state_delta_stream rows to stream_id %i",
  84. stream_id,
  85. )
  86. clipped_stream_id = stream_id
  87. break
  88. else:
  89. # if there's no problem, we may as well go right up to the max_stream_id
  90. clipped_stream_id = max_stream_id
  91. # Now actually get the deltas
  92. sql = """
  93. SELECT stream_id, room_id, type, state_key, event_id, prev_event_id
  94. FROM current_state_delta_stream
  95. WHERE ? < stream_id AND stream_id <= ?
  96. ORDER BY stream_id ASC
  97. """
  98. txn.execute(sql, (prev_stream_id, clipped_stream_id))
  99. return clipped_stream_id, self.db_pool.cursor_to_dict(txn)
  100. return await self.db_pool.runInteraction(
  101. "get_current_state_deltas", get_current_state_deltas_txn
  102. )
  103. def _get_max_stream_id_in_current_state_deltas_txn(
  104. self, txn: LoggingTransaction
  105. ) -> int:
  106. return self.db_pool.simple_select_one_onecol_txn(
  107. txn,
  108. table="current_state_delta_stream",
  109. keyvalues={},
  110. retcol="COALESCE(MAX(stream_id), -1)",
  111. )
  112. async def get_max_stream_id_in_current_state_deltas(self) -> int:
  113. return await self.db_pool.runInteraction(
  114. "get_max_stream_id_in_current_state_deltas",
  115. self._get_max_stream_id_in_current_state_deltas_txn,
  116. )