Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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 ##
Expand Down
29 changes: 29 additions & 0 deletions docs/topic.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
------------

Expand Down
20 changes: 20 additions & 0 deletions tests/topics/test_topic_transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
76 changes: 74 additions & 2 deletions ydb/_topic_reader/events.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
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

__all__ = [
"OnCommit",
"OnPartitionGetStartOffsetRequest",
"OnPartitionGetStartOffsetResponse",
"OnPartitionSessionStart",
"OnPartitionSessionStop",
"OnInitPartition",
"OnShutdownPartition",
"EventHandler",
Expand Down Expand Up @@ -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

Expand All @@ -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)
Expand All @@ -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):
Expand Down
88 changes: 66 additions & 22 deletions ydb/_topic_reader/topic_reader_asyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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}, "
Expand Down
Loading
Loading