diff --git a/CHANGELOG.md b/CHANGELOG.md index a7bdd8bc..68fb7823 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,5 @@ +* Fix repeated `ydb.aio.Driver.stop()` raising `CancelledError` after discovery was cancelled during shutdown. + ## 3.38.0 ## * Add automatic long polling for endpoint discovery in sync and asyncio drivers * 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. diff --git a/tests/aio/test_connection_pool.py b/tests/aio/test_connection_pool.py index e9f84775..a9fd3854 100644 --- a/tests/aio/test_connection_pool.py +++ b/tests/aio/test_connection_pool.py @@ -6,6 +6,26 @@ import ydb +@pytest.mark.asyncio +async def test_repeated_stop_during_discovery(monkeypatch): + connecting = asyncio.Event() + connection_ready = asyncio.get_running_loop().create_future() + + async def wait_for_connection(self, ready_timeout=10): + connecting.set() + await connection_ready + + monkeypatch.setattr("ydb.aio.connection.Connection.connection_ready", wait_for_connection) + driver = Driver(endpoint="localhost:2135", database="/local") + try: + await asyncio.wait_for(connecting.wait(), timeout=5) + finally: + await asyncio.gather(driver.stop(timeout=0), driver.stop()) + + assert connection_ready.cancelled() + await driver.stop(timeout=0) + + @pytest.mark.asyncio async def test_async_call(endpoint, database): driver_config = ydb.DriverConfig( diff --git a/ydb/aio/driver.py b/ydb/aio/driver.py index 88221e94..7f38af33 100644 --- a/ydb/aio/driver.py +++ b/ydb/aio/driver.py @@ -1,3 +1,4 @@ +import asyncio from typing import Any, Optional, TYPE_CHECKING from . import pool, scheme, table @@ -74,6 +75,7 @@ def __init__( super(Driver, self).__init__(config) + self._stop_lock = asyncio.Lock() self._credentials = config.credentials self.scheme_client = scheme.SchemeClient(self) @@ -82,6 +84,9 @@ def __init__( self.coordination_client = coordination.CoordinationClient(self) async def stop(self, timeout: int = 10) -> None: # type: ignore[override] # async override of sync method - await self.table_client._stop_pool_if_needed(timeout=timeout) - self.topic_client.close() - await super().stop(timeout=timeout) + async with self._stop_lock: + if self._stopped: + return + await self.table_client._stop_pool_if_needed(timeout=timeout) + self.topic_client.close() + await super().stop(timeout=timeout)