From cdeeba17abe5425d60bd2eb17dcbdc664e6d9516 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Tue, 24 Nov 2026 18:30:58 -0700 Subject: [PATCH] fix(remote): close a session channel whose loop already ended --- tests/remote/unit/test_remote_probes.py | 18 +++++++++++++++++- unshackle/core/remote_channel.py | 3 ++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/tests/remote/unit/test_remote_probes.py b/tests/remote/unit/test_remote_probes.py index 52b6d0d8..afc14284 100644 --- a/tests/remote/unit/test_remote_probes.py +++ b/tests/remote/unit/test_remote_probes.py @@ -2,8 +2,10 @@ from __future__ import annotations +import asyncio import json from threading import Event, Thread +from types import SimpleNamespace from typing import Any, Callable import pytest @@ -11,7 +13,7 @@ import responses from tests.remote.unit.test_session_reopen import SERVER, make_service from unshackle.core import remote_channel, remote_service -from unshackle.core.remote_channel import PollingChannel, ServerMessages +from unshackle.core.remote_channel import PollingChannel, ServerMessages, WebSocketChannel from unshackle.core.remote_protocol import ClientErrorKind from unshackle.core.remote_service import RemoteClient @@ -136,3 +138,17 @@ def test_a_tunnel_copies_the_auth_header_the_server_reads(monkeypatch: pytest.Mo remote_service.start_tunnel(client) assert sent[0].get("X-Api-Key") == KEY and "X-Secret-Key" not in sent[0] + + +def test_a_channel_closes_after_its_loop_has_closed() -> None: + """A refused upgrade closes the loop of the channel thread before the thread ends.""" + service = make_service() + service.ctx = SimpleNamespace(obj=None) + messages = ServerMessages(service) + channel = WebSocketChannel(messages, PollingChannel(messages)) + loop = asyncio.new_event_loop() + loop.close() + channel.loop, channel.task = loop, SimpleNamespace(cancel=lambda: None) + channel.thread = SimpleNamespace(is_alive=lambda: True, join=lambda timeout=None: None) + + channel.close() diff --git a/unshackle/core/remote_channel.py b/unshackle/core/remote_channel.py index ce06ecb1..14513e8f 100644 --- a/unshackle/core/remote_channel.py +++ b/unshackle/core/remote_channel.py @@ -468,7 +468,8 @@ class WebSocketChannel: def close(self) -> None: if self.loop and self.task and self.thread.is_alive(): - self.loop.call_soon_threadsafe(self.task.cancel) + with contextlib.suppress(RuntimeError): # the loop closes before its thread ends + self.loop.call_soon_threadsafe(self.task.cancel) self.thread.join(5) self.fallback.close() self.messages.close_cdm_sessions()