id_generators.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  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 heapq
  16. import logging
  17. import threading
  18. from collections import deque
  19. from contextlib import contextmanager
  20. from typing import Dict, List, Optional, Set, Union
  21. import attr
  22. from typing_extensions import Deque
  23. from synapse.metrics.background_process_metrics import run_as_background_process
  24. from synapse.storage.database import DatabasePool, LoggingTransaction
  25. from synapse.storage.types import Cursor
  26. from synapse.storage.util.sequence import PostgresSequenceGenerator
  27. logger = logging.getLogger(__name__)
  28. class IdGenerator:
  29. def __init__(self, db_conn, table, column):
  30. self._lock = threading.Lock()
  31. self._next_id = _load_current_id(db_conn, table, column)
  32. def get_next(self):
  33. with self._lock:
  34. self._next_id += 1
  35. return self._next_id
  36. def _load_current_id(db_conn, table, column, step=1):
  37. """
  38. Args:
  39. db_conn (object):
  40. table (str):
  41. column (str):
  42. step (int):
  43. Returns:
  44. int
  45. """
  46. # debug logging for https://github.com/matrix-org/synapse/issues/7968
  47. logger.info("initialising stream generator for %s(%s)", table, column)
  48. cur = db_conn.cursor(txn_name="_load_current_id")
  49. if step == 1:
  50. cur.execute("SELECT MAX(%s) FROM %s" % (column, table))
  51. else:
  52. cur.execute("SELECT MIN(%s) FROM %s" % (column, table))
  53. (val,) = cur.fetchone()
  54. cur.close()
  55. current_id = int(val) if val else step
  56. return (max if step > 0 else min)(current_id, step)
  57. class StreamIdGenerator:
  58. """Used to generate new stream ids when persisting events while keeping
  59. track of which transactions have been completed.
  60. This allows us to get the "current" stream id, i.e. the stream id such that
  61. all ids less than or equal to it have completed. This handles the fact that
  62. persistence of events can complete out of order.
  63. Args:
  64. db_conn(connection): A database connection to use to fetch the
  65. initial value of the generator from.
  66. table(str): A database table to read the initial value of the id
  67. generator from.
  68. column(str): The column of the database table to read the initial
  69. value from the id generator from.
  70. extra_tables(list): List of pairs of database tables and columns to
  71. use to source the initial value of the generator from. The value
  72. with the largest magnitude is used.
  73. step(int): which direction the stream ids grow in. +1 to grow
  74. upwards, -1 to grow downwards.
  75. Usage:
  76. async with stream_id_gen.get_next() as stream_id:
  77. # ... persist event ...
  78. """
  79. def __init__(self, db_conn, table, column, extra_tables=[], step=1):
  80. assert step != 0
  81. self._lock = threading.Lock()
  82. self._step = step
  83. self._current = _load_current_id(db_conn, table, column, step)
  84. for table, column in extra_tables:
  85. self._current = (max if step > 0 else min)(
  86. self._current, _load_current_id(db_conn, table, column, step)
  87. )
  88. self._unfinished_ids = deque() # type: Deque[int]
  89. def get_next(self):
  90. """
  91. Usage:
  92. async with stream_id_gen.get_next() as stream_id:
  93. # ... persist event ...
  94. """
  95. with self._lock:
  96. self._current += self._step
  97. next_id = self._current
  98. self._unfinished_ids.append(next_id)
  99. @contextmanager
  100. def manager():
  101. try:
  102. yield next_id
  103. finally:
  104. with self._lock:
  105. self._unfinished_ids.remove(next_id)
  106. return _AsyncCtxManagerWrapper(manager())
  107. def get_next_mult(self, n):
  108. """
  109. Usage:
  110. async with stream_id_gen.get_next(n) as stream_ids:
  111. # ... persist events ...
  112. """
  113. with self._lock:
  114. next_ids = range(
  115. self._current + self._step,
  116. self._current + self._step * (n + 1),
  117. self._step,
  118. )
  119. self._current += n * self._step
  120. for next_id in next_ids:
  121. self._unfinished_ids.append(next_id)
  122. @contextmanager
  123. def manager():
  124. try:
  125. yield next_ids
  126. finally:
  127. with self._lock:
  128. for next_id in next_ids:
  129. self._unfinished_ids.remove(next_id)
  130. return _AsyncCtxManagerWrapper(manager())
  131. def get_current_token(self) -> int:
  132. """Returns the maximum stream id such that all stream ids less than or
  133. equal to it have been successfully persisted.
  134. Returns:
  135. The maximum stream id.
  136. """
  137. with self._lock:
  138. if self._unfinished_ids:
  139. return self._unfinished_ids[0] - self._step
  140. return self._current
  141. def get_current_token_for_writer(self, instance_name: str) -> int:
  142. """Returns the position of the given writer.
  143. For streams with single writers this is equivalent to
  144. `get_current_token`.
  145. """
  146. return self.get_current_token()
  147. class MultiWriterIdGenerator:
  148. """An ID generator that tracks a stream that can have multiple writers.
  149. Uses a Postgres sequence to coordinate ID assignment, but positions of other
  150. writers will only get updated when `advance` is called (by replication).
  151. Note: Only works with Postgres.
  152. Args:
  153. db_conn
  154. db
  155. stream_name: A name for the stream.
  156. instance_name: The name of this instance.
  157. table: Database table associated with stream.
  158. instance_column: Column that stores the row's writer's instance name
  159. id_column: Column that stores the stream ID.
  160. sequence_name: The name of the postgres sequence used to generate new
  161. IDs.
  162. writers: A list of known writers to use to populate current positions
  163. on startup. Can be empty if nothing uses `get_current_token` or
  164. `get_positions` (e.g. caches stream).
  165. positive: Whether the IDs are positive (true) or negative (false).
  166. When using negative IDs we go backwards from -1 to -2, -3, etc.
  167. """
  168. def __init__(
  169. self,
  170. db_conn,
  171. db: DatabasePool,
  172. stream_name: str,
  173. instance_name: str,
  174. table: str,
  175. instance_column: str,
  176. id_column: str,
  177. sequence_name: str,
  178. writers: List[str],
  179. positive: bool = True,
  180. ):
  181. self._db = db
  182. self._stream_name = stream_name
  183. self._instance_name = instance_name
  184. self._positive = positive
  185. self._writers = writers
  186. self._return_factor = 1 if positive else -1
  187. # We lock as some functions may be called from DB threads.
  188. self._lock = threading.Lock()
  189. # Note: If we are a negative stream then we still store all the IDs as
  190. # positive to make life easier for us, and simply negate the IDs when we
  191. # return them.
  192. self._current_positions = {} # type: Dict[str, int]
  193. # Set of local IDs that we're still processing. The current position
  194. # should be less than the minimum of this set (if not empty).
  195. self._unfinished_ids = set() # type: Set[int]
  196. # Set of local IDs that we've processed that are larger than the current
  197. # position, due to there being smaller unpersisted IDs.
  198. self._finished_ids = set() # type: Set[int]
  199. # We track the max position where we know everything before has been
  200. # persisted. This is done by a) looking at the min across all instances
  201. # and b) noting that if we have seen a run of persisted positions
  202. # without gaps (e.g. 5, 6, 7) then we can skip forward (e.g. to 7).
  203. #
  204. # Note: There is no guarentee that the IDs generated by the sequence
  205. # will be gapless; gaps can form when e.g. a transaction was rolled
  206. # back. This means that sometimes we won't be able to skip forward the
  207. # position even though everything has been persisted. However, since
  208. # gaps should be relatively rare it's still worth doing the book keeping
  209. # that allows us to skip forwards when there are gapless runs of
  210. # positions.
  211. #
  212. # We start at 1 here as a) the first generated stream ID will be 2, and
  213. # b) other parts of the code assume that stream IDs are strictly greater
  214. # than 0.
  215. self._persisted_upto_position = (
  216. min(self._current_positions.values()) if self._current_positions else 1
  217. )
  218. self._known_persisted_positions = [] # type: List[int]
  219. self._sequence_gen = PostgresSequenceGenerator(sequence_name)
  220. # We check that the table and sequence haven't diverged.
  221. self._sequence_gen.check_consistency(
  222. db_conn, table=table, id_column=id_column, positive=positive
  223. )
  224. # This goes and fills out the above state from the database.
  225. self._load_current_ids(db_conn, table, instance_column, id_column)
  226. def _load_current_ids(
  227. self, db_conn, table: str, instance_column: str, id_column: str
  228. ):
  229. cur = db_conn.cursor(txn_name="_load_current_ids")
  230. # Load the current positions of all writers for the stream.
  231. if self._writers:
  232. # We delete any stale entries in the positions table. This is
  233. # important if we add back a writer after a long time; we want to
  234. # consider that a "new" writer, rather than using the old stale
  235. # entry here.
  236. sql = """
  237. DELETE FROM stream_positions
  238. WHERE
  239. stream_name = ?
  240. AND instance_name != ALL(?)
  241. """
  242. cur.execute(sql, (self._stream_name, self._writers))
  243. sql = """
  244. SELECT instance_name, stream_id FROM stream_positions
  245. WHERE stream_name = ?
  246. """
  247. cur.execute(sql, (self._stream_name,))
  248. self._current_positions = {
  249. instance: stream_id * self._return_factor
  250. for instance, stream_id in cur
  251. if instance in self._writers
  252. }
  253. # We set the `_persisted_upto_position` to be the minimum of all current
  254. # positions. If empty we use the max stream ID from the DB table.
  255. min_stream_id = min(self._current_positions.values(), default=None)
  256. if min_stream_id is None:
  257. # We add a GREATEST here to ensure that the result is always
  258. # positive. (This can be a problem for e.g. backfill streams where
  259. # the server has never backfilled).
  260. sql = """
  261. SELECT GREATEST(COALESCE(%(agg)s(%(id)s), 1), 1)
  262. FROM %(table)s
  263. """ % {
  264. "id": id_column,
  265. "table": table,
  266. "agg": "MAX" if self._positive else "-MIN",
  267. }
  268. cur.execute(sql)
  269. (stream_id,) = cur.fetchone()
  270. self._persisted_upto_position = stream_id
  271. else:
  272. # If we have a min_stream_id then we pull out everything greater
  273. # than it from the DB so that we can prefill
  274. # `_known_persisted_positions` and get a more accurate
  275. # `_persisted_upto_position`.
  276. #
  277. # We also check if any of the later rows are from this instance, in
  278. # which case we use that for this instance's current position. This
  279. # is to handle the case where we didn't finish persisting to the
  280. # stream positions table before restart (or the stream position
  281. # table otherwise got out of date).
  282. sql = """
  283. SELECT %(instance)s, %(id)s FROM %(table)s
  284. WHERE ? %(cmp)s %(id)s
  285. """ % {
  286. "id": id_column,
  287. "table": table,
  288. "instance": instance_column,
  289. "cmp": "<=" if self._positive else ">=",
  290. }
  291. cur.execute(sql, (min_stream_id * self._return_factor,))
  292. self._persisted_upto_position = min_stream_id
  293. with self._lock:
  294. for (instance, stream_id,) in cur:
  295. stream_id = self._return_factor * stream_id
  296. self._add_persisted_position(stream_id)
  297. if instance == self._instance_name:
  298. self._current_positions[instance] = stream_id
  299. cur.close()
  300. def _load_next_id_txn(self, txn) -> int:
  301. return self._sequence_gen.get_next_id_txn(txn)
  302. def _load_next_mult_id_txn(self, txn, n: int) -> List[int]:
  303. return self._sequence_gen.get_next_mult_txn(txn, n)
  304. def get_next(self):
  305. """
  306. Usage:
  307. async with stream_id_gen.get_next() as stream_id:
  308. # ... persist event ...
  309. """
  310. return _MultiWriterCtxManager(self)
  311. def get_next_mult(self, n: int):
  312. """
  313. Usage:
  314. async with stream_id_gen.get_next_mult(5) as stream_ids:
  315. # ... persist events ...
  316. """
  317. return _MultiWriterCtxManager(self, n)
  318. def get_next_txn(self, txn: LoggingTransaction):
  319. """
  320. Usage:
  321. stream_id = stream_id_gen.get_next(txn)
  322. # ... persist event ...
  323. """
  324. next_id = self._load_next_id_txn(txn)
  325. with self._lock:
  326. self._unfinished_ids.add(next_id)
  327. txn.call_after(self._mark_id_as_finished, next_id)
  328. txn.call_on_exception(self._mark_id_as_finished, next_id)
  329. # Update the `stream_positions` table with newly updated stream
  330. # ID (unless self._writers is not set in which case we don't
  331. # bother, as nothing will read it).
  332. #
  333. # We only do this on the success path so that the persisted current
  334. # position points to a persited row with the correct instance name.
  335. if self._writers:
  336. txn.call_after(
  337. run_as_background_process,
  338. "MultiWriterIdGenerator._update_table",
  339. self._db.runInteraction,
  340. "MultiWriterIdGenerator._update_table",
  341. self._update_stream_positions_table_txn,
  342. )
  343. return self._return_factor * next_id
  344. def _mark_id_as_finished(self, next_id: int):
  345. """The ID has finished being processed so we should advance the
  346. current position if possible.
  347. """
  348. with self._lock:
  349. self._unfinished_ids.discard(next_id)
  350. self._finished_ids.add(next_id)
  351. new_cur = None # type: Optional[int]
  352. if self._unfinished_ids:
  353. # If there are unfinished IDs then the new position will be the
  354. # largest finished ID less than the minimum unfinished ID.
  355. finished = set()
  356. min_unfinshed = min(self._unfinished_ids)
  357. for s in self._finished_ids:
  358. if s < min_unfinshed:
  359. if new_cur is None or new_cur < s:
  360. new_cur = s
  361. else:
  362. finished.add(s)
  363. # We clear these out since they're now all less than the new
  364. # position.
  365. self._finished_ids = finished
  366. else:
  367. # There are no unfinished IDs so the new position is simply the
  368. # largest finished one.
  369. new_cur = max(self._finished_ids)
  370. # We clear these out since they're now all less than the new
  371. # position.
  372. self._finished_ids.clear()
  373. if new_cur:
  374. curr = self._current_positions.get(self._instance_name, 0)
  375. self._current_positions[self._instance_name] = max(curr, new_cur)
  376. self._add_persisted_position(next_id)
  377. def get_current_token(self) -> int:
  378. """Returns the maximum stream id such that all stream ids less than or
  379. equal to it have been successfully persisted.
  380. """
  381. return self.get_persisted_upto_position()
  382. def get_current_token_for_writer(self, instance_name: str) -> int:
  383. """Returns the position of the given writer.
  384. """
  385. # If we don't have an entry for the given instance name, we assume it's a
  386. # new writer.
  387. #
  388. # For new writers we assume their initial position to be the current
  389. # persisted up to position. This stops Synapse from doing a full table
  390. # scan when a new writer announces itself over replication.
  391. with self._lock:
  392. return self._return_factor * self._current_positions.get(
  393. instance_name, self._persisted_upto_position
  394. )
  395. def get_positions(self) -> Dict[str, int]:
  396. """Get a copy of the current positon map.
  397. Note that this won't necessarily include all configured writers if some
  398. writers haven't written anything yet.
  399. """
  400. with self._lock:
  401. return {
  402. name: self._return_factor * i
  403. for name, i in self._current_positions.items()
  404. }
  405. def advance(self, instance_name: str, new_id: int):
  406. """Advance the postion of the named writer to the given ID, if greater
  407. than existing entry.
  408. """
  409. new_id *= self._return_factor
  410. with self._lock:
  411. self._current_positions[instance_name] = max(
  412. new_id, self._current_positions.get(instance_name, 0)
  413. )
  414. self._add_persisted_position(new_id)
  415. def get_persisted_upto_position(self) -> int:
  416. """Get the max position where all previous positions have been
  417. persisted.
  418. Note: In the worst case scenario this will be equal to the minimum
  419. position across writers. This means that the returned position here can
  420. lag if one writer doesn't write very often.
  421. """
  422. with self._lock:
  423. return self._return_factor * self._persisted_upto_position
  424. def _add_persisted_position(self, new_id: int):
  425. """Record that we have persisted a position.
  426. This is used to keep the `_current_positions` up to date.
  427. """
  428. # We require that the lock is locked by caller
  429. assert self._lock.locked()
  430. heapq.heappush(self._known_persisted_positions, new_id)
  431. # If we're a writer and we don't have any active writes we update our
  432. # current position to the latest position seen. This allows the instance
  433. # to report a recent position when asked, rather than a potentially old
  434. # one (if this instance hasn't written anything for a while).
  435. our_current_position = self._current_positions.get(self._instance_name)
  436. if our_current_position and not self._unfinished_ids:
  437. self._current_positions[self._instance_name] = max(
  438. our_current_position, new_id
  439. )
  440. # We move the current min position up if the minimum current positions
  441. # of all instances is higher (since by definition all positions less
  442. # that that have been persisted).
  443. min_curr = min(self._current_positions.values(), default=0)
  444. self._persisted_upto_position = max(min_curr, self._persisted_upto_position)
  445. # We now iterate through the seen positions, discarding those that are
  446. # less than the current min positions, and incrementing the min position
  447. # if its exactly one greater.
  448. #
  449. # This is also where we discard items from `_known_persisted_positions`
  450. # (to ensure the list doesn't infinitely grow).
  451. while self._known_persisted_positions:
  452. if self._known_persisted_positions[0] <= self._persisted_upto_position:
  453. heapq.heappop(self._known_persisted_positions)
  454. elif (
  455. self._known_persisted_positions[0] == self._persisted_upto_position + 1
  456. ):
  457. heapq.heappop(self._known_persisted_positions)
  458. self._persisted_upto_position += 1
  459. else:
  460. # There was a gap in seen positions, so there is nothing more to
  461. # do.
  462. break
  463. def _update_stream_positions_table_txn(self, txn: Cursor):
  464. """Update the `stream_positions` table with newly persisted position.
  465. """
  466. if not self._writers:
  467. return
  468. # We upsert the value, ensuring on conflict that we always increase the
  469. # value (or decrease if stream goes backwards).
  470. sql = """
  471. INSERT INTO stream_positions (stream_name, instance_name, stream_id)
  472. VALUES (?, ?, ?)
  473. ON CONFLICT (stream_name, instance_name)
  474. DO UPDATE SET
  475. stream_id = %(agg)s(stream_positions.stream_id, EXCLUDED.stream_id)
  476. """ % {
  477. "agg": "GREATEST" if self._positive else "LEAST",
  478. }
  479. pos = (self.get_current_token_for_writer(self._instance_name),)
  480. txn.execute(sql, (self._stream_name, self._instance_name, pos))
  481. @attr.s(slots=True)
  482. class _AsyncCtxManagerWrapper:
  483. """Helper class to convert a plain context manager to an async one.
  484. This is mainly useful if you have a plain context manager but the interface
  485. requires an async one.
  486. """
  487. inner = attr.ib()
  488. async def __aenter__(self):
  489. return self.inner.__enter__()
  490. async def __aexit__(self, exc_type, exc, tb):
  491. return self.inner.__exit__(exc_type, exc, tb)
  492. @attr.s(slots=True)
  493. class _MultiWriterCtxManager:
  494. """Async context manager returned by MultiWriterIdGenerator
  495. """
  496. id_gen = attr.ib(type=MultiWriterIdGenerator)
  497. multiple_ids = attr.ib(type=Optional[int], default=None)
  498. stream_ids = attr.ib(type=List[int], factory=list)
  499. async def __aenter__(self) -> Union[int, List[int]]:
  500. # It's safe to run this in autocommit mode as fetching values from a
  501. # sequence ignores transaction semantics anyway.
  502. self.stream_ids = await self.id_gen._db.runInteraction(
  503. "_load_next_mult_id",
  504. self.id_gen._load_next_mult_id_txn,
  505. self.multiple_ids or 1,
  506. db_autocommit=True,
  507. )
  508. with self.id_gen._lock:
  509. self.id_gen._unfinished_ids.update(self.stream_ids)
  510. if self.multiple_ids is None:
  511. return self.stream_ids[0] * self.id_gen._return_factor
  512. else:
  513. return [i * self.id_gen._return_factor for i in self.stream_ids]
  514. async def __aexit__(self, exc_type, exc, tb):
  515. for i in self.stream_ids:
  516. self.id_gen._mark_id_as_finished(i)
  517. if exc_type is not None:
  518. return False
  519. # Update the `stream_positions` table with newly updated stream
  520. # ID (unless self._writers is not set in which case we don't
  521. # bother, as nothing will read it).
  522. #
  523. # We only do this on the success path so that the persisted current
  524. # position points to a persisted row with the correct instance name.
  525. #
  526. # We do this in autocommit mode as a) the upsert works correctly outside
  527. # transactions and b) reduces the amount of time the rows are locked
  528. # for. If we don't do this then we'll often hit serialization errors due
  529. # to the fact we default to REPEATABLE READ isolation levels.
  530. if self.id_gen._writers:
  531. await self.id_gen._db.runInteraction(
  532. "MultiWriterIdGenerator._update_table",
  533. self.id_gen._update_stream_positions_table_txn,
  534. db_autocommit=True,
  535. )
  536. return False