Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

don't suppress exception on aexit #232

Merged
merged 3 commits into from
Jul 18, 2023
Merged
Changes from 1 commit
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
31 changes: 19 additions & 12 deletions aiomqtt/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,15 +511,19 @@ async def connect(self, *, timeout: float | None = None) -> None:
if self._disconnected.done():
self._disconnected = asyncio.Future()

async def disconnect(self, *, timeout: float | None = None) -> None:
"""Disconnect from the broker."""
# Early out if already disconnected...
def _early_out_on_disconnected(self)-> bool:
# Early out if already disconnected...
if self._disconnected.done():
disc_exc = self._disconnected.exception()
if disc_exc is not None:
if (disc_exc:= self._disconnected.exception()) is not None:
edenhaus marked this conversation as resolved.
Show resolved Hide resolved
# ...by raising the error that caused the disconnect
raise disc_exc
# ...by returning since the disconnect was intentional
return True
return False

async def disconnect(self, *, timeout: float | None = None) -> None:
"""Disconnect from the broker."""
if self._early_out_on_disconnected():
return
# Try to gracefully disconnect from the broker
rc = self._client.disconnect()
Expand Down Expand Up @@ -1037,13 +1041,16 @@ async def __aexit__(
) -> None:
"""Try to gracefully disconnect from the broker."""
try:
await self.disconnect()
except MqttError as error:
# We tried to be graceful. Now there is no mercy.
self._logger.warning(
f'Could not gracefully disconnect due to "{error}". Forcing'
" disconnection."
)
if self._early_out_on_disconnected():
return
try:
await self.disconnect()
except MqttError as error:
# We tried to be graceful. Now there is no mercy.
self._logger.warning(
f'Could not gracefully disconnect due to "{error}". Forcing'
" disconnection."
)
finally:
self._force_disconnect()
self._lock.release()
Expand Down