mirror of
https://github.com/mikumifa/biliTickerBuy.git
synced 2026-11-07 17:42:56 -08:00
Add proxy pool fanout assignment strategy
This commit is contained in:
1 parent
99540ddc57
commit
dcef76b770
15 files changed
+3333
-4
No files matched your search
@@ -140,6 +140,15 @@ class BuyConfig(BasicConfig):
|
||||
)
|
||||
"""Number of create-order requests sent in one batch."""
|
||||
|
||||
create_request_proxy_strategy: str = config_field(
|
||||
"standard",
|
||||
env="BTB_CREATE_REQUEST_PROXY_STRATEGY",
|
||||
runtime="create_request_proxy_strategy",
|
||||
cli="--create-request-proxy-strategy",
|
||||
cast=lambda value: str(value or "standard").lower(),
|
||||
)
|
||||
"""Internal create-order request transport strategy."""
|
||||
|
||||
rate_limit_delay_ms: int = config_field(
|
||||
DEFAULT_RATE_LIMIT_DELAY_MS,
|
||||
env="BTB_RATE_LIMIT_DELAY_MS",
|
||||
|
||||
@@ -27,6 +27,7 @@ class RuntimeOptions:
|
||||
outer_interval: int = 0
|
||||
create_retry_limit: int = 20
|
||||
create_request_batch_size: int = 3
|
||||
create_request_proxy_strategy: str = "standard"
|
||||
time_start: str = ""
|
||||
audio_path: str = ""
|
||||
pushplusToken: str = ""
|
||||
@@ -295,6 +296,7 @@ def build_runtime_options(
|
||||
outer_interval: int = 0,
|
||||
create_retry_limit: int = 20,
|
||||
create_request_batch_size: int = 3,
|
||||
create_request_proxy_strategy: str = "standard",
|
||||
time_start: str = "",
|
||||
audio_path: str = "",
|
||||
pushplusToken: str = "",
|
||||
@@ -331,6 +333,9 @@ def build_runtime_options(
|
||||
create_request_batch_size,
|
||||
default=3,
|
||||
),
|
||||
create_request_proxy_strategy=str(
|
||||
create_request_proxy_strategy or "standard"
|
||||
).lower(),
|
||||
time_start=normalize_time_start(time_start),
|
||||
audio_path=audio_path,
|
||||
pushplusToken=pushplusToken,
|
||||
|
||||
@@ -41,6 +41,7 @@ dependencies = [
|
||||
"rich>=15.0.0",
|
||||
"tyro>=0.9.28",
|
||||
"gradio>=6.19.0",
|
||||
"cryptography~=48.0.0",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
|
||||
@@ -16,3 +16,4 @@ httpx[brotli,http2,socks,zstd]>=0.28.1
|
||||
textual>=8.2.7
|
||||
rich>=15.0.0
|
||||
tyro>=0.9.28
|
||||
cryptography~=48.0.0
|
||||
@@ -27,6 +27,12 @@ def go_settings_tab(header_ui):
|
||||
proxy_assignment_strategy_default = str(
|
||||
ConfigDB.get("proxyAssignmentStrategy") or "balanced"
|
||||
).lower()
|
||||
if proxy_assignment_strategy_default not in {
|
||||
"balanced",
|
||||
"queue",
|
||||
"local_fanout",
|
||||
}:
|
||||
proxy_assignment_strategy_default = "balanced"
|
||||
|
||||
def _split_proxy_lines(proxy_text: str | None) -> list[str]:
|
||||
if not proxy_text:
|
||||
@@ -229,6 +235,10 @@ def go_settings_tab(header_ui):
|
||||
ConfigDB.insert("proxyAssignmentStrategy", value)
|
||||
return gr.update(value=ConfigDB.get("proxyAssignmentStrategy"))
|
||||
|
||||
def update_proxy_include_direct(value):
|
||||
ConfigDB.insert("proxyIncludeDirect", value)
|
||||
return gr.update(value=ConfigDB.get_as_bool("proxyIncludeDirect", True))
|
||||
|
||||
def update_log_level(value):
|
||||
ConfigDB.insert("logLevel", value)
|
||||
return gr.update(value=ConfigDB.get("logLevel"))
|
||||
@@ -606,12 +616,18 @@ def go_settings_tab(header_ui):
|
||||
choices=[
|
||||
("均匀分配", "balanced"),
|
||||
("队列模式", "queue"),
|
||||
("代理池并发", "local_fanout"),
|
||||
],
|
||||
value=proxy_assignment_strategy_default,
|
||||
interactive=True,
|
||||
allow_custom_value=False,
|
||||
filterable=False,
|
||||
)
|
||||
proxy_include_direct_ui = gr.Checkbox(
|
||||
label="允许使用直连(none)",
|
||||
value=ConfigDB.get_as_bool("proxyIncludeDirect", True),
|
||||
info="开启后,任务代理分配会把直连作为一个可用出口;关闭后,所有任务只使用已配置代理。",
|
||||
)
|
||||
queue_concurrency_limit_ui = gr.Number(
|
||||
label="队列并发上限(仅队列模式)",
|
||||
value=ConfigDB.get_as_int("queueConcurrencyLimit", 0),
|
||||
@@ -802,6 +818,11 @@ def go_settings_tab(header_ui):
|
||||
inputs=proxy_assignment_strategy_ui,
|
||||
outputs=proxy_assignment_strategy_ui,
|
||||
)
|
||||
proxy_include_direct_ui.change(
|
||||
fn=update_proxy_include_direct,
|
||||
inputs=proxy_include_direct_ui,
|
||||
outputs=proxy_include_direct_ui,
|
||||
)
|
||||
_bind_number_commit(
|
||||
queue_concurrency_limit_ui,
|
||||
update_queue_concurrency_limit,
|
||||
@@ -886,6 +907,7 @@ def go_settings_tab(header_ui):
|
||||
gr.update(
|
||||
value=str(ConfigDB.get("proxyAssignmentStrategy") or "balanced").lower()
|
||||
),
|
||||
gr.update(value=ConfigDB.get_as_bool("proxyIncludeDirect", True)),
|
||||
gr.update(value=ConfigDB.get_as_int("queueConcurrencyLimit", 0)),
|
||||
gr.update(value=buy_defaults.log_level),
|
||||
gr.update(value=ConfigDB.get_as_bool("autoCleanupLogs", True)),
|
||||
@@ -927,6 +949,7 @@ def go_settings_tab(header_ui):
|
||||
show_qrcode_ui,
|
||||
auto_open_payment_url_ui,
|
||||
proxy_assignment_strategy_ui,
|
||||
proxy_include_direct_ui,
|
||||
queue_concurrency_limit_ui,
|
||||
log_level_ui,
|
||||
auto_cleanup_logs_ui,
|
||||
|
||||
@@ -32,6 +32,7 @@ from util.Constant import (
|
||||
DEFAULT_REQUEST_INTERVAL,
|
||||
GO_UPLOADED_FILES_STATE_KEY,
|
||||
)
|
||||
from util.proxy.ProxyManager import ProxyManager
|
||||
|
||||
|
||||
def withTimeString(string):
|
||||
@@ -49,6 +50,14 @@ def _build_task_log_path(filename: str) -> str:
|
||||
return os.path.join(LOG_DIR, f"{safe_name}_{uuid.uuid4().hex[:8]}.log")
|
||||
|
||||
|
||||
def _build_task_proxy_list(proxy_string: str | None, *, include_direct: bool) -> list[str]:
|
||||
proxies = ProxyManager.parse_proxy_list(proxy_string)
|
||||
proxies = [proxy for proxy in proxies if proxy.lower() != "none"]
|
||||
if include_direct:
|
||||
return ["none", *proxies]
|
||||
return proxies
|
||||
|
||||
|
||||
def _parse_sale_start(value) -> datetime.datetime | None:
|
||||
if isinstance(value, (int, float)):
|
||||
return datetime.datetime.fromtimestamp(value, tz=BEIJING_TZ)
|
||||
@@ -311,7 +320,14 @@ def go_start_tab():
|
||||
ConfigDB.insert("requestInterval", interval)
|
||||
|
||||
https_proxys = ConfigDB.get("https_proxy") or ""
|
||||
https_proxy_list = ["none"] + https_proxys.split(",")
|
||||
include_direct_proxy = ConfigDB.get_as_bool("proxyIncludeDirect", True)
|
||||
https_proxy_list = _build_task_proxy_list(
|
||||
https_proxys,
|
||||
include_direct=include_direct_proxy,
|
||||
)
|
||||
if not https_proxy_list:
|
||||
gr.Warning("已关闭直连,请至少配置一个代理。")
|
||||
return gr.update(visible=False)
|
||||
assigned_proxies: list[list[str]] = []
|
||||
assigned_proxies_next_idx = 0
|
||||
# 从配置文件加载
|
||||
@@ -322,6 +338,8 @@ def go_start_tab():
|
||||
proxy_assignment_strategy = str(
|
||||
ConfigDB.get("proxyAssignmentStrategy") or "balanced"
|
||||
).lower()
|
||||
if proxy_assignment_strategy not in {"balanced", "queue", "local_fanout"}:
|
||||
proxy_assignment_strategy = "balanced"
|
||||
queue_concurrency_limit = ConfigDB.get_as_int("queueConcurrencyLimit", 0)
|
||||
log_retention_days = buy_config.log_retention_days
|
||||
auto_cleanup_logs = ConfigDB.get("autoCleanupLogs")
|
||||
@@ -372,6 +390,24 @@ def go_start_tab():
|
||||
gr.Info("抢票任务已按队列模式启动。")
|
||||
return gr.update(visible=True)
|
||||
|
||||
if proxy_assignment_strategy == "local_fanout":
|
||||
fanout_proxy_pool = ",".join(
|
||||
proxy for proxy in https_proxy_list if proxy.lower() != "none"
|
||||
)
|
||||
if not fanout_proxy_pool:
|
||||
gr.Warning("代理池并发策略需要至少配置一个代理。")
|
||||
return gr.update(visible=False)
|
||||
for filename in files:
|
||||
launch_task(
|
||||
filename,
|
||||
config=buy_config.with_overrides(
|
||||
https_proxys=fanout_proxy_pool,
|
||||
create_request_proxy_strategy="local_fanout",
|
||||
),
|
||||
)
|
||||
gr.Info("抢票任务已按代理池并发策略启动。")
|
||||
return gr.update(visible=True)
|
||||
|
||||
for idx, filename in enumerate(files):
|
||||
if assigned_proxies == []:
|
||||
left_task_num = len(files) - idx
|
||||
|
||||
+17
@@ -56,6 +56,9 @@ from util.request.BiliRequest import BiliRequest
|
||||
from util.request.exceptions import BiliConnectionError, BiliRateLimitError
|
||||
|
||||
|
||||
LOCAL_FANOUT_PROXY_STRATEGY = "local_fanout"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Buy:
|
||||
config: BuyConfig
|
||||
@@ -391,11 +394,25 @@ def buy_stream(config: BuyConfig):
|
||||
tickets_info["deliver_info"] = json.dumps(tickets_info["deliver_info"])
|
||||
masked_proxies = ProxyManager.mask_proxy_string(config.https_proxys)
|
||||
logger.info(f"目前已配置代理:{masked_proxies or '直连'}")
|
||||
h2_client_type = None
|
||||
h2_client_options = None
|
||||
if config.create_request_proxy_strategy == LOCAL_FANOUT_PROXY_STRATEGY:
|
||||
from util.h2client.ja_h2_client import ProxyPoolCreateV2FanoutJA3H2Client
|
||||
|
||||
proxy_pool = [
|
||||
proxy
|
||||
for proxy in ProxyManager.parse_proxy_list(config.https_proxys)
|
||||
if proxy.lower() != "none"
|
||||
]
|
||||
h2_client_type = ProxyPoolCreateV2FanoutJA3H2Client
|
||||
h2_client_options = {"proxy_pool": proxy_pool}
|
||||
_request = BiliRequest(
|
||||
cookies=cookies,
|
||||
proxy=config.https_proxys,
|
||||
proxy_failure_threshold=config.proxy_max_consecutive_failures,
|
||||
proxy_cooldown_seconds=config.proxy_cooldown_seconds,
|
||||
h2_client_type=h2_client_type,
|
||||
h2_client_options=h2_client_options,
|
||||
)
|
||||
proxy_backoff = ProxyBackoff(max_seconds=config.proxy_backoff_max_seconds)
|
||||
is_hot_project = bool(tickets_info.get("is_hot_project", False))
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from app_cmd.config.BuyConfig import BuyConfig
|
||||
from interface.config import build_runtime_options
|
||||
from tab.go import _build_task_proxy_list
|
||||
from util.request.BiliRequest import AbstractH2Client, BiliRequest
|
||||
from util.h2client.h2connection import H2Response
|
||||
from util.h2client.ja_h2_client import ProxyPoolCreateV2FanoutJA3H2Client
|
||||
|
||||
|
||||
class FakeCookies:
|
||||
def __init__(self) -> None:
|
||||
self.values: list[tuple[str, str, str]] = []
|
||||
|
||||
def set(
|
||||
self,
|
||||
name: str,
|
||||
value: str,
|
||||
domain: str = "",
|
||||
path: str = "/",
|
||||
) -> None:
|
||||
self.values.append((name, value, domain))
|
||||
|
||||
|
||||
class FakeH2Client(AbstractH2Client):
|
||||
instances: list["FakeH2Client"] = []
|
||||
|
||||
def __init__(self, **kwargs: Any) -> None:
|
||||
self.kwargs = kwargs
|
||||
self._headers = dict(kwargs.get("headers", {}))
|
||||
self._cookies = FakeCookies()
|
||||
self.calls: list[tuple] = []
|
||||
self.closed = False
|
||||
self.instances.append(self)
|
||||
|
||||
@property
|
||||
def headers(self) -> dict[str, str]:
|
||||
return self._headers
|
||||
|
||||
@property
|
||||
def cookies(self) -> FakeCookies:
|
||||
return self._cookies
|
||||
|
||||
def head(self, url: str) -> httpx.Response:
|
||||
self.calls.append(("head", url))
|
||||
return httpx.Response(200, request=httpx.Request("HEAD", url))
|
||||
|
||||
def get(self, url: str, *, params: Any = None) -> httpx.Response:
|
||||
self.calls.append(("get", url, params))
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"msg": ""},
|
||||
request=httpx.Request("GET", url),
|
||||
)
|
||||
|
||||
def post(
|
||||
self,
|
||||
url: str,
|
||||
*,
|
||||
data: Any = None,
|
||||
json: Any = None,
|
||||
) -> httpx.Response:
|
||||
self.calls.append(("post", url, data, json))
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"msg": ""},
|
||||
request=httpx.Request("POST", url),
|
||||
)
|
||||
|
||||
def close(self) -> None:
|
||||
self.closed = True
|
||||
|
||||
|
||||
class FakeH2Connection:
|
||||
instances: list["FakeH2Connection"] = []
|
||||
post_bodies_by_proxy: dict[str, list[bytes]] = {}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
remote_host: str,
|
||||
source_ip: str | None,
|
||||
*,
|
||||
port: int = 443,
|
||||
sni: str | None = None,
|
||||
family: str = "auto",
|
||||
timeout: float = 10.0,
|
||||
proxy_url: str | None = None,
|
||||
assert_ja: bool = False,
|
||||
) -> None:
|
||||
self.remote_host = remote_host
|
||||
self.source_ip = source_ip
|
||||
self.proxy_url = proxy_url
|
||||
self.calls: list[tuple[str, str]] = []
|
||||
self.closed = False
|
||||
self.instances.append(self)
|
||||
|
||||
def get(self, url: str, headers=None) -> H2Response:
|
||||
self.calls.append(("GET", url))
|
||||
return H2Response(
|
||||
status=200,
|
||||
headers=[(":status", "200")],
|
||||
body=b"ok",
|
||||
stream_id=len(self.calls),
|
||||
)
|
||||
|
||||
def post(self, url: str, headers=None, content=None) -> H2Response:
|
||||
self.calls.append(("POST", url))
|
||||
bodies = self.post_bodies_by_proxy.get(self.proxy_url or "", [])
|
||||
body = bodies.pop(0) if bodies else b'{"errno":0}'
|
||||
return H2Response(
|
||||
status=200,
|
||||
headers=[(":status", "200")],
|
||||
body=body,
|
||||
stream_id=len(self.calls),
|
||||
)
|
||||
|
||||
def close(self) -> None:
|
||||
self.closed = True
|
||||
|
||||
|
||||
def test_task_proxy_list_includes_direct_when_enabled():
|
||||
assert _build_task_proxy_list(
|
||||
"http://127.0.0.1:18080,http://127.0.0.1:28080",
|
||||
include_direct=True,
|
||||
) == [
|
||||
"none",
|
||||
"http://127.0.0.1:18080",
|
||||
"http://127.0.0.1:28080",
|
||||
]
|
||||
|
||||
|
||||
def test_task_proxy_list_excludes_direct_when_disabled():
|
||||
assert _build_task_proxy_list(
|
||||
"none,http://127.0.0.1:18080,direct,http://127.0.0.1:28080",
|
||||
include_direct=False,
|
||||
) == [
|
||||
"http://127.0.0.1:18080",
|
||||
"http://127.0.0.1:28080",
|
||||
]
|
||||
|
||||
|
||||
def test_task_proxy_list_can_require_configured_proxy():
|
||||
assert _build_task_proxy_list("", include_direct=False) == []
|
||||
|
||||
|
||||
def test_runtime_strategy_flows_into_buy_config():
|
||||
runtime = build_runtime_options(
|
||||
create_request_proxy_strategy="local_fanout",
|
||||
)
|
||||
|
||||
config = BuyConfig.from_runtime_options("{}", runtime)
|
||||
|
||||
assert config.create_request_proxy_strategy == "local_fanout"
|
||||
assert "--create-request-proxy-strategy" in config.to_cli_args()
|
||||
|
||||
|
||||
def test_h2_client_constructor_uses_abstract_client_interface():
|
||||
FakeH2Client.instances = []
|
||||
request = BiliRequest(
|
||||
cookies=[{"name": "SESSDATA", "value": "abc"}],
|
||||
h2_client_type=FakeH2Client,
|
||||
h2_client_options={"proxy_pool": ["http://127.0.0.1:8080"]},
|
||||
)
|
||||
url = "https://show.bilibili.com/api/ticket/order/createV2"
|
||||
|
||||
request.prewarm_h2_connection(url)
|
||||
request._h2_send("post", url, data={"project_id": 1}, isJson=True)
|
||||
request._h2_send("get", url, data={"project_id": 1})
|
||||
|
||||
client = FakeH2Client.instances[0]
|
||||
assert client.kwargs["http2"] is True
|
||||
assert client.kwargs["proxy_pool"] == ["http://127.0.0.1:8080"]
|
||||
assert client.headers["user-agent"] == request.get_user_agent()
|
||||
assert client.cookies.values == [
|
||||
("SESSDATA", "abc", ".bilibili.com"),
|
||||
("SESSDATA", "abc", ".bilibili.com"),
|
||||
("SESSDATA", "abc", ".bilibili.com"),
|
||||
]
|
||||
assert client.calls == [
|
||||
("head", url),
|
||||
("post", url, None, {"project_id": 1}),
|
||||
("get", url, {"project_id": 1}),
|
||||
]
|
||||
|
||||
request._invalidate_h2_client()
|
||||
|
||||
assert client.closed is True
|
||||
|
||||
|
||||
def test_replace_proxy_pool_updates_h2_client_options():
|
||||
FakeH2Client.instances = []
|
||||
request = BiliRequest(
|
||||
cookies=[{"name": "SESSDATA", "value": "abc"}],
|
||||
proxy="http://127.0.0.1:18080",
|
||||
h2_client_type=FakeH2Client,
|
||||
h2_client_options={"proxy_pool": ["http://127.0.0.1:18080"]},
|
||||
)
|
||||
url = "https://show.bilibili.com/api/ticket/order/createV2"
|
||||
|
||||
request._h2_send("post", url, data={"project_id": 1}, isJson=True)
|
||||
first_client = FakeH2Client.instances[0]
|
||||
|
||||
request.replace_proxy_pool("http://127.0.0.1:28080,http://127.0.0.1:38080")
|
||||
request._h2_send("post", url, data={"project_id": 1}, isJson=True)
|
||||
|
||||
assert first_client.closed is True
|
||||
assert FakeH2Client.instances[1].kwargs["proxy_pool"] == [
|
||||
"http://127.0.0.1:28080",
|
||||
"http://127.0.0.1:38080",
|
||||
]
|
||||
|
||||
|
||||
def test_proxy_pool_fanout_builds_one_create_connection_per_proxy():
|
||||
FakeH2Connection.instances = []
|
||||
FakeH2Connection.post_bodies_by_proxy = {}
|
||||
client = ProxyPoolCreateV2FanoutJA3H2Client(
|
||||
proxy_pool=[
|
||||
"http://127.0.0.1:18080",
|
||||
"socks5://127.0.0.1:19090",
|
||||
],
|
||||
connection_factory=FakeH2Connection,
|
||||
connections_per_source_ip=1,
|
||||
)
|
||||
|
||||
response = client.post(
|
||||
"https://show.bilibili.com/api/ticket/order/createV2",
|
||||
json={"project_id": 1},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
business_connections = [
|
||||
instance
|
||||
for instance in FakeH2Connection.instances
|
||||
if instance.calls
|
||||
and instance.calls[-1][1]
|
||||
== "https://show.bilibili.com/api/ticket/order/createV2"
|
||||
]
|
||||
assert sorted(instance.proxy_url for instance in business_connections) == [
|
||||
"http://127.0.0.1:18080",
|
||||
"socks5://127.0.0.1:19090",
|
||||
]
|
||||
|
||||
|
||||
def test_proxy_pool_fanout_repeats_until_one_proxy_succeeds():
|
||||
FakeH2Connection.instances = []
|
||||
FakeH2Connection.post_bodies_by_proxy = {
|
||||
"http://127.0.0.1:18080": [b'{"errno":900001}', b'{"errno":900001}'],
|
||||
"http://127.0.0.1:28080": [b'{"errno":900001}', b'{"errno":0}'],
|
||||
}
|
||||
client = ProxyPoolCreateV2FanoutJA3H2Client(
|
||||
proxy_pool=[
|
||||
"http://127.0.0.1:18080",
|
||||
"http://127.0.0.1:28080",
|
||||
],
|
||||
connection_factory=FakeH2Connection,
|
||||
connections_per_source_ip=1,
|
||||
)
|
||||
|
||||
response = client.post(
|
||||
"https://show.bilibili.com/api/ticket/order/createV2",
|
||||
json={"project_id": 1},
|
||||
)
|
||||
|
||||
assert response.json()["errno"] == 0
|
||||
post_count = sum(
|
||||
1
|
||||
for instance in FakeH2Connection.instances
|
||||
for call in instance.calls
|
||||
if call[0] == "POST"
|
||||
)
|
||||
assert post_count >= 4
|
||||
@@ -0,0 +1,69 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Callable
|
||||
from typing import Any, Protocol
|
||||
|
||||
|
||||
class H2Headers(Protocol):
|
||||
def __setitem__(self, key: str, value: str) -> None: ...
|
||||
|
||||
|
||||
class H2Cookies(Protocol):
|
||||
def set(
|
||||
self,
|
||||
name: str,
|
||||
value: str,
|
||||
domain: str = "",
|
||||
path: str = "/",
|
||||
) -> None: ...
|
||||
|
||||
|
||||
class H2Response(Protocol):
|
||||
status_code: int
|
||||
text: str
|
||||
url: Any
|
||||
headers: Any
|
||||
|
||||
def json(self) -> Any: ...
|
||||
|
||||
def raise_for_status(self) -> None: ...
|
||||
|
||||
|
||||
class AbstractH2Client(ABC):
|
||||
"""BiliRequest only needs headers, cookies, head/get/post, and close."""
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def headers(self) -> H2Headers:
|
||||
raise NotImplementedError
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def cookies(self) -> H2Cookies:
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def head(self, url: str) -> H2Response:
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def get(self, url: str, *, params: Any = None) -> H2Response:
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def post(
|
||||
self,
|
||||
url: str,
|
||||
*,
|
||||
data: Any = None,
|
||||
json: Any = None,
|
||||
) -> H2Response:
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def close(self) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
H2ClientConstructor = Callable[..., AbstractH2Client]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
H2CLIENT_CONNECTIONS_PER_SOURCE_IP = 3
|
||||
H2CLIENT_HEALTHCHECK_URL = "https://show.bilibili.com/"
|
||||
H2CLIENT_HEALTHCHECK_HOST = "show.bilibili.com"
|
||||
H2CLIENT_HEALTHCHECK_TIMEOUT = 2.0
|
||||
@@ -0,0 +1,580 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import urllib.parse
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Literal
|
||||
|
||||
from h2.config import H2Configuration
|
||||
from h2.connection import H2Connection as H2State
|
||||
from h2.events import (
|
||||
ConnectionTerminated,
|
||||
DataReceived,
|
||||
ResponseReceived,
|
||||
StreamEnded,
|
||||
StreamReset,
|
||||
TrailersReceived,
|
||||
)
|
||||
from loguru import logger
|
||||
|
||||
try:
|
||||
from .client_ja import (
|
||||
ClientHelloProfile,
|
||||
Fingerprints,
|
||||
TARGET_JA3,
|
||||
TARGET_JA3_FULL,
|
||||
TARGET_JA4,
|
||||
TARGET_JA4_R,
|
||||
TLS13Connection,
|
||||
build_client_hello,
|
||||
connect_tcp,
|
||||
fingerprints_from_client_hello,
|
||||
open_tls13_connection,
|
||||
)
|
||||
except ImportError: # pragma: no cover - supports direct execution from this dir.
|
||||
from client_ja import (
|
||||
ClientHelloProfile,
|
||||
Fingerprints,
|
||||
TARGET_JA3,
|
||||
TARGET_JA3_FULL,
|
||||
TARGET_JA4,
|
||||
TARGET_JA4_R,
|
||||
TLS13Connection,
|
||||
build_client_hello,
|
||||
connect_tcp,
|
||||
fingerprints_from_client_hello,
|
||||
open_tls13_connection,
|
||||
)
|
||||
|
||||
|
||||
HeaderItems = Mapping[str, str] | Sequence[tuple[str, str]]
|
||||
AddressFamily = Literal["auto", "ipv4", "ipv6"]
|
||||
|
||||
_CONNECTION_SPECIFIC_HEADERS = {
|
||||
"connection",
|
||||
"host",
|
||||
"keep-alive",
|
||||
"proxy-connection",
|
||||
"te",
|
||||
"trailer",
|
||||
"transfer-encoding",
|
||||
"upgrade",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class H2Response:
|
||||
status: int | None
|
||||
headers: list[tuple[str, str]]
|
||||
body: bytes
|
||||
stream_id: int
|
||||
|
||||
@property
|
||||
def text(self) -> str:
|
||||
return self.body.decode("utf-8", errors="replace")
|
||||
|
||||
def json(self):
|
||||
return json.loads(self.text)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RequestTarget:
|
||||
scheme: str
|
||||
authority: str
|
||||
path: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class JAMatch:
|
||||
fingerprints: Fingerprints
|
||||
expected: dict[str, str]
|
||||
padding_len: int
|
||||
|
||||
@property
|
||||
def ok(self) -> bool:
|
||||
return (
|
||||
self.fingerprints.ja3_full == self.expected["ja3_full"]
|
||||
and self.fingerprints.ja3 == self.expected["ja3"]
|
||||
and self.fingerprints.ja4 == self.expected["ja4"]
|
||||
and self.fingerprints.ja4_r == self.expected["ja4_r"]
|
||||
)
|
||||
|
||||
@property
|
||||
def mismatches(self) -> dict[str, tuple[str, str]]:
|
||||
values = {
|
||||
"ja3_full": self.fingerprints.ja3_full,
|
||||
"ja3": self.fingerprints.ja3,
|
||||
"ja4": self.fingerprints.ja4,
|
||||
"ja4_r": self.fingerprints.ja4_r,
|
||||
}
|
||||
return {
|
||||
name: (actual, self.expected[name])
|
||||
for name, actual in values.items()
|
||||
if actual != self.expected[name]
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class H2ConnectionConfig:
|
||||
remote_host: str
|
||||
source_ip: str | None
|
||||
port: int = 443
|
||||
sni: str | None = None
|
||||
family: AddressFamily = "auto"
|
||||
timeout: float = 10.0
|
||||
proxy_url: str | None = None
|
||||
profile: ClientHelloProfile = field(default_factory=ClientHelloProfile)
|
||||
|
||||
@property
|
||||
def effective_sni(self) -> str:
|
||||
return self.sni or self.remote_host
|
||||
|
||||
@property
|
||||
def authority(self) -> str:
|
||||
return format_authority(self.remote_host, self.port)
|
||||
|
||||
|
||||
def format_authority(host: str, port: int) -> str:
|
||||
host_part = f"[{host}]" if ":" in host and not host.startswith("[") else host
|
||||
return host_part if port == 443 else f"{host_part}:{port}"
|
||||
|
||||
|
||||
def verify_client_hello_ja(
|
||||
sni: str,
|
||||
*,
|
||||
profile: ClientHelloProfile | None = None,
|
||||
expected: Mapping[str, str] | None = None,
|
||||
) -> JAMatch:
|
||||
profile = profile or ClientHelloProfile()
|
||||
built = build_client_hello(sni=sni, profile=profile)
|
||||
fingerprints = fingerprints_from_client_hello(built.record)
|
||||
expected_values = {
|
||||
"ja3_full": TARGET_JA3_FULL,
|
||||
"ja3": TARGET_JA3,
|
||||
"ja4": TARGET_JA4,
|
||||
"ja4_r": TARGET_JA4_R,
|
||||
}
|
||||
if expected:
|
||||
expected_values.update(expected)
|
||||
return JAMatch(
|
||||
fingerprints=fingerprints,
|
||||
expected=expected_values,
|
||||
padding_len=built.padding_len,
|
||||
)
|
||||
|
||||
|
||||
def assert_client_hello_ja(
|
||||
sni: str,
|
||||
*,
|
||||
profile: ClientHelloProfile | None = None,
|
||||
expected: Mapping[str, str] | None = None,
|
||||
) -> JAMatch:
|
||||
result = verify_client_hello_ja(
|
||||
sni,
|
||||
profile=profile,
|
||||
expected=expected,
|
||||
)
|
||||
if not result.ok:
|
||||
details = ", ".join(
|
||||
f"{name}: actual={actual!r}, expected={expected!r}"
|
||||
for name, (actual, expected) in result.mismatches.items()
|
||||
)
|
||||
raise RuntimeError(f"generated ClientHello JA mismatch: {details}")
|
||||
return result
|
||||
|
||||
|
||||
def _coerce_body(content: bytes | str | None) -> bytes:
|
||||
if content is None:
|
||||
return b""
|
||||
if isinstance(content, bytes):
|
||||
return content
|
||||
return content.encode("utf-8")
|
||||
|
||||
|
||||
def _body_for_log(body: bytes) -> str:
|
||||
return body.decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def _header_value(headers: Sequence[tuple[str, str]], name: str) -> str:
|
||||
for header_name, value in headers:
|
||||
if header_name == name:
|
||||
return value
|
||||
return ""
|
||||
|
||||
|
||||
def _normalize_header_items(headers: HeaderItems | None) -> list[tuple[str, str]]:
|
||||
if headers is None:
|
||||
return []
|
||||
items: Iterable[tuple[str, str]]
|
||||
if isinstance(headers, Mapping):
|
||||
items = headers.items()
|
||||
else:
|
||||
items = headers
|
||||
|
||||
normalized: list[tuple[str, str]] = []
|
||||
for name, value in items:
|
||||
lower_name = str(name).lower()
|
||||
if lower_name.startswith(":"):
|
||||
continue
|
||||
if lower_name in _CONNECTION_SPECIFIC_HEADERS:
|
||||
continue
|
||||
normalized.append((lower_name, str(value)))
|
||||
return normalized
|
||||
|
||||
|
||||
def _parse_request_target(
|
||||
url: str,
|
||||
*,
|
||||
remote_host: str,
|
||||
port: int,
|
||||
) -> RequestTarget:
|
||||
parsed = urllib.parse.urlsplit(url)
|
||||
if parsed.scheme:
|
||||
if parsed.scheme != "https":
|
||||
raise ValueError("only https:// URLs are supported")
|
||||
if not parsed.hostname:
|
||||
raise ValueError("URL must include a hostname")
|
||||
url_port = parsed.port or 443
|
||||
if parsed.hostname.lower() != remote_host.lower() or url_port != port:
|
||||
raise ValueError(
|
||||
"request URL host/port must match this maintained connection"
|
||||
)
|
||||
path = parsed.path or "/"
|
||||
if parsed.query:
|
||||
path = f"{path}?{parsed.query}"
|
||||
return RequestTarget(
|
||||
scheme="https",
|
||||
authority=format_authority(parsed.hostname, url_port),
|
||||
path=path,
|
||||
)
|
||||
|
||||
path = url or "/"
|
||||
if not path.startswith("/"):
|
||||
path = f"/{path}"
|
||||
return RequestTarget(
|
||||
scheme="https",
|
||||
authority=format_authority(remote_host, port),
|
||||
path=path,
|
||||
)
|
||||
|
||||
|
||||
def build_request_headers(
|
||||
method: str,
|
||||
url: str,
|
||||
*,
|
||||
remote_host: str,
|
||||
port: int = 443,
|
||||
headers: HeaderItems | None = None,
|
||||
content_length: int | None = None,
|
||||
) -> list[tuple[str, str]]:
|
||||
method = method.upper()
|
||||
target = _parse_request_target(url, remote_host=remote_host, port=port)
|
||||
user_headers = _normalize_header_items(headers)
|
||||
|
||||
request_headers = [
|
||||
(":method", method),
|
||||
(":authority", target.authority),
|
||||
(":scheme", target.scheme),
|
||||
(":path", target.path),
|
||||
]
|
||||
if content_length is not None:
|
||||
user_headers = [
|
||||
(name, value)
|
||||
for name, value in user_headers
|
||||
if name != "content-length"
|
||||
]
|
||||
request_headers.extend(user_headers)
|
||||
|
||||
if content_length is not None:
|
||||
request_headers.append(("content-length", str(content_length)))
|
||||
|
||||
return request_headers
|
||||
|
||||
|
||||
class H2Connection:
|
||||
def __init__(
|
||||
self,
|
||||
remote_host: str,
|
||||
source_ip: str | None,
|
||||
*,
|
||||
port: int = 443,
|
||||
sni: str | None = None,
|
||||
family: AddressFamily = "auto",
|
||||
timeout: float = 10.0,
|
||||
proxy_url: str | None = None,
|
||||
profile: ClientHelloProfile | None = None,
|
||||
assert_ja: bool = False,
|
||||
) -> None:
|
||||
self.config = H2ConnectionConfig(
|
||||
remote_host=remote_host,
|
||||
source_ip=source_ip,
|
||||
port=port,
|
||||
sni=sni,
|
||||
family=family,
|
||||
timeout=timeout,
|
||||
proxy_url=proxy_url,
|
||||
profile=profile or ClientHelloProfile(),
|
||||
)
|
||||
if assert_ja:
|
||||
assert_client_hello_ja(
|
||||
self.config.effective_sni,
|
||||
profile=self.config.profile,
|
||||
)
|
||||
self._sock = None
|
||||
self._tls: TLS13Connection | None = None
|
||||
self._h2: H2State | None = None
|
||||
|
||||
@property
|
||||
def connected(self) -> bool:
|
||||
return self._tls is not None and self._h2 is not None
|
||||
|
||||
@property
|
||||
def selected_alpn(self) -> str | None:
|
||||
return self._tls.selected_alpn if self._tls is not None else None
|
||||
|
||||
@property
|
||||
def cipher_suite(self) -> str | None:
|
||||
return self._tls.cipher_suite if self._tls is not None else None
|
||||
|
||||
def verify_ja(self) -> JAMatch:
|
||||
return verify_client_hello_ja(
|
||||
self.config.effective_sni,
|
||||
profile=self.config.profile,
|
||||
)
|
||||
|
||||
def connect(self) -> None:
|
||||
if self.connected:
|
||||
return
|
||||
|
||||
self._h2 = H2State(
|
||||
config=H2Configuration(
|
||||
client_side=True,
|
||||
header_encoding="utf-8",
|
||||
validate_outbound_headers=True,
|
||||
validate_inbound_headers=False,
|
||||
)
|
||||
)
|
||||
sock = None
|
||||
try:
|
||||
sock = connect_tcp(
|
||||
host=self.config.remote_host,
|
||||
port=self.config.port,
|
||||
family=self.config.family,
|
||||
source_ip=self.config.source_ip,
|
||||
timeout=self.config.timeout,
|
||||
proxy_url=self.config.proxy_url,
|
||||
)
|
||||
built = build_client_hello(
|
||||
sni=self.config.effective_sni,
|
||||
profile=self.config.profile,
|
||||
)
|
||||
self._tls = open_tls13_connection(sock, built)
|
||||
if self._tls.selected_alpn != "h2":
|
||||
raise RuntimeError(
|
||||
f"server selected ALPN {self._tls.selected_alpn!r}, expected 'h2'"
|
||||
)
|
||||
|
||||
self._sock = sock
|
||||
self._h2.initiate_connection()
|
||||
self._flush()
|
||||
except Exception:
|
||||
if sock is not None:
|
||||
sock.close()
|
||||
self._sock = None
|
||||
self._tls = None
|
||||
self._h2 = None
|
||||
raise
|
||||
|
||||
def close(self) -> None:
|
||||
try:
|
||||
if self._h2 is not None and self._tls is not None:
|
||||
try:
|
||||
self._h2.close_connection()
|
||||
self._flush()
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
if self._sock is not None:
|
||||
try:
|
||||
self._sock.close()
|
||||
finally:
|
||||
self._sock = None
|
||||
self._tls = None
|
||||
self._h2 = None
|
||||
|
||||
def __enter__(self) -> H2Connection:
|
||||
self.connect()
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb) -> None:
|
||||
self.close()
|
||||
|
||||
def get(self, url: str, headers: HeaderItems | None = None) -> H2Response:
|
||||
return self.request("GET", url, headers=headers)
|
||||
|
||||
def post(
|
||||
self,
|
||||
url: str,
|
||||
headers: HeaderItems | None = None,
|
||||
content: bytes | str | None = b"",
|
||||
) -> H2Response:
|
||||
return self.request("POST", url, headers=headers, content=content)
|
||||
|
||||
def request(
|
||||
self,
|
||||
method: str,
|
||||
url: str,
|
||||
*,
|
||||
headers: HeaderItems | None = None,
|
||||
content: bytes | str | None = None,
|
||||
) -> H2Response:
|
||||
method = method.upper()
|
||||
if method not in {"GET", "POST"}:
|
||||
raise ValueError("only GET and POST are supported")
|
||||
|
||||
body = b"" if method == "GET" else _coerce_body(content)
|
||||
request_headers = build_request_headers(
|
||||
method,
|
||||
url,
|
||||
remote_host=self.config.remote_host,
|
||||
port=self.config.port,
|
||||
headers=headers,
|
||||
content_length=len(body) if method == "POST" else None,
|
||||
)
|
||||
last_exc: Exception | None = None
|
||||
for attempt in range(2):
|
||||
self._log_request(method, request_headers, body)
|
||||
try:
|
||||
response = self._request_once(request_headers, body)
|
||||
self._log_response(response)
|
||||
return response
|
||||
except Exception as exc:
|
||||
last_exc = exc
|
||||
self.close()
|
||||
if attempt == 0:
|
||||
logger.warning(
|
||||
"H2 request failed; reconnecting source_ip={} "
|
||||
"method={} path={} error={}: {}",
|
||||
self.config.source_ip or "auto",
|
||||
method,
|
||||
_header_value(request_headers, ":path"),
|
||||
exc.__class__.__name__,
|
||||
exc,
|
||||
)
|
||||
continue
|
||||
raise
|
||||
|
||||
assert last_exc is not None
|
||||
raise last_exc
|
||||
|
||||
def _request_once(
|
||||
self,
|
||||
request_headers: list[tuple[str, str]],
|
||||
body: bytes,
|
||||
) -> H2Response:
|
||||
self.connect()
|
||||
assert self._h2 is not None
|
||||
stream_id = self._h2.get_next_available_stream_id()
|
||||
self._h2.send_headers(
|
||||
stream_id,
|
||||
request_headers,
|
||||
end_stream=(len(body) == 0),
|
||||
)
|
||||
if body:
|
||||
self._send_body(stream_id, body)
|
||||
self._flush()
|
||||
return self._read_response(stream_id)
|
||||
|
||||
def _send_body(self, stream_id: int, body: bytes) -> None:
|
||||
assert self._h2 is not None
|
||||
max_frame_size = self._h2.max_outbound_frame_size
|
||||
pos = 0
|
||||
while pos < len(body):
|
||||
chunk = body[pos : pos + max_frame_size]
|
||||
pos += len(chunk)
|
||||
self._h2.send_data(
|
||||
stream_id,
|
||||
chunk,
|
||||
end_stream=(pos >= len(body)),
|
||||
)
|
||||
|
||||
def _log_request(
|
||||
self,
|
||||
method: str,
|
||||
headers: list[tuple[str, str]],
|
||||
body: bytes,
|
||||
) -> None:
|
||||
logger.debug(
|
||||
"H2 request source_ip={} method={} path={} body_len={} header={}",
|
||||
self.config.source_ip or "auto",
|
||||
method,
|
||||
_header_value(headers, ":path"),
|
||||
len(body),
|
||||
str({name: value for name, value in headers}),
|
||||
)
|
||||
|
||||
def _log_response(self, response: H2Response) -> None:
|
||||
logger.debug(
|
||||
"H2 response source_ip={} stream_id={} status={} "
|
||||
"body_len={}",
|
||||
self.config.source_ip or "auto",
|
||||
response.stream_id,
|
||||
response.status,
|
||||
len(response.body),
|
||||
)
|
||||
|
||||
def _flush(self) -> None:
|
||||
assert self._tls is not None
|
||||
assert self._h2 is not None
|
||||
data = self._h2.data_to_send()
|
||||
if data:
|
||||
self._tls.send_application_data(data)
|
||||
|
||||
def _read_events(self):
|
||||
assert self._tls is not None
|
||||
assert self._h2 is not None
|
||||
data = self._tls.read_application_data()
|
||||
events = self._h2.receive_data(data)
|
||||
self._flush()
|
||||
return events
|
||||
|
||||
def _read_response(self, stream_id: int) -> H2Response:
|
||||
assert self._h2 is not None
|
||||
response_headers: list[tuple[str, str]] = []
|
||||
response_body = bytearray()
|
||||
status: int | None = None
|
||||
|
||||
while True:
|
||||
for event in self._read_events():
|
||||
if isinstance(event, ResponseReceived) and event.stream_id == stream_id:
|
||||
response_headers.extend(event.headers)
|
||||
for name, value in event.headers:
|
||||
if name == ":status":
|
||||
status = int(value)
|
||||
elif isinstance(event, TrailersReceived) and event.stream_id == stream_id:
|
||||
response_headers.extend(event.headers)
|
||||
elif isinstance(event, DataReceived) and event.stream_id == stream_id:
|
||||
response_body.extend(event.data)
|
||||
self._h2.acknowledge_received_data(
|
||||
event.flow_controlled_length,
|
||||
event.stream_id,
|
||||
)
|
||||
self._flush()
|
||||
elif isinstance(event, StreamEnded) and event.stream_id == stream_id:
|
||||
return H2Response(
|
||||
status=status,
|
||||
headers=response_headers,
|
||||
body=bytes(response_body),
|
||||
stream_id=stream_id,
|
||||
)
|
||||
elif isinstance(event, StreamReset) and event.stream_id == stream_id:
|
||||
raise RuntimeError(
|
||||
f"stream reset by peer: error_code={event.error_code}"
|
||||
)
|
||||
elif isinstance(event, ConnectionTerminated):
|
||||
raise RuntimeError(
|
||||
"HTTP/2 connection terminated by peer: "
|
||||
f"error_code={event.error_code}, "
|
||||
f"last_stream_id={event.last_stream_id}"
|
||||
)
|
||||
@@ -0,0 +1,892 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import random
|
||||
import socket
|
||||
import threading
|
||||
import urllib.parse
|
||||
from collections.abc import Callable, Mapping, Sequence
|
||||
from concurrent.futures import Future, ThreadPoolExecutor, as_completed
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from loguru import logger
|
||||
|
||||
try:
|
||||
from .abstract_h2_client import AbstractH2Client
|
||||
from .constants import (
|
||||
H2CLIENT_CONNECTIONS_PER_SOURCE_IP,
|
||||
H2CLIENT_HEALTHCHECK_HOST,
|
||||
H2CLIENT_HEALTHCHECK_TIMEOUT,
|
||||
H2CLIENT_HEALTHCHECK_URL,
|
||||
)
|
||||
from .h2connection import AddressFamily, H2Connection, H2Response
|
||||
except ImportError: # pragma: no cover - supports direct import from util/h2client.
|
||||
from abstract_h2_client import AbstractH2Client
|
||||
from constants import (
|
||||
H2CLIENT_CONNECTIONS_PER_SOURCE_IP,
|
||||
H2CLIENT_HEALTHCHECK_HOST,
|
||||
H2CLIENT_HEALTHCHECK_TIMEOUT,
|
||||
H2CLIENT_HEALTHCHECK_URL,
|
||||
)
|
||||
from h2connection import AddressFamily, H2Connection, H2Response
|
||||
|
||||
|
||||
HeaderItems = Mapping[str, str] | Sequence[tuple[str, str]]
|
||||
SourceIPProvider = Callable[[], list["SourceAddress"]]
|
||||
ConnectionFactory = Callable[..., H2Connection]
|
||||
SlotChooser = Callable[[Sequence["ConnectionSlot"]], "ConnectionSlot"]
|
||||
FallbackClientFactory = Callable[..., Any]
|
||||
|
||||
|
||||
def _normalize_proxy_list(proxy: str | None) -> list[str]:
|
||||
if not proxy:
|
||||
return []
|
||||
values: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for raw in str(proxy).split(","):
|
||||
item = raw.strip()
|
||||
if not item or item.lower() in {"none", "direct"}:
|
||||
continue
|
||||
key = item.lower()
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
values.append(item)
|
||||
return values
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SourceAddress:
|
||||
ip: str
|
||||
family: AddressFamily
|
||||
interface_alias: str = ""
|
||||
proxy_url: str | None = None
|
||||
|
||||
@property
|
||||
def display(self) -> str:
|
||||
return self.proxy_url or self.ip
|
||||
|
||||
|
||||
@dataclass
|
||||
class ConnectionSlot:
|
||||
source: SourceAddress
|
||||
connection: H2Connection
|
||||
lock: threading.Lock = field(default_factory=threading.Lock)
|
||||
|
||||
def close(self) -> None:
|
||||
self.connection.close()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FanoutOutcome:
|
||||
slot: ConnectionSlot
|
||||
response: httpx.Response | None = None
|
||||
exc: Exception | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HealthcheckOutcome:
|
||||
source: SourceAddress
|
||||
attempt: int
|
||||
ok: bool
|
||||
|
||||
|
||||
def _dedupe_sources(sources: Sequence[SourceAddress]) -> list[SourceAddress]:
|
||||
seen: set[tuple[str, AddressFamily]] = set()
|
||||
result: list[SourceAddress] = []
|
||||
for source in sources:
|
||||
key = (source.ip, source.family)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
result.append(source)
|
||||
return result
|
||||
|
||||
|
||||
def _append_params(url: str, params: Any) -> str:
|
||||
if not params:
|
||||
return url
|
||||
parsed = urllib.parse.urlsplit(url)
|
||||
query = parsed.query
|
||||
if isinstance(params, str):
|
||||
new_query = params
|
||||
else:
|
||||
new_query = urllib.parse.urlencode(params, doseq=True)
|
||||
query = f"{query}&{new_query}" if query and new_query else query or new_query
|
||||
return urllib.parse.urlunsplit(
|
||||
(parsed.scheme, parsed.netloc, parsed.path, query, parsed.fragment)
|
||||
)
|
||||
|
||||
|
||||
def _json_body(value: Any) -> bytes:
|
||||
return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
||||
|
||||
|
||||
def _form_body(value: Any) -> bytes:
|
||||
if value is None:
|
||||
return b""
|
||||
if isinstance(value, bytes):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
return value.encode("utf-8")
|
||||
return urllib.parse.urlencode(value, doseq=True).encode("utf-8")
|
||||
|
||||
|
||||
def _header_mapping(headers: HeaderItems | None) -> httpx.Headers:
|
||||
return httpx.Headers(headers or {})
|
||||
|
||||
|
||||
def _set_default_header(headers: httpx.Headers, name: str, value: str) -> None:
|
||||
if name not in headers:
|
||||
headers[name] = value
|
||||
|
||||
|
||||
def _timeout_seconds(timeout: Any, default: float) -> float:
|
||||
if timeout is None:
|
||||
return default
|
||||
if isinstance(timeout, (int, float)):
|
||||
return float(timeout)
|
||||
values = [
|
||||
value
|
||||
for value in (
|
||||
getattr(timeout, "connect", None),
|
||||
getattr(timeout, "read", None),
|
||||
getattr(timeout, "write", None),
|
||||
)
|
||||
if isinstance(value, (int, float))
|
||||
]
|
||||
return float(max(values)) if values else default
|
||||
|
||||
|
||||
def _content_length(content: bytes | str | None) -> int:
|
||||
if content is None:
|
||||
return 0
|
||||
if isinstance(content, bytes):
|
||||
return len(content)
|
||||
return len(content.encode("utf-8"))
|
||||
|
||||
|
||||
def _response_errno(response: httpx.Response) -> int | None:
|
||||
try:
|
||||
payload = response.json()
|
||||
except Exception:
|
||||
return None
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
raw_errno = payload.get("errno", payload.get("code"))
|
||||
if raw_errno is None:
|
||||
return None
|
||||
try:
|
||||
return int(raw_errno)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _is_create_success_response(response: httpx.Response) -> bool:
|
||||
if response.status_code != 200:
|
||||
return False
|
||||
return _response_errno(response) == 0
|
||||
|
||||
|
||||
class _SourcePoolJA3H2Client(AbstractH2Client):
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
http2: bool = True,
|
||||
verify: bool | str = True,
|
||||
proxy: str | None = None,
|
||||
timeout: Any = None,
|
||||
limits: Any = None,
|
||||
headers: HeaderItems | None = None,
|
||||
cookies: Any = None,
|
||||
connections_per_source_ip: int = H2CLIENT_CONNECTIONS_PER_SOURCE_IP,
|
||||
healthcheck_url: str = H2CLIENT_HEALTHCHECK_URL,
|
||||
healthcheck_host: str = H2CLIENT_HEALTHCHECK_HOST,
|
||||
source_ip_provider: SourceIPProvider | None = None,
|
||||
connection_factory: ConnectionFactory = H2Connection,
|
||||
slot_chooser: SlotChooser | None = None,
|
||||
fallback_client_factory: FallbackClientFactory = httpx.Client,
|
||||
**_: Any,
|
||||
) -> None:
|
||||
if not http2:
|
||||
raise ValueError("_SourcePoolJA3H2Client only supports HTTP/2")
|
||||
if source_ip_provider is None:
|
||||
raise ValueError(
|
||||
"source_ip_provider is required; use "
|
||||
"ProxyPoolCreateV2FanoutJA3H2Client for proxy-pool fanout"
|
||||
)
|
||||
|
||||
self.http2 = http2
|
||||
self.verify = verify
|
||||
self.proxy = proxy
|
||||
self.limits = limits
|
||||
fallback_kwargs: dict[str, Any] = {
|
||||
"http2": http2,
|
||||
"verify": verify,
|
||||
"headers": headers,
|
||||
"cookies": cookies,
|
||||
}
|
||||
if proxy is not None:
|
||||
fallback_kwargs["proxy"] = proxy
|
||||
if timeout is not None:
|
||||
fallback_kwargs["timeout"] = timeout
|
||||
if limits is not None:
|
||||
fallback_kwargs["limits"] = limits
|
||||
self._fallback_client = fallback_client_factory(**fallback_kwargs)
|
||||
self._headers = self._fallback_client.headers
|
||||
self._cookies = self._fallback_client.cookies
|
||||
self._connections_per_source_ip = max(1, int(connections_per_source_ip))
|
||||
self._healthcheck_url = healthcheck_url
|
||||
self._healthcheck_host = healthcheck_host
|
||||
self._timeout = _timeout_seconds(timeout, H2CLIENT_HEALTHCHECK_TIMEOUT)
|
||||
self._source_ip_provider = source_ip_provider
|
||||
self._connection_factory = connection_factory
|
||||
self._slot_chooser = slot_chooser or random.choice
|
||||
self._lock = threading.RLock()
|
||||
self._available_sources: list[SourceAddress] = []
|
||||
self._pools: dict[tuple[str, int], list[ConnectionSlot]] = {}
|
||||
|
||||
try:
|
||||
self._init_healthchecked_pool()
|
||||
except Exception:
|
||||
self._fallback_client.close()
|
||||
raise
|
||||
|
||||
@property
|
||||
def headers(self) -> httpx.Headers:
|
||||
return self._headers
|
||||
|
||||
@property
|
||||
def cookies(self) -> httpx.Cookies:
|
||||
return self._cookies
|
||||
|
||||
@property
|
||||
def available_source_ips(self) -> list[str]:
|
||||
return [source.ip for source in self._available_sources]
|
||||
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
slots = [
|
||||
slot
|
||||
for pool in self._pools.values()
|
||||
for slot in pool
|
||||
]
|
||||
self._pools.clear()
|
||||
self._available_sources.clear()
|
||||
for slot in slots:
|
||||
slot.close()
|
||||
self._fallback_client.close()
|
||||
|
||||
def head(self, url: str) -> httpx.Response:
|
||||
if self._should_use_fallback(url):
|
||||
return self._fallback_client.head(url)
|
||||
response = self.get(url)
|
||||
return httpx.Response(
|
||||
response.status_code,
|
||||
headers=response.headers,
|
||||
content=b"",
|
||||
request=response.request,
|
||||
)
|
||||
|
||||
def get(
|
||||
self,
|
||||
url: str,
|
||||
*,
|
||||
params: Any = None,
|
||||
headers: HeaderItems | None = None,
|
||||
**kwargs: Any,
|
||||
) -> httpx.Response:
|
||||
if self._should_use_fallback(url):
|
||||
return self._fallback_client.get(
|
||||
url,
|
||||
params=params,
|
||||
headers=headers,
|
||||
**kwargs,
|
||||
)
|
||||
return self._request("GET", _append_params(url, params), headers=headers)
|
||||
|
||||
def post(
|
||||
self,
|
||||
url: str,
|
||||
*,
|
||||
data: Any = None,
|
||||
json: Any = None,
|
||||
content: bytes | str | None = None,
|
||||
headers: HeaderItems | None = None,
|
||||
**kwargs: Any,
|
||||
) -> httpx.Response:
|
||||
if self._should_use_fallback(url):
|
||||
return self._fallback_client.post(
|
||||
url,
|
||||
data=data,
|
||||
json=json,
|
||||
content=content,
|
||||
headers=headers,
|
||||
**kwargs,
|
||||
)
|
||||
request_headers = _header_mapping(headers)
|
||||
if json is not None:
|
||||
body = _json_body(json)
|
||||
_set_default_header(request_headers, "content-type", "application/json")
|
||||
elif content is not None:
|
||||
body = content if isinstance(content, bytes) else content.encode("utf-8")
|
||||
else:
|
||||
body = _form_body(data)
|
||||
if data is not None and not isinstance(data, (bytes, str)):
|
||||
_set_default_header(
|
||||
request_headers,
|
||||
"content-type",
|
||||
"application/x-www-form-urlencoded",
|
||||
)
|
||||
return self._request("POST", url, headers=request_headers, content=body)
|
||||
|
||||
def _should_use_fallback(self, url: str) -> bool:
|
||||
parsed = urllib.parse.urlsplit(url)
|
||||
return (parsed.hostname or "").lower() != self._healthcheck_host.lower()
|
||||
|
||||
def _init_healthchecked_pool(self) -> None:
|
||||
sources = _dedupe_sources(self._source_ip_provider())
|
||||
if not sources:
|
||||
raise httpx.ConnectError("no usable H2 sources were provided")
|
||||
|
||||
key = (self._healthcheck_host, 443)
|
||||
passed: dict[SourceAddress, int] = {source: 0 for source in sources}
|
||||
max_workers = max(1, min(len(sources) * self._connections_per_source_ip, 64))
|
||||
with ThreadPoolExecutor(
|
||||
max_workers=max_workers,
|
||||
thread_name_prefix="btb-h2-healthcheck",
|
||||
) as executor:
|
||||
futures = [
|
||||
executor.submit(self._healthcheck_source_once, source, attempt)
|
||||
for source in sources
|
||||
for attempt in range(1, self._connections_per_source_ip + 1)
|
||||
]
|
||||
for future in as_completed(futures):
|
||||
outcome = future.result()
|
||||
if outcome.ok:
|
||||
passed[outcome.source] += 1
|
||||
|
||||
available_sources = [
|
||||
source
|
||||
for source in sources
|
||||
if passed[source] > 0
|
||||
]
|
||||
if not available_sources:
|
||||
raise httpx.ConnectError("no H2 source passed healthcheck")
|
||||
|
||||
self._available_sources = available_sources
|
||||
self._pools[key] = [
|
||||
ConnectionSlot(
|
||||
source=source,
|
||||
connection=self._build_connection(self._healthcheck_host, 443, source),
|
||||
)
|
||||
for source in available_sources
|
||||
for _ in range(self._connections_per_source_ip)
|
||||
]
|
||||
logger.info(
|
||||
"H2 healthcheck completed host={} usable_sources={} pool_slots={}",
|
||||
self._healthcheck_host,
|
||||
len(self._available_sources),
|
||||
len(self._pools[key]),
|
||||
)
|
||||
|
||||
def _healthcheck_source_once(
|
||||
self,
|
||||
source: SourceAddress,
|
||||
attempt: int,
|
||||
) -> HealthcheckOutcome:
|
||||
connection = self._build_connection(self._healthcheck_host, 443, source)
|
||||
try:
|
||||
response = connection.get(
|
||||
self._healthcheck_url,
|
||||
headers=self._request_headers("GET", self._healthcheck_url),
|
||||
)
|
||||
ok = response.status is not None and response.status < 500
|
||||
if ok:
|
||||
logger.debug(
|
||||
"H2 healthcheck passed source_ip={} attempt={} status={}",
|
||||
source.ip,
|
||||
attempt,
|
||||
response.status,
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
"H2 healthcheck rejected source_ip={} attempt={} status={}",
|
||||
source.ip,
|
||||
attempt,
|
||||
response.status,
|
||||
)
|
||||
return HealthcheckOutcome(source=source, attempt=attempt, ok=ok)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"H2 healthcheck failed source_ip={} attempt={} error={}: {}",
|
||||
source.ip,
|
||||
attempt,
|
||||
exc.__class__.__name__,
|
||||
exc,
|
||||
)
|
||||
return HealthcheckOutcome(source=source, attempt=attempt, ok=False)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def _build_connection(
|
||||
self,
|
||||
host: str,
|
||||
port: int,
|
||||
source: SourceAddress,
|
||||
) -> H2Connection:
|
||||
return self._connection_factory(
|
||||
host,
|
||||
source.ip,
|
||||
port=port,
|
||||
sni=host,
|
||||
family=source.family,
|
||||
timeout=self._timeout,
|
||||
proxy_url=source.proxy_url,
|
||||
assert_ja=True,
|
||||
)
|
||||
|
||||
def _ensure_pool(self, host: str, port: int) -> list[ConnectionSlot]:
|
||||
key = (host, port)
|
||||
with self._lock:
|
||||
pool = self._pools.get(key)
|
||||
if pool:
|
||||
return pool
|
||||
|
||||
pool = []
|
||||
for source in self._available_sources:
|
||||
for _ in range(self._connections_per_source_ip):
|
||||
pool.append(
|
||||
ConnectionSlot(
|
||||
source=source,
|
||||
connection=self._build_connection(host, port, source),
|
||||
)
|
||||
)
|
||||
if not pool:
|
||||
raise httpx.ConnectError(f"no available H2 connections for {host}")
|
||||
self._pools[key] = pool
|
||||
return pool
|
||||
|
||||
def _discard_slot(
|
||||
self,
|
||||
host: str,
|
||||
port: int,
|
||||
slot: ConnectionSlot,
|
||||
*,
|
||||
reason: str = "unspecified",
|
||||
exc: Exception | None = None,
|
||||
) -> None:
|
||||
removed = False
|
||||
with self._lock:
|
||||
pool = self._pools.get((host, port), [])
|
||||
if slot in pool:
|
||||
pool.remove(slot)
|
||||
removed = True
|
||||
if exc is None:
|
||||
logger.warning(
|
||||
"H2 discard connection source_ip={} host={}:{} "
|
||||
"reason={} removed={}",
|
||||
slot.source.ip,
|
||||
host,
|
||||
port,
|
||||
reason,
|
||||
removed,
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
"H2 discard connection source_ip={} host={}:{} "
|
||||
"reason={} removed={} error={}: {}",
|
||||
slot.source.ip,
|
||||
host,
|
||||
port,
|
||||
reason,
|
||||
removed,
|
||||
exc.__class__.__name__,
|
||||
exc,
|
||||
)
|
||||
slot.close()
|
||||
|
||||
def _request(
|
||||
self,
|
||||
method: str,
|
||||
url: str,
|
||||
*,
|
||||
headers: HeaderItems | None = None,
|
||||
content: bytes | str | None = None,
|
||||
) -> httpx.Response:
|
||||
parsed = urllib.parse.urlsplit(url)
|
||||
if parsed.scheme != "https" or not parsed.hostname:
|
||||
raise ValueError("only absolute https:// URLs are supported")
|
||||
host = parsed.hostname
|
||||
port = parsed.port or 443
|
||||
request = httpx.Request(method, url)
|
||||
request_headers = self._request_headers(
|
||||
method,
|
||||
url,
|
||||
headers=headers,
|
||||
content=content,
|
||||
)
|
||||
|
||||
last_exc: Exception | None = None
|
||||
failed_sources: set[str] = set()
|
||||
while True:
|
||||
pool = [
|
||||
slot
|
||||
for slot in self._ensure_pool(host, port)
|
||||
if slot.source.ip not in failed_sources
|
||||
]
|
||||
if not pool:
|
||||
break
|
||||
|
||||
slot = self._slot_chooser(pool)
|
||||
try:
|
||||
with slot.lock:
|
||||
if method == "GET":
|
||||
h2_response = slot.connection.get(url, headers=request_headers)
|
||||
else:
|
||||
h2_response = slot.connection.post(
|
||||
url,
|
||||
headers=request_headers,
|
||||
content=content,
|
||||
)
|
||||
return self._to_httpx_response(request, h2_response)
|
||||
except Exception as exc:
|
||||
last_exc = exc
|
||||
failed_sources.add(slot.source.ip)
|
||||
self._discard_slot(
|
||||
host,
|
||||
port,
|
||||
slot,
|
||||
reason="request_exception",
|
||||
exc=exc,
|
||||
)
|
||||
|
||||
raise self._to_httpx_error(method, url, last_exc)
|
||||
|
||||
def _request_headers(
|
||||
self,
|
||||
method: str,
|
||||
url: str,
|
||||
headers: HeaderItems | None = None,
|
||||
content: bytes | str | None = None,
|
||||
) -> httpx.Headers:
|
||||
request_headers = httpx.Headers(self._headers)
|
||||
request_headers.update(headers or {})
|
||||
request = httpx.Request(method, url, headers=request_headers)
|
||||
self._cookies.set_cookie_header(request)
|
||||
if method.upper() == "POST":
|
||||
request.headers["content-length"] = str(_content_length(content))
|
||||
return request.headers
|
||||
|
||||
def _to_httpx_response(
|
||||
self,
|
||||
request: httpx.Request,
|
||||
response: H2Response,
|
||||
) -> httpx.Response:
|
||||
headers = [
|
||||
(name, value)
|
||||
for name, value in response.headers
|
||||
if not name.startswith(":")
|
||||
]
|
||||
return httpx.Response(
|
||||
response.status or 0,
|
||||
headers=headers,
|
||||
content=response.body,
|
||||
request=request,
|
||||
)
|
||||
|
||||
def _to_httpx_error(
|
||||
self,
|
||||
method: str,
|
||||
url: str,
|
||||
exc: Exception | None,
|
||||
) -> httpx.HTTPError:
|
||||
request = httpx.Request(method, url)
|
||||
if exc is None:
|
||||
return httpx.ConnectError("no available H2 connections", request=request)
|
||||
message = str(exc) or exc.__class__.__name__
|
||||
if isinstance(exc, (socket.timeout, TimeoutError)):
|
||||
return httpx.TimeoutException(message, request=request)
|
||||
if isinstance(exc, OSError):
|
||||
return httpx.ConnectError(message, request=request)
|
||||
return httpx.LocalProtocolError(message, request=request)
|
||||
|
||||
|
||||
class _CreateV2FanoutJA3H2Client(_SourcePoolJA3H2Client):
|
||||
def _request(
|
||||
self,
|
||||
method: str,
|
||||
url: str,
|
||||
*,
|
||||
headers: HeaderItems | None = None,
|
||||
content: bytes | str | None = None,
|
||||
) -> httpx.Response:
|
||||
if not self._should_fanout_create_v2(url):
|
||||
return super()._request(method, url, headers=headers, content=content)
|
||||
|
||||
parsed = urllib.parse.urlsplit(url)
|
||||
if parsed.scheme != "https" or not parsed.hostname:
|
||||
raise ValueError("only absolute https:// URLs are supported")
|
||||
host = parsed.hostname
|
||||
port = parsed.port or 443
|
||||
request = httpx.Request(method, url)
|
||||
request_headers = self._request_headers(
|
||||
method,
|
||||
url,
|
||||
headers=headers,
|
||||
content=content,
|
||||
)
|
||||
pool = list(self._ensure_pool(host, port))
|
||||
if not pool:
|
||||
raise httpx.ConnectError(
|
||||
f"no available H2 connections for {host}",
|
||||
request=request,
|
||||
)
|
||||
|
||||
executor = ThreadPoolExecutor(
|
||||
max_workers=len(pool),
|
||||
thread_name_prefix="btb-createv2-fanout",
|
||||
)
|
||||
futures = [
|
||||
executor.submit(
|
||||
self._send_fanout_request,
|
||||
slot,
|
||||
method,
|
||||
url,
|
||||
request_headers,
|
||||
content,
|
||||
request,
|
||||
)
|
||||
for slot in pool
|
||||
]
|
||||
for future in futures:
|
||||
future.add_done_callback(
|
||||
lambda done, host=host, port=port: self._handle_fanout_done(
|
||||
host,
|
||||
port,
|
||||
done,
|
||||
)
|
||||
)
|
||||
|
||||
first_429: httpx.Response | None = None
|
||||
first_412: httpx.Response | None = None
|
||||
first_900001: httpx.Response | None = None
|
||||
first_other: httpx.Response | None = None
|
||||
last_exc: Exception | None = None
|
||||
try:
|
||||
for future in as_completed(futures):
|
||||
outcome = future.result()
|
||||
if outcome.response is None:
|
||||
last_exc = outcome.exc
|
||||
continue
|
||||
|
||||
status_code = outcome.response.status_code
|
||||
if status_code == 200:
|
||||
errno = _response_errno(outcome.response)
|
||||
if errno != 900001 and first_other is None:
|
||||
first_other = outcome.response
|
||||
elif errno == 900001 and first_900001 is None:
|
||||
first_900001 = outcome.response
|
||||
if status_code == 429 and first_429 is None:
|
||||
first_429 = outcome.response
|
||||
elif status_code == 412 and first_412 is None:
|
||||
first_412 = outcome.response
|
||||
elif status_code not in {200, 412, 429} and first_other is None:
|
||||
first_other = outcome.response
|
||||
|
||||
if first_other is not None:
|
||||
return first_other
|
||||
if first_900001 is not None:
|
||||
return first_900001
|
||||
if first_429 is not None:
|
||||
return first_429
|
||||
if first_412 is not None:
|
||||
return first_412
|
||||
raise self._to_httpx_error(method, url, last_exc)
|
||||
finally:
|
||||
executor.shutdown(wait=True, cancel_futures=False)
|
||||
|
||||
def _should_fanout_create_v2(self, url: str) -> bool:
|
||||
parsed = urllib.parse.urlsplit(url)
|
||||
return (
|
||||
(parsed.hostname or "").lower() == self._healthcheck_host.lower()
|
||||
and "createV2" in parsed.path
|
||||
)
|
||||
|
||||
def _send_fanout_request(
|
||||
self,
|
||||
slot: ConnectionSlot,
|
||||
method: str,
|
||||
url: str,
|
||||
headers: HeaderItems,
|
||||
content: bytes | str | None,
|
||||
request: httpx.Request,
|
||||
) -> FanoutOutcome:
|
||||
try:
|
||||
with slot.lock:
|
||||
if method == "GET":
|
||||
h2_response = slot.connection.get(url, headers=headers)
|
||||
else:
|
||||
h2_response = slot.connection.post(
|
||||
url,
|
||||
headers=headers,
|
||||
content=content,
|
||||
)
|
||||
return FanoutOutcome(
|
||||
slot=slot,
|
||||
response=self._to_httpx_response(request, h2_response),
|
||||
)
|
||||
except Exception as exc:
|
||||
return FanoutOutcome(slot=slot, exc=exc)
|
||||
|
||||
def _handle_fanout_done(
|
||||
self,
|
||||
host: str,
|
||||
port: int,
|
||||
future: Future,
|
||||
) -> None:
|
||||
if future.cancelled():
|
||||
return
|
||||
try:
|
||||
outcome = future.result()
|
||||
except Exception:
|
||||
return
|
||||
if outcome.response is None:
|
||||
self._discard_slot(
|
||||
host,
|
||||
port,
|
||||
outcome.slot,
|
||||
reason="fanout_exception",
|
||||
exc=outcome.exc,
|
||||
)
|
||||
elif outcome.response.status_code == 412:
|
||||
self._discard_slot(
|
||||
host,
|
||||
port,
|
||||
outcome.slot,
|
||||
reason="http_412",
|
||||
)
|
||||
|
||||
|
||||
class ProxyPoolCreateV2FanoutJA3H2Client(_CreateV2FanoutJA3H2Client):
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
proxy_pool: Sequence[str] | None = None,
|
||||
proxy: str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
proxies = list(proxy_pool or _normalize_proxy_list(proxy))
|
||||
if not proxies:
|
||||
raise httpx.ConnectError("proxy pool fanout requires at least one proxy")
|
||||
self._proxy_pool = proxies
|
||||
super().__init__(
|
||||
proxy=proxy,
|
||||
source_ip_provider=self._proxy_sources,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def _proxy_sources(self) -> list[SourceAddress]:
|
||||
return [
|
||||
SourceAddress(
|
||||
ip=f"proxy-{index + 1}",
|
||||
family="auto",
|
||||
interface_alias="proxy",
|
||||
proxy_url=proxy,
|
||||
)
|
||||
for index, proxy in enumerate(self._proxy_pool)
|
||||
]
|
||||
|
||||
def _request(
|
||||
self,
|
||||
method: str,
|
||||
url: str,
|
||||
*,
|
||||
headers: HeaderItems | None = None,
|
||||
content: bytes | str | None = None,
|
||||
) -> httpx.Response:
|
||||
if not self._should_fanout_create_v2(url):
|
||||
return super()._request(method, url, headers=headers, content=content)
|
||||
|
||||
parsed = urllib.parse.urlsplit(url)
|
||||
if parsed.scheme != "https" or not parsed.hostname:
|
||||
raise ValueError("only absolute https:// URLs are supported")
|
||||
host = parsed.hostname
|
||||
port = parsed.port or 443
|
||||
request = httpx.Request(method, url)
|
||||
request_headers = self._request_headers(
|
||||
method,
|
||||
url,
|
||||
headers=headers,
|
||||
content=content,
|
||||
)
|
||||
|
||||
first_429: httpx.Response | None = None
|
||||
first_412: httpx.Response | None = None
|
||||
first_900001: httpx.Response | None = None
|
||||
first_other: httpx.Response | None = None
|
||||
last_exc: Exception | None = None
|
||||
|
||||
while True:
|
||||
pool = list(self._ensure_pool(host, port))
|
||||
if not pool:
|
||||
if first_other is not None:
|
||||
return first_other
|
||||
if first_900001 is not None:
|
||||
return first_900001
|
||||
if first_429 is not None:
|
||||
return first_429
|
||||
if first_412 is not None:
|
||||
return first_412
|
||||
raise self._to_httpx_error(method, url, last_exc)
|
||||
|
||||
executor = ThreadPoolExecutor(
|
||||
max_workers=len(pool),
|
||||
thread_name_prefix="btb-proxy-createv2-fanout",
|
||||
)
|
||||
futures = [
|
||||
executor.submit(
|
||||
self._send_fanout_request,
|
||||
slot,
|
||||
method,
|
||||
url,
|
||||
request_headers,
|
||||
content,
|
||||
request,
|
||||
)
|
||||
for slot in pool
|
||||
]
|
||||
for future in futures:
|
||||
future.add_done_callback(
|
||||
lambda done, host=host, port=port: self._handle_fanout_done(
|
||||
host,
|
||||
port,
|
||||
done,
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
for future in as_completed(futures):
|
||||
outcome = future.result()
|
||||
if outcome.response is None:
|
||||
last_exc = outcome.exc
|
||||
continue
|
||||
|
||||
if _is_create_success_response(outcome.response):
|
||||
executor.shutdown(wait=False, cancel_futures=False)
|
||||
return outcome.response
|
||||
|
||||
status_code = outcome.response.status_code
|
||||
errno = _response_errno(outcome.response)
|
||||
if status_code == 200 and errno == 900001 and first_900001 is None:
|
||||
first_900001 = outcome.response
|
||||
elif status_code == 429 and first_429 is None:
|
||||
first_429 = outcome.response
|
||||
elif status_code == 412 and first_412 is None:
|
||||
first_412 = outcome.response
|
||||
elif status_code not in {412, 429} and first_other is None:
|
||||
first_other = outcome.response
|
||||
finally:
|
||||
executor.shutdown(wait=True, cancel_futures=False)
|
||||
@@ -0,0 +1,139 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import json
|
||||
import socket
|
||||
import subprocess
|
||||
from collections.abc import Sequence
|
||||
|
||||
try:
|
||||
from .h2connection import AddressFamily
|
||||
from .ja_h2_client import SourceAddress
|
||||
except ImportError: # pragma: no cover - supports direct import from util/h2client.
|
||||
from h2connection import AddressFamily
|
||||
from ja_h2_client import SourceAddress
|
||||
|
||||
|
||||
H2CLIENT_SOURCE_INTERFACE_ALIASES = ("WLAN", "以太网")
|
||||
|
||||
|
||||
def _is_usable_source_ip(value: str) -> bool:
|
||||
try:
|
||||
ip = ipaddress.ip_address(value.split("%", 1)[0])
|
||||
except ValueError:
|
||||
return False
|
||||
return not (
|
||||
ip.is_loopback
|
||||
or ip.is_unspecified
|
||||
or ip.is_multicast
|
||||
or ip.is_link_local
|
||||
)
|
||||
|
||||
|
||||
def _source_address(value: str, interface_alias: str = "") -> SourceAddress | None:
|
||||
if not _is_usable_source_ip(value):
|
||||
return None
|
||||
ip = ipaddress.ip_address(value.split("%", 1)[0])
|
||||
return SourceAddress(
|
||||
ip=str(ip),
|
||||
family="ipv6" if ip.version == 6 else "ipv4",
|
||||
interface_alias=interface_alias,
|
||||
)
|
||||
|
||||
|
||||
def _dedupe_sources(sources: Sequence[SourceAddress]) -> list[SourceAddress]:
|
||||
seen: set[tuple[str, AddressFamily]] = set()
|
||||
result: list[SourceAddress] = []
|
||||
for source in sources:
|
||||
key = (source.ip, source.family)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
result.append(source)
|
||||
return result
|
||||
|
||||
|
||||
def _discover_sources_with_powershell(
|
||||
interface_aliases: Sequence[str],
|
||||
) -> list[SourceAddress] | None:
|
||||
quoted_aliases = ",".join(
|
||||
"'" + alias.replace("'", "''") + "'" for alias in interface_aliases
|
||||
)
|
||||
script = (
|
||||
"[Console]::OutputEncoding=[System.Text.Encoding]::UTF8; "
|
||||
"$OutputEncoding=[System.Text.Encoding]::UTF8; "
|
||||
f"$aliases=@({quoted_aliases}); "
|
||||
"Get-NetIPAddress -InterfaceAlias $aliases "
|
||||
"-AddressFamily IPv4,IPv6 -ErrorAction SilentlyContinue | "
|
||||
"Where-Object { $_.IPAddress } | "
|
||||
"Select-Object IPAddress,InterfaceAlias | "
|
||||
"ConvertTo-Json -Compress"
|
||||
)
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
[
|
||||
"powershell",
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-Command",
|
||||
script,
|
||||
],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
timeout=3,
|
||||
)
|
||||
except OSError:
|
||||
return None
|
||||
if completed.returncode != 0:
|
||||
return None
|
||||
if not completed.stdout.strip():
|
||||
return []
|
||||
|
||||
payload = json.loads(completed.stdout)
|
||||
rows = payload if isinstance(payload, list) else [payload]
|
||||
sources: list[SourceAddress] = []
|
||||
for row in rows:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
ip = str(row.get("IPAddress") or "")
|
||||
alias = str(row.get("InterfaceAlias") or "")
|
||||
source = _source_address(ip, alias)
|
||||
if source is not None:
|
||||
sources.append(source)
|
||||
return _dedupe_sources(sources)
|
||||
|
||||
|
||||
def _discover_sources_with_socket() -> list[SourceAddress]:
|
||||
sources: list[SourceAddress] = []
|
||||
try:
|
||||
infos = socket.getaddrinfo(socket.gethostname(), None, socket.AF_UNSPEC)
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
for family, _, _, _, sockaddr in infos:
|
||||
if family == socket.AF_INET:
|
||||
ip = sockaddr[0]
|
||||
elif family == socket.AF_INET6:
|
||||
ip = sockaddr[0]
|
||||
else:
|
||||
continue
|
||||
source = _source_address(ip)
|
||||
if source is not None:
|
||||
sources.append(source)
|
||||
return _dedupe_sources(sources)
|
||||
|
||||
|
||||
def discover_interface_source_ips(
|
||||
interface_aliases: Sequence[str] = H2CLIENT_SOURCE_INTERFACE_ALIASES,
|
||||
) -> list[SourceAddress]:
|
||||
try:
|
||||
sources = _discover_sources_with_powershell(interface_aliases)
|
||||
except Exception:
|
||||
sources = None
|
||||
if sources is not None:
|
||||
return sources
|
||||
return _discover_sources_with_socket()
|
||||
@@ -1,11 +1,13 @@
|
||||
import secrets
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from typing import cast
|
||||
|
||||
import loguru
|
||||
import requests
|
||||
from requests import Response
|
||||
from util.Constant import H2_LIMITS, H2_TIMEOUT
|
||||
from util.h2client.abstract_h2_client import AbstractH2Client, H2ClientConstructor
|
||||
from util.request.BrowerState import (
|
||||
BrowserFingerprintState,
|
||||
build_headers_from_browser_state,
|
||||
@@ -27,6 +29,8 @@ class BiliRequest:
|
||||
browser_state: BrowserFingerprintState | None = None,
|
||||
proxy_failure_threshold: int = 2,
|
||||
proxy_cooldown_seconds: float = 180.0,
|
||||
h2_client_type: H2ClientConstructor | None = None,
|
||||
h2_client_options: dict | None = None,
|
||||
):
|
||||
self.browser_state = browser_state or generate_browser_fingerprint_state()
|
||||
self.deviceId = finalize_device_id(secrets.token_hex(16))
|
||||
@@ -45,7 +49,9 @@ class BiliRequest:
|
||||
)
|
||||
self.request_count = 0 # 记录请求次数
|
||||
self.proxy_manager.apply_to_session(self.session)
|
||||
self._h2_client = None
|
||||
self._h2_client: AbstractH2Client | None = None
|
||||
self._h2_client_type = h2_client_type
|
||||
self._h2_client_options = dict(h2_client_options or {})
|
||||
self.createTime = int(time.time() * 1000)
|
||||
self._handle_100001: Callable[[], None] | None = None
|
||||
|
||||
@@ -109,6 +115,12 @@ class BiliRequest:
|
||||
|
||||
def replace_proxy_pool(self, proxy_string: str) -> None:
|
||||
self.proxy_manager.replace_proxy_list(proxy_string)
|
||||
if "proxy_pool" in self._h2_client_options:
|
||||
self._h2_client_options["proxy_pool"] = [
|
||||
proxy
|
||||
for proxy in self.proxy_manager.proxy_list
|
||||
if proxy.lower() != "none"
|
||||
]
|
||||
self.proxy_manager.apply_to_session(self.session)
|
||||
self._invalidate_h2_client()
|
||||
|
||||
@@ -147,7 +159,7 @@ class BiliRequest:
|
||||
f"body_preview={body}"
|
||||
)
|
||||
|
||||
def _build_h2_client(self):
|
||||
def _build_h2_client(self) -> AbstractH2Client:
|
||||
import httpx
|
||||
|
||||
proxies = self.session.proxies or {}
|
||||
@@ -157,7 +169,10 @@ class BiliRequest:
|
||||
if isinstance(self.session.verify, (bool, str))
|
||||
else True
|
||||
)
|
||||
return httpx.Client(
|
||||
h2_client_type = self._h2_client_type
|
||||
if h2_client_type is None:
|
||||
h2_client_type = cast(H2ClientConstructor, httpx.Client)
|
||||
return h2_client_type(
|
||||
http2=True,
|
||||
verify=verify,
|
||||
proxy=proxy,
|
||||
@@ -169,6 +184,7 @@ class BiliRequest:
|
||||
"connection": "keep-alive",
|
||||
"user-agent": self.headers.get("user-agent", ""),
|
||||
},
|
||||
**self._h2_client_options,
|
||||
)
|
||||
|
||||
def prewarm_h2_connection(self, url: str) -> None:
|
||||
|
||||
Reference in new issue
Block a user