From 20f14b0a6a823043e966515c6e30b4a2cbc89cc4 Mon Sep 17 00:00:00 2001 From: FZambia Date: Fri, 11 Sep 2026 22:27:50 +0300 Subject: [PATCH] Handle replies and disconnects for cancelled commands Cancelling a coroutine awaiting a command reply (for example asyncio.wait_for(client.rpc(...), timeout)) cancels the future registered for that command. _future_success and _future_error resolved that future unconditionally, which raised InvalidStateError: - a late reply killed the task processing incoming messages, so no further replies, pushes or pings were handled until the no-ping timer forced a reconnect; - a disconnect with such a command still in flight raised from _clear_outgoing_futures, aborting disconnect half-way. Skip resolving futures that are already done, still dropping the in-flight entry and cancelling its timeout timer. --- centrifuge/client.py | 18 +++++---- tests/test_cancelled_command.py | 67 +++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 8 deletions(-) create mode 100644 tests/test_cancelled_command.py diff --git a/centrifuge/client.py b/centrifuge/client.py index e928374..e6aad00 100644 --- a/centrifuge/client.py +++ b/centrifuge/client.py @@ -1309,24 +1309,26 @@ def cb(): done.set_result(True) def _future_error(self, cmd_id: int, exc: Exception): - cb = self._inflight_commands.get(cmd_id) + cb = self._inflight_commands.pop(cmd_id, None) if not cb: return - cb.future.set_exception(exc) - if cb.done: + # The future is already done (cancelled) when the coroutine awaiting it + # was cancelled, e.g. by asyncio.wait_for() - resolving it again raises. + if not cb.future.done(): + cb.future.set_exception(exc) + if cb.done and not cb.done.done(): cb.done.set_result(True) # Cancel timeout timer to prevent timer leak if cb.timeout: cb.timeout.cancel() - del self._inflight_commands[cmd_id] async def _future_success(self, cmd_id: int, reply): - cb = self._inflight_commands.get(cmd_id) + cb = self._inflight_commands.pop(cmd_id, None) if not cb: return - future = cb.future - future.set_result(reply) - del self._inflight_commands[cmd_id] + # See _future_error: the awaiting coroutine may have been cancelled. + if not cb.future.done(): + cb.future.set_result(reply) if cb.timeout: cb.timeout.cancel() if cb.done: diff --git a/tests/test_cancelled_command.py b/tests/test_cancelled_command.py new file mode 100644 index 0000000..b32f5be --- /dev/null +++ b/tests/test_cancelled_command.py @@ -0,0 +1,67 @@ +import asyncio +import unittest + +import centrifuge.protocol.client_pb2 as protocol +from centrifuge import Client, ClientState +from tests.fake_server import FakeCentrifugoServer + +# Cancelling a coroutine awaiting a command reply - e.g. with asyncio.wait_for() +# - cancels the future registered for that command. The client must cope with +# the reply (or the disconnect) coming for such a command afterwards. + + +class TestCancelledCommand(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self): + self.server = FakeCentrifugoServer() + await self.server.start() + self.held_rpc_ids = [] + + def on_command(cmd): + if not cmd.HasField("rpc"): + return None + if cmd.rpc.method == "slow": + # Do not reply now, the test sends the reply itself later. A + # reply with an id the client never used is sent instead, since + # returning None would fall through to the default reply. + self.held_rpc_ids.append(cmd.id) + return protocol.Reply(id=0xFFFFFF) + return protocol.Reply(id=cmd.id, rpc=protocol.RPCResult()) + + self.server.on_command = on_command + self.client = Client(self.server.url, use_protobuf=True, timeout=1) + await self.client.connect() + await self.client.ready() + + async def asyncTearDown(self): + await self.client.disconnect() + await self.server.stop() + + async def _cancel_slow_rpc(self): + with self.assertRaises(asyncio.TimeoutError): # noqa: PT027 + await asyncio.wait_for(self.client.rpc("slow", b""), timeout=0.1) + self.assertEqual(len(self.held_rpc_ids), 1) + + async def test_late_reply_to_cancelled_command(self): + await self._cancel_slow_rpc() + + await self.server.send_reply(protocol.Reply(id=self.held_rpc_ids[0])) + + # Used to fail with OperationTimeoutError: setting the result of the + # cancelled future raised InvalidStateError, which killed the task + # processing incoming messages, so no further reply was ever handled. + await self.client.rpc("fast", b"") + self.assertEqual(self.client.state, ClientState.CONNECTED) + + async def test_disconnect_with_cancelled_command_in_flight(self): + await self._cancel_slow_rpc() + + # Used to raise InvalidStateError from failing the cancelled future, + # leaving the client stuck in the connected state. + await self.client.disconnect() + + self.assertEqual(self.client.state, ClientState.DISCONNECTED) + self.assertEqual(self.client._inflight_commands, {}) + + +if __name__ == "__main__": + unittest.main()