Skip to content

Commit 0557743

Browse files
committed
fix: cancellation handling
1 parent 7d7436a commit 0557743

3 files changed

Lines changed: 13 additions & 2 deletions

File tree

src/zeroconf/_core.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,7 @@ def started(self) -> bool:
207207
not self.done
208208
and self.engine.running_future
209209
and self.engine.running_future.done()
210+
and not self.engine.running_future.cancelled()
210211
and not self.engine.running_future.exception()
211212
)
212213

@@ -242,7 +243,12 @@ async def async_wait_for_start(self) -> None:
242243
raise NotRunningException
243244
assert self.engine.running_future is not None
244245
await wait_future_or_timeout(self.engine.running_future, timeout=_STARTUP_TIMEOUT)
245-
if not self.engine.running_future.done() or self.engine.running_future.exception() or self.done:
246+
if (
247+
not self.engine.running_future.done()
248+
or self.engine.running_future.cancelled()
249+
or self.engine.running_future.exception()
250+
or self.done
251+
):
246252
raise NotRunningException
247253

248254
@property

src/zeroconf/_utils/asyncio.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import asyncio
2626
import concurrent.futures
2727
import contextlib
28+
import sys
2829
from typing import Any, Awaitable, Coroutine
2930

3031
from .._exceptions import EventLoopBlocked
@@ -70,6 +71,9 @@ async def wait_future_or_timeout(future: asyncio.Future[bool | None], timeout: f
7071
handle = loop.call_later(timeout, _set_future_none_if_not_done, future)
7172
try:
7273
await future
74+
except asyncio.CancelledError:
75+
if sys.version_info >= (3, 11) and (task := asyncio.current_task()) and task.cancelling():
76+
raise
7377
finally:
7478
handle.cancel()
7579

src/zeroconf/asyncio.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929

3030
from ._core import Zeroconf
3131
from ._dns import DNSQuestionType
32+
from ._exceptions import NotRunningException
3233
from ._services import ServiceListener
3334
from ._services.browser import _ServiceBrowserBase
3435
from ._services.info import AsyncServiceInfo, ServiceInfo
@@ -227,7 +228,7 @@ async def async_close(self) -> None:
227228
"""Ends the background threads, and prevent this instance from
228229
servicing further queries."""
229230
if not self.zeroconf.done:
230-
with contextlib.suppress(asyncio.TimeoutError):
231+
with contextlib.suppress(asyncio.TimeoutError, NotRunningException):
231232
await asyncio.wait_for(self.zeroconf.async_wait_for_start(), timeout=1)
232233
await self.async_remove_all_service_listeners()
233234
await self.async_unregister_all_services()

0 commit comments

Comments
 (0)