id_generators.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2021 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. import abc
  16. import heapq
  17. import logging
  18. import threading
  19. from collections import OrderedDict
  20. from contextlib import contextmanager
  21. from types import TracebackType
  22. from typing import (
  23. AsyncContextManager,
  24. ContextManager,
  25. Dict,
  26. Generator,
  27. Generic,
  28. Iterable,
  29. List,
  30. Optional,
  31. Sequence,
  32. Set,
  33. Tuple,
  34. Type,
  35. TypeVar,
  36. Union,
  37. cast,
  38. )
  39. import attr
  40. from sortedcontainers import SortedList, SortedSet
  41. from synapse.metrics.background_process_metrics import run_as_background_process
  42. from synapse.storage.database import (
  43. DatabasePool,
  44. LoggingDatabaseConnection,
  45. LoggingTransaction,
  46. )
  47. from synapse.storage.types import Cursor
  48. from synapse.storage.util.sequence import PostgresSequenceGenerator
  49. logger = logging.getLogger(__name__)
  50. T = TypeVar("T")
  51. class IdGenerator:
  52. def __init__(
  53. self,
  54. db_conn: LoggingDatabaseConnection,
  55. table: str,
  56. column: str,
  57. ):
  58. self._lock = threading.Lock()
  59. self._next_id = _load_current_id(db_conn, table, column)
  60. def get_next(self) -> int:
  61. with self._lock:
  62. self._next_id += 1
  63. return self._next_id
  64. def _load_current_id(
  65. db_conn: LoggingDatabaseConnection, table: str, column: str, step: int = 1
  66. ) -> int:
  67. cur = db_conn.cursor(txn_name="_load_current_id")
  68. if step == 1:
  69. cur.execute("SELECT MAX(%s) FROM %s" % (column, table))
  70. else:
  71. cur.execute("SELECT MIN(%s) FROM %s" % (column, table))
  72. result = cur.fetchone()
  73. assert result is not None
  74. (val,) = result
  75. cur.close()
  76. current_id = int(val) if val else step
  77. res = (max if step > 0 else min)(current_id, step)
  78. logger.info("Initialising stream generator for %s(%s): %i", table, column, res)
  79. return res
  80. class AbstractStreamIdTracker(metaclass=abc.ABCMeta):
  81. """Tracks the "current" stream ID of a stream that may have multiple writers.
  82. Stream IDs are monotonically increasing or decreasing integers representing write
  83. transactions. The "current" stream ID is the stream ID such that all transactions
  84. with equal or smaller stream IDs have completed. Since transactions may complete out
  85. of order, this is not the same as the stream ID of the last completed transaction.
  86. Completed transactions include both committed transactions and transactions that
  87. have been rolled back.
  88. """
  89. @abc.abstractmethod
  90. def advance(self, instance_name: str, new_id: int) -> None:
  91. """Advance the position of the named writer to the given ID, if greater
  92. than existing entry.
  93. """
  94. raise NotImplementedError()
  95. @abc.abstractmethod
  96. def get_current_token(self) -> int:
  97. """Returns the maximum stream id such that all stream ids less than or
  98. equal to it have been successfully persisted.
  99. Returns:
  100. The maximum stream id.
  101. """
  102. raise NotImplementedError()
  103. @abc.abstractmethod
  104. def get_current_token_for_writer(self, instance_name: str) -> int:
  105. """Returns the position of the given writer.
  106. For streams with single writers this is equivalent to `get_current_token`.
  107. """
  108. raise NotImplementedError()
  109. class AbstractStreamIdGenerator(AbstractStreamIdTracker):
  110. """Generates stream IDs for a stream that may have multiple writers.
  111. Each stream ID represents a write transaction, whose completion is tracked
  112. so that the "current" stream ID of the stream can be determined.
  113. See `AbstractStreamIdTracker` for more details.
  114. """
  115. @abc.abstractmethod
  116. def get_next(self) -> AsyncContextManager[int]:
  117. """
  118. Usage:
  119. async with stream_id_gen.get_next() as stream_id:
  120. # ... persist event ...
  121. """
  122. raise NotImplementedError()
  123. @abc.abstractmethod
  124. def get_next_mult(self, n: int) -> AsyncContextManager[Sequence[int]]:
  125. """
  126. Usage:
  127. async with stream_id_gen.get_next(n) as stream_ids:
  128. # ... persist events ...
  129. """
  130. raise NotImplementedError()
  131. class StreamIdGenerator(AbstractStreamIdGenerator):
  132. """Generates and tracks stream IDs for a stream with a single writer.
  133. This class must only be used when the current Synapse process is the sole
  134. writer for a stream.
  135. Args:
  136. db_conn(connection): A database connection to use to fetch the
  137. initial value of the generator from.
  138. table(str): A database table to read the initial value of the id
  139. generator from.
  140. column(str): The column of the database table to read the initial
  141. value from the id generator from.
  142. extra_tables(list): List of pairs of database tables and columns to
  143. use to source the initial value of the generator from. The value
  144. with the largest magnitude is used.
  145. step(int): which direction the stream ids grow in. +1 to grow
  146. upwards, -1 to grow downwards.
  147. Usage:
  148. async with stream_id_gen.get_next() as stream_id:
  149. # ... persist event ...
  150. """
  151. def __init__(
  152. self,
  153. db_conn: LoggingDatabaseConnection,
  154. table: str,
  155. column: str,
  156. extra_tables: Iterable[Tuple[str, str]] = (),
  157. step: int = 1,
  158. ) -> None:
  159. assert step != 0
  160. self._lock = threading.Lock()
  161. self._step: int = step
  162. self._current: int = _load_current_id(db_conn, table, column, step)
  163. for table, column in extra_tables:
  164. self._current = (max if step > 0 else min)(
  165. self._current, _load_current_id(db_conn, table, column, step)
  166. )
  167. # We use this as an ordered set, as we want to efficiently append items,
  168. # remove items and get the first item. Since we insert IDs in order, the
  169. # insertion ordering will ensure its in the correct ordering.
  170. #
  171. # The key and values are the same, but we never look at the values.
  172. self._unfinished_ids: OrderedDict[int, int] = OrderedDict()
  173. def advance(self, instance_name: str, new_id: int) -> None:
  174. # `StreamIdGenerator` should only be used when there is a single writer,
  175. # so replication should never happen.
  176. raise Exception("Replication is not supported by StreamIdGenerator")
  177. def get_next(self) -> AsyncContextManager[int]:
  178. with self._lock:
  179. self._current += self._step
  180. next_id = self._current
  181. self._unfinished_ids[next_id] = next_id
  182. @contextmanager
  183. def manager() -> Generator[int, None, None]:
  184. try:
  185. yield next_id
  186. finally:
  187. with self._lock:
  188. self._unfinished_ids.pop(next_id)
  189. return _AsyncCtxManagerWrapper(manager())
  190. def get_next_mult(self, n: int) -> AsyncContextManager[Sequence[int]]:
  191. with self._lock:
  192. next_ids = range(
  193. self._current + self._step,
  194. self._current + self._step * (n + 1),
  195. self._step,
  196. )
  197. self._current += n * self._step
  198. for next_id in next_ids:
  199. self._unfinished_ids[next_id] = next_id
  200. @contextmanager
  201. def manager() -> Generator[Sequence[int], None, None]:
  202. try:
  203. yield next_ids
  204. finally:
  205. with self._lock:
  206. for next_id in next_ids:
  207. self._unfinished_ids.pop(next_id)
  208. return _AsyncCtxManagerWrapper(manager())
  209. def get_current_token(self) -> int:
  210. with self._lock:
  211. if self._unfinished_ids:
  212. return next(iter(self._unfinished_ids)) - self._step
  213. return self._current
  214. def get_current_token_for_writer(self, instance_name: str) -> int:
  215. return self.get_current_token()
  216. class MultiWriterIdGenerator(AbstractStreamIdGenerator):
  217. """Generates and tracks stream IDs for a stream with multiple writers.
  218. Uses a Postgres sequence to coordinate ID assignment, but positions of other
  219. writers will only get updated when `advance` is called (by replication).
  220. Note: Only works with Postgres.
  221. Args:
  222. db_conn
  223. db
  224. stream_name: A name for the stream, for use in the `stream_positions`
  225. table. (Does not need to be the same as the replication stream name)
  226. instance_name: The name of this instance.
  227. tables: List of tables associated with the stream. Tuple of table
  228. name, column name that stores the writer's instance name, and
  229. column name that stores the stream ID.
  230. sequence_name: The name of the postgres sequence used to generate new
  231. IDs.
  232. writers: A list of known writers to use to populate current positions
  233. on startup. Can be empty if nothing uses `get_current_token` or
  234. `get_positions` (e.g. caches stream).
  235. positive: Whether the IDs are positive (true) or negative (false).
  236. When using negative IDs we go backwards from -1 to -2, -3, etc.
  237. """
  238. def __init__(
  239. self,
  240. db_conn: LoggingDatabaseConnection,
  241. db: DatabasePool,
  242. stream_name: str,
  243. instance_name: str,
  244. tables: List[Tuple[str, str, str]],
  245. sequence_name: str,
  246. writers: List[str],
  247. positive: bool = True,
  248. ) -> None:
  249. self._db = db
  250. self._stream_name = stream_name
  251. self._instance_name = instance_name
  252. self._positive = positive
  253. self._writers = writers
  254. self._return_factor = 1 if positive else -1
  255. # We lock as some functions may be called from DB threads.
  256. self._lock = threading.Lock()
  257. # Note: If we are a negative stream then we still store all the IDs as
  258. # positive to make life easier for us, and simply negate the IDs when we
  259. # return them.
  260. self._current_positions: Dict[str, int] = {}
  261. # Set of local IDs that we're still processing. The current position
  262. # should be less than the minimum of this set (if not empty).
  263. self._unfinished_ids: SortedSet[int] = SortedSet()
  264. # We also need to track when we've requested some new stream IDs but
  265. # they haven't yet been added to the `_unfinished_ids` set. Every time
  266. # we request a new stream ID we add the current max stream ID to the
  267. # list, and remove it once we've added the newly allocated IDs to the
  268. # `_unfinished_ids` set. This means that we *may* be allocated stream
  269. # IDs above those in the list, and so we can't advance the local current
  270. # position beyond the minimum stream ID in this list.
  271. self._in_flight_fetches: SortedList[int] = SortedList()
  272. # Set of local IDs that we've processed that are larger than the current
  273. # position, due to there being smaller unpersisted IDs.
  274. self._finished_ids: Set[int] = set()
  275. # We track the max position where we know everything before has been
  276. # persisted. This is done by a) looking at the min across all instances
  277. # and b) noting that if we have seen a run of persisted positions
  278. # without gaps (e.g. 5, 6, 7) then we can skip forward (e.g. to 7).
  279. #
  280. # Note: There is no guarantee that the IDs generated by the sequence
  281. # will be gapless; gaps can form when e.g. a transaction was rolled
  282. # back. This means that sometimes we won't be able to skip forward the
  283. # position even though everything has been persisted. However, since
  284. # gaps should be relatively rare it's still worth doing the book keeping
  285. # that allows us to skip forwards when there are gapless runs of
  286. # positions.
  287. #
  288. # We start at 1 here as a) the first generated stream ID will be 2, and
  289. # b) other parts of the code assume that stream IDs are strictly greater
  290. # than 0.
  291. self._persisted_upto_position = (
  292. min(self._current_positions.values()) if self._current_positions else 1
  293. )
  294. self._known_persisted_positions: List[int] = []
  295. # The maximum stream ID that we have seen been allocated across any writer.
  296. self._max_seen_allocated_stream_id = 1
  297. self._sequence_gen = PostgresSequenceGenerator(sequence_name)
  298. # We check that the table and sequence haven't diverged.
  299. for table, _, id_column in tables:
  300. self._sequence_gen.check_consistency(
  301. db_conn,
  302. table=table,
  303. id_column=id_column,
  304. stream_name=stream_name,
  305. positive=positive,
  306. )
  307. # This goes and fills out the above state from the database.
  308. self._load_current_ids(db_conn, tables)
  309. self._max_seen_allocated_stream_id = max(
  310. self._current_positions.values(), default=1
  311. )
  312. def _load_current_ids(
  313. self,
  314. db_conn: LoggingDatabaseConnection,
  315. tables: List[Tuple[str, str, str]],
  316. ) -> None:
  317. cur = db_conn.cursor(txn_name="_load_current_ids")
  318. # Load the current positions of all writers for the stream.
  319. if self._writers:
  320. # We delete any stale entries in the positions table. This is
  321. # important if we add back a writer after a long time; we want to
  322. # consider that a "new" writer, rather than using the old stale
  323. # entry here.
  324. sql = """
  325. DELETE FROM stream_positions
  326. WHERE
  327. stream_name = ?
  328. AND instance_name != ALL(?)
  329. """
  330. cur.execute(sql, (self._stream_name, self._writers))
  331. sql = """
  332. SELECT instance_name, stream_id FROM stream_positions
  333. WHERE stream_name = ?
  334. """
  335. cur.execute(sql, (self._stream_name,))
  336. self._current_positions = {
  337. instance: stream_id * self._return_factor
  338. for instance, stream_id in cur
  339. if instance in self._writers
  340. }
  341. # We set the `_persisted_upto_position` to be the minimum of all current
  342. # positions. If empty we use the max stream ID from the DB table.
  343. min_stream_id = min(self._current_positions.values(), default=None)
  344. if min_stream_id is None:
  345. # We add a GREATEST here to ensure that the result is always
  346. # positive. (This can be a problem for e.g. backfill streams where
  347. # the server has never backfilled).
  348. max_stream_id = 1
  349. for table, _, id_column in tables:
  350. sql = """
  351. SELECT GREATEST(COALESCE(%(agg)s(%(id)s), 1), 1)
  352. FROM %(table)s
  353. """ % {
  354. "id": id_column,
  355. "table": table,
  356. "agg": "MAX" if self._positive else "-MIN",
  357. }
  358. cur.execute(sql)
  359. result = cur.fetchone()
  360. assert result is not None
  361. (stream_id,) = result
  362. max_stream_id = max(max_stream_id, stream_id)
  363. self._persisted_upto_position = max_stream_id
  364. else:
  365. # If we have a min_stream_id then we pull out everything greater
  366. # than it from the DB so that we can prefill
  367. # `_known_persisted_positions` and get a more accurate
  368. # `_persisted_upto_position`.
  369. #
  370. # We also check if any of the later rows are from this instance, in
  371. # which case we use that for this instance's current position. This
  372. # is to handle the case where we didn't finish persisting to the
  373. # stream positions table before restart (or the stream position
  374. # table otherwise got out of date).
  375. self._persisted_upto_position = min_stream_id
  376. rows: List[Tuple[str, int]] = []
  377. for table, instance_column, id_column in tables:
  378. sql = """
  379. SELECT %(instance)s, %(id)s FROM %(table)s
  380. WHERE ? %(cmp)s %(id)s
  381. """ % {
  382. "id": id_column,
  383. "table": table,
  384. "instance": instance_column,
  385. "cmp": "<=" if self._positive else ">=",
  386. }
  387. cur.execute(sql, (min_stream_id * self._return_factor,))
  388. # Cast safety: this corresponds to the types returned by the query above.
  389. rows.extend(cast(Iterable[Tuple[str, int]], cur))
  390. # Sort so that we handle rows in order for each instance.
  391. rows.sort()
  392. with self._lock:
  393. for (
  394. instance,
  395. stream_id,
  396. ) in rows:
  397. stream_id = self._return_factor * stream_id
  398. self._add_persisted_position(stream_id)
  399. if instance == self._instance_name:
  400. self._current_positions[instance] = stream_id
  401. cur.close()
  402. def _load_next_id_txn(self, txn: Cursor) -> int:
  403. stream_ids = self._load_next_mult_id_txn(txn, 1)
  404. return stream_ids[0]
  405. def _load_next_mult_id_txn(self, txn: Cursor, n: int) -> List[int]:
  406. # We need to track that we've requested some more stream IDs, and what
  407. # the current max allocated stream ID is. This is to prevent a race
  408. # where we've been allocated stream IDs but they have not yet been added
  409. # to the `_unfinished_ids` set, allowing the current position to advance
  410. # past them.
  411. with self._lock:
  412. current_max = self._max_seen_allocated_stream_id
  413. self._in_flight_fetches.add(current_max)
  414. try:
  415. stream_ids = self._sequence_gen.get_next_mult_txn(txn, n)
  416. with self._lock:
  417. self._unfinished_ids.update(stream_ids)
  418. self._max_seen_allocated_stream_id = max(
  419. self._max_seen_allocated_stream_id, self._unfinished_ids[-1]
  420. )
  421. finally:
  422. with self._lock:
  423. self._in_flight_fetches.remove(current_max)
  424. return stream_ids
  425. def get_next(self) -> AsyncContextManager[int]:
  426. # If we have a list of instances that are allowed to write to this
  427. # stream, make sure we're in it.
  428. if self._writers and self._instance_name not in self._writers:
  429. raise Exception("Tried to allocate stream ID on non-writer")
  430. # Cast safety: the second argument to _MultiWriterCtxManager, multiple_ids,
  431. # controls the return type. If `None` or omitted, the context manager yields
  432. # a single integer stream_id; otherwise it yields a list of stream_ids.
  433. return cast(AsyncContextManager[int], _MultiWriterCtxManager(self))
  434. def get_next_mult(self, n: int) -> AsyncContextManager[List[int]]:
  435. # If we have a list of instances that are allowed to write to this
  436. # stream, make sure we're in it.
  437. if self._writers and self._instance_name not in self._writers:
  438. raise Exception("Tried to allocate stream ID on non-writer")
  439. # Cast safety: see get_next.
  440. return cast(AsyncContextManager[List[int]], _MultiWriterCtxManager(self, n))
  441. def get_next_txn(self, txn: LoggingTransaction) -> int:
  442. """
  443. Usage:
  444. stream_id = stream_id_gen.get_next(txn)
  445. # ... persist event ...
  446. """
  447. # If we have a list of instances that are allowed to write to this
  448. # stream, make sure we're in it.
  449. if self._writers and self._instance_name not in self._writers:
  450. raise Exception("Tried to allocate stream ID on non-writer")
  451. next_id = self._load_next_id_txn(txn)
  452. txn.call_after(self._mark_id_as_finished, next_id)
  453. txn.call_on_exception(self._mark_id_as_finished, next_id)
  454. # Update the `stream_positions` table with newly updated stream
  455. # ID (unless self._writers is not set in which case we don't
  456. # bother, as nothing will read it).
  457. #
  458. # We only do this on the success path so that the persisted current
  459. # position points to a persisted row with the correct instance name.
  460. if self._writers:
  461. txn.call_after(
  462. run_as_background_process,
  463. "MultiWriterIdGenerator._update_table",
  464. self._db.runInteraction,
  465. "MultiWriterIdGenerator._update_table",
  466. self._update_stream_positions_table_txn,
  467. )
  468. return self._return_factor * next_id
  469. def _mark_id_as_finished(self, next_id: int) -> None:
  470. """The ID has finished being processed so we should advance the
  471. current position if possible.
  472. """
  473. with self._lock:
  474. self._unfinished_ids.discard(next_id)
  475. self._finished_ids.add(next_id)
  476. new_cur: Optional[int] = None
  477. if self._unfinished_ids or self._in_flight_fetches:
  478. # If there are unfinished IDs then the new position will be the
  479. # largest finished ID strictly less than the minimum unfinished
  480. # ID.
  481. # The minimum unfinished ID needs to take account of both
  482. # `_unfinished_ids` and `_in_flight_fetches`.
  483. if self._unfinished_ids and self._in_flight_fetches:
  484. # `_in_flight_fetches` stores the maximum safe stream ID, so
  485. # we add one to make it equivalent to the minimum unsafe ID.
  486. min_unfinished = min(
  487. self._unfinished_ids[0], self._in_flight_fetches[0] + 1
  488. )
  489. elif self._in_flight_fetches:
  490. min_unfinished = self._in_flight_fetches[0] + 1
  491. else:
  492. min_unfinished = self._unfinished_ids[0]
  493. finished = set()
  494. for s in self._finished_ids:
  495. if s < min_unfinished:
  496. if new_cur is None or new_cur < s:
  497. new_cur = s
  498. else:
  499. finished.add(s)
  500. # We clear these out since they're now all less than the new
  501. # position.
  502. self._finished_ids = finished
  503. else:
  504. # There are no unfinished IDs so the new position is simply the
  505. # largest finished one.
  506. new_cur = max(self._finished_ids)
  507. # We clear these out since they're now all less than the new
  508. # position.
  509. self._finished_ids.clear()
  510. if new_cur:
  511. curr = self._current_positions.get(self._instance_name, 0)
  512. self._current_positions[self._instance_name] = max(curr, new_cur)
  513. self._add_persisted_position(next_id)
  514. def get_current_token(self) -> int:
  515. return self.get_persisted_upto_position()
  516. def get_current_token_for_writer(self, instance_name: str) -> int:
  517. # If we don't have an entry for the given instance name, we assume it's a
  518. # new writer.
  519. #
  520. # For new writers we assume their initial position to be the current
  521. # persisted up to position. This stops Synapse from doing a full table
  522. # scan when a new writer announces itself over replication.
  523. with self._lock:
  524. return self._return_factor * self._current_positions.get(
  525. instance_name, self._persisted_upto_position
  526. )
  527. def get_positions(self) -> Dict[str, int]:
  528. """Get a copy of the current positon map.
  529. Note that this won't necessarily include all configured writers if some
  530. writers haven't written anything yet.
  531. """
  532. with self._lock:
  533. return {
  534. name: self._return_factor * i
  535. for name, i in self._current_positions.items()
  536. }
  537. def advance(self, instance_name: str, new_id: int) -> None:
  538. new_id *= self._return_factor
  539. with self._lock:
  540. self._current_positions[instance_name] = max(
  541. new_id, self._current_positions.get(instance_name, 0)
  542. )
  543. self._max_seen_allocated_stream_id = max(
  544. self._max_seen_allocated_stream_id, new_id
  545. )
  546. self._add_persisted_position(new_id)
  547. def get_persisted_upto_position(self) -> int:
  548. """Get the max position where all previous positions have been
  549. persisted.
  550. Note: In the worst case scenario this will be equal to the minimum
  551. position across writers. This means that the returned position here can
  552. lag if one writer doesn't write very often.
  553. """
  554. with self._lock:
  555. return self._return_factor * self._persisted_upto_position
  556. def _add_persisted_position(self, new_id: int) -> None:
  557. """Record that we have persisted a position.
  558. This is used to keep the `_current_positions` up to date.
  559. """
  560. # We require that the lock is locked by caller
  561. assert self._lock.locked()
  562. heapq.heappush(self._known_persisted_positions, new_id)
  563. # If we're a writer and we don't have any active writes we update our
  564. # current position to the latest position seen. This allows the instance
  565. # to report a recent position when asked, rather than a potentially old
  566. # one (if this instance hasn't written anything for a while).
  567. our_current_position = self._current_positions.get(self._instance_name)
  568. if (
  569. our_current_position
  570. and not self._unfinished_ids
  571. and not self._in_flight_fetches
  572. ):
  573. self._current_positions[self._instance_name] = max(
  574. our_current_position, new_id
  575. )
  576. # We move the current min position up if the minimum current positions
  577. # of all instances is higher (since by definition all positions less
  578. # that that have been persisted).
  579. min_curr = min(self._current_positions.values(), default=0)
  580. self._persisted_upto_position = max(min_curr, self._persisted_upto_position)
  581. # We now iterate through the seen positions, discarding those that are
  582. # less than the current min positions, and incrementing the min position
  583. # if its exactly one greater.
  584. #
  585. # This is also where we discard items from `_known_persisted_positions`
  586. # (to ensure the list doesn't infinitely grow).
  587. while self._known_persisted_positions:
  588. if self._known_persisted_positions[0] <= self._persisted_upto_position:
  589. heapq.heappop(self._known_persisted_positions)
  590. elif (
  591. self._known_persisted_positions[0] == self._persisted_upto_position + 1
  592. ):
  593. heapq.heappop(self._known_persisted_positions)
  594. self._persisted_upto_position += 1
  595. else:
  596. # There was a gap in seen positions, so there is nothing more to
  597. # do.
  598. break
  599. def _update_stream_positions_table_txn(self, txn: Cursor) -> None:
  600. """Update the `stream_positions` table with newly persisted position."""
  601. if not self._writers:
  602. return
  603. # We upsert the value, ensuring on conflict that we always increase the
  604. # value (or decrease if stream goes backwards).
  605. sql = """
  606. INSERT INTO stream_positions (stream_name, instance_name, stream_id)
  607. VALUES (?, ?, ?)
  608. ON CONFLICT (stream_name, instance_name)
  609. DO UPDATE SET
  610. stream_id = %(agg)s(stream_positions.stream_id, EXCLUDED.stream_id)
  611. """ % {
  612. "agg": "GREATEST" if self._positive else "LEAST",
  613. }
  614. pos = (self.get_current_token_for_writer(self._instance_name),)
  615. txn.execute(sql, (self._stream_name, self._instance_name, pos))
  616. @attr.s(frozen=True, auto_attribs=True)
  617. class _AsyncCtxManagerWrapper(Generic[T]):
  618. """Helper class to convert a plain context manager to an async one.
  619. This is mainly useful if you have a plain context manager but the interface
  620. requires an async one.
  621. """
  622. inner: ContextManager[T]
  623. async def __aenter__(self) -> T:
  624. return self.inner.__enter__()
  625. async def __aexit__(
  626. self,
  627. exc_type: Optional[Type[BaseException]],
  628. exc: Optional[BaseException],
  629. tb: Optional[TracebackType],
  630. ) -> Optional[bool]:
  631. return self.inner.__exit__(exc_type, exc, tb)
  632. @attr.s(slots=True, auto_attribs=True)
  633. class _MultiWriterCtxManager:
  634. """Async context manager returned by MultiWriterIdGenerator"""
  635. id_gen: MultiWriterIdGenerator
  636. multiple_ids: Optional[int] = None
  637. stream_ids: List[int] = attr.Factory(list)
  638. async def __aenter__(self) -> Union[int, List[int]]:
  639. # It's safe to run this in autocommit mode as fetching values from a
  640. # sequence ignores transaction semantics anyway.
  641. self.stream_ids = await self.id_gen._db.runInteraction(
  642. "_load_next_mult_id",
  643. self.id_gen._load_next_mult_id_txn,
  644. self.multiple_ids or 1,
  645. db_autocommit=True,
  646. )
  647. if self.multiple_ids is None:
  648. return self.stream_ids[0] * self.id_gen._return_factor
  649. else:
  650. return [i * self.id_gen._return_factor for i in self.stream_ids]
  651. async def __aexit__(
  652. self,
  653. exc_type: Optional[Type[BaseException]],
  654. exc: Optional[BaseException],
  655. tb: Optional[TracebackType],
  656. ) -> bool:
  657. for i in self.stream_ids:
  658. self.id_gen._mark_id_as_finished(i)
  659. if exc_type is not None:
  660. return False
  661. # Update the `stream_positions` table with newly updated stream
  662. # ID (unless self._writers is not set in which case we don't
  663. # bother, as nothing will read it).
  664. #
  665. # We only do this on the success path so that the persisted current
  666. # position points to a persisted row with the correct instance name.
  667. #
  668. # We do this in autocommit mode as a) the upsert works correctly outside
  669. # transactions and b) reduces the amount of time the rows are locked
  670. # for. If we don't do this then we'll often hit serialization errors due
  671. # to the fact we default to REPEATABLE READ isolation levels.
  672. if self.id_gen._writers:
  673. await self.id_gen._db.runInteraction(
  674. "MultiWriterIdGenerator._update_table",
  675. self.id_gen._update_stream_positions_table_txn,
  676. db_autocommit=True,
  677. )
  678. return False