test_id_generators.py 33 KB

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