id_generators.py 32 KB

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