diff --git a/tests/remote/unit/test_remote_probes.py b/tests/remote/unit/test_remote_probes.py index 19490363f..619c4783d 100644 --- a/tests/remote/unit/test_remote_probes.py +++ b/tests/remote/unit/test_remote_probes.py @@ -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() diff --git a/unshackle/core/remote_channel.py b/unshackle/core/remote_channel.py index da2d7e111..97b5a89e7 100644 --- a/unshackle/core/remote_channel.py +++ b/unshackle/core/remote_channel.py @@ -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.""" diff --git a/unshackle/core/tunnel.py b/unshackle/core/tunnel.py index 3c8835e25..559142404 100644 --- a/unshackle/core/tunnel.py +++ b/unshackle/core/tunnel.py @@ -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,7 +561,8 @@ 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(): - 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) async def run(self) -> None: