Socket occupation fix

This commit is contained in:
Flowseal
2026-11-23 06:28:14 +03:00
parent 0970820f1f
commit 13d764f809
9 changed files with 295 additions and 41 deletions
+29
View File
@@ -26,6 +26,35 @@ def _wake_later(loop, callback):
return thread
class ClientSetupTest(unittest.IsolatedAsyncioTestCase):
async def test_fin_cancels_pending_setup_and_closes_accepted_socket(self):
started, cancelled = asyncio.Event(), asyncio.Event()
async def handle(reader, writer):
try:
with event_loop.client_setup(reader, writer):
started.set()
await asyncio.Future()
except asyncio.CancelledError:
cancelled.set()
finally:
writer.close()
await writer.wait_closed()
loop = asyncio.get_running_loop()
server = await loop.create_server(lambda: event_loop.ClientStreamProtocol(handle), '127.0.0.1', 0)
async with server:
peer, writer = await asyncio.open_connection('127.0.0.1', server.sockets[0].getsockname()[1])
try:
await asyncio.wait_for(started.wait(), 1)
writer.write_eof()
await asyncio.wait_for(cancelled.wait(), 1)
self.assertEqual(await asyncio.wait_for(peer.read(1), 1), b'')
finally:
writer.close()
await writer.wait_closed()
@unittest.skipUnless(sys.platform == 'win32', 'Windows proactor self-pipe')
class WindowsSelfPipeTest(unittest.TestCase):
def setUp(self):
+6 -2
View File
@@ -1,4 +1,5 @@
"""H2 belongs to CF fallback, never to the direct route."""
import asyncio
import unittest
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock, patch
@@ -14,7 +15,7 @@ class H2RoutingTest(unittest.IsolatedAsyncioTestCase):
writer = Mock()
writer.get_extra_info.return_value = None
writer.wait_closed = AsyncMock()
ws = Mock(send=AsyncMock())
ws = Mock(send_init=AsyncMock())
pool = SimpleNamespace(open=AsyncMock())
with patch.object(proxy_config, 'dc_redirects', {2: '149.154.167.51'}), \
patch.object(proxy_config, 'force_test_dc', False), \
@@ -30,6 +31,7 @@ class H2RoutingTest(unittest.IsolatedAsyncioTestCase):
patch.object(tg_ws_proxy, 'do_fallback', AsyncMock()) as fallback:
await tg_ws_proxy._handle_client(reader, writer, b'')
direct.assert_awaited_once()
ws.send_init.assert_awaited_once()
fallback.assert_not_awaited()
pool.open.assert_not_awaited()
@@ -89,8 +91,10 @@ class H2RoutingTest(unittest.IsolatedAsyncioTestCase):
patch.object(bridge, '_cfproxy_fallback', side_effect=route('ws')), \
patch.object(bridge, '_cfproxy_worker_fallback', side_effect=route('worker')), \
patch.object(bridge, '_tcp_fallback', side_effect=route('tcp')):
writer = Mock()
writer.is_closing.return_value = False
result = await bridge.do_fallback(
Mock(), Mock(), b'', 'test', 2, test_dc, media, '', Mock(),
asyncio.StreamReader(), writer, b'', 'test', 2, test_dc, media, '', Mock(),
h2_pool=pool, proto_tag=PROTO_TAG_INTERMEDIATE)
self.assertTrue(result)
self.assertEqual(calls, expected)
+108 -2
View File
@@ -2,6 +2,7 @@ import asyncio
import unittest
from unittest.mock import AsyncMock, Mock, patch
from proxy import raw_websocket
from proxy.raw_websocket import RawWebSocket, WsHandshakeError, _xor_mask
@@ -199,6 +200,16 @@ class HandshakeErrorTest(unittest.TestCase):
class HandshakeCleanupTest(unittest.IsolatedAsyncioTestCase):
async def test_init_send_failure_or_cancellation_aborts_transport(self):
for error in (ConnectionResetError(), asyncio.CancelledError()):
with self.subTest(error=type(error)):
writer = Mock(drain=AsyncMock(side_effect=error))
ws = RawWebSocket(asyncio.StreamReader(), writer)
with self.assertRaises(type(error)):
await ws.send_init(b'init')
writer.transport.abort.assert_called_once()
self.assertTrue(ws._closed)
async def test_cancelling_pending_upgrade_closes_socket(self):
reader = asyncio.StreamReader()
writer = Mock(drain=AsyncMock())
@@ -216,7 +227,7 @@ class HandshakeCleanupTest(unittest.IsolatedAsyncioTestCase):
task.cancel()
with self.assertRaises(asyncio.CancelledError):
await task
writer.close.assert_called_once()
writer.transport.abort.assert_called_once()
async def test_failed_upgrade_closes_socket(self):
for error in (ConnectionResetError(), asyncio.TimeoutError()):
@@ -228,7 +239,102 @@ class HandshakeCleanupTest(unittest.IsolatedAsyncioTestCase):
patch('proxy.raw_websocket.set_sock_opts'):
with self.assertRaises(type(error)):
await RawWebSocket.connect('192.0.2.1', 'example.org')
writer.close.assert_called_once()
writer.transport.abort.assert_called_once()
class CfDomainTimeoutTest(unittest.IsolatedAsyncioTestCase):
def setUp(self):
raw_websocket.reset_cf_timeouts()
self.addCleanup(raw_websocket.reset_cf_timeouts)
async def connect(self, *hosts):
return await raw_websocket.connect_cf_domains(((h, h) for h in hosts), secure=True, label='test')
async def test_clients_dial_in_parallel_and_http_responses_do_not_throttle(self):
statuses = iter((101, 429, 101, 503, 429))
started = asyncio.Queue()
release = asyncio.Event()
async def dial(host, *args, **kwargs):
if host == 'preferred':
status = next(statuses)
started.put_nowait(host)
await release.wait()
if status != 101:
raise WsHandshakeError(status, 'unavailable')
return object()
with patch.object(RawWebSocket, 'connect', side_effect=dial):
clients = [asyncio.create_task(self.connect('preferred', 'other')) for _ in range(5)]
try:
for _ in clients:
await asyncio.wait_for(started.get(), 1)
release.set()
results = await asyncio.gather(*clients)
self.assertCountEqual([name for _, name in results], ['preferred'] * 2 + ['other'] * 3)
finally:
for task in clients:
task.cancel()
await asyncio.gather(*clients, return_exceptions=True)
with patch.object(RawWebSocket, 'connect', return_value=object()):
self.assertEqual((await self.connect('preferred'))[1], 'preferred')
async def test_five_timeouts_end_search_and_later_clients_skip_timed_out_domains(self):
hosts = ('a', 'http-error', 'b', 'c', 'd', 'e', 'f')
responses = [asyncio.TimeoutError(), WsHandshakeError(503, 'unavailable'),
TimeoutError(), TimeoutError(), TimeoutError(), TimeoutError(),
WsHandshakeError(429, 'busy'), object()]
with patch.object(RawWebSocket, 'connect', side_effect=responses) as dial:
self.assertIsNone(await self.connect(*hosts))
self.assertEqual((await self.connect(*hosts))[1], 'f')
self.assertEqual([(call.args[0], call.kwargs['timeout']) for call in dial.await_args_list],
[('a', 10), ('http-error', 6), ('b', 6), ('c', 4),
('d', 3), ('e', 3), ('http-error', 10), ('f', 10)])
async def test_timeout_retry_skips_to_other_front_without_waiting(self):
with patch.object(raw_websocket, 'CF_TIMEOUT_COOLDOWN', 0), \
patch.object(RawWebSocket, 'connect', side_effect=asyncio.TimeoutError()):
self.assertIsNone(await self.connect('a'))
started, release = asyncio.Event(), asyncio.Event()
async def dial(host, *args, **kwargs):
if host == 'a':
started.set()
await release.wait()
raise WsHandshakeError(429, 'busy')
return object()
with patch.object(RawWebSocket, 'connect', side_effect=dial) as connect:
retry = asyncio.create_task(self.connect('a'))
try:
await asyncio.wait_for(started.wait(), 1)
self.assertEqual((await asyncio.wait_for(self.connect('a', 'b'), 1))[1], 'b')
self.assertEqual(connect.await_count, 2)
finally:
release.set()
await retry
with patch.object(RawWebSocket, 'connect', return_value=object()):
self.assertEqual((await self.connect('a'))[1], 'a')
async def test_cancelling_timeout_retry_releases_it_for_next_client(self):
with patch.object(raw_websocket, 'CF_TIMEOUT_COOLDOWN', 0), \
patch.object(RawWebSocket, 'connect', side_effect=asyncio.TimeoutError()):
await self.connect('a')
started = asyncio.Event()
async def dial(*args, **kwargs):
started.set()
await asyncio.Future()
with patch.object(RawWebSocket, 'connect', side_effect=dial):
retry = asyncio.create_task(self.connect('a'))
await asyncio.wait_for(started.wait(), 1)
retry.cancel()
with self.assertRaises(asyncio.CancelledError):
await retry
with patch.object(RawWebSocket, 'connect', return_value=object()):
self.assertEqual((await self.connect('a'))[1], 'a')
if __name__ == '__main__':
+3 -1
View File
@@ -14,8 +14,10 @@ class TcpFallbackTest(unittest.IsolatedAsyncioTestCase):
self.remote = Mock(drain=AsyncMock(), wait_closed=AsyncMock())
async def fallback(self, dst='192.0.2.1', port=443):
writer = Mock()
writer.is_closing.return_value = False
return await bridge._tcp_fallback(
Mock(), Mock(), dst, port, b'init', 'test', Mock())
asyncio.StreamReader(), writer, dst, port, b'init', 'test', Mock())
async def test_failure_backoff_doubles_caps_and_skips_new_connections(self):
with patch.object(bridge.asyncio, 'open_connection',