From d648c1cbde57a11956e26cb831095aa7258fe050 Mon Sep 17 00:00:00 2001 From: FZambia Date: Wed, 14 Oct 2026 18:53:55 +0300 Subject: [PATCH] Stop the client when an event handler raises Handler exceptions were handled in three ways: while handling a server message the client disconnected with bad protocol; during a connection attempt or a teardown they were logged and the client carried on; from a state change inside connect(), subscribe() or unsubscribe() the change completed and the call raised. Now every exception escaping a handler fails the same loud way, as in centrifuge-js: it is passed to the event loop's exception handler, and the client disconnects with bad protocol and doesn't reconnect. The SDK's own work completes as if the handler had returned, as for a handler calling disconnect(), and a publication whose handler raised doesn't count as delivered, so a recovery delivers it again. Handlers are called through a guard that looks them up at call time, so a handler replaced on the handler object is still guarded. The README section on callbacks that raise describes the behaviour. --- README.md | 9 +- centrifuge/client.py | 190 +++++++++++++++++++++---------- tests/test_handler_exceptions.py | 128 ++++++++++++++------- tests/test_teardown.py | 45 ++++++-- 4 files changed, 257 insertions(+), 115 deletions(-) diff --git a/README.md b/README.md index 89ca5b6..8186303 100644 --- a/README.md +++ b/README.md @@ -105,11 +105,12 @@ The fact WebSocket read is blocked for the time we execute callbacks means that ## Callbacks should not raise -Callbacks are awaited as part of the SDK's own flow, so handle errors inside the callback. An exception escaping a callback is logged through the SDK's `centrifuge` logger, and: +Callbacks are awaited as part of the SDK's own flow, so handle errors inside the callback. The SDK can't know what a callback that raised left undone, so it fails loudly instead of going on as if nothing happened, as centrifuge-js does: -* when it escapes while the client handles a message from the server (a publication, a reply, `on_connected`, `on_subscribed`, ...), the client can't know what was applied: it disconnects with code `2` ("bad protocol"), as centrifuge-js does. Call `connect()` to start again; -* when it escapes while a connection or subscription attempt is in progress (for example from `on_error` reporting a failed attempt), the attempt is retried with backoff; -* when it escapes from a callback about a state change (`on_connecting`, `on_disconnected`, `on_subscribing`, `on_unsubscribed`), the change completes as usual: `connect()` still connects, `subscribe()` still subscribes, `unsubscribe()` still tells the server, a lost connection still reconnects. Called from `connect()`, `subscribe()` or `unsubscribe()`, the exception is then raised by that call, as in centrifuge-js. +* the exception is passed to the event loop's exception handler (`loop.call_exception_handler`; the default one logs it), and not raised to the caller of `connect()`, `subscribe()` or `unsubscribe()`; +* the client disconnects with code `2` ("bad protocol") and the reason `exception in event handler: ...`, and doesn't reconnect. Call `connect()` to start again; +* the SDK's own work completes as if the callback had returned, so the client is left in a consistent state; +* a publication whose callback raised doesn't count as delivered: after `connect()`, a recoverable subscription receives it again. Keep an eye on error logs. diff --git a/centrifuge/client.py b/centrifuge/client.py index 73cab00..9f9f705 100644 --- a/centrifuge/client.py +++ b/centrifuge/client.py @@ -120,6 +120,47 @@ def _task_cancelling() -> bool: _LATE_TIMER_GRACE = 1.0 +class _GuardedEvents: + """Calls the event handlers of the app (looked up when called, so a handler + replaced on the handler object is the one called). An exception escaping a + handler doesn't reach the SDK's own code: it is reported, and the client stops + (see Client._handler_raised); the SDK goes on as if the handler had returned.""" + + def __init__( + self, + events: Callable[[], Any], + client: Callable[[], Optional["Client"]], + publication_failed: Callable[[Any], None], + ) -> None: + self._events = events + self._client = client + self._publication_failed = publication_failed + + def __getattr__(self, name: str) -> Callable[..., Awaitable[Any]]: + handler = getattr(self._events(), name) + + async def call(*args: Any, **kwargs: Any) -> Any: + try: + return await handler(*args, **kwargs) + except asyncio.CancelledError: + raise + except Exception as e: + if name == "on_publication" and args: + # Not delivered: the teardown that follows must not count it. + self._publication_failed(args[0]) + client = self._client() + if client is not None: + await client._handler_raised(e) + else: + asyncio.get_running_loop().call_exception_handler({ + "message": "exception in a centrifuge event handler", + "exception": e, + }) + return None + + return call + + class _TimeoutTimer: """A loop.call_later() for timeouts. A timer that fires much later than scheduled means the process was suspended (frozen in the background, stopped @@ -343,6 +384,10 @@ def __init__( self.__connected_future: Optional[asyncio.Future] = None self._token = token self._get_token = get_token + self._handler_failures = 0 + self._ev = _GuardedEvents( + lambda: self.events, lambda: self, self._server_publication_failed + ) # Set when the server answered "token expired" (109): the next attempt gets # a new token from get_token - or, without one, stops as unauthorized. self._refresh_required = False @@ -592,6 +637,27 @@ async def _create_connection(self) -> None: logger.exception("exception during connection attempt") await self._handler_failed(attempt, e) + async def _handler_raised(self, e: Exception) -> None: + """An exception escaping an event handler of the app. The SDK can't know + what the handler left undone, so it fails loudly instead of going on as if + nothing happened, as centrifuge-js does: the exception is re-raised to the + event loop's exception handler, and the client disconnects with "bad + protocol" and doesn't reconnect. Its own processing goes on as if the + handler had returned, as for a handler calling disconnect().""" + self._handler_failures += 1 + asyncio.get_running_loop().call_exception_handler({ + "message": "exception in a centrifuge event handler", + "exception": e, + }) + if self.state != ClientState.DISCONNECTED: + code = _DisconnectedCode.BAD_PROTOCOL + await self._disconnect(_code_number(code), f"exception in event handler: {e}", False) + + def _server_publication_failed(self, ctx: Any) -> None: + channel = getattr(ctx, "channel", None) + if channel is not None: + self._server_pending.pop(channel, None) + async def _handler_failed(self, attempt: int, e: Exception) -> None: if self._attempt_current(attempt): # Still connecting: retry with backoff. @@ -621,7 +687,7 @@ async def _connection_attempt(self) -> None: if self._refresh_required and self._get_token is None: # The token expired and there is nothing to get a new one with. - handler = self.events.on_error + handler = self._ev.on_error await handler( ErrorContext( code=_code_number(_ErrorCode.BAD_CONFIGURATION), @@ -671,7 +737,7 @@ async def _connection_attempt(self) -> None: self._open_task = None if not self._attempt_current(attempt): return - handler = self.events.on_error + handler = self._ev.on_error await handler(ErrorContext(code=_code_number(_ErrorCode.TRANSPORT_CLOSED), error=e)) if self._attempt_current(attempt): await self._schedule_reconnect() @@ -703,14 +769,14 @@ async def _connection_attempt(self) -> None: except OperationTimeoutError as e: if not self._attempt_current(attempt): return - handler = self.events.on_error + handler = self._ev.on_error await handler(ErrorContext(code=_code_number(_ErrorCode.TIMEOUT), error=e)) await self._fail_connection_attempt(attempt) return except Exception as e: if not self._attempt_current(attempt): return - handler = self.events.on_error + handler = self._ev.on_error await handler( ErrorContext(code=_code_number(_ErrorCode.CONNECT_ERROR), error=e), ) @@ -731,7 +797,7 @@ async def _connection_attempt(self) -> None: if sent_token == self._token: self._refresh_required = True if temporary: - handler = self.events.on_error + handler = self._ev.on_error await handler( ErrorContext( code=_code_number(_ErrorCode.CONNECT_ERROR), @@ -768,7 +834,7 @@ async def _connected(self, connect: Dict[str, Any], attempt: int) -> None: self._connected_future.set_result(True) - handler = self.events.on_connected + handler = self._ev.on_connected await handler( ConnectedContext( client=connect.get("client"), @@ -829,7 +895,7 @@ async def _connect_token_failed(self, attempt: int, e: BaseException) -> None: code = _DisconnectedCode.UNAUTHORIZED await self._disconnect(_code_number(code), _code_message(code), False) return - handler = self.events.on_error + handler = self._ev.on_error await handler( ErrorContext(code=_code_number(_ErrorCode.CLIENT_CONNECT_TOKEN), error=e), ) @@ -896,7 +962,7 @@ async def _process_server_subs(self, subs: Dict[str, Dict[str, Any]], attempt: i epoch=subscribe.get("epoch", ""), ) - handler = self.events.on_subscribed + handler = self._ev.on_subscribed await handler( ServerSubscribedContext( channel=channel, @@ -924,7 +990,7 @@ async def _process_server_subs(self, subs: Dict[str, Dict[str, Any]], attempt: i for channel in channels_to_delete: if not self._connection_current(attempt): return - handler = self.events.on_unsubscribed + handler = self._ev.on_unsubscribed await handler(ServerUnsubscribedContext(channel=channel)) async def _process_server_publication(self, channel: str, pub: Any): @@ -932,13 +998,18 @@ async def _process_server_publication(self, channel: str, pub: Any): connection = self._transport_id if publication.offset > 0: self._server_pending[channel] = (connection, publication.offset) + failures = self._handler_failures try: - await self.events.on_publication( + await self._ev.on_publication( ServerPublicationContext(channel=channel, pub=publication) ) finally: if self._server_pending.get(channel, (None,))[0] == connection: del self._server_pending[channel] + if self._handler_failures != failures: + # The handler raised: the publication isn't delivered, the position + # stays before it and the client stopped. + return # A handler that finishes after its connection was lost (handlers aren't # cancelled) must not move the position the next connection recovers # from, possibly back. @@ -975,7 +1046,7 @@ async def _clear_connected_state(self, transition: int) -> None: if sub._attempt != attempt or sub.state != SubscriptionState.SUBSCRIBING: continue try: - await sub.events.on_subscribing( + await sub._ev.on_subscribing( SubscribingContext(code=_code_number(code), reason=_code_message(code)) ) except Exception: @@ -985,7 +1056,7 @@ async def _clear_connected_state(self, transition: int) -> None: if self._transition != transition: return try: - await self.events.on_subscribing(ServerSubscribingContext(channel=channel)) + await self._ev.on_subscribing(ServerSubscribingContext(channel=channel)) except Exception: logger.exception("exception in on_subscribing handler") @@ -1011,17 +1082,10 @@ async def connect(self) -> None: self._connected_future = asyncio.Future() code = _ConnectingCode.CONNECT_CALLED - try: - await self.events.on_connecting( - ConnectingContext(code=_code_number(code), reason=_code_message(code)) - ) - except Exception: - # As in centrifuge-js: the attempt starts all the same - the client - # must not stay connecting with nothing in progress - and the - # exception propagates to the caller afterwards. - if self._transition == transition and self.state == ClientState.CONNECTING: - self._spawn(self._create_connection()) - raise + await self._ev.on_connecting( + ConnectingContext(code=_code_number(code), reason=_code_message(code)) + ) + # A handler may have disconnected (or raised, which disconnects). if self._transition != transition or self.state != ClientState.CONNECTING: return # The attempt runs in a task of its own: cancelling connect() (e.g. with @@ -1082,7 +1146,7 @@ async def _refresh(self, connection: Optional[int] = None) -> None: except Exception as e: if not self._connection_current(connection): return - handler = self.events.on_error + handler = self._ev.on_error await handler( ErrorContext(code=_code_number(_ErrorCode.CLIENT_REFRESH_TOKEN), error=e), ) @@ -1102,7 +1166,7 @@ async def _refresh(self, connection: Optional[int] = None) -> None: # connected. await self._disconnect(code, message, False) return - handler = self.events.on_error + handler = self._ev.on_error await handler( ErrorContext( code=_code_number(_ErrorCode.CLIENT_REFRESH_TOKEN), @@ -1131,7 +1195,7 @@ async def _refresh_token_failed(self, connection: int, e: BaseException) -> None code = _DisconnectedCode.UNAUTHORIZED await self._disconnect(_code_number(code), _code_message(code), False) return - handler = self.events.on_error + handler = self._ev.on_error await handler( ErrorContext(code=_code_number(_ErrorCode.CLIENT_REFRESH_TOKEN), error=e), ) @@ -1213,7 +1277,7 @@ def current() -> bool: except Exception as e: if not current(): return - handler = sub.events.on_error + handler = sub._ev.on_error await handler( SubscriptionErrorContext( code=_code_number(_ErrorCode.SUBSCRIPTION_REFRESH_TOKEN), @@ -1235,7 +1299,7 @@ def current() -> bool: # to the unsubscribed state, like on a terminal subscribe error. await sub._move_unsubscribed(code, message, send_unsubscribe_command=True) return - handler = sub.events.on_error + handler = sub._ev.on_error await handler( SubscriptionErrorContext( code=_code_number(_ErrorCode.SUBSCRIPTION_REFRESH_TOKEN), @@ -1270,7 +1334,7 @@ async def _sub_refresh_token_failed( send_unsubscribe_command=True, ) return - handler = sub.events.on_error + handler = sub._ev.on_error await handler( SubscriptionErrorContext( code=_code_number(_ErrorCode.SUBSCRIPTION_REFRESH_TOKEN), @@ -1407,7 +1471,7 @@ async def _subscribe_steps( except OperationTimeoutError as e: if not current(): return None - handler = sub.events.on_error + handler = sub._ev.on_error await handler( SubscriptionErrorContext(code=_code_number(_ErrorCode.TIMEOUT), error=e), ) @@ -1421,7 +1485,7 @@ async def _subscribe_steps( except Exception as e: if not current(): return None - handler = sub.events.on_error + handler = sub._ev.on_error await handler( SubscriptionErrorContext( code=_code_number(_ErrorCode.SUBSCRIBE_ERROR), @@ -1453,7 +1517,7 @@ async def _subscribe_steps( # The token expired and there is no get_token to get another # one: unauthorized, like a connection (instead of # subscribing again without a token, which the server denies). - handler = sub.events.on_error + handler = sub._ev.on_error await handler( SubscriptionErrorContext( code=_code_number(_ErrorCode.BAD_CONFIGURATION), @@ -1472,7 +1536,7 @@ async def _subscribe_steps( temporary = True sub._token = "" if temporary: - handler = sub.events.on_error + handler = sub._ev.on_error await handler( SubscriptionErrorContext( code=_code_number(_ErrorCode.SUBSCRIBE_ERROR), @@ -1495,7 +1559,7 @@ async def _subscribe_token_failed( code = _UnsubscribedCode.UNAUTHORIZED await sub._move_unsubscribed(_code_number(code), _code_message(code)) return - handler = sub.events.on_error + handler = sub._ev.on_error await handler( SubscriptionErrorContext( code=_code_number(_ErrorCode.SUBSCRIPTION_SUBSCRIBE_TOKEN), @@ -1519,7 +1583,7 @@ async def _load_state_position( except Exception as e: if not current(): return False - handler = sub.events.on_error + handler = sub._ev.on_error await handler( SubscriptionErrorContext( code=_code_number(_ErrorCode.SUBSCRIPTION_GET_STATE), @@ -1993,10 +2057,10 @@ async def _emit_teardown_event( self, code: int, reason: str, reconnect: bool, previous_state: ClientState ) -> None: if not reconnect: - handler = self.events.on_disconnected + handler = self._ev.on_disconnected await handler(DisconnectedContext(code=code, reason=reason)) elif previous_state == ClientState.CONNECTED: - handler = self.events.on_connecting + handler = self._ev.on_connecting await handler(ConnectingContext(code=code, reason=reason)) def _stop_transport_tasks(self) -> None: @@ -2081,7 +2145,7 @@ async def _send_commands( logger.error("protocol error during send: %s", e) if self._conn is not conn: return - handler = self.events.on_error + handler = self._ev.on_error await handler(ErrorContext(code=_code_number(_ErrorCode.TRANSPORT_CLOSED), error=e)) code = _ConnectingCode.TRANSPORT_CLOSED await self._disconnect(_code_number(code), _code_message(code), True) @@ -2106,7 +2170,7 @@ async def _process_unsubscribe(self, channel: str, unsubscribe: Dict[str, Any]) server_sub = self._server_subs.get(channel) if server_sub: del self._server_subs[channel] - handler = self.events.on_unsubscribed + handler = self._ev.on_unsubscribed await handler(ServerUnsubscribedContext(channel=channel)) async def _process_subscribe(self, channel: str, subscribe: Dict[str, Any]) -> None: @@ -2122,7 +2186,7 @@ async def _process_subscribe(self, channel: str, subscribe: Dict[str, Any]) -> N stream_position = None if positioned or recoverable: stream_position = StreamPosition(offset=offset, epoch=epoch) - handler = self.events.on_subscribed + handler = self._ev.on_subscribed await handler( ServerSubscribedContext( channel=channel, @@ -2208,17 +2272,17 @@ async def _process_join(self, channel: str, join: Any, push_id: int = 0) -> None client_info = self._extract_client_info(join["info"]) sub = self._subscribed_sub_for_push(channel, push_id) if sub: - await sub.events.on_join(JoinContext(info=client_info)) + await sub._ev.on_join(JoinContext(info=client_info)) elif push_id == 0 and channel in self._server_subs: - await self.events.on_join(ServerJoinContext(channel=channel, info=client_info)) + await self._ev.on_join(ServerJoinContext(channel=channel, info=client_info)) async def _process_leave(self, channel: str, leave: Any, push_id: int = 0) -> None: client_info = self._extract_client_info(leave["info"]) sub = self._subscribed_sub_for_push(channel, push_id) if sub: - await sub.events.on_leave(LeaveContext(info=client_info)) + await sub._ev.on_leave(LeaveContext(info=client_info)) elif push_id == 0 and channel in self._server_subs: - await self.events.on_leave(ServerLeaveContext(channel=channel, info=client_info)) + await self._ev.on_leave(ServerLeaveContext(channel=channel, info=client_info)) def _extract_client_info(self, info: Any) -> ClientInfo: return ClientInfo( @@ -2364,6 +2428,9 @@ def _initialize( self.channel = channel self.state = SubscriptionState.UNSUBSCRIBED self.events = events or SubscriptionEventHandler() + self._ev = _GuardedEvents( + lambda: self.events, lambda: self._client, self._publication_failed + ) self._subscribed_future: asyncio.Future[bool] = asyncio.Future() self._subscribed = False self._client: Optional[Client] = client @@ -2491,15 +2558,13 @@ async def subscribe(self) -> None: self._subscribed_future = asyncio.Future() code = _SubscribingCode.SUBSCRIBE_CALLED - try: - await self.events.on_subscribing( - SubscribingContext(code=_code_number(code), reason=_code_message(code)) - ) - finally: - # The subscribe starts also when the handler raises (the exception - # propagates to the caller afterwards); not when it unsubscribed. - if self.state == SubscriptionState.SUBSCRIBING and self._client is not None: - await self._client._resubscribe(self) + await self._ev.on_subscribing( + SubscribingContext(code=_code_number(code), reason=_code_message(code)) + ) + # Not when a handler unsubscribed. A handler that raised stopped the client: + # the subscribe waits for the next connect. + if self.state == SubscriptionState.SUBSCRIBING and self._client is not None: + await self._client._resubscribe(self) async def unsubscribe(self) -> None: code = _UnsubscribedCode.UNSUBSCRIBE_CALLED @@ -2516,6 +2581,11 @@ def _next_attempt(self) -> int: def _session_current(self, session: int) -> bool: return self._attempt == session and self.state == SubscriptionState.SUBSCRIBED + def _publication_failed(self, _ctx: Any) -> None: + # The publication being handled isn't delivered: the end of the session + # must not commit it. + self._pending = None + def _commit_pending(self) -> None: # Called when the subscribed session ends. if self._pending is not None and self._pending[0] == self._attempt: @@ -2577,7 +2647,7 @@ async def _move_unsubscribed( # noinspection PyProtectedMember await client._unsubscribe(self) - await self.events.on_unsubscribed(UnsubscribedContext(code=code, reason=reason)) + await self._ev.on_unsubscribed(UnsubscribedContext(code=code, reason=reason)) async def _consume_subscribed_future(self) -> None: with contextlib.suppress(CentrifugeError): @@ -2615,7 +2685,7 @@ async def _move_subscribing( attempt = self._attempt try: - await self.events.on_subscribing(SubscribingContext(code=code, reason=reason)) + await self._ev.on_subscribing(SubscribingContext(code=code, reason=reason)) finally: # The resubscribe starts also when the handler raises. if ( @@ -2638,7 +2708,7 @@ async def _move_subscribed(self, subscribe: Dict[str, Any]) -> None: self.state = SubscriptionState.SUBSCRIBED session = self._next_attempt() self._subscribed_future.set_result(True) - on_subscribed_handler = self.events.on_subscribed + on_subscribed_handler = self._ev.on_subscribed recoverable = subscribe.get("recoverable", False) positioned = subscribe.get("positioned", False) stream_position = None @@ -2742,11 +2812,17 @@ async def _process_publication(self, pub: Any) -> None: if publication.offset > 0: self._pending = (session, publication.offset) + client = self._client + failures = client._handler_failures if client is not None else 0 try: - await self.events.on_publication(PublicationContext(pub=publication)) + await self._ev.on_publication(PublicationContext(pub=publication)) finally: if self._pending is not None and self._pending[0] == session: self._pending = None + if client is not None and client._handler_failures != failures: + # The handler raised: the publication isn't delivered, the position + # stays before it and the client stopped. + return # The position moves after the app has the publication - and only in the # session it belongs to: handlers aren't cancelled, and one that finishes # after its session ended must not move the position (possibly back). diff --git a/tests/test_handler_exceptions.py b/tests/test_handler_exceptions.py index 0b5ec18..340b531 100644 --- a/tests/test_handler_exceptions.py +++ b/tests/test_handler_exceptions.py @@ -1,8 +1,15 @@ +"""An exception escaping an event handler stops the client, as in centrifuge-js: +it is re-raised to the event loop's exception handler, and the client +disconnects with "bad protocol" (code 2) and doesn't reconnect. The SDK's own +work completes as if the handler had returned, and a publication whose handler +raised isn't delivered: the position stays before it.""" + import asyncio import unittest from centrifuge import Client from centrifuge.client import ClientState, SubscriptionState +from centrifuge.protocol import client_pb2 as protocol from tests.fake_server import FakeCentrifugoServer _BAD_PROTOCOL = 2 @@ -26,6 +33,11 @@ async def asyncSetUp(self): self.server = FakeCentrifugoServer() await self.server.start() self.disconnects = [] + # Where the exceptions of handlers are re-raised. + self.reported = [] + asyncio.get_running_loop().set_exception_handler( + lambda _loop, ctx: self.reported.append(ctx.get("exception")) + ) async def asyncTearDown(self): await self.server.stop() @@ -34,36 +46,58 @@ def _client(self, **kwargs): client = Client(self.server.url, use_protobuf=True, min_reconnect_delay=0.05, **kwargs) async def on_disconnected(ctx): - self.disconnects.append(ctx.code) + self.disconnects.append((ctx.code, ctx.reason)) client.events.on_disconnected = on_disconnected return client - async def test_raising_publication_handler_disconnects_visibly(self): + def _assert_stopped(self, client): + self.assertEqual(client.state, ClientState.DISCONNECTED) + self.assertEqual(len(self.disconnects), 1) + code, reason = self.disconnects[0] + self.assertEqual(code, _BAD_PROTOCOL) + self.assertTrue(reason.startswith("exception in event handler"), reason) + self.assertEqual([type(e) for e in self.reported], [AppError]) + + async def test_raising_publication_handler_stops_and_is_recovered_again(self): + self.server.on_subscribe = lambda _ch, req: protocol.SubscribeResult( + recoverable=True, + epoch="e", + offset=req.offset if req.recover else 0, + was_recovering=req.recover, + recovered=req.recover, + ) client = self._client() - sub = client.new_subscription("ch") + sub = client.new_subscription("ch", recoverable=True) + calls = [] async def on_publication(_ctx): - raise AppError("handler bug") + calls.append(1) + if len(calls) == 1: + raise AppError("handler bug") sub.events.on_publication = on_publication await client.connect() await sub.subscribe() await sub.ready() - with self.assertLogs("centrifuge", level="ERROR"): - await self.server.publish(b"1", channel="ch") - # It used to stop reading silently: connected, but deaf. - self.assertTrue(await wait_until(lambda: client.state == ClientState.DISCONNECTED)) - self.assertEqual(self.disconnects, [_BAD_PROTOCOL]) + push = protocol.Push(channel="ch") + push.pub.data = b"{}" + push.pub.offset = 1 + await self.server.send_push(push) + # It used to stop reading silently: connected, but deaf. + self.assertTrue(await wait_until(lambda: client.state == ClientState.DISCONNECTED)) + self._assert_stopped(client) - sub.events.on_publication = SubscriptionHandlerOk.on_publication await client.connect() await sub.ready() - self.assertEqual(sub.state, SubscriptionState.SUBSCRIBED) + # Not delivered: recovered from before it. + last = self.server.last_subscribe() + self.assertTrue(last.recover) + self.assertEqual(last.offset, 0) await client.disconnect() - async def test_raising_error_handler_does_not_stop_retries(self): + async def test_raising_error_handler_stops_the_client(self): calls = [] async def get_token(): @@ -73,29 +107,42 @@ async def get_token(): return "token" client = self._client(get_token=get_token) + errors = [] async def on_error(_ctx): - raise AppError("error reporting failed") + errors.append(1) + if len(errors) == 1: + raise AppError("error reporting failed") client.events.on_error = on_error - with self.assertLogs("centrifuge", level="ERROR"): - await client.connect() - # It used to stay connecting with no reconnect scheduled. - self.assertTrue(await wait_until(lambda: client.state == ClientState.CONNECTED)) - self.assertEqual(len(calls), 2) + await client.connect() + self.assertTrue(await wait_until(lambda: client.state == ClientState.DISCONNECTED)) + await asyncio.sleep(0.2) + self._assert_stopped(client) + # No retry after the stop. + self.assertEqual(len(calls), 1) + + await client.connect() + self.assertTrue(await wait_until(lambda: client.state == ClientState.CONNECTED)) await client.disconnect() async def test_raising_connecting_handler_in_connect(self): client = self._client() + calls = [] async def on_connecting(_ctx): - raise AppError("handler bug") + calls.append(1) + if len(calls) == 1: + raise AppError("handler bug") client.events.on_connecting = on_connecting - # The exception reaches the caller, but the client connects all the same - # (it used to stay connecting for good). - with self.assertRaises(AppError): # noqa: PT027 - await client.connect() + # Not raised to the caller: re-raised to the loop, and the client stops. + await client.connect() + self._assert_stopped(client) + await asyncio.sleep(0.1) + self.assertFalse(any(cmd.HasField("connect") for cmd in self.server.received)) + + await client.connect() self.assertTrue(await wait_until(lambda: client.state == ClientState.CONNECTED)) await client.disconnect() @@ -104,14 +151,21 @@ async def test_raising_subscribing_handler_in_subscribe(self): await client.connect() await client.ready() sub = client.new_subscription("ch") + calls = [] async def on_subscribing(_ctx): - raise AppError("handler bug") + calls.append(1) + if len(calls) == 1: + raise AppError("handler bug") sub.events.on_subscribing = on_subscribing - # Raises, and subscribes all the same (it used to stay subscribing). - with self.assertRaises(AppError): # noqa: PT027 - await sub.subscribe() + await sub.subscribe() + self._assert_stopped(client) + # The subscribe completed as far as it could: it waits for the connection + # (it used to stay subscribing for good). + self.assertEqual(sub.state, SubscriptionState.SUBSCRIBING) + + await client.connect() self.assertTrue(await wait_until(lambda: sub.state == SubscriptionState.SUBSCRIBED)) await client.disconnect() @@ -126,18 +180,8 @@ async def on_unsubscribed(_ctx): await client.connect() await sub.subscribe() await sub.ready() - with self.assertRaises(AppError): # noqa: PT027 - await sub.unsubscribe() - # The server is told all the same (it would keep the subscription otherwise). - self.assertTrue( - await wait_until( - lambda: any(cmd.HasField("unsubscribe") for cmd in self.server.received) - ) - ) - await client.disconnect() - - -class SubscriptionHandlerOk: - @staticmethod - async def on_publication(_ctx): - return None + await sub.unsubscribe() + # Unsubscribed, and the client stopped: the connection, and with it the + # subscription on the server, is gone. + self.assertEqual(sub.state, SubscriptionState.UNSUBSCRIBED) + self._assert_stopped(client) diff --git a/tests/test_teardown.py b/tests/test_teardown.py index 33a53db..c598f27 100644 --- a/tests/test_teardown.py +++ b/tests/test_teardown.py @@ -225,7 +225,8 @@ async def get_token(): class TestTeardownWithRaisingHandlers(unittest.IsolatedAsyncioTestCase): - """A teardown completes - and reconnects - whatever its event handlers do.""" + """A teardown completes whatever its event handlers do. A handler that raises + stops the client (bad protocol, no reconnect): it connects again when asked.""" async def asyncSetUp(self): self.server = FakeCentrifugoServer() @@ -244,9 +245,14 @@ async def on_connecting(ctx): self.client.events.on_connecting = on_connecting await self.client.connect() await self.client.ready() - with self.assertLogs("centrifuge", level="ERROR"): - await self.server.close_connection() - self.assertTrue(await wait_until(lambda: len(connect_commands(self.server)) == 2)) + asyncio.get_running_loop().set_exception_handler(lambda _loop, _ctx: None) + await self.server.close_connection() + self.assertTrue(await wait_until(lambda: self.client.state == ClientState.DISCONNECTED)) + await asyncio.sleep(0.2) + self.assertEqual(len(connect_commands(self.server)), 1) + + self.client.events.on_connecting = ConnectingOk.on_connecting + await self.client.connect() self.assertTrue(await wait_until(lambda: self.client.state == ClientState.CONNECTED)) async def test_raising_subscribing_handler(self): @@ -260,9 +266,13 @@ async def on_subscribing(ctx): await self.client.connect() await sub.subscribe() await sub.ready() - with self.assertLogs("centrifuge", level="ERROR"): - await self.server.close_connection() - self.assertTrue(await wait_until(lambda: len(connect_commands(self.server)) == 2)) + asyncio.get_running_loop().set_exception_handler(lambda _loop, _ctx: None) + await self.server.close_connection() + self.assertTrue(await wait_until(lambda: self.client.state == ClientState.DISCONNECTED)) + self.assertEqual(sub.state, SubscriptionState.SUBSCRIBING) + + sub.events.on_subscribing = SubscribingOk.on_subscribing + await self.client.connect() self.assertTrue(await wait_until(lambda: sub.state == SubscriptionState.SUBSCRIBED)) async def test_new_subscription_from_subscribing_handler(self): @@ -395,11 +405,22 @@ async def on_subscribing(ctx): self.first.events.on_subscribing = on_subscribing await self._subscribe_both() - with self.assertLogs("centrifuge", level="ERROR"): - await self.server.close_connection() - self.assertTrue( - await wait_until(lambda: self._subscribes_on_connection(2) == ["a", "b"]) - ) + asyncio.get_running_loop().set_exception_handler(lambda _loop, _ctx: None) + await self.server.close_connection() + # The raise stopped the client; both subscriptions wait for the next connect. + self.assertTrue(await wait_until(lambda: self.client.state == ClientState.DISCONNECTED)) + self.assertEqual(self.first.state, SubscriptionState.SUBSCRIBING) + self.assertEqual(self.second.state, SubscriptionState.SUBSCRIBING) + + self.first.events.on_subscribing = SubscribingOk.on_subscribing + await self.client.connect() + self.assertTrue(await wait_until(lambda: self._subscribes_on_connection(2) == ["a", "b"])) + + +class ConnectingOk: + @staticmethod + async def on_connecting(_ctx): + return None class SubscribingOk: