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.
 
 
 
 
 
 

364 lines
14 KiB

  1. # Copyright 2020 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 Callable, List, Tuple
  15. from unittest.mock import Mock, call
  16. from twisted.internet import defer
  17. from twisted.internet.defer import CancelledError, Deferred
  18. from twisted.test.proto_helpers import MemoryReactor
  19. from synapse.server import HomeServer
  20. from synapse.storage.database import (
  21. DatabasePool,
  22. LoggingDatabaseConnection,
  23. LoggingTransaction,
  24. make_tuple_comparison_clause,
  25. )
  26. from synapse.util import Clock
  27. from tests import unittest
  28. from tests.utils import USE_POSTGRES_FOR_TESTS
  29. class TupleComparisonClauseTestCase(unittest.TestCase):
  30. def test_native_tuple_comparison(self) -> None:
  31. clause, args = make_tuple_comparison_clause([("a", 1), ("b", 2)])
  32. self.assertEqual(clause, "(a,b) > (?,?)")
  33. self.assertEqual(args, [1, 2])
  34. class ExecuteScriptTestCase(unittest.HomeserverTestCase):
  35. """Tests for `BaseDatabaseEngine.executescript` implementations."""
  36. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  37. self.store = hs.get_datastores().main
  38. self.db_pool: DatabasePool = self.store.db_pool
  39. self.get_success(
  40. self.db_pool.runInteraction(
  41. "create",
  42. lambda txn: txn.execute("CREATE TABLE foo (name TEXT PRIMARY KEY)"),
  43. )
  44. )
  45. def test_transaction(self) -> None:
  46. """Test that all statements are run in a single transaction."""
  47. def run(conn: LoggingDatabaseConnection) -> None:
  48. cur = conn.cursor(txn_name="test_transaction")
  49. self.db_pool.engine.executescript(
  50. cur,
  51. ";".join(
  52. [
  53. "INSERT INTO foo (name) VALUES ('transaction test')",
  54. # This next statement will fail. When `executescript` is not
  55. # transactional, the previous row will be observed later.
  56. "INSERT INTO foo (name) VALUES ('transaction test')",
  57. ]
  58. ),
  59. )
  60. self.get_failure(
  61. self.db_pool.runWithConnection(run),
  62. self.db_pool.engine.module.IntegrityError,
  63. )
  64. self.assertIsNone(
  65. self.get_success(
  66. self.db_pool.simple_select_one_onecol(
  67. "foo",
  68. keyvalues={"name": "transaction test"},
  69. retcol="name",
  70. allow_none=True,
  71. )
  72. ),
  73. "executescript is not running statements inside a transaction",
  74. )
  75. def test_commit(self) -> None:
  76. """Test that the script transaction remains open and can be committed."""
  77. def run(conn: LoggingDatabaseConnection) -> None:
  78. cur = conn.cursor(txn_name="test_commit")
  79. self.db_pool.engine.executescript(
  80. cur, "INSERT INTO foo (name) VALUES ('commit test')"
  81. )
  82. cur.execute("COMMIT")
  83. self.get_success(self.db_pool.runWithConnection(run))
  84. self.assertIsNotNone(
  85. self.get_success(
  86. self.db_pool.simple_select_one_onecol(
  87. "foo",
  88. keyvalues={"name": "commit test"},
  89. retcol="name",
  90. allow_none=True,
  91. )
  92. ),
  93. )
  94. def test_rollback(self) -> None:
  95. """Test that the script transaction remains open and can be rolled back."""
  96. def run(conn: LoggingDatabaseConnection) -> None:
  97. cur = conn.cursor(txn_name="test_rollback")
  98. self.db_pool.engine.executescript(
  99. cur, "INSERT INTO foo (name) VALUES ('rollback test')"
  100. )
  101. cur.execute("ROLLBACK")
  102. self.get_success(self.db_pool.runWithConnection(run))
  103. self.assertIsNone(
  104. self.get_success(
  105. self.db_pool.simple_select_one_onecol(
  106. "foo",
  107. keyvalues={"name": "rollback test"},
  108. retcol="name",
  109. allow_none=True,
  110. )
  111. ),
  112. "executescript is not leaving the script transaction open",
  113. )
  114. class CallbacksTestCase(unittest.HomeserverTestCase):
  115. """Tests for transaction callbacks."""
  116. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  117. self.store = hs.get_datastores().main
  118. self.db_pool: DatabasePool = self.store.db_pool
  119. def _run_interaction(
  120. self, func: Callable[[LoggingTransaction], object]
  121. ) -> Tuple[Mock, Mock]:
  122. """Run the given function in a database transaction, with callbacks registered.
  123. Args:
  124. func: The function to be run in a transaction. The transaction will be
  125. retried if `func` raises an `OperationalError`.
  126. Returns:
  127. Two mocks, which were registered as an `after_callback` and an
  128. `exception_callback` respectively, on every transaction attempt.
  129. """
  130. after_callback = Mock()
  131. exception_callback = Mock()
  132. def _test_txn(txn: LoggingTransaction) -> None:
  133. txn.call_after(after_callback, 123, 456, extra=789)
  134. txn.call_on_exception(exception_callback, 987, 654, extra=321)
  135. func(txn)
  136. try:
  137. self.get_success_or_raise(
  138. self.db_pool.runInteraction("test_transaction", _test_txn)
  139. )
  140. except Exception:
  141. pass
  142. return after_callback, exception_callback
  143. def test_after_callback(self) -> None:
  144. """Test that the after callback is called when a transaction succeeds."""
  145. after_callback, exception_callback = self._run_interaction(lambda txn: None)
  146. after_callback.assert_called_once_with(123, 456, extra=789)
  147. exception_callback.assert_not_called()
  148. def test_exception_callback(self) -> None:
  149. """Test that the exception callback is called when a transaction fails."""
  150. _test_txn = Mock(side_effect=ZeroDivisionError)
  151. after_callback, exception_callback = self._run_interaction(_test_txn)
  152. after_callback.assert_not_called()
  153. exception_callback.assert_called_once_with(987, 654, extra=321)
  154. def test_failed_retry(self) -> None:
  155. """Test that the exception callback is called for every failed attempt."""
  156. # Always raise an `OperationalError`.
  157. _test_txn = Mock(side_effect=self.db_pool.engine.module.OperationalError)
  158. after_callback, exception_callback = self._run_interaction(_test_txn)
  159. after_callback.assert_not_called()
  160. exception_callback.assert_has_calls(
  161. [
  162. call(987, 654, extra=321),
  163. call(987, 654, extra=321),
  164. call(987, 654, extra=321),
  165. call(987, 654, extra=321),
  166. call(987, 654, extra=321),
  167. call(987, 654, extra=321),
  168. ]
  169. )
  170. self.assertEqual(exception_callback.call_count, 6) # no additional calls
  171. def test_successful_retry(self) -> None:
  172. """Test callbacks for a failed transaction followed by a successful attempt."""
  173. # Raise an `OperationalError` on the first attempt only.
  174. _test_txn = Mock(
  175. side_effect=[self.db_pool.engine.module.OperationalError, None]
  176. )
  177. after_callback, exception_callback = self._run_interaction(_test_txn)
  178. # Calling both `after_callback`s when the first attempt failed is rather
  179. # surprising (https://github.com/matrix-org/synapse/issues/12184).
  180. # Let's document the behaviour in a test.
  181. after_callback.assert_has_calls(
  182. [
  183. call(123, 456, extra=789),
  184. call(123, 456, extra=789),
  185. ]
  186. )
  187. self.assertEqual(after_callback.call_count, 2) # no additional calls
  188. exception_callback.assert_not_called()
  189. class CancellationTestCase(unittest.HomeserverTestCase):
  190. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  191. self.store = hs.get_datastores().main
  192. self.db_pool: DatabasePool = self.store.db_pool
  193. def test_after_callback(self) -> None:
  194. """Test that the after callback is called when a transaction succeeds."""
  195. d: "Deferred[None]"
  196. after_callback = Mock()
  197. exception_callback = Mock()
  198. def _test_txn(txn: LoggingTransaction) -> None:
  199. txn.call_after(after_callback, 123, 456, extra=789)
  200. txn.call_on_exception(exception_callback, 987, 654, extra=321)
  201. d.cancel()
  202. d = defer.ensureDeferred(
  203. self.db_pool.runInteraction("test_transaction", _test_txn)
  204. )
  205. self.get_failure(d, CancelledError)
  206. after_callback.assert_called_once_with(123, 456, extra=789)
  207. exception_callback.assert_not_called()
  208. def test_exception_callback(self) -> None:
  209. """Test that the exception callback is called when a transaction fails."""
  210. d: "Deferred[None]"
  211. after_callback = Mock()
  212. exception_callback = Mock()
  213. def _test_txn(txn: LoggingTransaction) -> None:
  214. txn.call_after(after_callback, 123, 456, extra=789)
  215. txn.call_on_exception(exception_callback, 987, 654, extra=321)
  216. d.cancel()
  217. # Simulate a retryable failure on every attempt.
  218. raise self.db_pool.engine.module.OperationalError()
  219. d = defer.ensureDeferred(
  220. self.db_pool.runInteraction("test_transaction", _test_txn)
  221. )
  222. self.get_failure(d, CancelledError)
  223. after_callback.assert_not_called()
  224. exception_callback.assert_has_calls(
  225. [
  226. call(987, 654, extra=321),
  227. call(987, 654, extra=321),
  228. call(987, 654, extra=321),
  229. call(987, 654, extra=321),
  230. call(987, 654, extra=321),
  231. call(987, 654, extra=321),
  232. ]
  233. )
  234. self.assertEqual(exception_callback.call_count, 6) # no additional calls
  235. class PostgresReplicaIdentityTestCase(unittest.HomeserverTestCase):
  236. if not USE_POSTGRES_FOR_TESTS:
  237. skip = "Requires Postgres"
  238. def prepare(
  239. self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
  240. ) -> None:
  241. self.db_pools = homeserver.get_datastores().databases
  242. def test_all_tables_have_postgres_replica_identity(self) -> None:
  243. """
  244. Tests that all tables have a Postgres REPLICA IDENTITY.
  245. (See https://github.com/matrix-org/synapse/issues/16224).
  246. Tables with a PRIMARY KEY have an implied REPLICA IDENTITY and are fine.
  247. Other tables need them to be set with `ALTER TABLE`.
  248. A REPLICA IDENTITY is required for Postgres logical replication to work
  249. properly without blocking updates and deletes.
  250. """
  251. sql = """
  252. -- Select tables that have no primary key and use the default replica identity rule
  253. -- (the default is to use the primary key)
  254. WITH tables_no_pkey AS (
  255. SELECT tbl.table_schema, tbl.table_name
  256. FROM information_schema.tables tbl
  257. WHERE table_type = 'BASE TABLE'
  258. AND table_schema not in ('pg_catalog', 'information_schema')
  259. AND NOT EXISTS (
  260. SELECT 1
  261. FROM information_schema.key_column_usage kcu
  262. WHERE kcu.table_name = tbl.table_name
  263. AND kcu.table_schema = tbl.table_schema
  264. )
  265. )
  266. SELECT pg_class.oid::regclass FROM tables_no_pkey INNER JOIN pg_class ON pg_class.oid::regclass = table_name::regclass
  267. WHERE relreplident = 'd'
  268. UNION
  269. -- Also select tables that use an index as a replica identity
  270. -- but where the index doesn't exist
  271. -- (e.g. it could have been deleted)
  272. SELECT pg_class.oid::regclass
  273. FROM information_schema.tables tbl
  274. INNER JOIN pg_class ON pg_class.oid::regclass = table_name::regclass
  275. WHERE table_type = 'BASE TABLE'
  276. AND table_schema not in ('pg_catalog', 'information_schema')
  277. -- 'i' means an index is used as the replica identity
  278. AND relreplident = 'i'
  279. -- look for indices that are marked as the replica identity
  280. AND NOT EXISTS (
  281. SELECT indexrelid::regclass
  282. FROM pg_index
  283. WHERE indrelid = pg_class.oid::regclass AND indisreplident
  284. )
  285. """
  286. def _list_tables_with_missing_replica_identities_txn(
  287. txn: LoggingTransaction,
  288. ) -> List[str]:
  289. txn.execute(sql)
  290. return [table_name for table_name, in txn]
  291. for pool in self.db_pools:
  292. missing = self.get_success(
  293. pool.runInteraction(
  294. "test_list_missing_replica_identities",
  295. _list_tables_with_missing_replica_identities_txn,
  296. )
  297. )
  298. self.assertEqual(
  299. len(missing),
  300. 0,
  301. f"The following tables in the {pool.name()!r} database are missing REPLICA IDENTITIES: {missing!r}.",
  302. )