2016-01-07 05:26:29 +01:00
|
|
|
# Copyright 2014-2016 OpenMarket Ltd
|
2021-11-11 14:47:31 +01:00
|
|
|
# Copyright 2021 The Matrix.org Foundation C.I.C.
|
2015-04-09 12:41:36 +02:00
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
2021-11-11 14:47:31 +01:00
|
|
|
import abc
|
2020-08-25 18:32:30 +02:00
|
|
|
import heapq
|
2020-09-07 14:36:02 +02:00
|
|
|
import logging
|
2015-04-09 12:41:36 +02:00
|
|
|
import threading
|
2021-01-21 17:31:51 +01:00
|
|
|
from collections import OrderedDict
|
2020-09-23 17:11:18 +02:00
|
|
|
from contextlib import contextmanager
|
2021-10-08 16:25:16 +02:00
|
|
|
from types import TracebackType
|
|
|
|
from typing import (
|
2023-01-20 19:02:18 +01:00
|
|
|
TYPE_CHECKING,
|
2021-10-08 16:25:16 +02:00
|
|
|
AsyncContextManager,
|
|
|
|
ContextManager,
|
|
|
|
Dict,
|
|
|
|
Generator,
|
|
|
|
Generic,
|
|
|
|
Iterable,
|
|
|
|
List,
|
|
|
|
Optional,
|
|
|
|
Sequence,
|
|
|
|
Set,
|
|
|
|
Tuple,
|
|
|
|
Type,
|
|
|
|
TypeVar,
|
|
|
|
Union,
|
|
|
|
cast,
|
|
|
|
)
|
2020-05-04 18:17:45 +02:00
|
|
|
|
2020-09-23 17:11:18 +02:00
|
|
|
import attr
|
2021-10-12 15:27:09 +02:00
|
|
|
from sortedcontainers import SortedList, SortedSet
|
2020-05-04 18:17:45 +02:00
|
|
|
|
2020-09-24 17:53:51 +02:00
|
|
|
from synapse.metrics.background_process_metrics import run_as_background_process
|
2021-10-08 16:25:16 +02:00
|
|
|
from synapse.storage.database import (
|
|
|
|
DatabasePool,
|
|
|
|
LoggingDatabaseConnection,
|
|
|
|
LoggingTransaction,
|
|
|
|
)
|
2020-10-07 16:15:57 +02:00
|
|
|
from synapse.storage.types import Cursor
|
2020-07-16 11:56:49 +02:00
|
|
|
from synapse.storage.util.sequence import PostgresSequenceGenerator
|
2015-04-09 12:41:36 +02:00
|
|
|
|
2023-01-20 19:02:18 +01:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
from synapse.notifier import ReplicationNotifier
|
|
|
|
|
2020-09-07 14:36:02 +02:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2015-04-09 12:41:36 +02:00
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
T = TypeVar("T")
|
|
|
|
|
|
|
|
|
2020-09-04 12:54:56 +02:00
|
|
|
class IdGenerator:
|
2021-10-08 16:25:16 +02:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
db_conn: LoggingDatabaseConnection,
|
|
|
|
table: str,
|
|
|
|
column: str,
|
|
|
|
):
|
2015-04-09 12:41:36 +02:00
|
|
|
self._lock = threading.Lock()
|
2016-04-01 14:29:05 +02:00
|
|
|
self._next_id = _load_current_id(db_conn, table, column)
|
2015-04-09 12:41:36 +02:00
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
def get_next(self) -> int:
|
2015-04-29 20:17:00 +02:00
|
|
|
with self._lock:
|
2015-04-09 12:41:36 +02:00
|
|
|
self._next_id += 1
|
2016-03-01 14:35:37 +01:00
|
|
|
return self._next_id
|
|
|
|
|
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
def _load_current_id(
|
|
|
|
db_conn: LoggingDatabaseConnection, table: str, column: str, step: int = 1
|
|
|
|
) -> int:
|
2020-10-02 16:20:45 +02:00
|
|
|
cur = db_conn.cursor(txn_name="_load_current_id")
|
2016-04-01 14:50:54 +02:00
|
|
|
if step == 1:
|
2019-04-03 11:07:29 +02:00
|
|
|
cur.execute("SELECT MAX(%s) FROM %s" % (column, table))
|
2016-04-01 14:29:05 +02:00
|
|
|
else:
|
2019-04-03 11:07:29 +02:00
|
|
|
cur.execute("SELECT MIN(%s) FROM %s" % (column, table))
|
2021-10-08 16:25:16 +02:00
|
|
|
result = cur.fetchone()
|
|
|
|
assert result is not None
|
|
|
|
(val,) = result
|
2016-03-01 14:35:37 +01:00
|
|
|
cur.close()
|
2016-04-01 14:50:54 +02:00
|
|
|
current_id = int(val) if val else step
|
2021-12-08 15:15:14 +01:00
|
|
|
res = (max if step > 0 else min)(current_id, step)
|
|
|
|
logger.info("Initialising stream generator for %s(%s): %i", table, column, res)
|
|
|
|
return res
|
2015-04-09 12:41:36 +02:00
|
|
|
|
|
|
|
|
2023-03-03 14:13:37 +01:00
|
|
|
class AbstractStreamIdGenerator(metaclass=abc.ABCMeta):
|
|
|
|
"""Generates or tracks stream IDs for a stream that may have multiple writers.
|
|
|
|
|
|
|
|
Each stream ID represents a write transaction, whose completion is tracked
|
|
|
|
so that the "current" stream ID of the stream can be determined.
|
2021-11-26 19:41:31 +01:00
|
|
|
|
|
|
|
Stream IDs are monotonically increasing or decreasing integers representing write
|
|
|
|
transactions. The "current" stream ID is the stream ID such that all transactions
|
|
|
|
with equal or smaller stream IDs have completed. Since transactions may complete out
|
|
|
|
of order, this is not the same as the stream ID of the last completed transaction.
|
|
|
|
|
|
|
|
Completed transactions include both committed transactions and transactions that
|
|
|
|
have been rolled back.
|
|
|
|
"""
|
2021-11-11 14:47:31 +01:00
|
|
|
|
|
|
|
@abc.abstractmethod
|
2021-11-26 19:41:31 +01:00
|
|
|
def advance(self, instance_name: str, new_id: int) -> None:
|
|
|
|
"""Advance the position of the named writer to the given ID, if greater
|
|
|
|
than existing entry.
|
|
|
|
"""
|
2021-11-11 14:47:31 +01:00
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
@abc.abstractmethod
|
|
|
|
def get_current_token(self) -> int:
|
2021-11-26 19:41:31 +01:00
|
|
|
"""Returns the maximum stream id such that all stream ids less than or
|
|
|
|
equal to it have been successfully persisted.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The maximum stream id.
|
|
|
|
"""
|
2021-11-11 14:47:31 +01:00
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
@abc.abstractmethod
|
|
|
|
def get_current_token_for_writer(self, instance_name: str) -> int:
|
2021-11-26 19:41:31 +01:00
|
|
|
"""Returns the position of the given writer.
|
|
|
|
|
|
|
|
For streams with single writers this is equivalent to `get_current_token`.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
@abc.abstractmethod
|
|
|
|
def get_next(self) -> AsyncContextManager[int]:
|
|
|
|
"""
|
|
|
|
Usage:
|
|
|
|
async with stream_id_gen.get_next() as stream_id:
|
|
|
|
# ... persist event ...
|
|
|
|
"""
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
@abc.abstractmethod
|
|
|
|
def get_next_mult(self, n: int) -> AsyncContextManager[Sequence[int]]:
|
|
|
|
"""
|
|
|
|
Usage:
|
|
|
|
async with stream_id_gen.get_next(n) as stream_ids:
|
|
|
|
# ... persist events ...
|
|
|
|
"""
|
2021-11-11 14:47:31 +01:00
|
|
|
raise NotImplementedError()
|
|
|
|
|
2023-03-02 19:27:00 +01:00
|
|
|
@abc.abstractmethod
|
|
|
|
def get_next_txn(self, txn: LoggingTransaction) -> int:
|
|
|
|
"""
|
|
|
|
Usage:
|
|
|
|
stream_id_gen.get_next_txn(txn)
|
|
|
|
# ... persist events ...
|
|
|
|
"""
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
2021-11-11 14:47:31 +01:00
|
|
|
|
|
|
|
class StreamIdGenerator(AbstractStreamIdGenerator):
|
2021-11-26 19:41:31 +01:00
|
|
|
"""Generates and tracks stream IDs for a stream with a single writer.
|
2015-04-09 12:41:36 +02:00
|
|
|
|
2021-11-26 19:41:31 +01:00
|
|
|
This class must only be used when the current Synapse process is the sole
|
|
|
|
writer for a stream.
|
2015-04-09 12:41:36 +02:00
|
|
|
|
2016-04-01 16:07:01 +02:00
|
|
|
Args:
|
|
|
|
db_conn(connection): A database connection to use to fetch the
|
|
|
|
initial value of the generator from.
|
|
|
|
table(str): A database table to read the initial value of the id
|
|
|
|
generator from.
|
|
|
|
column(str): The column of the database table to read the initial
|
|
|
|
value from the id generator from.
|
|
|
|
extra_tables(list): List of pairs of database tables and columns to
|
|
|
|
use to source the initial value of the generator from. The value
|
|
|
|
with the largest magnitude is used.
|
|
|
|
step(int): which direction the stream ids grow in. +1 to grow
|
|
|
|
upwards, -1 to grow downwards.
|
2016-04-01 14:29:05 +02:00
|
|
|
|
2015-04-09 12:41:36 +02:00
|
|
|
Usage:
|
2020-09-23 17:11:18 +02:00
|
|
|
async with stream_id_gen.get_next() as stream_id:
|
2015-04-09 12:41:36 +02:00
|
|
|
# ... persist event ...
|
|
|
|
"""
|
2019-04-03 11:07:29 +02:00
|
|
|
|
2021-04-08 23:38:54 +02:00
|
|
|
def __init__(
|
|
|
|
self,
|
2021-10-08 16:25:16 +02:00
|
|
|
db_conn: LoggingDatabaseConnection,
|
2023-01-20 19:02:18 +01:00
|
|
|
notifier: "ReplicationNotifier",
|
2021-10-08 16:25:16 +02:00
|
|
|
table: str,
|
|
|
|
column: str,
|
2021-04-08 23:38:54 +02:00
|
|
|
extra_tables: Iterable[Tuple[str, str]] = (),
|
2021-10-08 16:25:16 +02:00
|
|
|
step: int = 1,
|
2022-11-16 23:16:46 +01:00
|
|
|
is_writer: bool = True,
|
2021-10-08 16:25:16 +02:00
|
|
|
) -> None:
|
2016-04-01 16:08:20 +02:00
|
|
|
assert step != 0
|
2015-04-09 12:41:36 +02:00
|
|
|
self._lock = threading.Lock()
|
2021-10-08 16:25:16 +02:00
|
|
|
self._step: int = step
|
|
|
|
self._current: int = _load_current_id(db_conn, table, column, step)
|
2022-11-16 23:16:46 +01:00
|
|
|
self._is_writer = is_writer
|
2016-03-15 18:01:43 +01:00
|
|
|
for table, column in extra_tables:
|
2016-04-01 14:50:54 +02:00
|
|
|
self._current = (max if step > 0 else min)(
|
2019-04-03 11:07:29 +02:00
|
|
|
self._current, _load_current_id(db_conn, table, column, step)
|
2016-03-15 18:01:43 +01:00
|
|
|
)
|
2021-01-21 17:31:51 +01:00
|
|
|
|
|
|
|
# We use this as an ordered set, as we want to efficiently append items,
|
|
|
|
# remove items and get the first item. Since we insert IDs in order, the
|
|
|
|
# insertion ordering will ensure its in the correct ordering.
|
|
|
|
#
|
|
|
|
# The key and values are the same, but we never look at the values.
|
2021-07-15 18:46:54 +02:00
|
|
|
self._unfinished_ids: OrderedDict[int, int] = OrderedDict()
|
2015-04-09 12:41:36 +02:00
|
|
|
|
2023-01-20 19:02:18 +01:00
|
|
|
self._notifier = notifier
|
|
|
|
|
2021-11-26 19:41:31 +01:00
|
|
|
def advance(self, instance_name: str, new_id: int) -> None:
|
2022-11-16 23:16:46 +01:00
|
|
|
# Advance should never be called on a writer instance, only over replication
|
|
|
|
if self._is_writer:
|
|
|
|
raise Exception("Replication is not supported by writer StreamIdGenerator")
|
|
|
|
|
|
|
|
self._current = (max if self._step > 0 else min)(self._current, new_id)
|
2021-11-26 19:41:31 +01:00
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
def get_next(self) -> AsyncContextManager[int]:
|
2015-04-29 20:15:23 +02:00
|
|
|
with self._lock:
|
2016-04-01 14:50:54 +02:00
|
|
|
self._current += self._step
|
2016-04-01 14:29:05 +02:00
|
|
|
next_id = self._current
|
2015-04-09 12:41:36 +02:00
|
|
|
|
2021-01-21 17:31:51 +01:00
|
|
|
self._unfinished_ids[next_id] = next_id
|
2015-04-09 12:41:36 +02:00
|
|
|
|
2020-09-23 17:11:18 +02:00
|
|
|
@contextmanager
|
2021-10-08 16:25:16 +02:00
|
|
|
def manager() -> Generator[int, None, None]:
|
2015-04-15 11:25:43 +02:00
|
|
|
try:
|
|
|
|
yield next_id
|
|
|
|
finally:
|
|
|
|
with self._lock:
|
2021-01-21 17:31:51 +01:00
|
|
|
self._unfinished_ids.pop(next_id)
|
2015-04-09 12:41:36 +02:00
|
|
|
|
2023-01-20 19:02:18 +01:00
|
|
|
self._notifier.notify_replication()
|
|
|
|
|
2020-09-23 17:11:18 +02:00
|
|
|
return _AsyncCtxManagerWrapper(manager())
|
2015-04-09 12:41:36 +02:00
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
def get_next_mult(self, n: int) -> AsyncContextManager[Sequence[int]]:
|
2015-06-25 18:18:19 +02:00
|
|
|
with self._lock:
|
2016-04-01 14:29:05 +02:00
|
|
|
next_ids = range(
|
2016-04-01 14:50:54 +02:00
|
|
|
self._current + self._step,
|
|
|
|
self._current + self._step * (n + 1),
|
2019-04-03 11:07:29 +02:00
|
|
|
self._step,
|
2016-04-01 14:29:05 +02:00
|
|
|
)
|
2016-04-07 17:26:52 +02:00
|
|
|
self._current += n * self._step
|
2015-06-25 18:18:19 +02:00
|
|
|
|
|
|
|
for next_id in next_ids:
|
2021-01-21 17:31:51 +01:00
|
|
|
self._unfinished_ids[next_id] = next_id
|
2015-06-25 18:18:19 +02:00
|
|
|
|
2020-09-23 17:11:18 +02:00
|
|
|
@contextmanager
|
2021-10-08 16:25:16 +02:00
|
|
|
def manager() -> Generator[Sequence[int], None, None]:
|
2015-06-25 18:18:19 +02:00
|
|
|
try:
|
|
|
|
yield next_ids
|
|
|
|
finally:
|
|
|
|
with self._lock:
|
|
|
|
for next_id in next_ids:
|
2021-01-21 17:31:51 +01:00
|
|
|
self._unfinished_ids.pop(next_id)
|
2015-06-25 18:18:19 +02:00
|
|
|
|
2023-01-20 19:02:18 +01:00
|
|
|
self._notifier.notify_replication()
|
|
|
|
|
2020-09-23 17:11:18 +02:00
|
|
|
return _AsyncCtxManagerWrapper(manager())
|
2015-06-25 18:18:19 +02:00
|
|
|
|
2023-03-02 19:27:00 +01:00
|
|
|
def get_next_txn(self, txn: LoggingTransaction) -> int:
|
|
|
|
"""
|
|
|
|
Retrieve the next stream ID from within a database transaction.
|
|
|
|
|
|
|
|
Clean-up functions will be called when the transaction finishes.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
txn: The database transaction object.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The next stream ID.
|
|
|
|
"""
|
|
|
|
if not self._is_writer:
|
|
|
|
raise Exception("Tried to allocate stream ID on non-writer")
|
|
|
|
|
|
|
|
# Get the next stream ID.
|
|
|
|
with self._lock:
|
|
|
|
self._current += self._step
|
|
|
|
next_id = self._current
|
|
|
|
|
|
|
|
self._unfinished_ids[next_id] = next_id
|
|
|
|
|
|
|
|
def clear_unfinished_id(id_to_clear: int) -> None:
|
|
|
|
"""A function to mark processing this ID as finished"""
|
|
|
|
with self._lock:
|
|
|
|
self._unfinished_ids.pop(id_to_clear)
|
|
|
|
|
|
|
|
# Mark this ID as finished once the database transaction itself finishes.
|
|
|
|
txn.call_after(clear_unfinished_id, next_id)
|
|
|
|
txn.call_on_exception(clear_unfinished_id, next_id)
|
|
|
|
|
|
|
|
# Return the new ID.
|
|
|
|
return next_id
|
|
|
|
|
2020-12-16 17:25:30 +01:00
|
|
|
def get_current_token(self) -> int:
|
2022-11-16 23:16:46 +01:00
|
|
|
if not self._is_writer:
|
|
|
|
return self._current
|
|
|
|
|
2015-04-09 12:41:36 +02:00
|
|
|
with self._lock:
|
|
|
|
if self._unfinished_ids:
|
2021-01-21 17:31:51 +01:00
|
|
|
return next(iter(self._unfinished_ids)) - self._step
|
2015-04-09 12:41:36 +02:00
|
|
|
|
2016-04-01 14:29:05 +02:00
|
|
|
return self._current
|
2016-03-01 14:35:37 +01:00
|
|
|
|
2020-08-19 11:39:31 +02:00
|
|
|
def get_current_token_for_writer(self, instance_name: str) -> int:
|
|
|
|
return self.get_current_token()
|
|
|
|
|
2016-03-01 14:35:37 +01:00
|
|
|
|
2021-11-11 14:47:31 +01:00
|
|
|
class MultiWriterIdGenerator(AbstractStreamIdGenerator):
|
2021-11-26 19:41:31 +01:00
|
|
|
"""Generates and tracks stream IDs for a stream with multiple writers.
|
2020-05-04 18:17:45 +02:00
|
|
|
|
|
|
|
Uses a Postgres sequence to coordinate ID assignment, but positions of other
|
|
|
|
writers will only get updated when `advance` is called (by replication).
|
|
|
|
|
|
|
|
Note: Only works with Postgres.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
db_conn
|
|
|
|
db
|
2021-01-18 16:47:59 +01:00
|
|
|
stream_name: A name for the stream, for use in the `stream_positions`
|
|
|
|
table. (Does not need to be the same as the replication stream name)
|
2020-05-04 18:17:45 +02:00
|
|
|
instance_name: The name of this instance.
|
2021-01-18 16:47:59 +01:00
|
|
|
tables: List of tables associated with the stream. Tuple of table
|
|
|
|
name, column name that stores the writer's instance name, and
|
|
|
|
column name that stores the stream ID.
|
2020-05-04 18:17:45 +02:00
|
|
|
sequence_name: The name of the postgres sequence used to generate new
|
|
|
|
IDs.
|
2020-09-24 17:53:51 +02:00
|
|
|
writers: A list of known writers to use to populate current positions
|
|
|
|
on startup. Can be empty if nothing uses `get_current_token` or
|
|
|
|
`get_positions` (e.g. caches stream).
|
2020-09-01 14:36:25 +02:00
|
|
|
positive: Whether the IDs are positive (true) or negative (false).
|
|
|
|
When using negative IDs we go backwards from -1 to -2, -3, etc.
|
2020-05-04 18:17:45 +02:00
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
2021-10-08 16:25:16 +02:00
|
|
|
db_conn: LoggingDatabaseConnection,
|
2020-08-05 22:38:57 +02:00
|
|
|
db: DatabasePool,
|
2023-01-20 19:02:18 +01:00
|
|
|
notifier: "ReplicationNotifier",
|
2020-09-24 17:53:51 +02:00
|
|
|
stream_name: str,
|
2020-05-04 18:17:45 +02:00
|
|
|
instance_name: str,
|
2021-01-18 16:47:59 +01:00
|
|
|
tables: List[Tuple[str, str, str]],
|
2020-05-04 18:17:45 +02:00
|
|
|
sequence_name: str,
|
2020-09-24 17:53:51 +02:00
|
|
|
writers: List[str],
|
2020-09-01 14:36:25 +02:00
|
|
|
positive: bool = True,
|
2021-10-08 16:25:16 +02:00
|
|
|
) -> None:
|
2020-05-04 18:17:45 +02:00
|
|
|
self._db = db
|
2023-01-20 19:02:18 +01:00
|
|
|
self._notifier = notifier
|
2020-09-24 17:53:51 +02:00
|
|
|
self._stream_name = stream_name
|
2020-05-04 18:17:45 +02:00
|
|
|
self._instance_name = instance_name
|
2020-09-01 14:36:25 +02:00
|
|
|
self._positive = positive
|
2020-09-24 17:53:51 +02:00
|
|
|
self._writers = writers
|
2020-09-01 14:36:25 +02:00
|
|
|
self._return_factor = 1 if positive else -1
|
2020-05-04 18:17:45 +02:00
|
|
|
|
|
|
|
# We lock as some functions may be called from DB threads.
|
|
|
|
self._lock = threading.Lock()
|
|
|
|
|
2020-09-01 14:36:25 +02:00
|
|
|
# Note: If we are a negative stream then we still store all the IDs as
|
|
|
|
# positive to make life easier for us, and simply negate the IDs when we
|
|
|
|
# return them.
|
2021-07-15 18:46:54 +02:00
|
|
|
self._current_positions: Dict[str, int] = {}
|
2020-05-04 18:17:45 +02:00
|
|
|
|
|
|
|
# Set of local IDs that we're still processing. The current position
|
|
|
|
# should be less than the minimum of this set (if not empty).
|
2021-09-03 19:23:46 +02:00
|
|
|
self._unfinished_ids: SortedSet[int] = SortedSet()
|
2020-05-04 18:17:45 +02:00
|
|
|
|
2021-10-12 15:27:09 +02:00
|
|
|
# We also need to track when we've requested some new stream IDs but
|
|
|
|
# they haven't yet been added to the `_unfinished_ids` set. Every time
|
|
|
|
# we request a new stream ID we add the current max stream ID to the
|
|
|
|
# list, and remove it once we've added the newly allocated IDs to the
|
|
|
|
# `_unfinished_ids` set. This means that we *may* be allocated stream
|
|
|
|
# IDs above those in the list, and so we can't advance the local current
|
|
|
|
# position beyond the minimum stream ID in this list.
|
|
|
|
self._in_flight_fetches: SortedList[int] = SortedList()
|
|
|
|
|
2020-09-08 15:26:54 +02:00
|
|
|
# Set of local IDs that we've processed that are larger than the current
|
|
|
|
# position, due to there being smaller unpersisted IDs.
|
2021-07-15 18:46:54 +02:00
|
|
|
self._finished_ids: Set[int] = set()
|
2020-09-08 15:26:54 +02:00
|
|
|
|
2020-08-25 18:32:30 +02:00
|
|
|
# We track the max position where we know everything before has been
|
|
|
|
# persisted. This is done by a) looking at the min across all instances
|
|
|
|
# and b) noting that if we have seen a run of persisted positions
|
|
|
|
# without gaps (e.g. 5, 6, 7) then we can skip forward (e.g. to 7).
|
|
|
|
#
|
2021-02-12 17:01:48 +01:00
|
|
|
# Note: There is no guarantee that the IDs generated by the sequence
|
2020-08-25 18:32:30 +02:00
|
|
|
# will be gapless; gaps can form when e.g. a transaction was rolled
|
|
|
|
# back. This means that sometimes we won't be able to skip forward the
|
|
|
|
# position even though everything has been persisted. However, since
|
|
|
|
# gaps should be relatively rare it's still worth doing the book keeping
|
|
|
|
# that allows us to skip forwards when there are gapless runs of
|
|
|
|
# positions.
|
2020-09-14 11:16:41 +02:00
|
|
|
#
|
|
|
|
# We start at 1 here as a) the first generated stream ID will be 2, and
|
|
|
|
# b) other parts of the code assume that stream IDs are strictly greater
|
|
|
|
# than 0.
|
2020-08-25 18:32:30 +02:00
|
|
|
self._persisted_upto_position = (
|
2020-09-14 11:16:41 +02:00
|
|
|
min(self._current_positions.values()) if self._current_positions else 1
|
2020-08-25 18:32:30 +02:00
|
|
|
)
|
2021-07-15 18:46:54 +02:00
|
|
|
self._known_persisted_positions: List[int] = []
|
2020-08-25 18:32:30 +02:00
|
|
|
|
2021-10-12 15:27:09 +02:00
|
|
|
# The maximum stream ID that we have seen been allocated across any writer.
|
|
|
|
self._max_seen_allocated_stream_id = 1
|
|
|
|
|
2020-07-16 11:56:49 +02:00
|
|
|
self._sequence_gen = PostgresSequenceGenerator(sequence_name)
|
|
|
|
|
2020-09-28 19:00:30 +02:00
|
|
|
# We check that the table and sequence haven't diverged.
|
2021-01-18 16:47:59 +01:00
|
|
|
for table, _, id_column in tables:
|
|
|
|
self._sequence_gen.check_consistency(
|
2021-01-21 16:09:09 +01:00
|
|
|
db_conn,
|
|
|
|
table=table,
|
|
|
|
id_column=id_column,
|
|
|
|
stream_name=stream_name,
|
|
|
|
positive=positive,
|
2021-01-18 16:47:59 +01:00
|
|
|
)
|
2020-09-28 19:00:30 +02:00
|
|
|
|
2020-09-24 17:53:51 +02:00
|
|
|
# This goes and fills out the above state from the database.
|
2021-01-18 16:47:59 +01:00
|
|
|
self._load_current_ids(db_conn, tables)
|
2020-09-24 17:53:51 +02:00
|
|
|
|
2021-10-12 15:27:09 +02:00
|
|
|
self._max_seen_allocated_stream_id = max(
|
|
|
|
self._current_positions.values(), default=1
|
|
|
|
)
|
|
|
|
|
2023-01-18 20:35:29 +01:00
|
|
|
if not writers:
|
|
|
|
# If there have been no explicit writers given then any instance can
|
|
|
|
# write to the stream. In which case, let's pre-seed our own
|
|
|
|
# position with the current minimum.
|
|
|
|
self._current_positions[self._instance_name] = self._persisted_upto_position
|
|
|
|
|
2020-05-04 18:17:45 +02:00
|
|
|
def _load_current_ids(
|
2021-02-16 23:32:34 +01:00
|
|
|
self,
|
2021-10-08 16:25:16 +02:00
|
|
|
db_conn: LoggingDatabaseConnection,
|
2021-02-16 23:32:34 +01:00
|
|
|
tables: List[Tuple[str, str, str]],
|
2021-10-08 16:25:16 +02:00
|
|
|
) -> None:
|
2020-10-02 16:20:45 +02:00
|
|
|
cur = db_conn.cursor(txn_name="_load_current_ids")
|
2020-05-04 18:17:45 +02:00
|
|
|
|
2020-09-24 17:53:51 +02:00
|
|
|
# Load the current positions of all writers for the stream.
|
|
|
|
if self._writers:
|
2020-09-29 17:42:19 +02:00
|
|
|
# We delete any stale entries in the positions table. This is
|
|
|
|
# important if we add back a writer after a long time; we want to
|
|
|
|
# consider that a "new" writer, rather than using the old stale
|
|
|
|
# entry here.
|
|
|
|
sql = """
|
|
|
|
DELETE FROM stream_positions
|
|
|
|
WHERE
|
|
|
|
stream_name = ?
|
|
|
|
AND instance_name != ALL(?)
|
|
|
|
"""
|
|
|
|
cur.execute(sql, (self._stream_name, self._writers))
|
|
|
|
|
2020-09-24 17:53:51 +02:00
|
|
|
sql = """
|
|
|
|
SELECT instance_name, stream_id FROM stream_positions
|
|
|
|
WHERE stream_name = ?
|
|
|
|
"""
|
|
|
|
cur.execute(sql, (self._stream_name,))
|
|
|
|
|
|
|
|
self._current_positions = {
|
|
|
|
instance: stream_id * self._return_factor
|
|
|
|
for instance, stream_id in cur
|
|
|
|
if instance in self._writers
|
|
|
|
}
|
|
|
|
|
|
|
|
# We set the `_persisted_upto_position` to be the minimum of all current
|
|
|
|
# positions. If empty we use the max stream ID from the DB table.
|
|
|
|
min_stream_id = min(self._current_positions.values(), default=None)
|
|
|
|
|
|
|
|
if min_stream_id is None:
|
2020-09-25 10:58:32 +02:00
|
|
|
# We add a GREATEST here to ensure that the result is always
|
|
|
|
# positive. (This can be a problem for e.g. backfill streams where
|
|
|
|
# the server has never backfilled).
|
2021-01-18 16:47:59 +01:00
|
|
|
max_stream_id = 1
|
|
|
|
for table, _, id_column in tables:
|
|
|
|
sql = """
|
|
|
|
SELECT GREATEST(COALESCE(%(agg)s(%(id)s), 1), 1)
|
|
|
|
FROM %(table)s
|
|
|
|
""" % {
|
|
|
|
"id": id_column,
|
|
|
|
"table": table,
|
|
|
|
"agg": "MAX" if self._positive else "-MIN",
|
|
|
|
}
|
|
|
|
cur.execute(sql)
|
2021-10-08 16:25:16 +02:00
|
|
|
result = cur.fetchone()
|
|
|
|
assert result is not None
|
|
|
|
(stream_id,) = result
|
2021-01-18 16:47:59 +01:00
|
|
|
|
|
|
|
max_stream_id = max(max_stream_id, stream_id)
|
|
|
|
|
|
|
|
self._persisted_upto_position = max_stream_id
|
2020-09-24 17:53:51 +02:00
|
|
|
else:
|
|
|
|
# If we have a min_stream_id then we pull out everything greater
|
|
|
|
# than it from the DB so that we can prefill
|
|
|
|
# `_known_persisted_positions` and get a more accurate
|
|
|
|
# `_persisted_upto_position`.
|
|
|
|
#
|
|
|
|
# We also check if any of the later rows are from this instance, in
|
|
|
|
# which case we use that for this instance's current position. This
|
|
|
|
# is to handle the case where we didn't finish persisting to the
|
|
|
|
# stream positions table before restart (or the stream position
|
|
|
|
# table otherwise got out of date).
|
|
|
|
|
|
|
|
self._persisted_upto_position = min_stream_id
|
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
rows: List[Tuple[str, int]] = []
|
2021-01-18 16:47:59 +01:00
|
|
|
for table, instance_column, id_column in tables:
|
|
|
|
sql = """
|
|
|
|
SELECT %(instance)s, %(id)s FROM %(table)s
|
|
|
|
WHERE ? %(cmp)s %(id)s
|
|
|
|
""" % {
|
|
|
|
"id": id_column,
|
|
|
|
"table": table,
|
|
|
|
"instance": instance_column,
|
|
|
|
"cmp": "<=" if self._positive else ">=",
|
|
|
|
}
|
|
|
|
cur.execute(sql, (min_stream_id * self._return_factor,))
|
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
# Cast safety: this corresponds to the types returned by the query above.
|
|
|
|
rows.extend(cast(Iterable[Tuple[str, int]], cur))
|
2021-01-18 16:47:59 +01:00
|
|
|
|
2022-08-24 19:53:46 +02:00
|
|
|
# Sort by stream_id (ascending, lowest -> highest) so that we handle
|
|
|
|
# rows in order for each instance because we don't want to overwrite
|
|
|
|
# the current_position of an instance to a lower stream ID than
|
|
|
|
# we're actually at.
|
|
|
|
def sort_by_stream_id_key_func(row: Tuple[str, int]) -> int:
|
|
|
|
(instance, stream_id) = row
|
|
|
|
# If `stream_id` is ever `None`, we will see a `TypeError: '<'
|
|
|
|
# not supported between instances of 'NoneType' and 'X'` error.
|
|
|
|
return stream_id
|
|
|
|
|
|
|
|
rows.sort(key=sort_by_stream_id_key_func)
|
2021-01-18 16:47:59 +01:00
|
|
|
|
2020-09-24 17:53:51 +02:00
|
|
|
with self._lock:
|
2021-02-16 23:32:34 +01:00
|
|
|
for (
|
|
|
|
instance,
|
|
|
|
stream_id,
|
|
|
|
) in rows:
|
2020-09-24 17:53:51 +02:00
|
|
|
stream_id = self._return_factor * stream_id
|
|
|
|
self._add_persisted_position(stream_id)
|
2020-05-04 18:17:45 +02:00
|
|
|
|
2020-09-24 17:53:51 +02:00
|
|
|
if instance == self._instance_name:
|
|
|
|
self._current_positions[instance] = stream_id
|
|
|
|
|
|
|
|
cur.close()
|
2020-05-04 18:17:45 +02:00
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
def _load_next_id_txn(self, txn: Cursor) -> int:
|
2021-10-12 15:27:09 +02:00
|
|
|
stream_ids = self._load_next_mult_id_txn(txn, 1)
|
|
|
|
return stream_ids[0]
|
2020-05-04 18:17:45 +02:00
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
def _load_next_mult_id_txn(self, txn: Cursor, n: int) -> List[int]:
|
2021-10-12 15:27:09 +02:00
|
|
|
# We need to track that we've requested some more stream IDs, and what
|
|
|
|
# the current max allocated stream ID is. This is to prevent a race
|
|
|
|
# where we've been allocated stream IDs but they have not yet been added
|
|
|
|
# to the `_unfinished_ids` set, allowing the current position to advance
|
|
|
|
# past them.
|
|
|
|
with self._lock:
|
|
|
|
current_max = self._max_seen_allocated_stream_id
|
|
|
|
self._in_flight_fetches.add(current_max)
|
|
|
|
|
|
|
|
try:
|
|
|
|
stream_ids = self._sequence_gen.get_next_mult_txn(txn, n)
|
|
|
|
|
|
|
|
with self._lock:
|
|
|
|
self._unfinished_ids.update(stream_ids)
|
|
|
|
self._max_seen_allocated_stream_id = max(
|
|
|
|
self._max_seen_allocated_stream_id, self._unfinished_ids[-1]
|
|
|
|
)
|
|
|
|
finally:
|
|
|
|
with self._lock:
|
|
|
|
self._in_flight_fetches.remove(current_max)
|
|
|
|
|
|
|
|
return stream_ids
|
2020-08-25 18:32:30 +02:00
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
def get_next(self) -> AsyncContextManager[int]:
|
2021-06-11 11:27:12 +02:00
|
|
|
# If we have a list of instances that are allowed to write to this
|
|
|
|
# stream, make sure we're in it.
|
|
|
|
if self._writers and self._instance_name not in self._writers:
|
|
|
|
raise Exception("Tried to allocate stream ID on non-writer")
|
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
# Cast safety: the second argument to _MultiWriterCtxManager, multiple_ids,
|
|
|
|
# controls the return type. If `None` or omitted, the context manager yields
|
|
|
|
# a single integer stream_id; otherwise it yields a list of stream_ids.
|
2023-01-20 19:02:18 +01:00
|
|
|
return cast(
|
|
|
|
AsyncContextManager[int], _MultiWriterCtxManager(self, self._notifier)
|
|
|
|
)
|
2020-05-04 18:17:45 +02:00
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
def get_next_mult(self, n: int) -> AsyncContextManager[List[int]]:
|
2021-06-11 11:27:12 +02:00
|
|
|
# If we have a list of instances that are allowed to write to this
|
|
|
|
# stream, make sure we're in it.
|
|
|
|
if self._writers and self._instance_name not in self._writers:
|
|
|
|
raise Exception("Tried to allocate stream ID on non-writer")
|
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
# Cast safety: see get_next.
|
2023-01-20 19:02:18 +01:00
|
|
|
return cast(
|
|
|
|
AsyncContextManager[List[int]],
|
|
|
|
_MultiWriterCtxManager(self, self._notifier, n),
|
|
|
|
)
|
2020-08-25 18:32:30 +02:00
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
def get_next_txn(self, txn: LoggingTransaction) -> int:
|
2020-05-04 18:17:45 +02:00
|
|
|
"""
|
|
|
|
Usage:
|
|
|
|
|
2023-03-02 19:27:00 +01:00
|
|
|
stream_id = stream_id_gen.get_next_txn(txn)
|
2020-05-04 18:17:45 +02:00
|
|
|
# ... persist event ...
|
|
|
|
"""
|
|
|
|
|
2021-06-11 11:27:12 +02:00
|
|
|
# If we have a list of instances that are allowed to write to this
|
|
|
|
# stream, make sure we're in it.
|
|
|
|
if self._writers and self._instance_name not in self._writers:
|
|
|
|
raise Exception("Tried to allocate stream ID on non-writer")
|
|
|
|
|
2020-05-04 18:17:45 +02:00
|
|
|
next_id = self._load_next_id_txn(txn)
|
|
|
|
|
|
|
|
txn.call_after(self._mark_id_as_finished, next_id)
|
|
|
|
txn.call_on_exception(self._mark_id_as_finished, next_id)
|
2023-01-20 19:02:18 +01:00
|
|
|
txn.call_after(self._notifier.notify_replication)
|
2020-05-04 18:17:45 +02:00
|
|
|
|
2020-09-24 17:53:51 +02:00
|
|
|
# Update the `stream_positions` table with newly updated stream
|
|
|
|
# ID (unless self._writers is not set in which case we don't
|
|
|
|
# bother, as nothing will read it).
|
|
|
|
#
|
|
|
|
# We only do this on the success path so that the persisted current
|
2021-02-12 17:01:48 +01:00
|
|
|
# position points to a persisted row with the correct instance name.
|
2020-09-24 17:53:51 +02:00
|
|
|
if self._writers:
|
|
|
|
txn.call_after(
|
|
|
|
run_as_background_process,
|
|
|
|
"MultiWriterIdGenerator._update_table",
|
|
|
|
self._db.runInteraction,
|
|
|
|
"MultiWriterIdGenerator._update_table",
|
|
|
|
self._update_stream_positions_table_txn,
|
|
|
|
)
|
|
|
|
|
2020-09-01 14:36:25 +02:00
|
|
|
return self._return_factor * next_id
|
2020-05-04 18:17:45 +02:00
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
def _mark_id_as_finished(self, next_id: int) -> None:
|
2020-05-04 18:17:45 +02:00
|
|
|
"""The ID has finished being processed so we should advance the
|
2020-09-08 15:26:54 +02:00
|
|
|
current position if possible.
|
2020-05-04 18:17:45 +02:00
|
|
|
"""
|
|
|
|
|
|
|
|
with self._lock:
|
|
|
|
self._unfinished_ids.discard(next_id)
|
2020-09-08 15:26:54 +02:00
|
|
|
self._finished_ids.add(next_id)
|
|
|
|
|
2021-07-15 18:46:54 +02:00
|
|
|
new_cur: Optional[int] = None
|
2020-09-08 15:26:54 +02:00
|
|
|
|
2021-10-12 15:27:09 +02:00
|
|
|
if self._unfinished_ids or self._in_flight_fetches:
|
2020-09-08 15:26:54 +02:00
|
|
|
# If there are unfinished IDs then the new position will be the
|
2021-10-12 15:27:09 +02:00
|
|
|
# largest finished ID strictly less than the minimum unfinished
|
|
|
|
# ID.
|
|
|
|
|
|
|
|
# The minimum unfinished ID needs to take account of both
|
|
|
|
# `_unfinished_ids` and `_in_flight_fetches`.
|
|
|
|
if self._unfinished_ids and self._in_flight_fetches:
|
|
|
|
# `_in_flight_fetches` stores the maximum safe stream ID, so
|
|
|
|
# we add one to make it equivalent to the minimum unsafe ID.
|
|
|
|
min_unfinished = min(
|
|
|
|
self._unfinished_ids[0], self._in_flight_fetches[0] + 1
|
|
|
|
)
|
|
|
|
elif self._in_flight_fetches:
|
|
|
|
min_unfinished = self._in_flight_fetches[0] + 1
|
|
|
|
else:
|
|
|
|
min_unfinished = self._unfinished_ids[0]
|
2020-09-08 15:26:54 +02:00
|
|
|
|
|
|
|
finished = set()
|
|
|
|
for s in self._finished_ids:
|
2021-10-12 15:27:09 +02:00
|
|
|
if s < min_unfinished:
|
2020-09-08 15:26:54 +02:00
|
|
|
if new_cur is None or new_cur < s:
|
|
|
|
new_cur = s
|
|
|
|
else:
|
|
|
|
finished.add(s)
|
|
|
|
|
|
|
|
# We clear these out since they're now all less than the new
|
|
|
|
# position.
|
|
|
|
self._finished_ids = finished
|
|
|
|
else:
|
|
|
|
# There are no unfinished IDs so the new position is simply the
|
|
|
|
# largest finished one.
|
|
|
|
new_cur = max(self._finished_ids)
|
|
|
|
|
|
|
|
# We clear these out since they're now all less than the new
|
|
|
|
# position.
|
|
|
|
self._finished_ids.clear()
|
2020-05-04 18:17:45 +02:00
|
|
|
|
2020-09-08 15:26:54 +02:00
|
|
|
if new_cur:
|
2020-05-04 18:17:45 +02:00
|
|
|
curr = self._current_positions.get(self._instance_name, 0)
|
2020-09-08 15:26:54 +02:00
|
|
|
self._current_positions[self._instance_name] = max(curr, new_cur)
|
2020-05-04 18:17:45 +02:00
|
|
|
|
2020-08-27 14:20:34 +02:00
|
|
|
self._add_persisted_position(next_id)
|
|
|
|
|
2020-08-19 11:39:31 +02:00
|
|
|
def get_current_token(self) -> int:
|
2020-09-14 11:16:41 +02:00
|
|
|
return self.get_persisted_upto_position()
|
2020-08-19 11:39:31 +02:00
|
|
|
|
|
|
|
def get_current_token_for_writer(self, instance_name: str) -> int:
|
2020-09-29 17:42:19 +02:00
|
|
|
# If we don't have an entry for the given instance name, we assume it's a
|
|
|
|
# new writer.
|
|
|
|
#
|
|
|
|
# For new writers we assume their initial position to be the current
|
|
|
|
# persisted up to position. This stops Synapse from doing a full table
|
|
|
|
# scan when a new writer announces itself over replication.
|
2020-05-04 18:17:45 +02:00
|
|
|
with self._lock:
|
2020-09-29 17:42:19 +02:00
|
|
|
return self._return_factor * self._current_positions.get(
|
|
|
|
instance_name, self._persisted_upto_position
|
|
|
|
)
|
2020-05-04 18:17:45 +02:00
|
|
|
|
|
|
|
def get_positions(self) -> Dict[str, int]:
|
|
|
|
"""Get a copy of the current positon map.
|
2020-09-29 17:42:19 +02:00
|
|
|
|
|
|
|
Note that this won't necessarily include all configured writers if some
|
|
|
|
writers haven't written anything yet.
|
2020-05-04 18:17:45 +02:00
|
|
|
"""
|
|
|
|
|
|
|
|
with self._lock:
|
2020-09-01 14:36:25 +02:00
|
|
|
return {
|
|
|
|
name: self._return_factor * i
|
|
|
|
for name, i in self._current_positions.items()
|
|
|
|
}
|
2020-05-04 18:17:45 +02:00
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
def advance(self, instance_name: str, new_id: int) -> None:
|
2020-09-01 14:36:25 +02:00
|
|
|
new_id *= self._return_factor
|
|
|
|
|
2020-05-04 18:17:45 +02:00
|
|
|
with self._lock:
|
|
|
|
self._current_positions[instance_name] = max(
|
|
|
|
new_id, self._current_positions.get(instance_name, 0)
|
|
|
|
)
|
2020-08-25 18:32:30 +02:00
|
|
|
|
2021-10-12 15:27:09 +02:00
|
|
|
self._max_seen_allocated_stream_id = max(
|
|
|
|
self._max_seen_allocated_stream_id, new_id
|
|
|
|
)
|
|
|
|
|
2020-08-25 18:32:30 +02:00
|
|
|
self._add_persisted_position(new_id)
|
|
|
|
|
|
|
|
def get_persisted_upto_position(self) -> int:
|
|
|
|
"""Get the max position where all previous positions have been
|
|
|
|
persisted.
|
|
|
|
|
|
|
|
Note: In the worst case scenario this will be equal to the minimum
|
|
|
|
position across writers. This means that the returned position here can
|
|
|
|
lag if one writer doesn't write very often.
|
|
|
|
"""
|
|
|
|
|
|
|
|
with self._lock:
|
2020-09-01 14:36:25 +02:00
|
|
|
return self._return_factor * self._persisted_upto_position
|
2020-08-25 18:32:30 +02:00
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
def _add_persisted_position(self, new_id: int) -> None:
|
2020-08-25 18:32:30 +02:00
|
|
|
"""Record that we have persisted a position.
|
|
|
|
|
|
|
|
This is used to keep the `_current_positions` up to date.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# We require that the lock is locked by caller
|
|
|
|
assert self._lock.locked()
|
|
|
|
|
|
|
|
heapq.heappush(self._known_persisted_positions, new_id)
|
|
|
|
|
|
|
|
# We move the current min position up if the minimum current positions
|
|
|
|
# of all instances is higher (since by definition all positions less
|
|
|
|
# that that have been persisted).
|
2023-01-18 20:35:29 +01:00
|
|
|
our_current_position = self._current_positions.get(self._instance_name, 0)
|
|
|
|
min_curr = min(
|
|
|
|
(
|
|
|
|
token
|
|
|
|
for name, token in self._current_positions.items()
|
|
|
|
if name != self._instance_name
|
|
|
|
),
|
|
|
|
default=our_current_position,
|
|
|
|
)
|
|
|
|
|
|
|
|
if our_current_position and (self._unfinished_ids or self._in_flight_fetches):
|
|
|
|
min_curr = min(min_curr, our_current_position)
|
|
|
|
|
2020-08-25 18:32:30 +02:00
|
|
|
self._persisted_upto_position = max(min_curr, self._persisted_upto_position)
|
|
|
|
|
|
|
|
# We now iterate through the seen positions, discarding those that are
|
|
|
|
# less than the current min positions, and incrementing the min position
|
|
|
|
# if its exactly one greater.
|
|
|
|
#
|
|
|
|
# This is also where we discard items from `_known_persisted_positions`
|
|
|
|
# (to ensure the list doesn't infinitely grow).
|
|
|
|
while self._known_persisted_positions:
|
|
|
|
if self._known_persisted_positions[0] <= self._persisted_upto_position:
|
|
|
|
heapq.heappop(self._known_persisted_positions)
|
|
|
|
elif (
|
|
|
|
self._known_persisted_positions[0] == self._persisted_upto_position + 1
|
|
|
|
):
|
|
|
|
heapq.heappop(self._known_persisted_positions)
|
|
|
|
self._persisted_upto_position += 1
|
|
|
|
else:
|
|
|
|
# There was a gap in seen positions, so there is nothing more to
|
|
|
|
# do.
|
|
|
|
break
|
2020-09-23 17:11:18 +02:00
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
def _update_stream_positions_table_txn(self, txn: Cursor) -> None:
|
2021-02-16 23:32:34 +01:00
|
|
|
"""Update the `stream_positions` table with newly persisted position."""
|
2020-09-24 17:53:51 +02:00
|
|
|
|
|
|
|
if not self._writers:
|
|
|
|
return
|
|
|
|
|
|
|
|
# We upsert the value, ensuring on conflict that we always increase the
|
|
|
|
# value (or decrease if stream goes backwards).
|
|
|
|
sql = """
|
|
|
|
INSERT INTO stream_positions (stream_name, instance_name, stream_id)
|
|
|
|
VALUES (?, ?, ?)
|
|
|
|
ON CONFLICT (stream_name, instance_name)
|
|
|
|
DO UPDATE SET
|
|
|
|
stream_id = %(agg)s(stream_positions.stream_id, EXCLUDED.stream_id)
|
|
|
|
""" % {
|
|
|
|
"agg": "GREATEST" if self._positive else "LEAST",
|
|
|
|
}
|
|
|
|
|
|
|
|
pos = (self.get_current_token_for_writer(self._instance_name),)
|
|
|
|
txn.execute(sql, (self._stream_name, self._instance_name, pos))
|
|
|
|
|
2020-09-23 17:11:18 +02:00
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
@attr.s(frozen=True, auto_attribs=True)
|
|
|
|
class _AsyncCtxManagerWrapper(Generic[T]):
|
2020-09-23 17:11:18 +02:00
|
|
|
"""Helper class to convert a plain context manager to an async one.
|
|
|
|
|
|
|
|
This is mainly useful if you have a plain context manager but the interface
|
|
|
|
requires an async one.
|
|
|
|
"""
|
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
inner: ContextManager[T]
|
2020-09-23 17:11:18 +02:00
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
async def __aenter__(self) -> T:
|
2020-09-23 17:11:18 +02:00
|
|
|
return self.inner.__enter__()
|
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
async def __aexit__(
|
|
|
|
self,
|
|
|
|
exc_type: Optional[Type[BaseException]],
|
|
|
|
exc: Optional[BaseException],
|
|
|
|
tb: Optional[TracebackType],
|
|
|
|
) -> Optional[bool]:
|
2020-09-23 17:11:18 +02:00
|
|
|
return self.inner.__exit__(exc_type, exc, tb)
|
|
|
|
|
|
|
|
|
2022-01-13 14:49:28 +01:00
|
|
|
@attr.s(slots=True, auto_attribs=True)
|
2020-09-23 17:11:18 +02:00
|
|
|
class _MultiWriterCtxManager:
|
2021-02-16 23:32:34 +01:00
|
|
|
"""Async context manager returned by MultiWriterIdGenerator"""
|
2020-09-23 17:11:18 +02:00
|
|
|
|
2022-01-13 14:49:28 +01:00
|
|
|
id_gen: MultiWriterIdGenerator
|
2023-01-20 19:02:18 +01:00
|
|
|
notifier: "ReplicationNotifier"
|
2022-01-13 14:49:28 +01:00
|
|
|
multiple_ids: Optional[int] = None
|
|
|
|
stream_ids: List[int] = attr.Factory(list)
|
2020-09-23 17:11:18 +02:00
|
|
|
|
|
|
|
async def __aenter__(self) -> Union[int, List[int]]:
|
2020-10-07 16:15:57 +02:00
|
|
|
# It's safe to run this in autocommit mode as fetching values from a
|
|
|
|
# sequence ignores transaction semantics anyway.
|
2020-09-23 17:11:18 +02:00
|
|
|
self.stream_ids = await self.id_gen._db.runInteraction(
|
|
|
|
"_load_next_mult_id",
|
|
|
|
self.id_gen._load_next_mult_id_txn,
|
|
|
|
self.multiple_ids or 1,
|
2020-10-07 16:15:57 +02:00
|
|
|
db_autocommit=True,
|
2020-09-23 17:11:18 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
if self.multiple_ids is None:
|
|
|
|
return self.stream_ids[0] * self.id_gen._return_factor
|
|
|
|
else:
|
|
|
|
return [i * self.id_gen._return_factor for i in self.stream_ids]
|
|
|
|
|
2021-10-08 16:25:16 +02:00
|
|
|
async def __aexit__(
|
|
|
|
self,
|
|
|
|
exc_type: Optional[Type[BaseException]],
|
|
|
|
exc: Optional[BaseException],
|
|
|
|
tb: Optional[TracebackType],
|
|
|
|
) -> bool:
|
2020-09-23 17:11:18 +02:00
|
|
|
for i in self.stream_ids:
|
|
|
|
self.id_gen._mark_id_as_finished(i)
|
|
|
|
|
2023-01-20 19:02:18 +01:00
|
|
|
self.notifier.notify_replication()
|
|
|
|
|
2020-09-23 17:11:18 +02:00
|
|
|
if exc_type is not None:
|
|
|
|
return False
|
|
|
|
|
2020-09-24 17:53:51 +02:00
|
|
|
# Update the `stream_positions` table with newly updated stream
|
|
|
|
# ID (unless self._writers is not set in which case we don't
|
|
|
|
# bother, as nothing will read it).
|
|
|
|
#
|
|
|
|
# We only do this on the success path so that the persisted current
|
|
|
|
# position points to a persisted row with the correct instance name.
|
2020-10-07 16:15:57 +02:00
|
|
|
#
|
|
|
|
# We do this in autocommit mode as a) the upsert works correctly outside
|
|
|
|
# transactions and b) reduces the amount of time the rows are locked
|
|
|
|
# for. If we don't do this then we'll often hit serialization errors due
|
|
|
|
# to the fact we default to REPEATABLE READ isolation levels.
|
2020-09-24 17:53:51 +02:00
|
|
|
if self.id_gen._writers:
|
|
|
|
await self.id_gen._db.runInteraction(
|
|
|
|
"MultiWriterIdGenerator._update_table",
|
|
|
|
self.id_gen._update_stream_positions_table_txn,
|
2020-10-07 16:15:57 +02:00
|
|
|
db_autocommit=True,
|
2020-09-24 17:53:51 +02:00
|
|
|
)
|
|
|
|
|
2020-09-23 17:11:18 +02:00
|
|
|
return False
|