fix(remote): run the session channel and tunnel loops without asyncio.run so exit starts no thread on Python 3.12.0-3.12.2

This commit is contained in:
imSp4rky
2026-11-29 07:38:18 -07:00
parent 6b662d4fc0
commit 6fc2d84bd7
3 changed files with 71 additions and 6 deletions
+45
View File
@@ -17,6 +17,7 @@ from unshackle.core import remote_channel, remote_service
from unshackle.core.remote_channel import PollingChannel, ServerMessages, WebSocketChannel
from unshackle.core.remote_protocol import ClientErrorKind
from unshackle.core.remote_service import RemoteClient
from unshackle.core.tunnel import TunnelClient, run_loop
pytestmark = pytest.mark.unit
@@ -153,3 +154,47 @@ def test_a_channel_closes_after_its_loop_has_closed() -> None:
channel.thread = SimpleNamespace(is_alive=lambda: True, join=lambda timeout=None: None)
channel.close()
def refuse_threads_after_executor_use(monkeypatch: pytest.MonkeyPatch) -> Callable[[Any], Any]:
"""A run that uses the default executor, then refuses every new thread, as Python 3.12.0 to 3.12.2 do at exit."""
def refuse(self: Thread) -> None:
raise RuntimeError("can't create new thread at interpreter shutdown")
async def run(self: Any) -> None:
await asyncio.get_running_loop().run_in_executor(None, lambda: None)
monkeypatch.setattr(Thread, "start", refuse)
return run
def test_a_channel_loop_ends_without_starting_a_thread(monkeypatch: pytest.MonkeyPatch) -> None:
"""The channel thread shuts its loop's executor down without a new thread."""
monkeypatch.setattr(WebSocketChannel, "run", refuse_threads_after_executor_use(monkeypatch))
service = make_service()
service.ctx = SimpleNamespace(obj=None)
messages = ServerMessages(service)
channel = WebSocketChannel(messages, PollingChannel(messages))
channel.thread.run()
def test_a_tunnel_loop_ends_without_starting_a_thread(monkeypatch: pytest.MonkeyPatch) -> None:
"""The tunnel thread, which the same atexit close stops, shuts its loop's executor down without a new thread."""
monkeypatch.setattr(TunnelClient, "run", refuse_threads_after_executor_use(monkeypatch))
client = TunnelClient(SERVER, {})
client.thread.run()
def test_a_thread_loop_cancels_the_tasks_its_run_leaves() -> None:
"""A task that the run leaves, such as a channel answer still sending, ends cancelled when the loop closes."""
left: list[asyncio.Future[None]] = []
async def main() -> None:
left.append(asyncio.ensure_future(asyncio.sleep(10)))
run_loop(main)
assert left[0].cancelled()
+2 -4
View File
@@ -42,7 +42,7 @@ from unshackle.core.remote_protocol import (
SessionInfo,
)
from unshackle.core.remote_service import RemoteError, quiet, ws_headers
from unshackle.core.tunnel import HEARTBEAT, retry_after
from unshackle.core.tunnel import HEARTBEAT, retry_after, run_loop
if TYPE_CHECKING:
from unshackle.core.remote_service import RemoteService
@@ -326,9 +326,7 @@ class WebSocketChannel:
self.ws: aiohttp.ClientWebSocketResponse | None = None
self.loop: asyncio.AbstractEventLoop | None = None
self.task: asyncio.Task[None] | None = None
self.thread = Thread(
target=lambda: asyncio.run(self.run()), name=f"{self.service.service_tag}-channel", daemon=True
)
self.thread = Thread(target=run_loop, args=(self.run,), name=f"{self.service.service_tag}-channel", daemon=True)
def open(self, timeout: float = CONNECT_TIMEOUT) -> bool:
"""Connect once; False when the server or a gateway refuses the channel, or the connection fails."""
+23 -1
View File
@@ -10,6 +10,7 @@ from __future__ import annotations
import asyncio
import base64
import contextlib
import functools
import ipaddress
import itertools
@@ -21,6 +22,7 @@ import socket
import ssl
import struct
import threading
from collections.abc import Callable, Coroutine
from typing import Any
from urllib.parse import unquote, urlsplit
@@ -509,6 +511,25 @@ def refusal(e: aiohttp.WSServerHandshakeError) -> str:
return "HTTP 429, the API key already has the maximum number of tunnels open"
def run_loop(main: Callable[[], Coroutine[Any, Any, None]]) -> None:
"""Run ``main()`` on an event loop of its own, for a daemon thread that an atexit handler stops.
Python 3.12.0 to 3.12.2 refuse a new thread from the start of interpreter shutdown, and asyncio.run starts one to
shut its default executor down; loop.close shuts the executor down without one.
"""
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(main())
finally:
left = asyncio.all_tasks(loop)
for task in left:
task.cancel()
if left:
loop.run_until_complete(asyncio.gather(*left, return_exceptions=True))
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
class TunnelClient:
"""The client side: a background thread that keeps the tunnel's WebSocket open and dials for the server."""
@@ -525,7 +546,7 @@ class TunnelClient:
self.ready = threading.Event()
self.relays: set[asyncio.Task[None]] = set()
self.refused: set[str] = set()
self.thread = threading.Thread(target=lambda: asyncio.run(self.run()), name="tunnel", daemon=True)
self.thread = threading.Thread(target=run_loop, args=(self.run,), name="tunnel", daemon=True)
self.loop: asyncio.AbstractEventLoop | None = None
self.task: asyncio.Task[None] | None = None
@@ -540,6 +561,7 @@ class TunnelClient:
def stop(self) -> None:
"""Close the tunnel and wait for its connections to end, so none is left pending at exit."""
if self.loop and self.task and self.thread.is_alive():
with contextlib.suppress(RuntimeError): # the loop closes before its thread ends
self.loop.call_soon_threadsafe(self.task.cancel)
self.thread.join(5)