diff --git a/proxy/raw_websocket.py b/proxy/raw_websocket.py index c18b610..d4e5abf 100644 --- a/proxy/raw_websocket.py +++ b/proxy/raw_websocket.py @@ -60,6 +60,21 @@ def _xor_mask(data: bytes, mask: bytes) -> bytes: int.from_bytes(mask_rep, 'big')).to_bytes(n, 'big') +async def _wait_close(awaitable, timeout): + # wait_for() can lose external cancellation when its task finishes at the + # same time on Python < 3.12. wait() leaves cancellation with the caller. + task = asyncio.ensure_future(awaitable) + try: + done, _ = await asyncio.wait((task,), timeout=timeout) + if not done: + raise asyncio.TimeoutError() + return task.result() + finally: + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + def set_sock_opts(transport, buffer_size): sock = transport.get_extra_info('socket') if sock is None: @@ -87,6 +102,7 @@ class RawWebSocket: OP_PONG = 0xA MAX_MESSAGE_LEN = 16 * 1024 * 1024 + CLOSE_TIMEOUT = 2.0 def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter): @@ -253,13 +269,22 @@ class RawWebSocket: try: self.writer.write( self._build_frame(self.OP_CLOSE, b'', mask=True)) - await self.writer.drain() + await _wait_close(self.writer.drain(), self.CLOSE_TIMEOUT) except Exception: pass finally: try: self.writer.close() - await self.writer.wait_closed() + # A silent TLS peer would hold us here for ssl_shutdown_timeout + # (30s) and delay proxy shutdown past the tray's stop timeout + await _wait_close(self.writer.wait_closed(), self.CLOSE_TIMEOUT) + except (asyncio.TimeoutError, asyncio.CancelledError) as exc: + try: + self.writer.transport.abort() + except Exception: + pass + if isinstance(exc, asyncio.CancelledError): + raise except Exception: pass diff --git a/tests/test_pool.py b/tests/test_pool.py index c31b51c..3f87cf4 100644 --- a/tests/test_pool.py +++ b/tests/test_pool.py @@ -295,6 +295,8 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase): self.assertIsNone(await self.pool.get(2, '192.0.2.2', ['worker.example'])) await self.wait_for(lambda: bool(self.pool._idle[2])) self.assertIs(self.pool._idle[2][0][0], ready) + # Refill and stale connection cleanup run independently. + await self.wait_for(lambda: stale.writer.close.called) stale.writer.close.assert_called_once() await self.pool.close() diff --git a/tests/test_raw_websocket.py b/tests/test_raw_websocket.py index ee8c795..3810ad3 100644 --- a/tests/test_raw_websocket.py +++ b/tests/test_raw_websocket.py @@ -16,6 +16,10 @@ def _raw_frame(opcode, data, fin=True): return bytes([b0, 127]) + n.to_bytes(8, 'big') + data +async def _hang(): + await asyncio.Future() + + class _NullWriter: def write(self, data): pass @@ -145,6 +149,23 @@ class ParseCloseTest(unittest.TestCase): class CloseTest(unittest.IsolatedAsyncioTestCase): + async def test_cancellation_when_close_operation_finishes_is_not_lost(self): + for operation in ('drain', 'wait_closed'): + with self.subTest(operation=operation): + task = None + + async def finish_and_cancel(): + task.cancel() + + writer = Mock(drain=AsyncMock(), wait_closed=AsyncMock()) + getattr(writer, operation).side_effect = finish_and_cancel + ws = RawWebSocket(asyncio.StreamReader(), writer) + task = asyncio.create_task(ws.close()) + with self.assertRaises(asyncio.CancelledError): + await task + writer.close.assert_called_once() + writer.wait_closed.assert_awaited_once() + async def test_peer_close_still_closes_transport_without_another_close_frame(self): reader = asyncio.StreamReader() reader.feed_data(_raw_frame(RawWebSocket.OP_CLOSE, b'\x03\xe8')) @@ -190,6 +211,55 @@ class CloseTest(unittest.IsolatedAsyncioTestCase): task.cancel() await asyncio.gather(task, return_exceptions=True) + async def test_silent_peer_does_not_hold_close_until_tls_shutdown_timeout(self): + # TLS wait_closed() waits for the peer's close_notify for up to 30s + writer = Mock(drain=AsyncMock(), wait_closed=AsyncMock(side_effect=_hang)) + ws = RawWebSocket(asyncio.StreamReader(), writer) + + with patch.object(RawWebSocket, 'CLOSE_TIMEOUT', .01): + await asyncio.wait_for(ws.close(), 1) + + writer.close.assert_called_once() + writer.transport.abort.assert_called_once() + + async def test_peer_that_stopped_reading_does_not_hold_close_in_drain(self): + writer = Mock(drain=AsyncMock(side_effect=_hang), wait_closed=AsyncMock()) + ws = RawWebSocket(asyncio.StreamReader(), writer) + + with patch.object(RawWebSocket, 'CLOSE_TIMEOUT', .01): + await asyncio.wait_for(ws.close(), 1) + + writer.close.assert_called_once() + writer.wait_closed.assert_awaited_once() + writer.transport.abort.assert_not_called() + + async def test_failing_abort_after_timeout_does_not_escape_close(self): + writer = Mock(drain=AsyncMock(), wait_closed=AsyncMock(side_effect=_hang)) + writer.transport.abort.side_effect = RuntimeError('transport already gone') + ws = RawWebSocket(asyncio.StreamReader(), writer) + + with patch.object(RawWebSocket, 'CLOSE_TIMEOUT', .01): + await asyncio.wait_for(ws.close(), 1) + + writer.transport.abort.assert_called_once() + + async def test_cancelling_close_during_wait_closed_propagates_without_hanging(self): + waiting = asyncio.Event() + + async def wait_closed(): + waiting.set() + await asyncio.Future() + + writer = Mock(drain=AsyncMock(), wait_closed=AsyncMock(side_effect=wait_closed)) + ws = RawWebSocket(asyncio.StreamReader(), writer) + task = asyncio.create_task(ws.close()) + await asyncio.wait_for(waiting.wait(), 1) + task.cancel() + with self.assertRaises(asyncio.CancelledError): + await asyncio.wait_for(task, 1) + writer.close.assert_called_once() + writer.transport.abort.assert_called_once() + class HandshakeErrorTest(unittest.TestCase): def test_redirect_status_codes(self): diff --git a/tests/test_tray_common.py b/tests/test_tray_common.py index 33ccdf3..0f77b12 100644 --- a/tests/test_tray_common.py +++ b/tests/test_tray_common.py @@ -1,8 +1,13 @@ +import asyncio +import threading import unittest from unittest import mock from utils import tray_common +# Captured before tests patch threading.Thread for the proxy thread +_RealThread = threading.Thread + class CheckUpdateAsyncTest(unittest.TestCase): def test_disabled_check_does_not_start_a_thread(self): @@ -45,5 +50,291 @@ class CheckUpdateAsyncTest(unittest.TestCase): self.assertEqual(seen, []) +class _StoppingThread: + """A proxy thread whose cleanup outlives stop_proxy()'s join timeout.""" + + def __init__(self, finishes_on_join): + self.alive = True + self.finishes_on_join = finishes_on_join + self.joins = [] + + def is_alive(self): + return self.alive + + def join(self, timeout=None): + self.joins.append(timeout) + if self.finishes_on_join: + self.alive = False + + +class _FakeLoop: + def __init__(self): + self.stop_requests = 0 + + def call_soon_threadsafe(self, callback): + self.stop_requests += 1 + + +class ProxyStartupTest(unittest.TestCase): + def test_restart_before_loop_is_ready_does_not_lose_stop(self): + entering_loop = threading.Event() + release_loop = threading.Event() + restarted = threading.Event() + new_event_loop = asyncio.new_event_loop + runs = [] + errors = [] + + def delayed_loop(): + entering_loop.set() + if not release_loop.wait(2): + raise AssertionError('proxy startup was not released') + return new_event_loop() + + async def run(stop_event): + runs.append(stop_event.is_set()) + if len(runs) == 2: + restarted.set() + await stop_event.wait() + + with mock.patch.object(tray_common, '_proxy_thread', None), \ + mock.patch.object(tray_common, '_async_stop', None), \ + mock.patch.object(tray_common, '_stop_requested', threading.Event()), \ + mock.patch.object(tray_common, '_lifecycle_version', 0), \ + mock.patch.object(tray_common, 'apply_proxy_config', return_value=True), \ + mock.patch.object(tray_common.asyncio, 'new_event_loop', side_effect=delayed_loop), \ + mock.patch.object(tray_common, '_run', side_effect=run), \ + mock.patch.object(tray_common.time, 'sleep'): + click = _RealThread(target=tray_common.restart_proxy, args=({}, errors.append)) + try: + tray_common.start_proxy({}, errors.append) + self.assertTrue(entering_loop.wait(1)) + click.start() + self.assertTrue(tray_common._stop_requested.wait(1)) + release_loop.set() + self.assertTrue(restarted.wait(2)) + click.join(2) + self.assertFalse(click.is_alive()) + self.assertEqual(runs, [True, False]) + self.assertEqual(errors, []) + finally: + release_loop.set() + tray_common.stop_proxy() + if click.ident is not None: + click.join(3) + + +class ProxyLifecycleTest(unittest.TestCase): + """Real start/stop/restart with a fake proxy thread: nothing binds a port.""" + + def setUp(self): + self.created = [] + self.started_beside_alive = 0 + + def new_thread(*args, **kwargs): + current = tray_common._proxy_thread + if any(t.is_alive() for t in self.created) or (current and current.is_alive()): + self.started_beside_alive += 1 + thread = _StoppingThread(finishes_on_join=True) + thread.start = lambda: None + self.created.append(thread) + return thread + + for patcher in ( + mock.patch.object(tray_common, '_proxy_thread', None), + mock.patch.object(tray_common, '_stop_requested', threading.Event()), + mock.patch.object(tray_common, '_lifecycle_version', 0), + mock.patch.object(tray_common, '_async_stop', (_FakeLoop(), threading.Event())), + mock.patch.object(tray_common, 'apply_proxy_config', return_value=True), + mock.patch.object(tray_common.threading, 'Thread', side_effect=new_thread), + mock.patch.object(tray_common.time, 'sleep')): + patcher.start() + self.addCleanup(patcher.stop) + + def test_start_does_not_replace_a_running_proxy(self): + running = _StoppingThread(finishes_on_join=False) + tray_common._proxy_thread = running + tray_common.start_proxy({}, lambda message: None) + self.assertIs(tray_common._proxy_thread, running) + self.assertEqual(self.created, []) + + def test_restart_waits_for_cleanup_and_starts_automatically(self): + stuck = _StoppingThread(finishes_on_join=False) + tray_common._proxy_thread = stuck + waiting = threading.Event() + finished = threading.Event() + + def join(timeout=None): + stuck.joins.append(timeout) + if timeout is None: + waiting.set() + if not finished.wait(2): + raise AssertionError('old proxy was not released') + stuck.alive = False + + stuck.join = join + click = _RealThread(target=tray_common.restart_proxy, + args=({}, lambda message: None)) + click.start() + try: + self.assertTrue(waiting.wait(1), 'restart must wait for the old proxy') + self.assertEqual(self.created, []) + self.assertTrue(stuck.is_alive()) + finally: + finished.set() + click.join(3) + + self.assertFalse(click.is_alive()) + self.assertEqual(stuck.joins, [None]) + self.assertFalse(stuck.is_alive()) + self.assertEqual(len(self.created), 1) + self.assertIs(tray_common._proxy_thread, self.created[0]) + + def test_start_after_stop_timeout_waits_for_cleanup(self): + running = _StoppingThread(finishes_on_join=False) + tray_common._proxy_thread = running + tray_common.stop_proxy() + self.assertIs(tray_common._proxy_thread, running) + + running.finishes_on_join = True + tray_common.start_proxy({}, lambda message: None) + + self.assertEqual(running.joins, [5, None]) + self.assertFalse(running.is_alive()) + self.assertEqual(len(self.created), 1) + + def test_stop_before_loop_is_ready_still_joins_thread(self): + running = _StoppingThread(finishes_on_join=True) + tray_common._proxy_thread = running + with mock.patch.object(tray_common, '_async_stop', None): + tray_common.stop_proxy() + self.assertTrue(tray_common._stop_requested.is_set()) + self.assertEqual(running.joins, [5]) + self.assertIsNone(tray_common._proxy_thread) + + def test_stop_handles_loop_closed_during_signal(self): + loop = mock.Mock() + loop.call_soon_threadsafe.side_effect = RuntimeError('Event loop is closed') + loop.is_closed.return_value = True + running = _StoppingThread(finishes_on_join=True) + tray_common._proxy_thread = running + with mock.patch.object(tray_common, '_async_stop', (loop, threading.Event())): + tray_common.restart_proxy({}, lambda message: None) + self.assertFalse(running.is_alive()) + self.assertEqual(len(self.created), 1) + + def test_stop_supersedes_pending_restart(self): + self.check_stop_supersedes(tray_common.restart_proxy) + + def test_stop_supersedes_pending_start_after_stop_timeout(self): + tray_common._stop_requested.set() + self.check_stop_supersedes(tray_common.start_proxy) + + def check_stop_supersedes(self, action): + running = _StoppingThread(finishes_on_join=False) + tray_common._proxy_thread = running + waiting = threading.Event() + finished = threading.Event() + + def join(timeout=None): + if timeout is None: + waiting.set() + if not finished.wait(2): + raise AssertionError('old proxy was not released') + running.alive = False + + running.join = join + click = _RealThread(target=action, + args=({}, lambda message: None)) + click.start() + try: + self.assertTrue(waiting.wait(1)) + # stop_proxy must return even while restart is waiting on cleanup. + stopped = threading.Event() + stop = _RealThread(target=lambda: (tray_common.stop_proxy(), stopped.set())) + stop.start() + try: + self.assertTrue(stopped.wait(1)) + finally: + finished.set() + stop.join(3) + finally: + finished.set() + click.join(3) + self.assertFalse(click.is_alive()) + self.assertEqual(self.created, []) + + def test_latest_restart_uses_latest_config(self): + running = _StoppingThread(finishes_on_join=False) + tray_common._proxy_thread = running + first_waiting = threading.Event() + both_waiting = threading.Event() + finished = threading.Event() + joins = [] + + def join(timeout=None): + joins.append(timeout) + first_waiting.set() + if len(joins) == 2: + both_waiting.set() + if not finished.wait(2): + raise AssertionError('old proxy was not released') + running.alive = False + + running.join = join + clicks = [_RealThread(target=tray_common.restart_proxy, + args=({'port': port}, lambda message: None)) + for port in (1080, 1081)] + clicks[0].start() + try: + self.assertTrue(first_waiting.wait(1)) + clicks[1].start() + self.assertTrue(both_waiting.wait(1)) + finally: + finished.set() + for click in clicks: + if click.ident is not None: + click.join(3) + self.assertTrue(all(not click.is_alive() for click in clicks)) + tray_common.apply_proxy_config.assert_called_once_with({'port': 1081}) + self.assertEqual(len(self.created), 1) + self.assertEqual(self.started_beside_alive, 0) + + def test_normal_stop_then_start(self): + running = _StoppingThread(finishes_on_join=True) + tray_common._proxy_thread = running + + tray_common.stop_proxy() + tray_common.start_proxy({}, lambda message: None) + + self.assertFalse(running.is_alive()) + self.assertEqual(len(self.created), 1) + self.assertIs(tray_common._proxy_thread, self.created[0]) + + def test_parallel_restarts_never_run_two_proxies_at_once(self): + tray_common._proxy_thread = _StoppingThread(finishes_on_join=True) + both_checked = threading.Barrier(2, timeout=1) + + def apply_after_both_checked(cfg): + # Without serialisation both restarts get here before either sets _proxy_thread + try: + both_checked.wait() + except threading.BrokenBarrierError: + pass + return True + + tray_common.apply_proxy_config.side_effect = apply_after_both_checked + clicks = [_RealThread(target=tray_common.restart_proxy, args=({}, lambda message: None)) + for _ in range(2)] + for click in clicks: + click.start() + for click in clicks: + click.join(5) + + # Concurrent requests may coalesce, but never start beside a live proxy. + self.assertEqual(self.started_beside_alive, 0) + self.assertEqual(sum(t.is_alive() for t in self.created), 1) + self.assertIs(tray_common._proxy_thread, self.created[-1]) + + if __name__ == '__main__': unittest.main() diff --git a/utils/tray_common.py b/utils/tray_common.py index 089d0ee..37f21db 100644 --- a/utils/tray_common.py +++ b/utils/tray_common.py @@ -304,6 +304,11 @@ def load_icon(): _proxy_thread: Optional[threading.Thread] = None _async_stop: Optional[Tuple[asyncio.AbstractEventLoop, asyncio.Event]] = None +_stop_requested = threading.Event() +_lifecycle_version = 0 +# Tray actions run start/stop/restart from worker threads; serialise them so +# repeated clicks cannot interleave and start two proxies +_lifecycle_lock = threading.RLock() def _run_proxy_thread(show_error: Callable[[str], None]) -> None: @@ -313,6 +318,8 @@ def _run_proxy_thread(show_error: Callable[[str], None]) -> None: asyncio.set_event_loop(loop) stop_ev = asyncio.Event() _async_stop = (loop, stop_ev) + if _stop_requested.is_set(): + stop_ev.set() try: loop.run_until_complete(_run(stop_event=stop_ev)) @@ -335,8 +342,8 @@ def _run_proxy_thread(show_error: Callable[[str], None]) -> None: *pending, return_exceptions=True )) loop.run_until_complete(loop.shutdown_asyncgens()) - loop.close() _async_stop = None + loop.close() def apply_proxy_config(cfg: dict) -> bool: @@ -378,43 +385,84 @@ def apply_proxy_config(cfg: dict) -> bool: def start_proxy(cfg: dict, on_error: Callable[[str], None]) -> None: - global _proxy_thread - if _proxy_thread and _proxy_thread.is_alive(): - log.info("Proxy already running") - return + global _proxy_thread, _lifecycle_version + with _lifecycle_lock: + previous = _proxy_thread + if previous and previous.is_alive() and not _stop_requested.is_set(): + log.info("Proxy already running") + return + _lifecycle_version += 1 + version = _lifecycle_version - if not apply_proxy_config(cfg): - from ui.i18n import t - on_error(t("error.dc_config")) - return + # Update recovery can call start_proxy() after a timed-out stop, too. + # Leave the lock free so a later stop can cancel this pending start. + if previous and previous.is_alive(): + previous.join() - pc = proxy_config - log.info("Starting proxy on %s:%d ...", pc.host, pc.port) - _proxy_thread = threading.Thread( - target=_run_proxy_thread, args=(on_error,), daemon=True, name="proxy" - ) - _proxy_thread.start() + with _lifecycle_lock: + if version != _lifecycle_version: + return + if not apply_proxy_config(cfg): + from ui.i18n import t + on_error(t("error.dc_config")) + return + + pc = proxy_config + log.info("Starting proxy on %s:%d ...", pc.host, pc.port) + _proxy_thread = threading.Thread( + target=_run_proxy_thread, args=(on_error,), daemon=True, name="proxy" + ) + _stop_requested.clear() + _proxy_thread.start() + + +def _request_proxy_stop(): + global _lifecycle_version + # Called under _lifecycle_lock. Remember stops issued before the proxy + # thread has published its loop, and invalidate any pending restart. + _lifecycle_version += 1 + _stop_requested.set() + handle = _async_stop + if handle: + loop, stop_ev = handle + try: + loop.call_soon_threadsafe(stop_ev.set) + except RuntimeError: + if not loop.is_closed(): + raise + return _proxy_thread, _lifecycle_version def stop_proxy() -> None: - global _proxy_thread, _async_stop - if _async_stop: - loop, stop_ev = _async_stop - loop.call_soon_threadsafe(stop_ev.set) - if _proxy_thread: - _proxy_thread.join(timeout=5) - if _proxy_thread.is_alive(): - log.warning("Proxy thread did not stop within timeout; " - "port may still be in use") - _proxy_thread = None - log.info("Proxy stopped") + global _proxy_thread + with _lifecycle_lock: + previous, _ = _request_proxy_stop() + if previous: + previous.join(timeout=5) + with _lifecycle_lock: + # Keep a thread that is still cleaning up, so start_proxy() and the + # next restart see it instead of starting a second proxy beside it + if _proxy_thread is previous and previous and not previous.is_alive(): + _proxy_thread = None + if previous and previous.is_alive(): + log.warning("Proxy thread did not stop within timeout; " + "port may still be in use") + return + log.info("Proxy stopped") def restart_proxy(cfg: dict, on_error: Callable[[str], None]) -> None: - log.info("Restarting proxy...") - stop_proxy() + with _lifecycle_lock: + log.info("Restarting proxy...") + previous, version = _request_proxy_stop() + # The old run still owns shared pools and the stop handle. Wait outside + # the lock so stopping or exiting can supersede this restart. + if previous and previous.is_alive(): + previous.join() time.sleep(1.0) - start_proxy(cfg, on_error) + with _lifecycle_lock: + if version == _lifecycle_version: + start_proxy(cfg, on_error) def tg_proxy_url(cfg: dict) -> str: