test_id_generators.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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 List, Optional
  15. from twisted.test.proto_helpers import MemoryReactor
  16. from synapse.server import HomeServer
  17. from synapse.storage.database import DatabasePool, LoggingTransaction
  18. from synapse.storage.engines import IncorrectDatabaseSetup
  19. from synapse.storage.util.id_generators import MultiWriterIdGenerator
  20. from synapse.util import Clock
  21. from tests.unittest import HomeserverTestCase
  22. from tests.utils import USE_POSTGRES_FOR_TESTS
  23. class MultiWriterIdGeneratorTestCase(HomeserverTestCase):
  24. if not USE_POSTGRES_FOR_TESTS:
  25. skip = "Requires Postgres"
  26. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  27. self.store = hs.get_datastores().main
  28. self.db_pool: DatabasePool = self.store.db_pool
  29. self.get_success(self.db_pool.runInteraction("_setup_db", self._setup_db))
  30. def _setup_db(self, txn: LoggingTransaction) -> None:
  31. txn.execute("CREATE SEQUENCE foobar_seq")
  32. txn.execute(
  33. """
  34. CREATE TABLE foobar (
  35. stream_id BIGINT NOT NULL,
  36. instance_name TEXT NOT NULL,
  37. data TEXT
  38. );
  39. """
  40. )
  41. def _create_id_generator(
  42. self, instance_name="master", writers: Optional[List[str]] = None
  43. ) -> MultiWriterIdGenerator:
  44. def _create(conn):
  45. return MultiWriterIdGenerator(
  46. conn,
  47. self.db_pool,
  48. stream_name="test_stream",
  49. instance_name=instance_name,
  50. tables=[("foobar", "instance_name", "stream_id")],
  51. sequence_name="foobar_seq",
  52. writers=writers or ["master"],
  53. )
  54. return self.get_success_or_raise(self.db_pool.runWithConnection(_create))
  55. def _insert_rows(self, instance_name: str, number: int) -> None:
  56. """Insert N rows as the given instance, inserting with stream IDs pulled
  57. from the postgres sequence.
  58. """
  59. def _insert(txn: LoggingTransaction) -> None:
  60. for _ in range(number):
  61. txn.execute(
  62. "INSERT INTO foobar VALUES (nextval('foobar_seq'), ?)",
  63. (instance_name,),
  64. )
  65. txn.execute(
  66. """
  67. INSERT INTO stream_positions VALUES ('test_stream', ?, lastval())
  68. ON CONFLICT (stream_name, instance_name) DO UPDATE SET stream_id = lastval()
  69. """,
  70. (instance_name,),
  71. )
  72. self.get_success(self.db_pool.runInteraction("_insert_rows", _insert))
  73. def _insert_row_with_id(self, instance_name: str, stream_id: int) -> None:
  74. """Insert one row as the given instance with given stream_id, updating
  75. the postgres sequence position to match.
  76. """
  77. def _insert(txn: LoggingTransaction) -> None:
  78. txn.execute(
  79. "INSERT INTO foobar VALUES (?, ?)",
  80. (
  81. stream_id,
  82. instance_name,
  83. ),
  84. )
  85. txn.execute("SELECT setval('foobar_seq', ?)", (stream_id,))
  86. txn.execute(
  87. """
  88. INSERT INTO stream_positions VALUES ('test_stream', ?, ?)
  89. ON CONFLICT (stream_name, instance_name) DO UPDATE SET stream_id = ?
  90. """,
  91. (instance_name, stream_id, stream_id),
  92. )
  93. self.get_success(self.db_pool.runInteraction("_insert_row_with_id", _insert))
  94. def test_empty(self) -> None:
  95. """Test an ID generator against an empty database gives sensible
  96. current positions.
  97. """
  98. id_gen = self._create_id_generator()
  99. # The table is empty so we expect an empty map for positions
  100. self.assertEqual(id_gen.get_positions(), {})
  101. def test_single_instance(self) -> None:
  102. """Test that reads and writes from a single process are handled
  103. correctly.
  104. """
  105. # Prefill table with 7 rows written by 'master'
  106. self._insert_rows("master", 7)
  107. id_gen = self._create_id_generator()
  108. self.assertEqual(id_gen.get_positions(), {"master": 7})
  109. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  110. # Try allocating a new ID gen and check that we only see position
  111. # advanced after we leave the context manager.
  112. async def _get_next_async() -> None:
  113. async with id_gen.get_next() as stream_id:
  114. self.assertEqual(stream_id, 8)
  115. self.assertEqual(id_gen.get_positions(), {"master": 7})
  116. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  117. self.get_success(_get_next_async())
  118. self.assertEqual(id_gen.get_positions(), {"master": 8})
  119. self.assertEqual(id_gen.get_current_token_for_writer("master"), 8)
  120. def test_out_of_order_finish(self) -> None:
  121. """Test that IDs persisted out of order are correctly handled"""
  122. # Prefill table with 7 rows written by 'master'
  123. self._insert_rows("master", 7)
  124. id_gen = self._create_id_generator()
  125. self.assertEqual(id_gen.get_positions(), {"master": 7})
  126. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  127. ctx1 = id_gen.get_next()
  128. ctx2 = id_gen.get_next()
  129. ctx3 = id_gen.get_next()
  130. ctx4 = id_gen.get_next()
  131. s1 = self.get_success(ctx1.__aenter__())
  132. s2 = self.get_success(ctx2.__aenter__())
  133. s3 = self.get_success(ctx3.__aenter__())
  134. s4 = self.get_success(ctx4.__aenter__())
  135. self.assertEqual(s1, 8)
  136. self.assertEqual(s2, 9)
  137. self.assertEqual(s3, 10)
  138. self.assertEqual(s4, 11)
  139. self.assertEqual(id_gen.get_positions(), {"master": 7})
  140. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  141. self.get_success(ctx2.__aexit__(None, None, None))
  142. self.assertEqual(id_gen.get_positions(), {"master": 7})
  143. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  144. self.get_success(ctx1.__aexit__(None, None, None))
  145. self.assertEqual(id_gen.get_positions(), {"master": 9})
  146. self.assertEqual(id_gen.get_current_token_for_writer("master"), 9)
  147. self.get_success(ctx4.__aexit__(None, None, None))
  148. self.assertEqual(id_gen.get_positions(), {"master": 9})
  149. self.assertEqual(id_gen.get_current_token_for_writer("master"), 9)
  150. self.get_success(ctx3.__aexit__(None, None, None))
  151. self.assertEqual(id_gen.get_positions(), {"master": 11})
  152. self.assertEqual(id_gen.get_current_token_for_writer("master"), 11)
  153. def test_multi_instance(self) -> None:
  154. """Test that reads and writes from multiple processes are handled
  155. correctly.
  156. """
  157. self._insert_rows("first", 3)
  158. self._insert_rows("second", 4)
  159. first_id_gen = self._create_id_generator("first", writers=["first", "second"])
  160. second_id_gen = self._create_id_generator("second", writers=["first", "second"])
  161. # The first ID gen will notice that it can advance its token to 7 as it
  162. # has no in progress writes...
  163. self.assertEqual(first_id_gen.get_positions(), {"first": 7, "second": 7})
  164. self.assertEqual(first_id_gen.get_current_token_for_writer("first"), 7)
  165. self.assertEqual(first_id_gen.get_current_token_for_writer("second"), 7)
  166. # ... but the second ID gen doesn't know that.
  167. self.assertEqual(second_id_gen.get_positions(), {"first": 3, "second": 7})
  168. self.assertEqual(second_id_gen.get_current_token_for_writer("first"), 3)
  169. self.assertEqual(second_id_gen.get_current_token_for_writer("second"), 7)
  170. # Try allocating a new ID gen and check that we only see position
  171. # advanced after we leave the context manager.
  172. async def _get_next_async() -> None:
  173. async with first_id_gen.get_next() as stream_id:
  174. self.assertEqual(stream_id, 8)
  175. self.assertEqual(
  176. first_id_gen.get_positions(), {"first": 7, "second": 7}
  177. )
  178. self.get_success(_get_next_async())
  179. self.assertEqual(first_id_gen.get_positions(), {"first": 8, "second": 7})
  180. # However the ID gen on the second instance won't have seen the update
  181. self.assertEqual(second_id_gen.get_positions(), {"first": 3, "second": 7})
  182. # ... but calling `get_next` on the second instance should give a unique
  183. # stream ID
  184. async def _get_next_async2() -> None:
  185. async with second_id_gen.get_next() as stream_id:
  186. self.assertEqual(stream_id, 9)
  187. self.assertEqual(
  188. second_id_gen.get_positions(), {"first": 3, "second": 7}
  189. )
  190. self.get_success(_get_next_async2())
  191. self.assertEqual(second_id_gen.get_positions(), {"first": 3, "second": 9})
  192. # If the second ID gen gets told about the first, it correctly updates
  193. second_id_gen.advance("first", 8)
  194. self.assertEqual(second_id_gen.get_positions(), {"first": 8, "second": 9})
  195. def test_get_next_txn(self) -> None:
  196. """Test that the `get_next_txn` function works correctly."""
  197. # Prefill table with 7 rows written by 'master'
  198. self._insert_rows("master", 7)
  199. id_gen = self._create_id_generator()
  200. self.assertEqual(id_gen.get_positions(), {"master": 7})
  201. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  202. # Try allocating a new ID gen and check that we only see position
  203. # advanced after we leave the context manager.
  204. def _get_next_txn(txn: LoggingTransaction) -> None:
  205. stream_id = id_gen.get_next_txn(txn)
  206. self.assertEqual(stream_id, 8)
  207. self.assertEqual(id_gen.get_positions(), {"master": 7})
  208. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  209. self.get_success(self.db_pool.runInteraction("test", _get_next_txn))
  210. self.assertEqual(id_gen.get_positions(), {"master": 8})
  211. self.assertEqual(id_gen.get_current_token_for_writer("master"), 8)
  212. def test_get_persisted_upto_position(self) -> None:
  213. """Test that `get_persisted_upto_position` correctly tracks updates to
  214. positions.
  215. """
  216. # The following tests are a bit cheeky in that we notify about new
  217. # positions via `advance` without *actually* advancing the postgres
  218. # sequence.
  219. self._insert_row_with_id("first", 3)
  220. self._insert_row_with_id("second", 5)
  221. id_gen = self._create_id_generator("worker", writers=["first", "second"])
  222. self.assertEqual(id_gen.get_positions(), {"first": 3, "second": 5})
  223. # Min is 3 and there is a gap between 5, so we expect it to be 3.
  224. self.assertEqual(id_gen.get_persisted_upto_position(), 3)
  225. # We advance "first" straight to 6. Min is now 5 but there is no gap so
  226. # we expect it to be 6
  227. id_gen.advance("first", 6)
  228. self.assertEqual(id_gen.get_persisted_upto_position(), 6)
  229. # No gap, so we expect 7.
  230. id_gen.advance("second", 7)
  231. self.assertEqual(id_gen.get_persisted_upto_position(), 7)
  232. # We haven't seen 8 yet, so we expect 7 still.
  233. id_gen.advance("second", 9)
  234. self.assertEqual(id_gen.get_persisted_upto_position(), 7)
  235. # Now that we've seen 7, 8 and 9 we can got straight to 9.
  236. id_gen.advance("first", 8)
  237. self.assertEqual(id_gen.get_persisted_upto_position(), 9)
  238. # Jump forward with gaps. The minimum is 11, even though we haven't seen
  239. # 10 we know that everything before 11 must be persisted.
  240. id_gen.advance("first", 11)
  241. id_gen.advance("second", 15)
  242. self.assertEqual(id_gen.get_persisted_upto_position(), 11)
  243. def test_get_persisted_upto_position_get_next(self) -> None:
  244. """Test that `get_persisted_upto_position` correctly tracks updates to
  245. positions when `get_next` is called.
  246. """
  247. self._insert_row_with_id("first", 3)
  248. self._insert_row_with_id("second", 5)
  249. id_gen = self._create_id_generator("first", writers=["first", "second"])
  250. self.assertEqual(id_gen.get_positions(), {"first": 5, "second": 5})
  251. self.assertEqual(id_gen.get_persisted_upto_position(), 5)
  252. async def _get_next_async() -> None:
  253. async with id_gen.get_next() as stream_id:
  254. self.assertEqual(stream_id, 6)
  255. self.assertEqual(id_gen.get_persisted_upto_position(), 5)
  256. self.get_success(_get_next_async())
  257. self.assertEqual(id_gen.get_persisted_upto_position(), 6)
  258. # We assume that so long as `get_next` does correctly advance the
  259. # `persisted_upto_position` in this case, then it will be correct in the
  260. # other cases that are tested above (since they'll hit the same code).
  261. def test_restart_during_out_of_order_persistence(self) -> None:
  262. """Test that restarting a process while another process is writing out
  263. of order updates are handled correctly.
  264. """
  265. # Prefill table with 7 rows written by 'master'
  266. self._insert_rows("master", 7)
  267. id_gen = self._create_id_generator()
  268. self.assertEqual(id_gen.get_positions(), {"master": 7})
  269. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  270. # Persist two rows at once
  271. ctx1 = id_gen.get_next()
  272. ctx2 = id_gen.get_next()
  273. s1 = self.get_success(ctx1.__aenter__())
  274. s2 = self.get_success(ctx2.__aenter__())
  275. self.assertEqual(s1, 8)
  276. self.assertEqual(s2, 9)
  277. self.assertEqual(id_gen.get_positions(), {"master": 7})
  278. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  279. # We finish persisting the second row before restart
  280. self.get_success(ctx2.__aexit__(None, None, None))
  281. # We simulate a restart of another worker by just creating a new ID gen.
  282. id_gen_worker = self._create_id_generator("worker")
  283. # Restarted worker should not see the second persisted row
  284. self.assertEqual(id_gen_worker.get_positions(), {"master": 7})
  285. self.assertEqual(id_gen_worker.get_current_token_for_writer("master"), 7)
  286. # Now if we persist the first row then both instances should jump ahead
  287. # correctly.
  288. self.get_success(ctx1.__aexit__(None, None, None))
  289. self.assertEqual(id_gen.get_positions(), {"master": 9})
  290. id_gen_worker.advance("master", 9)
  291. self.assertEqual(id_gen_worker.get_positions(), {"master": 9})
  292. def test_writer_config_change(self) -> None:
  293. """Test that changing the writer config correctly works."""
  294. self._insert_row_with_id("first", 3)
  295. self._insert_row_with_id("second", 5)
  296. # Initial config has two writers
  297. id_gen = self._create_id_generator("worker", writers=["first", "second"])
  298. self.assertEqual(id_gen.get_persisted_upto_position(), 3)
  299. self.assertEqual(id_gen.get_current_token_for_writer("first"), 3)
  300. self.assertEqual(id_gen.get_current_token_for_writer("second"), 5)
  301. # New config removes one of the configs. Note that if the writer is
  302. # removed from config we assume that it has been shut down and has
  303. # finished persisting, hence why the persisted upto position is 5.
  304. id_gen_2 = self._create_id_generator("second", writers=["second"])
  305. self.assertEqual(id_gen_2.get_persisted_upto_position(), 5)
  306. self.assertEqual(id_gen_2.get_current_token_for_writer("second"), 5)
  307. # This config points to a single, previously unused writer.
  308. id_gen_3 = self._create_id_generator("third", writers=["third"])
  309. self.assertEqual(id_gen_3.get_persisted_upto_position(), 5)
  310. # For new writers we assume their initial position to be the current
  311. # persisted up to position. This stops Synapse from doing a full table
  312. # scan when a new writer comes along.
  313. self.assertEqual(id_gen_3.get_current_token_for_writer("third"), 5)
  314. id_gen_4 = self._create_id_generator("fourth", writers=["third"])
  315. self.assertEqual(id_gen_4.get_current_token_for_writer("third"), 5)
  316. # Check that we get a sane next stream ID with this new config.
  317. async def _get_next_async() -> None:
  318. async with id_gen_3.get_next() as stream_id:
  319. self.assertEqual(stream_id, 6)
  320. self.get_success(_get_next_async())
  321. self.assertEqual(id_gen_3.get_persisted_upto_position(), 6)
  322. # If we add back the old "first" then we shouldn't see the persisted up
  323. # to position revert back to 3.
  324. id_gen_5 = self._create_id_generator("five", writers=["first", "third"])
  325. self.assertEqual(id_gen_5.get_persisted_upto_position(), 6)
  326. self.assertEqual(id_gen_5.get_current_token_for_writer("first"), 6)
  327. self.assertEqual(id_gen_5.get_current_token_for_writer("third"), 6)
  328. def test_sequence_consistency(self) -> None:
  329. """Test that we error out if the table and sequence diverges."""
  330. # Prefill with some rows
  331. self._insert_row_with_id("master", 3)
  332. # Now we add a row *without* updating the stream ID
  333. def _insert(txn):
  334. txn.execute("INSERT INTO foobar VALUES (26, 'master')")
  335. self.get_success(self.db_pool.runInteraction("_insert", _insert))
  336. # Creating the ID gen should error
  337. with self.assertRaises(IncorrectDatabaseSetup):
  338. self._create_id_generator("first")
  339. class BackwardsMultiWriterIdGeneratorTestCase(HomeserverTestCase):
  340. """Tests MultiWriterIdGenerator that produce *negative* stream IDs."""
  341. if not USE_POSTGRES_FOR_TESTS:
  342. skip = "Requires Postgres"
  343. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  344. self.store = hs.get_datastores().main
  345. self.db_pool: DatabasePool = self.store.db_pool
  346. self.get_success(self.db_pool.runInteraction("_setup_db", self._setup_db))
  347. def _setup_db(self, txn: LoggingTransaction) -> None:
  348. txn.execute("CREATE SEQUENCE foobar_seq")
  349. txn.execute(
  350. """
  351. CREATE TABLE foobar (
  352. stream_id BIGINT NOT NULL,
  353. instance_name TEXT NOT NULL,
  354. data TEXT
  355. );
  356. """
  357. )
  358. def _create_id_generator(
  359. self, instance_name="master", writers: Optional[List[str]] = None
  360. ) -> MultiWriterIdGenerator:
  361. def _create(conn):
  362. return MultiWriterIdGenerator(
  363. conn,
  364. self.db_pool,
  365. stream_name="test_stream",
  366. instance_name=instance_name,
  367. tables=[("foobar", "instance_name", "stream_id")],
  368. sequence_name="foobar_seq",
  369. writers=writers or ["master"],
  370. positive=False,
  371. )
  372. return self.get_success(self.db_pool.runWithConnection(_create))
  373. def _insert_row(self, instance_name: str, stream_id: int) -> None:
  374. """Insert one row as the given instance with given stream_id."""
  375. def _insert(txn: LoggingTransaction) -> None:
  376. txn.execute(
  377. "INSERT INTO foobar VALUES (?, ?)",
  378. (
  379. stream_id,
  380. instance_name,
  381. ),
  382. )
  383. txn.execute(
  384. """
  385. INSERT INTO stream_positions VALUES ('test_stream', ?, ?)
  386. ON CONFLICT (stream_name, instance_name) DO UPDATE SET stream_id = ?
  387. """,
  388. (instance_name, -stream_id, -stream_id),
  389. )
  390. self.get_success(self.db_pool.runInteraction("_insert_row", _insert))
  391. def test_single_instance(self) -> None:
  392. """Test that reads and writes from a single process are handled
  393. correctly.
  394. """
  395. id_gen = self._create_id_generator()
  396. async def _get_next_async() -> None:
  397. async with id_gen.get_next() as stream_id:
  398. self._insert_row("master", stream_id)
  399. self.get_success(_get_next_async())
  400. self.assertEqual(id_gen.get_positions(), {"master": -1})
  401. self.assertEqual(id_gen.get_current_token_for_writer("master"), -1)
  402. self.assertEqual(id_gen.get_persisted_upto_position(), -1)
  403. async def _get_next_async2() -> None:
  404. async with id_gen.get_next_mult(3) as stream_ids:
  405. for stream_id in stream_ids:
  406. self._insert_row("master", stream_id)
  407. self.get_success(_get_next_async2())
  408. self.assertEqual(id_gen.get_positions(), {"master": -4})
  409. self.assertEqual(id_gen.get_current_token_for_writer("master"), -4)
  410. self.assertEqual(id_gen.get_persisted_upto_position(), -4)
  411. # Test loading from DB by creating a second ID gen
  412. second_id_gen = self._create_id_generator()
  413. self.assertEqual(second_id_gen.get_positions(), {"master": -4})
  414. self.assertEqual(second_id_gen.get_current_token_for_writer("master"), -4)
  415. self.assertEqual(second_id_gen.get_persisted_upto_position(), -4)
  416. def test_multiple_instance(self) -> None:
  417. """Tests that having multiple instances that get advanced over
  418. federation works corretly.
  419. """
  420. id_gen_1 = self._create_id_generator("first", writers=["first", "second"])
  421. id_gen_2 = self._create_id_generator("second", writers=["first", "second"])
  422. async def _get_next_async() -> None:
  423. async with id_gen_1.get_next() as stream_id:
  424. self._insert_row("first", stream_id)
  425. id_gen_2.advance("first", stream_id)
  426. self.get_success(_get_next_async())
  427. self.assertEqual(id_gen_1.get_positions(), {"first": -1})
  428. self.assertEqual(id_gen_2.get_positions(), {"first": -1})
  429. self.assertEqual(id_gen_1.get_persisted_upto_position(), -1)
  430. self.assertEqual(id_gen_2.get_persisted_upto_position(), -1)
  431. async def _get_next_async2() -> None:
  432. async with id_gen_2.get_next() as stream_id:
  433. self._insert_row("second", stream_id)
  434. id_gen_1.advance("second", stream_id)
  435. self.get_success(_get_next_async2())
  436. self.assertEqual(id_gen_1.get_positions(), {"first": -2, "second": -2})
  437. self.assertEqual(id_gen_2.get_positions(), {"first": -1, "second": -2})
  438. self.assertEqual(id_gen_1.get_persisted_upto_position(), -2)
  439. self.assertEqual(id_gen_2.get_persisted_upto_position(), -2)
  440. class MultiTableMultiWriterIdGeneratorTestCase(HomeserverTestCase):
  441. if not USE_POSTGRES_FOR_TESTS:
  442. skip = "Requires Postgres"
  443. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  444. self.store = hs.get_datastores().main
  445. self.db_pool: DatabasePool = self.store.db_pool
  446. self.get_success(self.db_pool.runInteraction("_setup_db", self._setup_db))
  447. def _setup_db(self, txn: LoggingTransaction) -> None:
  448. txn.execute("CREATE SEQUENCE foobar_seq")
  449. txn.execute(
  450. """
  451. CREATE TABLE foobar1 (
  452. stream_id BIGINT NOT NULL,
  453. instance_name TEXT NOT NULL,
  454. data TEXT
  455. );
  456. """
  457. )
  458. txn.execute(
  459. """
  460. CREATE TABLE foobar2 (
  461. stream_id BIGINT NOT NULL,
  462. instance_name TEXT NOT NULL,
  463. data TEXT
  464. );
  465. """
  466. )
  467. def _create_id_generator(
  468. self, instance_name="master", writers: Optional[List[str]] = None
  469. ) -> MultiWriterIdGenerator:
  470. def _create(conn):
  471. return MultiWriterIdGenerator(
  472. conn,
  473. self.db_pool,
  474. stream_name="test_stream",
  475. instance_name=instance_name,
  476. tables=[
  477. ("foobar1", "instance_name", "stream_id"),
  478. ("foobar2", "instance_name", "stream_id"),
  479. ],
  480. sequence_name="foobar_seq",
  481. writers=writers or ["master"],
  482. )
  483. return self.get_success_or_raise(self.db_pool.runWithConnection(_create))
  484. def _insert_rows(
  485. self,
  486. table: str,
  487. instance_name: str,
  488. number: int,
  489. update_stream_table: bool = True,
  490. ):
  491. """Insert N rows as the given instance, inserting with stream IDs pulled
  492. from the postgres sequence.
  493. """
  494. def _insert(txn: LoggingTransaction) -> None:
  495. for _ in range(number):
  496. txn.execute(
  497. "INSERT INTO %s VALUES (nextval('foobar_seq'), ?)" % (table,),
  498. (instance_name,),
  499. )
  500. if update_stream_table:
  501. txn.execute(
  502. """
  503. INSERT INTO stream_positions VALUES ('test_stream', ?, lastval())
  504. ON CONFLICT (stream_name, instance_name) DO UPDATE SET stream_id = lastval()
  505. """,
  506. (instance_name,),
  507. )
  508. self.get_success(self.db_pool.runInteraction("_insert_rows", _insert))
  509. def test_load_existing_stream(self) -> None:
  510. """Test creating ID gens with multiple tables that have rows from after
  511. the position in `stream_positions` table.
  512. """
  513. self._insert_rows("foobar1", "first", 3)
  514. self._insert_rows("foobar2", "second", 3)
  515. self._insert_rows("foobar2", "second", 1, update_stream_table=False)
  516. first_id_gen = self._create_id_generator("first", writers=["first", "second"])
  517. second_id_gen = self._create_id_generator("second", writers=["first", "second"])
  518. # The first ID gen will notice that it can advance its token to 7 as it
  519. # has no in progress writes...
  520. self.assertEqual(first_id_gen.get_positions(), {"first": 7, "second": 6})
  521. self.assertEqual(first_id_gen.get_current_token_for_writer("first"), 7)
  522. self.assertEqual(first_id_gen.get_current_token_for_writer("second"), 6)
  523. self.assertEqual(first_id_gen.get_persisted_upto_position(), 7)
  524. # ... but the second ID gen doesn't know that.
  525. self.assertEqual(second_id_gen.get_positions(), {"first": 3, "second": 7})
  526. self.assertEqual(second_id_gen.get_current_token_for_writer("first"), 3)
  527. self.assertEqual(second_id_gen.get_current_token_for_writer("second"), 7)
  528. self.assertEqual(first_id_gen.get_persisted_upto_position(), 7)