Fallback CF-worker to HTTP after TimeoutError

This commit is contained in:
Flowseal
2026-11-23 12:14:38 +03:00
parent f42468b77a
commit 4a338a0f5f
4 changed files with 79 additions and 44 deletions
+26 -1
View File
@@ -3,12 +3,15 @@ import asyncio
import time
import unittest
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
from unittest.mock import AsyncMock, Mock, patch
from proxy import bridge
from proxy._aes import Cipher, algorithms, modes
from proxy.bridge import MsgSplitter, bridge_ws_reencrypt
from proxy.config import proxy_config
from proxy.network_debug import WsActivity, log_ws_flow
from proxy.utils import (
DC_DEFAULT_IPS,
PROTO_ABRIDGED_INT,
PROTO_INTERMEDIATE_INT,
PROTO_PADDED_INTERMEDIATE_INT,
@@ -38,6 +41,28 @@ def _intermediate(payload: bytes) -> bytes:
return len(payload).to_bytes(4, 'little') + payload
class CfWorkerFallbackTest(unittest.IsolatedAsyncioTestCase):
async def test_pool_miss_connects_through_the_worker_pool(self):
reader = asyncio.StreamReader()
writer = Mock()
writer.is_closing.return_value = False
ws = Mock(send_init=AsyncMock())
domains = ['worker.example']
pool = SimpleNamespace(get=AsyncMock(return_value=None),
connect_one=AsyncMock(return_value=(ws, domains[0])))
ctx = Mock()
with patch.object(proxy_config, 'cfproxy_worker_domains', domains), \
patch.object(bridge, 'cf_worker_pool', pool), \
patch.object(bridge, 'bridge_ws_reencrypt', new_callable=AsyncMock) as relay:
self.assertTrue(await bridge.do_fallback(
reader, writer, b'init', 'test', 2, False, True, ' media', ctx))
pool.get.assert_awaited_once_with(2, DC_DEFAULT_IPS[2], domains)
pool.connect_one.assert_awaited_once_with(domains, DC_DEFAULT_IPS[2], 2, timeout=10.0)
ws.send_init.assert_awaited_once_with(b'init')
relay.assert_awaited_once_with(reader, writer, ws, 'test', ctx, dc=2, is_media=True, splitter=None)
class MsgSplitterTest(unittest.TestCase):
def _split(self, proto_int, packets, chunk_sizes=None):
relay_init = _relay_init()
+30 -8
View File
@@ -247,6 +247,7 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
self.pool.WS_POOL_CHECK_INTERVAL = .01
for name, value in [
('pool_size', 4),
('disable_secure', False),
('dc_redirects', {dc: ip for dc, ip in DC_DEFAULT_IPS.items() if dc != 2}),
('cfproxy_worker_domains', ['worker.example'])]:
patcher = mock.patch.object(proxy_config, name, value)
@@ -260,10 +261,31 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
await asyncio.sleep(.001)
await asyncio.wait_for(wait(), 1)
async def test_connect_one_retries_timeouts_and_starts_with_last_successful_mode(self):
ws = _open_ws()
domains = ['worker.example']
with mock.patch.object(RawWebSocket, 'connect',
side_effect=[TimeoutError(), ws, ws, TimeoutError(), ws]) as dial:
for _ in range(3):
self.assertEqual(await self.pool.connect_one(domains, '192.0.2.2', 2),
(ws, 'worker.example'))
self.assertEqual([call.kwargs['secure'] for call in dial.await_args_list],
[True, False, False, False, True])
self.assertTrue(all(call.args == ('worker.example', 'worker.example')
for call in dial.await_args_list))
self.assertFalse(self.pool._exhausted_until)
async def test_connect_one_never_tries_tls_when_disabled(self):
with mock.patch.object(proxy_config, 'disable_secure', True), \
mock.patch.object(RawWebSocket, 'connect', side_effect=TimeoutError()) as dial:
self.assertIsNone(await self.pool.connect_one(['worker.example'], '192.0.2.2', 2))
dial.assert_awaited_once_with('worker.example', 'worker.example', timeout=8.0,
path='/apiws?dst=192.0.2.2&dc=2', secure=False)
async def test_failed_warmup_recovers_without_new_client_requests(self):
ready = _open_ws()
self.pool.REFILL_BACKOFF_INITIAL = .03
with mock.patch.object(self.pool, '_connect_one',
with mock.patch.object(self.pool, 'connect_one',
side_effect=[None, (ready, 'worker.example')]) as dial:
await self.pool.warmup()
await self.wait_for(lambda: 2 in self.pool._refill_after)
@@ -290,7 +312,7 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
else:
stale.writer.transport.is_closing = lambda: True
self.pool._idle[2] = deque([(stale, created, 'worker.example')])
with mock.patch.object(self.pool, '_connect_one',
with mock.patch.object(self.pool, 'connect_one',
return_value=(ready, 'worker.example')):
self.assertIsNone(await self.pool.get(2, '192.0.2.2', ['worker.example']))
await self.wait_for(lambda: bool(self.pool._idle[2]))
@@ -304,7 +326,7 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
stale, ready = _open_ws(), _open_ws()
self.pool.WS_POOL_MAX_AGE = .05
self.pool._idle[2] = deque([(stale, time.monotonic(), 'worker.example')])
with mock.patch.object(self.pool, '_connect_one',
with mock.patch.object(self.pool, 'connect_one',
return_value=(ready, 'worker.example')) as dial:
await self.pool.warmup()
await self.wait_for(lambda: stale.writer.close.called)
@@ -319,7 +341,7 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
started.set()
await asyncio.Future()
with mock.patch.object(self.pool, '_connect_one', side_effect=connect) as dial:
with mock.patch.object(self.pool, 'connect_one', side_effect=connect) as dial:
for _ in range(10):
self.assertIsNone(await self.pool.get(2, '192.0.2.2', ['worker.example']))
await asyncio.wait_for(started.wait(), 1)
@@ -329,7 +351,7 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
ready = _open_ws()
self.pool.REFILL_BACKOFF_INITIAL = 1
self.pool.REFILL_BACKOFF_MAX = 2
with mock.patch.object(self.pool, '_connect_one',
with mock.patch.object(self.pool, 'connect_one',
side_effect=[None, None, None, (ready, 'worker.example')]), \
mock.patch.object(self.pool, '_schedule_rotation'):
for failures, delay in enumerate((1, 2, 2), 1):
@@ -350,7 +372,7 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
async def test_misses_during_backoff_do_not_retry_and_shutdown_cancels_retry(self):
self.pool.REFILL_BACKOFF_INITIAL = 60
with mock.patch.object(self.pool, '_connect_one', return_value=None) as dial:
with mock.patch.object(self.pool, 'connect_one', return_value=None) as dial:
await self.pool.warmup()
await self.wait_for(lambda: 2 in self.pool._refill_after)
for _ in range(10):
@@ -421,7 +443,7 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
self.assertNotIn(2, self.pool._refill_failures)
async def test_zero_size_and_missing_worker_domains_do_not_start_refills(self):
with mock.patch.object(self.pool, '_connect_one') as dial:
with mock.patch.object(self.pool, 'connect_one') as dial:
with mock.patch.object(proxy_config, 'pool_size', 0):
await self.pool.warmup()
self.assertIsNone(await self.pool.get(2, '192.0.2.2', ['worker.example']))
@@ -447,7 +469,7 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
return ready, 'b.example'
with mock.patch.object(proxy_config, 'pool_size', 1), \
mock.patch.object(pool, '_connect_one', side_effect=connect):
mock.patch.object(pool, 'connect_one', side_effect=connect):
pool._schedule_refill(4, '192.0.2.4', ['b.example'])
await asyncio.wait_for(started.wait(), 1)
await pool.close()