diff --git a/CHANGELOG.md b/CHANGELOG.md index 35f7c4ce..2abebf91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,4 @@ +* Add `EventHandler.on_partition_session_start` to confirm topic reader partitions manually with read and commit offsets, and `EventHandler.on_partition_session_stop` to observe partition stops. * Add `grpc_channel_shutdown_timeout` for graceful shutdown of channels removed by discovery in both drivers. ## 3.37.0 ## diff --git a/docs/topic.rst b/docs/topic.rst index 616dd268..40f5f71b 100644 --- a/docs/topic.rst +++ b/docs/topic.rst @@ -601,6 +601,35 @@ property: reader.commit(batch) +Confirming Partition Assignment +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +By default the reader confirms every assigned partition immediately and reads it from the +committed offset. To choose the start position yourself, for example from offsets stored in +your own database, override ``on_partition_session_start`` in an event handler. No data is read +from the partition until ``event.confirm()`` is called. It may be called later, from any thread. + +.. code-block:: python + + class Handler(ydb.TopicReaderEvents.EventHandler): + def on_partition_session_start(self, event): + # event.committed_offset, event.read_offset and event.end_offset come from the server + stored = load_offset(event.topic, event.partition_id) + if stored is None: + event.confirm() + else: + event.confirm(read_offset=stored + 1, commit_offset=stored + 1) + + def on_partition_session_stop(self, event): + forget_partition(event.topic, event.partition_id) + + reader = driver.topic_client.reader("/local/my-topic", consumer="my-consumer", event_handler=Handler()) + +``read_offset`` must not be less than the committed offset, otherwise the server closes the read +session. ``commit_offset`` commits all messages before it. ``on_partition_session_stop`` is a +notification: the reader confirms the stop to the server itself. + + Transactions ------------ diff --git a/tests/topics/test_topic_transactions.py b/tests/topics/test_topic_transactions.py index 1263e7d4..5587d732 100644 --- a/tests/topics/test_topic_transactions.py +++ b/tests/topics/test_topic_transactions.py @@ -10,6 +10,26 @@ @pytest.mark.asyncio class TestTopicTransactionalReader: + async def test_commit_after_manual_partition_start(self, driver, topic_with_messages, topic_consumer): + class Handler(ydb.TopicReaderEvents.EventHandler): + def on_partition_session_start(self, event): + event.confirm(read_offset=1, commit_offset=1) + + async with ydb.aio.QuerySessionPool(driver) as pool: + async with driver.topic_client.reader( + topic_with_messages, topic_consumer, event_handler=Handler() + ) as reader: + + async def read_one(tx): + batch = await wait_for(reader.receive_batch_with_tx(tx, max_messages=1), DEFAULT_TIMEOUT) + assert batch.messages[0].offset == 1 + + await pool.retry_tx_async(read_one, retry_settings=DEFAULT_RETRY_SETTINGS) + + async with driver.topic_client.reader(topic_with_messages, topic_consumer) as reader: + message = await wait_for(reader.receive_message(), DEFAULT_TIMEOUT) + assert message.offset == 2 + async def test_commit(self, driver: ydb.aio.Driver, topic_with_messages, topic_consumer): async with ydb.aio.QuerySessionPool(driver) as pool: async with driver.topic_client.reader(topic_with_messages, topic_consumer) as reader: diff --git a/ydb/_topic_reader/events.py b/ydb/_topic_reader/events.py index 7e1988f3..08ea33b1 100644 --- a/ydb/_topic_reader/events.py +++ b/ydb/_topic_reader/events.py @@ -1,6 +1,7 @@ import asyncio -from dataclasses import dataclass -from typing import Awaitable, Optional, Union +import threading +from dataclasses import dataclass, field +from typing import Awaitable, Callable, Optional, Union from ..issues import ClientInternalError @@ -8,6 +9,8 @@ "OnCommit", "OnPartitionGetStartOffsetRequest", "OnPartitionGetStartOffsetResponse", + "OnPartitionSessionStart", + "OnPartitionSessionStop", "OnInitPartition", "OnShutdownPartition", "EventHandler", @@ -35,6 +38,50 @@ class OnPartitionGetStartOffsetResponse: start_offset: Optional[int] +@dataclass +class OnPartitionSessionStart(BaseReaderEvent): + """ + Server assigned a partition to the reader. No data is read from the partition until confirm() is called. + confirm() may be called after the handler returns, from any thread. + """ + + topic: str + partition_id: int + committed_offset: int + """All messages with offset less than committed_offset are committed by the consumer.""" + read_offset: int + """Offset the server will start reading from if confirm() is called without read_offset.""" + end_offset: int + """Offset after the last message in the partition at the moment of the assignment.""" + + _confirm_callback: Callable[[Optional[int], Optional[int]], None] = field(repr=False, compare=False) + _confirmed: bool = field(default=False, init=False, repr=False, compare=False) + _confirm_lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False, compare=False) + + def confirm(self, read_offset: Optional[int] = None, commit_offset: Optional[int] = None) -> None: + """ + Start reading the partition. + + :param read_offset: read messages starting from this offset. The server checks that it is not less than + the committed offset and closes the read session otherwise. + :param commit_offset: all messages with offset less than commit_offset are processed by the client, + the server commits this position if it is not committed yet. + """ + with self._confirm_lock: + if self._confirmed: + raise ValueError("partition session start is already confirmed") + self._confirmed = True + self._confirm_callback(read_offset, commit_offset) + + +@dataclass +class OnPartitionSessionStop(BaseReaderEvent): + topic: str + partition_id: int + committed_offset: int + graceful: bool + + class OnInitPartition(BaseReaderEvent): pass @@ -56,12 +103,27 @@ def on_partition_get_start_offset( ) -> Union[OnPartitionGetStartOffsetResponse, Awaitable[OnPartitionGetStartOffsetResponse]]: return OnPartitionGetStartOffsetResponse(start_offset=None) + def on_partition_session_start(self, event: OnPartitionSessionStart) -> Union[None, Awaitable[None]]: + """ + Override to confirm partitions manually. The overridden method must call event.confirm(), + now or later, otherwise the partition is never read. + By default confirms immediately with the offset returned by on_partition_get_start_offset. + """ + return self._confirm_with_start_offset(event) + + def on_partition_session_stop(self, event: OnPartitionSessionStop) -> Union[None, Awaitable[None]]: + return None + def on_init_partition(self, event: OnInitPartition) -> Union[None, Awaitable[None]]: return None def on_shutdown_partition(self, event: OnShutdownPartition) -> Union[None, Awaitable[None]]: return None + async def _confirm_with_start_offset(self, event: OnPartitionSessionStart) -> None: + resp = await self._dispatch(OnPartitionGetStartOffsetRequest(event.topic, event.partition_id)) + event.confirm(read_offset=None if resp is None else resp.start_offset) + async def _dispatch(self, event: BaseReaderEvent) -> TopicEventDispatchType: if isinstance(event, OnCommit): commit_result = self.on_commit(event) @@ -73,6 +135,16 @@ async def _dispatch(self, event: BaseReaderEvent) -> TopicEventDispatchType: if asyncio.iscoroutine(offset_result): return await offset_result return offset_result # type: ignore[return-value] + elif isinstance(event, OnPartitionSessionStart): + start_result = self.on_partition_session_start(event) + if start_result is not None: + await start_result + return None + elif isinstance(event, OnPartitionSessionStop): + stop_result = self.on_partition_session_stop(event) + if stop_result is not None: + await stop_result + return None elif isinstance(event, OnInitPartition): init_result = self.on_init_partition(event) if asyncio.iscoroutine(init_result): diff --git a/ydb/_topic_reader/topic_reader_asyncio.py b/ydb/_topic_reader/topic_reader_asyncio.py index 74e9bca7..ddeebce2 100644 --- a/ydb/_topic_reader/topic_reader_asyncio.py +++ b/ydb/_topic_reader/topic_reader_asyncio.py @@ -799,7 +799,7 @@ async def _read_messages_loop(self): self._log_prefix, message.server_message.partition_session_id, ) - self._on_partition_session_stop(message.server_message) + await self._on_partition_session_stop(message.server_message) elif isinstance( message.server_message, @@ -859,7 +859,7 @@ async def _on_start_partition_session(self, message: StreamReadMessage.StartPart "Double start partition session: %s" % message.partition_session.partition_session_id ) - self._partition_sessions[message.partition_session.partition_session_id] = datatypes.PartitionSession( + partition_session = datatypes.PartitionSession( id=message.partition_session.partition_session_id, state=datatypes.PartitionSession.State.Active, topic_path=message.partition_session.path, @@ -868,32 +868,66 @@ async def _on_start_partition_session(self, message: StreamReadMessage.StartPart reader_reconnector_id=self._reader_reconnector_id, reader_stream_id=self._id, ) + self._partition_sessions[partition_session.id] = partition_session - read_offset = None + event = events.OnPartitionSessionStart( + topic=message.partition_session.path, + partition_id=message.partition_session.partition_id, + committed_offset=message.committed_offset, + read_offset=message.partition_offsets.start, + end_offset=message.partition_offsets.end, + _confirm_callback=lambda read_offset, commit_offset: self._confirm_partition_session_start( + partition_session, read_offset, commit_offset + ), + ) - if self._settings.event_handler is not None: - resp = await self._settings.event_handler._dispatch( - events.OnPartitionGetStartOffsetRequest( - message.partition_session.path, - message.partition_session.partition_id, - ) + if self._settings.event_handler is None: + event.confirm() + else: + await self._settings.event_handler._dispatch(event) + except YdbError as err: + self._set_first_error(err) + + def _confirm_partition_session_start( + self, + partition_session: datatypes.PartitionSession, + read_offset: Optional[int], + commit_offset: Optional[int], + ): + try: + in_reader_loop = asyncio.get_running_loop() is self._loop + except RuntimeError: + in_reader_loop = False + + if not in_reader_loop: + try: + self._loop.call_soon_threadsafe( + self._confirm_partition_session_start, partition_session, read_offset, commit_offset ) - read_offset = None if resp is None else resp.start_offset + except RuntimeError: + if not self._loop.is_closed(): + raise + return - if self._stream is not None: - self._stream.write( - StreamReadMessage.FromClient( - client_message=StreamReadMessage.StartPartitionSessionResponse( - partition_session_id=message.partition_session.partition_session_id, - read_offset=read_offset, - commit_offset=None, - ) - ), + if self._closed or self._stream is None: + return + + if self._partition_sessions.get(partition_session.id) is not partition_session: + return + + self._stream.write( + StreamReadMessage.FromClient( + client_message=StreamReadMessage.StartPartitionSessionResponse( + partition_session_id=partition_session.id, + read_offset=read_offset, + commit_offset=commit_offset, ) - except YdbError as err: - self._set_first_error(err) + ), + ) + if commit_offset is not None: + partition_session._next_message_start_commit_offset = max(partition_session.committed_offset, commit_offset) - def _on_partition_session_stop(self, message: StreamReadMessage.StopPartitionSessionRequest): + async def _on_partition_session_stop(self, message: StreamReadMessage.StopPartitionSessionRequest): if message.partition_session_id not in self._partition_sessions: # may if receive stop partition with graceful=false after response on stop partition # with graceful=true and remove partition from internal dictionary @@ -911,6 +945,16 @@ def _on_partition_session_stop(self, message: StreamReadMessage.StopPartitionSes ) ) + if self._settings.event_handler is not None: + await self._settings.event_handler._dispatch( + events.OnPartitionSessionStop( + topic=partition.topic_path, + partition_id=partition.partition_id, + committed_offset=message.committed_offset, + graceful=message.graceful, + ) + ) + def _on_end_partition_session(self, message: StreamReadMessage.EndPartitionSession): logger.debug( f"End partition session with id: {message.partition_session_id}, " diff --git a/ydb/_topic_reader/topic_reader_asyncio_test.py b/ydb/_topic_reader/topic_reader_asyncio_test.py index 6d677f77..30dbdcec 100644 --- a/ydb/_topic_reader/topic_reader_asyncio_test.py +++ b/ydb/_topic_reader/topic_reader_asyncio_test.py @@ -3,6 +3,7 @@ import copy import datetime import gzip +import threading import typing from collections import OrderedDict from dataclasses import dataclass @@ -718,6 +719,203 @@ def session_count(): reader_stream_id=stream_reader._id, ) + @staticmethod + def start_partition_message(partition_session_id=30, partition_id=7, committed_offset=18, start=18, end=40): + return StreamReadMessage.FromServer( + server_status=ServerStatus(ydb_status_codes_pb2.StatusIds.SUCCESS, []), + server_message=StreamReadMessage.StartPartitionSessionRequest( + partition_session=StreamReadMessage.PartitionSession( + partition_session_id=partition_session_id, + path="test-topic", + partition_id=partition_id, + ), + committed_offset=committed_offset, + partition_offsets=OffsetsRange(start=start, end=end), + ), + ) + + @staticmethod + def start_partition_response(partition_session_id=30, read_offset=None, commit_offset=None): + return StreamReadMessage.FromClient( + client_message=StreamReadMessage.StartPartitionSessionResponse( + partition_session_id=partition_session_id, + read_offset=read_offset, + commit_offset=commit_offset, + ) + ) + + async def get_reader_with_handler(self, stream, default_reader_settings, handler) -> ReaderStream: + settings = copy.copy(default_reader_settings) + settings.event_handler = handler + return await self.get_started_reader(stream, settings) + + async def test_start_partition_default_event_handler_confirms(self, stream, default_reader_settings): + reader = await self.get_reader_with_handler( + stream, default_reader_settings, topic_reader_asyncio.events.EventHandler() + ) + + stream.from_server.put_nowait(self.start_partition_message()) + + assert await wait_for_fast(stream.from_client.get()) == self.start_partition_response() + await reader.close(False) + + async def test_start_partition_uses_get_start_offset(self, stream, default_reader_settings): + events = topic_reader_asyncio.events + + class Handler(events.EventHandler): + async def on_partition_get_start_offset(self, event): + assert (event.topic, event.partition_id) == ("test-topic", 7) + return events.OnPartitionGetStartOffsetResponse(start_offset=25) + + reader = await self.get_reader_with_handler(stream, default_reader_settings, Handler()) + + stream.from_server.put_nowait(self.start_partition_message()) + + assert await wait_for_fast(stream.from_client.get()) == self.start_partition_response(read_offset=25) + await reader.close(False) + + @pytest.mark.parametrize(("commit_offset", "expected_start"), [(20, 20), (17, 18), (None, 18)]) + async def test_start_partition_manual_confirm(self, stream, default_reader_settings, commit_offset, expected_start): + events = topic_reader_asyncio.events + received: asyncio.Queue = asyncio.Queue() + + class Handler(events.EventHandler): + def on_partition_session_start(self, event): + received.put_nowait(event) + + reader = await self.get_reader_with_handler(stream, default_reader_settings, Handler()) + + stream.from_server.put_nowait(self.start_partition_message()) + event = await wait_for_fast(received.get()) + + assert (event.topic, event.partition_id) == ("test-topic", 7) + assert (event.committed_offset, event.read_offset, event.end_offset) == (18, 18, 40) + assert 30 in reader._partition_sessions + await asyncio.sleep(0) + with pytest.raises(asyncio.QueueEmpty): + stream.from_client.get_nowait() + + event.confirm(read_offset=21, commit_offset=commit_offset) + + assert await wait_for_fast(stream.from_client.get()) == self.start_partition_response( + read_offset=21, commit_offset=commit_offset + ) + message = self.create_message(reader._partition_sessions[30], seqno=1, offset_delta=1) + message.offset = 21 + await self.send_message(reader, message) + assert reader.receive_batch_nowait()._commit_get_offsets_range() == OffsetsRange(expected_start, 22) + with pytest.raises(ValueError): + event.confirm() + await reader.close(False) + + async def test_start_partition_confirm_from_other_thread(self, stream, default_reader_settings): + events = topic_reader_asyncio.events + received: asyncio.Queue = asyncio.Queue() + + class Handler(events.EventHandler): + def on_partition_session_start(self, event): + received.put_nowait(event) + + reader = await self.get_reader_with_handler(stream, default_reader_settings, Handler()) + + stream.from_server.put_nowait(self.start_partition_message()) + event = await wait_for_fast(received.get()) + + barrier = threading.Barrier(2) + + def confirm(): + barrier.wait(timeout=5) + event.confirm(read_offset=19) + + loop = asyncio.get_running_loop() + results = await asyncio.gather(*(loop.run_in_executor(None, confirm) for _ in range(2)), return_exceptions=True) + assert results.count(None) == 1 + assert sum(isinstance(result, ValueError) for result in results) == 1 + + assert await wait_for_fast(stream.from_client.get()) == self.start_partition_response(read_offset=19) + assert stream.from_client.empty() + await reader.close(False) + + async def test_confirm_after_reader_loop_closed(self, default_reader_settings): + events = topic_reader_asyncio.events + received = [] + + class Handler(events.EventHandler): + def on_partition_session_start(self, event): + received.append(event) + + async def run_reader(): + default_reader_settings.event_handler = Handler() + reader = ReaderStream(self.default_reader_reconnector_id, default_reader_settings) + await reader._on_start_partition_session(self.start_partition_message().server_message) + await reader.close(False) + + await asyncio.to_thread(asyncio.run, run_reader()) + received[0].confirm() + + async def test_partition_handlers_await_future(self): + events = topic_reader_asyncio.events + loop = asyncio.get_running_loop() + start = loop.create_future() + stop = loop.create_future() + + class Handler(events.EventHandler): + def on_partition_session_start(self, event): + return start + + def on_partition_session_stop(self, event): + return stop + + handler = Handler() + for event, future in ( + (events.OnPartitionSessionStart("topic", 0, 0, 0, 0, mock.Mock()), start), + (events.OnPartitionSessionStop("topic", 0, 0, False), stop), + ): + dispatch = asyncio.create_task(handler._dispatch(event)) + await asyncio.sleep(0) + assert not dispatch.done() + future.set_result(None) + await wait_for_fast(dispatch) + + async def test_start_partition_confirm_after_stop_is_ignored(self, stream, default_reader_settings): + events = topic_reader_asyncio.events + received: asyncio.Queue = asyncio.Queue() + stopped: asyncio.Queue = asyncio.Queue() + + class Handler(events.EventHandler): + def on_partition_session_start(self, event): + received.put_nowait(event) + + async def on_partition_session_stop(self, event): + stopped.put_nowait(event) + + reader = await self.get_reader_with_handler(stream, default_reader_settings, Handler()) + + stream.from_server.put_nowait(self.start_partition_message()) + event = await wait_for_fast(received.get()) + + stream.from_server.put_nowait( + StreamReadMessage.FromServer( + server_status=ServerStatus(ydb_status_codes_pb2.StatusIds.SUCCESS, []), + server_message=StreamReadMessage.StopPartitionSessionRequest( + partition_session_id=30, + graceful=False, + committed_offset=18, + ), + ) + ) + stop_event = await wait_for_fast(stopped.get()) + assert stop_event == events.OnPartitionSessionStop( + topic="test-topic", partition_id=7, committed_offset=18, graceful=False + ) + + event.confirm(read_offset=21) + + await asyncio.sleep(0) + with pytest.raises(asyncio.QueueEmpty): + stream.from_client.get_nowait() + await reader.close(False) + async def test_partition_stop_force(self, stream, stream_reader, partition_session): def session_count(): return len(stream_reader._partition_sessions) diff --git a/ydb/topic.py b/ydb/topic.py index 9bf7b97f..1c30848a 100644 --- a/ydb/topic.py +++ b/ydb/topic.py @@ -336,7 +336,7 @@ def reader( if event_handler is None: raise issues.Error( "To use reader without consumer it is required to specify event_handler with " - "on_partition_get_start_offset method." + "on_partition_get_start_offset or on_partition_session_start method." ) settings = TopicReaderSettings(**args) @@ -700,7 +700,7 @@ def reader( if event_handler is None: raise issues.Error( "To use reader without consumer it is required to specify event_handler with " - "on_partition_get_start_offset method." + "on_partition_get_start_offset or on_partition_session_start method." ) settings = TopicReaderSettings(**args)