test_receipts.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. # Copyright 2022 The Matrix.org Foundation C.I.C.
  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. from typing import Any, Dict, Optional, Sequence, Tuple
  15. from twisted.test.proto_helpers import MemoryReactor
  16. from synapse.rest import admin
  17. from synapse.rest.client import login, room
  18. from synapse.server import HomeServer
  19. from synapse.storage.database import LoggingTransaction
  20. from synapse.util import Clock
  21. from tests.unittest import HomeserverTestCase
  22. class ReceiptsBackgroundUpdateStoreTestCase(HomeserverTestCase):
  23. servlets = [
  24. admin.register_servlets,
  25. room.register_servlets,
  26. login.register_servlets,
  27. ]
  28. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  29. self.store = hs.get_datastores().main
  30. self.user_id = self.register_user("foo", "pass")
  31. self.token = self.login("foo", "pass")
  32. self.room_id = self.helper.create_room_as(self.user_id, tok=self.token)
  33. self.other_room_id = self.helper.create_room_as(self.user_id, tok=self.token)
  34. def _test_background_receipts_unique_index(
  35. self,
  36. update_name: str,
  37. index_name: str,
  38. table: str,
  39. receipts: Dict[Tuple[str, str, str], Sequence[Dict[str, Any]]],
  40. expected_unique_receipts: Dict[Tuple[str, str, str], Optional[Dict[str, Any]]],
  41. ) -> None:
  42. """Test that the background update to uniqueify non-thread receipts in
  43. the given receipts table works properly.
  44. Args:
  45. update_name: The name of the background update to test.
  46. index_name: The name of the index that the background update creates.
  47. table: The table of receipts that the background update fixes.
  48. receipts: The test data containing duplicate receipts.
  49. A list of receipt rows to insert, grouped by
  50. `(room_id, receipt_type, user_id)`.
  51. expected_unique_receipts: A dictionary of `(room_id, receipt_type, user_id)`
  52. keys and expected receipt key-values after duplicate receipts have been
  53. removed.
  54. """
  55. # First, undo the background update.
  56. def drop_receipts_unique_index(txn: LoggingTransaction) -> None:
  57. txn.execute(f"DROP INDEX IF EXISTS {index_name}")
  58. self.get_success(
  59. self.store.db_pool.runInteraction(
  60. "drop_receipts_unique_index",
  61. drop_receipts_unique_index,
  62. )
  63. )
  64. # Populate the receipts table, including duplicates.
  65. for (room_id, receipt_type, user_id), rows in receipts.items():
  66. for row in rows:
  67. self.get_success(
  68. self.store.db_pool.simple_insert(
  69. table,
  70. {
  71. "room_id": room_id,
  72. "receipt_type": receipt_type,
  73. "user_id": user_id,
  74. "thread_id": None,
  75. "data": "{}",
  76. **row,
  77. },
  78. )
  79. )
  80. # Insert and run the background update.
  81. self.get_success(
  82. self.store.db_pool.simple_insert(
  83. "background_updates",
  84. {
  85. "update_name": update_name,
  86. "progress_json": "{}",
  87. },
  88. )
  89. )
  90. self.store.db_pool.updates._all_done = False
  91. self.wait_for_background_updates()
  92. # Check that the remaining receipts match expectations.
  93. for (
  94. room_id,
  95. receipt_type,
  96. user_id,
  97. ), expected_row in expected_unique_receipts.items():
  98. # Include the receipt key in the returned columns, for more informative
  99. # assertion messages.
  100. columns = ["room_id", "receipt_type", "user_id"]
  101. if expected_row is not None:
  102. columns += expected_row.keys()
  103. rows = self.get_success(
  104. self.store.db_pool.simple_select_list(
  105. table=table,
  106. keyvalues={
  107. "room_id": room_id,
  108. "receipt_type": receipt_type,
  109. "user_id": user_id,
  110. # `simple_select_onecol` does not support NULL filters,
  111. # so skip the filter on `thread_id`.
  112. },
  113. retcols=columns,
  114. desc="get_receipt",
  115. )
  116. )
  117. if expected_row is not None:
  118. self.assertEqual(
  119. len(rows),
  120. 1,
  121. f"Background update did not leave behind latest receipt in {table}",
  122. )
  123. self.assertEqual(
  124. rows[0],
  125. {
  126. "room_id": room_id,
  127. "receipt_type": receipt_type,
  128. "user_id": user_id,
  129. **expected_row,
  130. },
  131. )
  132. else:
  133. self.assertEqual(
  134. len(rows),
  135. 0,
  136. f"Background update did not remove all duplicate receipts from {table}",
  137. )
  138. def test_background_receipts_linearized_unique_index(self) -> None:
  139. """Test that the background update to uniqueify non-thread receipts in
  140. `receipts_linearized` works properly.
  141. """
  142. self._test_background_receipts_unique_index(
  143. "receipts_linearized_unique_index",
  144. "receipts_linearized_unique_index",
  145. "receipts_linearized",
  146. receipts={
  147. (self.room_id, "m.read", self.user_id): [
  148. {"stream_id": 5, "event_id": "$some_event"},
  149. {"stream_id": 6, "event_id": "$some_event"},
  150. ],
  151. (self.other_room_id, "m.read", self.user_id): [
  152. {"stream_id": 7, "event_id": "$some_event"}
  153. ],
  154. },
  155. expected_unique_receipts={
  156. (self.room_id, "m.read", self.user_id): {"stream_id": 6},
  157. (self.other_room_id, "m.read", self.user_id): {"stream_id": 7},
  158. },
  159. )
  160. def test_background_receipts_graph_unique_index(self) -> None:
  161. """Test that the background update to uniqueify non-thread receipts in
  162. `receipts_graph` works properly.
  163. """
  164. self._test_background_receipts_unique_index(
  165. "receipts_graph_unique_index",
  166. "receipts_graph_unique_index",
  167. "receipts_graph",
  168. receipts={
  169. (self.room_id, "m.read", self.user_id): [
  170. {
  171. "event_ids": '["$some_event"]',
  172. },
  173. {
  174. "event_ids": '["$some_event"]',
  175. },
  176. ],
  177. (self.other_room_id, "m.read", self.user_id): [
  178. {
  179. "event_ids": '["$some_event"]',
  180. }
  181. ],
  182. },
  183. expected_unique_receipts={
  184. (self.room_id, "m.read", self.user_id): None,
  185. (self.other_room_id, "m.read", self.user_id): {
  186. "event_ids": '["$some_event"]'
  187. },
  188. },
  189. )