1
0

test_id_generators.py 26 KB

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