Fallback CF-proxy to HTTP after TimeoutError

This commit is contained in:
Flowseal
2026-11-23 11:41:24 +03:00
parent c01fad5218
commit 219f38c07d
6 changed files with 146 additions and 28 deletions
+2 -2
View File
@@ -10,7 +10,7 @@ from .utils import *
from .stats import stats
from .balancer import balancer
from .config import proxy_config
from .raw_websocket import RawWebSocket, connect_cf_domains
from .raw_websocket import RawWebSocket, cf_prefers_tls, connect_cf_domains
from .pool import cf_worker_pool
from .network_debug import WsActivity
from .cf_h2 import bridge_h2
@@ -162,7 +162,7 @@ async def do_fallback(reader, writer, relay_init, label,
if ok:
return True
elif method == 'cf':
if is_media and h2_pool is not None and proto_tag is not None:
if is_media and h2_pool is not None and proto_tag is not None and cf_prefers_tls():
with client_setup(reader, writer):
channel = await h2_pool.open(dc, label)
if channel is not None:
+3
View File
@@ -13,6 +13,7 @@ import httpx
from .balancer import balancer
from .h2_transport import H2Transport
from .raw_websocket import cf_tls_in_cooldown
from .stats import stats
from .utils import (
DC_DEFAULT_IPS, PROTO_TAG_ABRIDGED,
@@ -887,6 +888,8 @@ class CfH2Pool:
log.warning('[%s] H2 unsupported DC%d -> existing WS route', label, dc)
return None
for base_domain in balancer.get_domains_for_dc(dc):
if cf_tls_in_cooldown(base_domain):
continue
host = 'kws%d.%s' % (dc, base_domain)
async with self.locks.setdefault(host, asyncio.Lock()):
if self.closed:
+50 -13
View File
@@ -3,9 +3,11 @@ import logging
import math
import base64
import struct
import time
import asyncio
import socket as _socket
from dataclasses import dataclass
from typing import Dict, Iterable, List, Optional, Tuple
from .config import proxy_config
from .event_loop import abort_transport
@@ -13,10 +15,15 @@ from .utils import create_ssl_context
log = logging.getLogger('tg-mtproto-proxy')
@dataclass
class CfConStats:
tls: int = 0
no_tls: int = 0
CF_TIMEOUT_COOLDOWN = 30.0
CF_CONNECT_TIMEOUTS = (10.0, 6.0, 4.0, 3.0, 3.0)
CF_CONNECT_TIMEOUTS = (3.0, 3.0, 5.0, 5.0, 10.0)
_cf_timeout_until: Dict[Tuple[str, bool], float] = {}
_cf_connection_stats = CfConStats()
_st_BB = struct.Struct('>BB')
@@ -348,53 +355,83 @@ class RawWebSocket:
def reset_cf_timeouts() -> None:
_cf_timeout_until.clear()
_cf_connection_stats.no_tls = 0
_cf_connection_stats.tls = 0
def cf_prefers_tls() -> bool:
return _cf_connection_stats.tls >= _cf_connection_stats.no_tls
def cf_tls_in_cooldown(name: str) -> bool:
retry_at = _cf_timeout_until.get((name, True))
return retry_at is not None and time.monotonic() < retry_at
async def connect_cf_domains(candidates: Iterable[Tuple[str, str]], *, label: str,
secure: bool, path: str = '/apiws', timeout: float = 10.0
) -> Optional[Tuple[RawWebSocket, str]]:
loop = asyncio.get_running_loop()
domains = list(candidates)
retry_single_domain = secure and len(domains) == 1
if retry_single_domain:
domains.append(domains[0])
timeouts = 0
tls_first = cf_prefers_tls()
for name, host in candidates:
key = (name, secure)
now = loop.time()
for index, (name, host) in enumerate(domains):
use_tls = secure and (tls_first != bool(timeouts % 2))
if retry_single_domain and index == 1 and timeouts == 0:
# The first try was skipped because of _cf_timeout_until.
use_tls = not tls_first
key = (name, use_tls)
retry_at = _cf_timeout_until.get(key)
if retry_at is not None:
if now < retry_at:
if time.monotonic() < retry_at:
continue
_cf_timeout_until[key] = math.inf
port = 443 if use_tls else 80
log.warning('[%s] Use TLS: %s', label, use_tls)
try:
attempt_timeout = min(timeout, CF_CONNECT_TIMEOUTS[timeouts])
ws = await RawWebSocket.connect(host, host, path=path, secure=secure, timeout=attempt_timeout)
ws = await RawWebSocket.connect(host, host, path=path,
secure=use_tls, timeout=attempt_timeout)
except (asyncio.TimeoutError, TimeoutError):
now = loop.time()
now = time.monotonic()
if retry_at is not None or key not in _cf_timeout_until:
for old_key, until in list(_cf_timeout_until.items()):
if until + CF_TIMEOUT_COOLDOWN <= now:
del _cf_timeout_until[old_key]
_cf_timeout_until[key] = now + CF_TIMEOUT_COOLDOWN
log.warning('[%s] CF WebSocket timed out (host=%s port=%d); retry in %.0fs',
label, host, 443 if secure else 80, CF_TIMEOUT_COOLDOWN)
label, host, port, CF_TIMEOUT_COOLDOWN)
timeouts += 1
if timeouts >= len(CF_CONNECT_TIMEOUTS):
break
continue
except Exception as exc:
log.warning('[%s] CF WebSocket failed (host=%s port=%d): %r',
label, host, 443 if secure else 80, exc)
log.warning('[%s] CF WebSocket failed (host=%s port=%d): %r', label, host, port, exc)
ws = None
finally:
if retry_at is not None and _cf_timeout_until.get(key) == math.inf:
_cf_timeout_until[key] = retry_at
_cf_timeout_until.pop(key, None)
if ws is not None:
if use_tls:
_cf_connection_stats.tls += 1
else:
_cf_connection_stats.no_tls += 1
return ws, name
if retry_single_domain:
break
return None
+20
View File
@@ -13,6 +13,7 @@ from proxy.cf_h2 import (
CfH2Pool, MAX_CHANNEL_REQUESTS, MAX_PACKET, _HttpChannel, _HttpLane,
_ReplayPacket, _encode_reply, _read_packet, bridge_h2,
)
from proxy.raw_websocket import RawWebSocket, connect_cf_domains, reset_cf_timeouts
from proxy.utils import PROTO_TAG_ABRIDGED, PROTO_TAG_INTERMEDIATE, PROTO_TAG_SECURE
class _IdentityCipher:
@@ -962,6 +963,25 @@ class HttpMultiplexTest(unittest.IsolatedAsyncioTestCase):
finally:
await pool.close()
async def test_h2_skips_domain_with_recent_secure_websocket_timeout(self):
reset_cf_timeouts()
self.addCleanup(reset_cf_timeouts)
pool = CfH2Pool()
self.addAsyncCleanup(pool.close)
balancer = _Balancer()
balancer.update_domains_list(['slow.example', 'ready.example'])
balancer.update_domain_for_dc(4, 'slow.example')
with patch.object(RawWebSocket, 'connect', side_effect=[TimeoutError(), ConnectionResetError()]):
self.assertIsNone(await connect_cf_domains(
[('slow.example', 'kws4.slow.example')], label='test', secure=True))
with patch('proxy.cf_h2.balancer', balancer), patch.object(_HttpLane, '_preflight', autospec=True) as preflight:
channel = await pool.open(4, 'test')
self.assertIsNotNone(channel)
self.assertEqual(channel.lane.host, 'kws4.ready.example')
preflight.assert_awaited_once_with(channel.lane)
async def test_hanging_setup_returns_to_ws_and_cleans_up_lane(self):
pool = CfH2Pool()
balancer = _Balancer()
+26
View File
@@ -5,7 +5,9 @@ from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock, patch
from proxy import bridge, tg_ws_proxy
from proxy.balancer import _Balancer
from proxy.config import proxy_config
from proxy.raw_websocket import RawWebSocket, reset_cf_timeouts
from proxy.utils import PROTO_TAG_INTERMEDIATE
@@ -98,3 +100,27 @@ class H2RoutingTest(unittest.IsolatedAsyncioTestCase):
h2_pool=pool, proto_tag=PROTO_TAG_INTERMEDIATE)
self.assertTrue(result)
self.assertEqual(calls, expected)
async def test_media_skips_h2_when_cf_websocket_prefers_plaintext(self):
reset_cf_timeouts()
self.addCleanup(reset_cf_timeouts)
balancer = _Balancer()
balancer.update_domains_list(['example.org'])
pool = SimpleNamespace(open=AsyncMock(return_value=None))
writer = Mock()
writer.is_closing.return_value = False
ws = Mock(send_init=AsyncMock())
with patch.object(proxy_config, 'fallback_cfproxy', True), \
patch.object(proxy_config, 'cfproxy_worker_domains', []), \
patch.object(proxy_config, 'disable_secure', False), \
patch.object(bridge, 'balancer', balancer), \
patch.object(bridge, 'bridge_ws_reencrypt', new_callable=AsyncMock), \
patch.object(RawWebSocket, 'connect', side_effect=[TimeoutError(), ws, ws]) as dial:
for media in (False, True):
self.assertTrue(await bridge.do_fallback(
asyncio.StreamReader(), writer, b'', 'test', 2, False, media, '', Mock(),
h2_pool=pool, proto_tag=PROTO_TAG_INTERMEDIATE))
pool.open.assert_not_awaited()
self.assertEqual([call.kwargs['secure'] for call in dial.await_args_list], [True, False, False])
+45 -13
View File
@@ -317,8 +317,8 @@ class CfDomainTimeoutTest(unittest.IsolatedAsyncioTestCase):
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 connect(self, *hosts, secure=True):
return await raw_websocket.connect_cf_domains(((h, h) for h in hosts), secure=secure, label='test')
async def test_clients_dial_in_parallel_and_http_responses_do_not_throttle(self):
statuses = iter((101, 429, 101, 503, 429))
@@ -349,22 +349,49 @@ class CfDomainTimeoutTest(unittest.IsolatedAsyncioTestCase):
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):
async def test_five_timeouts_cover_five_domains_and_cooldown_is_per_mode(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)])
self.assertEqual((await self.connect(*hosts))[1], 'b')
self.assertEqual(
[(call.args[0], call.kwargs['secure'], call.kwargs['timeout'])
for call in dial.await_args_list],
[('a', True, 3), ('http-error', False, 3), ('b', False, 3),
('c', True, 5), ('d', False, 5), ('e', True, 10),
('http-error', True, 3), ('b', True, 3)],
)
async def test_timeout_retries_same_domain_and_successes_set_first_mode(self):
ws = object()
with patch.object(RawWebSocket, 'connect',
side_effect=[TimeoutError(), ws, ws, TimeoutError(), ws]) as dial:
self.assertEqual(await self.connect('a'), (ws, 'a'))
self.assertEqual(await self.connect('b'), (ws, 'b'))
self.assertEqual(await self.connect('b'), (ws, 'b'))
self.assertEqual(
[(call.args[0], call.kwargs['secure']) for call in dial.await_args_list],
[('a', True), ('a', False), ('b', False), ('b', False), ('b', True)],
)
async def test_single_domain_tries_other_mode_on_timeout_or_cooldown(self):
ws = object()
responses = [WsHandshakeError(503, 'unavailable'), TimeoutError(),
WsHandshakeError(503, 'unavailable'), ws]
with patch.object(RawWebSocket, 'connect', side_effect=responses) as dial:
self.assertIsNone(await self.connect('a'))
self.assertIsNone(await self.connect('a'))
self.assertEqual(await self.connect('a'), (ws, 'a'))
self.assertEqual([call.kwargs['secure'] for call in dial.await_args_list],
[True, True, False, False])
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'))
self.assertIsNone(await self.connect('a', secure=False))
started, release = asyncio.Event(), asyncio.Event()
@@ -376,16 +403,20 @@ class CfDomainTimeoutTest(unittest.IsolatedAsyncioTestCase):
return object()
with patch.object(RawWebSocket, 'connect', side_effect=dial) as connect:
retry = asyncio.create_task(self.connect('a'))
retry = asyncio.create_task(self.connect('a', secure=False))
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)
result = await asyncio.wait_for(self.connect('a', 'b', secure=False), 1)
self.assertEqual(result[1], 'b')
self.assertEqual(
[(call.args[0], call.kwargs['secure']) for call in connect.await_args_list],
[('a', False), ('b', False)],
)
finally:
release.set()
await retry
with patch.object(RawWebSocket, 'connect', return_value=object()):
self.assertEqual((await self.connect('a'))[1], 'a')
self.assertEqual((await self.connect('a', secure=False))[1], 'a')
async def test_cancelling_timeout_retry_releases_it_for_next_client(self):
with patch.object(raw_websocket, 'CF_TIMEOUT_COOLDOWN', 0), \
@@ -403,8 +434,9 @@ class CfDomainTimeoutTest(unittest.IsolatedAsyncioTestCase):
retry.cancel()
with self.assertRaises(asyncio.CancelledError):
await retry
with patch.object(RawWebSocket, 'connect', return_value=object()):
with patch.object(RawWebSocket, 'connect', return_value=object()) as connect:
self.assertEqual((await self.connect('a'))[1], 'a')
connect.assert_awaited_once_with('a', 'a', path='/apiws', secure=True, timeout=3.0)
if __name__ == '__main__':