tls-client-python 1.16.0.1__py3-none-macosx_10_9_universal2.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tls_client/_core.py ADDED
@@ -0,0 +1,4738 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ tls_client._core – Low‑level CFFI binding for the Go tls-client engine.
4
+
5
+ Architecture
6
+ ────────────
7
+ • Go shared library compiled with `-buildmode=c-shared` exports four
8
+ symbols: ExecuteRequest, RequestAsync, FreeResponse, ClearClientPool.
9
+ • Sync path: ExecuteRequest blocks until completion, returns CResponseResult*.
10
+ Python wraps it with `raw_res = ffi.gc(raw_res, lib.FreeResponse)` for
11
+ automatic cleanup.
12
+ • Async path: RequestAsync deep-copies all C data into Go heap, dispatches a
13
+ goroutine, and returns immediately. The goroutine executes the HTTP request
14
+ and calls a CFFI callback with (request_id, CResponseResult*). Python
15
+ unpacks the response in the callback, calls FreeResponse, and resolves an
16
+ asyncio.Future via `loop.call_soon_threadsafe()`. No thread pool — Python's
17
+ event loop is never blocked.
18
+ • Response body is read via `ffi.buffer(res.body, res.body_len)[:]` for
19
+ a single zero-copy-style memory view → Python bytes conversion.
20
+ • All temporary C allocations are anchored in a `keep_alive` list for the
21
+ duration of the call, preventing premature GC and dangling pointers.
22
+
23
+ Classes
24
+ ───────
25
+ • Session – synchronous client. Supports `with` context manager.
26
+ • AsyncSession – asynchronous client using Go goroutines + CFFI callbacks.
27
+ Compatible with uvloop / winloop for maximum event-loop performance.
28
+ """
29
+
30
+ import asyncio
31
+ import base64
32
+ import ctypes
33
+ import copy
34
+ import json as _json
35
+ import os
36
+ import platform
37
+ import sys
38
+ import threading
39
+ from pathlib import Path
40
+ from typing import Any, Dict, List, Optional, Tuple, Union
41
+ import hashlib
42
+ from urllib.parse import urlencode
43
+
44
+ from tls_client._default_headers import DEFAULT_HEADERS
45
+
46
+ try:
47
+ from typing import Literal, TypedDict
48
+ except ImportError:
49
+ from typing_extensions import Literal, TypedDict # Python 3.6–3.7
50
+
51
+ try:
52
+ from typing import TypeAlias
53
+ except ImportError:
54
+ from typing_extensions import TypeAlias # Python 3.6-3.9
55
+
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # Supported TLS client identifiers — literal type for IDE autocompletion
59
+ # ---------------------------------------------------------------------------
60
+
61
+ ClientIdentifiers: TypeAlias = Literal[
62
+ # ── Chrome ──
63
+ "chrome_103", "chrome_104", "chrome_105", "chrome_106",
64
+ "chrome_107", "chrome_108", "chrome_109", "chrome_110",
65
+ "chrome_111", "chrome_112",
66
+ "chrome_116_PSK", "chrome_116_PSK_PQ",
67
+ "chrome_117", "chrome_120", "chrome_124",
68
+ "chrome_130_PSK",
69
+ "chrome_131", "chrome_131_PSK",
70
+ "chrome_133", "chrome_133_PSK",
71
+ "chrome_144", "chrome_144_PSK",
72
+ "chrome_146", "chrome_146_PSK",
73
+ "chrome_150", "chrome_150_PSK",
74
+ "chrome_152", "chrome_152_PSK",
75
+ # ── Brave ──
76
+ "brave_146", "brave_146_PSK",
77
+ # ── Safari ──
78
+ "safari_15_6_1", "safari_16_0",
79
+ "safari_ipad_15_6",
80
+ "safari_ios_15_5", "safari_ios_15_6", "safari_ios_16_0",
81
+ "safari_ios_17_0",
82
+ "safari_ios_18_0", "safari_ios_18_5",
83
+ "safari_ios_26_0",
84
+ # ── Firefox ──
85
+ "firefox_102", "firefox_104", "firefox_105", "firefox_106",
86
+ "firefox_108", "firefox_110",
87
+ "firefox_117", "firefox_120", "firefox_123",
88
+ "firefox_132", "firefox_133", "firefox_135",
89
+ "firefox_146_PSK",
90
+ "firefox_147", "firefox_147_PSK",
91
+ "firefox_148",
92
+ # ── Opera ──
93
+ "opera_89", "opera_90", "opera_91",
94
+ # ── Zalando ──
95
+ "zalando_android_mobile", "zalando_ios_mobile",
96
+ # ── Nike ──
97
+ "nike_ios_mobile", "nike_android_mobile",
98
+ # ── Cloudflare ──
99
+ "cloudscraper",
100
+ # ── MMS ──
101
+ "mms_ios", "mms_ios_1", "mms_ios_2", "mms_ios_3",
102
+ # ── Mesh ──
103
+ "mesh_ios", "mesh_ios_1", "mesh_ios_2",
104
+ "mesh_android", "mesh_android_1", "mesh_android_2",
105
+ # ── Confirmed ──
106
+ "confirmed_ios", "confirmed_android",
107
+ # ── OkHttp ──
108
+ "okhttp4_android_7", "okhttp4_android_8", "okhttp4_android_9",
109
+ "okhttp4_android_10", "okhttp4_android_11",
110
+ "okhttp4_android_12", "okhttp4_android_13",
111
+ ]
112
+
113
+ # Runtime counterpart of ``ClientIdentifiers``. Keeping this derived from
114
+ # the header/profile table lets callers fail fast instead of silently sending
115
+ # a request with an unknown fingerprint.
116
+ SUPPORTED_CLIENT_IDENTIFIERS = frozenset(DEFAULT_HEADERS)
117
+
118
+
119
+ # ---------------------------------------------------------------------------
120
+ # 强类型请求对象 ─ 提供 IDE 自动补全
121
+ # Strongly-typed request object — provides IDE autocompletion
122
+ # ---------------------------------------------------------------------------
123
+
124
+ class Request(TypedDict, total=False):
125
+ """强类型请求对象,提供 IDE 自动补全。
126
+
127
+ Strongly-typed request object for IDE autocompletion.
128
+ """
129
+
130
+ method: str
131
+ """HTTP 方法,如 ``"GET"``、``"POST"``。在 :meth:`Session.typed_request` 中必填。
132
+
133
+ HTTP method, e.g. ``"GET"``, ``"POST"``. Required in :meth:`Session.typed_request`.
134
+ """
135
+ url: str
136
+ """请求 URL。在 :meth:`Session.typed_request` 中必填。
137
+
138
+ Request URL. Required in :meth:`Session.typed_request`.
139
+ """
140
+ headers: Optional[Dict[str, str]]
141
+ """请求头字典。
142
+
143
+ Request headers dict.
144
+ """
145
+ header_order: Optional[List[str]]
146
+ """请求头发送顺序列表。
147
+
148
+ Header send-order list.
149
+ """
150
+ body: Optional[bytes]
151
+ """请求体原始字节串。
152
+
153
+ Request body as raw bytes.
154
+ """
155
+ client_identifier: Optional[str]
156
+ """TLS 指纹标识。
157
+
158
+ TLS fingerprint identifier.
159
+ """
160
+ timeout: Optional[int]
161
+ """超时时间(秒)。
162
+
163
+ Timeout in seconds.
164
+ """
165
+ timeout_milliseconds: Optional[int]
166
+ """超时时间(毫秒)。
167
+
168
+ Timeout in milliseconds.
169
+ """
170
+ follow_redirects: Optional[bool]
171
+ """是否跟随重定向。
172
+
173
+ Whether to follow redirects.
174
+ """
175
+ verify: Optional[bool]
176
+ """是否验证 TLS 证书。
177
+
178
+ Whether to verify the TLS certificate.
179
+ """
180
+ force_http1: Optional[bool]
181
+ """是否强制 HTTP/1.1。
182
+
183
+ Whether to force HTTP/1.1.
184
+ """
185
+ random_tls_extension_order: Optional[bool]
186
+ """是否随机 TLS 扩展顺序。
187
+
188
+ Whether to randomise TLS extension order.
189
+ """
190
+ with_protocol_racing: Optional[bool]
191
+ """是否启用协议竞速。
192
+
193
+ Whether to enable protocol racing.
194
+ """
195
+ server_name_overwrite: Optional[str]
196
+ """SNI 主机名覆盖。
197
+
198
+ SNI hostname override.
199
+ """
200
+ request_host_override: Optional[str]
201
+ """Host 请求头覆盖。
202
+
203
+ Host header override.
204
+ """
205
+ proxy: Optional[str]
206
+ """代理 URL。
207
+
208
+ Proxy URL.
209
+ """
210
+ local_address: Optional[str]
211
+ """本地绑定地址。
212
+
213
+ Local bind address.
214
+ """
215
+ pseudo_header_order: Optional[List[str]]
216
+ """HTTP/2 伪头顺序。
217
+
218
+ HTTP/2 pseudo-header order.
219
+ """
220
+ h3_pseudo_header_order: Optional[List[str]]
221
+ """HTTP/3 伪头顺序。
222
+
223
+ HTTP/3 pseudo-header order.
224
+ """
225
+ max_idle_connections: Optional[int]
226
+ """全局最大空闲连接数。
227
+
228
+ Global max idle connections.
229
+ """
230
+ max_idle_connections_per_host: Optional[int]
231
+ """每 Host 最大空闲连接数。
232
+
233
+ Max idle connections per host.
234
+ """
235
+ max_connections_per_host: Optional[int]
236
+ """每 Host 最大总连接数。
237
+
238
+ Max total connections per host.
239
+ """
240
+ disable_keep_alives: Optional[bool]
241
+ """是否禁用 Keep-Alive。
242
+
243
+ Whether to disable Keep-Alive.
244
+ """
245
+ disable_compression: Optional[bool]
246
+ """是否禁用响应解压。
247
+
248
+ Whether to disable decompression.
249
+ """
250
+ idle_conn_timeout_seconds: Optional[int]
251
+ """空闲连接超时(秒)。
252
+
253
+ Idle connection timeout (seconds).
254
+ """
255
+ max_response_header_bytes: Optional[int]
256
+ """响应头最大字节数。
257
+
258
+ Max response header bytes.
259
+ """
260
+ write_buffer_size: Optional[int]
261
+ """写缓冲区大小。
262
+
263
+ Write buffer size.
264
+ """
265
+ read_buffer_size: Optional[int]
266
+ """读缓冲区大小。
267
+
268
+ Read buffer size.
269
+ """
270
+ allow_empty_cookies: Optional[bool]
271
+ """是否允许空 Cookie。
272
+
273
+ Whether to allow empty cookies.
274
+ """
275
+ without_cookie_jar: Optional[bool]
276
+ """是否禁用 Cookie Jar。
277
+
278
+ Whether to disable Cookie Jar.
279
+ """
280
+ disable_http3: Optional[bool]
281
+ """是否禁用 HTTP/3。
282
+
283
+ Whether to disable HTTP/3.
284
+ """
285
+ disable_ipv4: Optional[bool]
286
+ """是否禁用 IPv4。
287
+
288
+ Whether to disable IPv4.
289
+ """
290
+ disable_ipv6: Optional[bool]
291
+ """是否禁用 IPv6。
292
+
293
+ Whether to disable IPv6.
294
+ """
295
+ tcp_ttl: Optional[int]
296
+ """IP TTL 覆盖。0=自动从预设推断。
297
+
298
+ IP TTL override. 0=auto from profile.
299
+ """
300
+ tcp_window_size: Optional[int]
301
+ """TCP 窗口大小覆盖。0=自动从预设推断。
302
+
303
+ TCP window size override. 0=auto from profile.
304
+ """
305
+ tcp_window_scale: Optional[int]
306
+ """TCP 窗口缩放因子覆盖。0=自动从预设推断。
307
+
308
+ TCP window scale override. 0=auto from profile.
309
+ """
310
+ tcp_mss: Optional[int]
311
+ """TCP MSS 覆盖。0=自动从预设推断。
312
+
313
+ TCP MSS override. 0=auto from profile.
314
+ """
315
+ catch_panics: Optional[bool]
316
+ """是否捕获 Go panic。
317
+
318
+ Whether to catch Go panics.
319
+ """
320
+ with_debug: Optional[bool]
321
+ """是否启用调试日志。
322
+
323
+ Whether to enable debug logging.
324
+ """
325
+ default_headers: Optional[Dict[str, str]]
326
+ """默认请求头字典,每次请求自动附加。
327
+
328
+ Default headers dict, automatically added to every request.
329
+ """
330
+ connect_headers: Optional[Dict[str, str]]
331
+ """代理 CONNECT 隧道请求头字典。
332
+
333
+ Proxy CONNECT tunnel headers dict.
334
+ """
335
+ certificate_pinning_hosts: Optional[Dict[str, List[str]]]
336
+ """SSL 证书固定字典,格式为 ``{host: [pin1, pin2, ...]}``。
337
+
338
+ SSL certificate pinning dict, format ``{host: [pin1, pin2, ...]}``.
339
+ """
340
+ with_default_bad_pin_handler: Optional[bool]
341
+ """是否在证书固定失败时调用默认 Bad-Pin 处理器。
342
+
343
+ Whether to invoke the default bad-pin handler on pin mismatch.
344
+ """
345
+ request_cookies: Optional[Dict[str, str]]
346
+ """预置 Cookie 字典,在发送请求前注入到 Cookie Jar。
347
+
348
+ Pre-populated cookie dict, injected into the Cookie Jar before sending.
349
+ """
350
+ custom_tls_client: Optional[Dict[str, Any]]
351
+ """完全自定义的 TLS 客户端配置字典。
352
+
353
+ Fully custom TLS client configuration dict.
354
+
355
+ 包含 JA3 字符串、密码套件、ECH、ALPN、HTTP/2/3 设置等 26 个字段。
356
+ 设置后将忽略 ``client_identifier``。
357
+
358
+ Contains JA3 string, cipher suites, ECH, ALPN, HTTP/2/3 settings, etc.
359
+ (26 fields). When set, ``client_identifier`` is ignored.
360
+ """
361
+ client_certificates: Optional[List[Dict[str, bytes]]]
362
+ """客户端证书列表,用于 mTLS 双向认证。
363
+
364
+ 每个元素为 ``{'cert_pem': bytes, 'key_pem': bytes}``。
365
+
366
+ Client certificate list for mTLS mutual authentication.
367
+
368
+ Each element is ``{'cert_pem': bytes, 'key_pem': bytes}``.
369
+ """
370
+
371
+
372
+ # ---------------------------------------------------------------------------
373
+ # Response – requests‑style response object
374
+ # ---------------------------------------------------------------------------
375
+
376
+ class Response:
377
+ """HTTP 响应对象,兼容 requests 库风格。
378
+
379
+ A requests‑compatible HTTP response object.
380
+
381
+ Attributes
382
+ ----------
383
+ status_code : int
384
+ HTTP 状态码 / HTTP status code.
385
+ headers : dict
386
+ 响应头字典 / Response headers.
387
+ content : bytes
388
+ 原始响应体字节串 / Raw response body as bytes.
389
+ text : str
390
+ 已解码的响应体文本 / Decoded response body text.
391
+ encoding : str
392
+ 检测到的字符编码 / Detected charset encoding.
393
+ url : str or None
394
+ 最终请求 URL(重定向后)/ Final URL after redirects.
395
+ cookies : dict
396
+ 响应 Cookie 字典 / Response cookies dict.
397
+ used_protocol : str or None
398
+ 实际使用的 HTTP 协议版本 / HTTP protocol version used.
399
+ """
400
+
401
+ __slots__ = (
402
+ "_status_code",
403
+ "_headers",
404
+ "_content",
405
+ "_text",
406
+ "_encoding",
407
+ "_url",
408
+ "_cookies",
409
+ "_used_protocol",
410
+ )
411
+
412
+ def __init__(
413
+ self,
414
+ status_code: int,
415
+ headers: Dict[str, List[str]],
416
+ content: bytes,
417
+ text: str,
418
+ encoding: str,
419
+ url: Optional[str] = None,
420
+ cookies: Optional[Dict[str, str]] = None,
421
+ used_protocol: Optional[str] = None,
422
+ ) -> None:
423
+ self._status_code = status_code
424
+ self._headers = headers
425
+ self._content = content
426
+ self._text = text
427
+ self._encoding = encoding
428
+ self._url = url
429
+ self._cookies = cookies or {}
430
+ self._used_protocol = used_protocol
431
+
432
+ # -- read‑only properties ----------------------------------------------
433
+
434
+ @property
435
+ def status_code(self) -> int:
436
+ """HTTP 状态码 / HTTP status code."""
437
+ return self._status_code
438
+
439
+ @property
440
+ def headers(self) -> Dict[str, List[str]]:
441
+ """响应头字典 / Response headers."""
442
+ return self._headers
443
+
444
+ @property
445
+ def content(self) -> bytes:
446
+ """原始响应体字节串 / Raw bytes body."""
447
+ return self._content
448
+
449
+ @property
450
+ def text(self) -> str:
451
+ """已解码的响应体文本 / Decoded text body."""
452
+ return self._text
453
+
454
+ @property
455
+ def encoding(self) -> str:
456
+ """文本编码 / Text encoding."""
457
+ return self._encoding
458
+
459
+ @property
460
+ def url(self) -> Optional[str]:
461
+ """最终请求 URL(重定向后)/ Final URL after redirects."""
462
+ return self._url
463
+
464
+ @property
465
+ def cookies(self) -> Dict[str, str]:
466
+ """响应 Cookie 字典 / Response cookies dict."""
467
+ return self._cookies
468
+
469
+ @property
470
+ def used_protocol(self) -> Optional[str]:
471
+ """使用的 HTTP 协议版本 / HTTP protocol version (e.g. ``"HTTP/2.0"``)."""
472
+ return self._used_protocol
473
+
474
+ @property
475
+ def ok(self) -> bool:
476
+ """状态码 < 400 时为 ``True``。 / ``True`` if status_code < 400."""
477
+ return self._status_code < 400
478
+
479
+ @property
480
+ def reason(self) -> str:
481
+ """HTTP 状态文本 / HTTP reason phrase."""
482
+ from http.client import responses
483
+ return responses.get(self._status_code, "Unknown")
484
+
485
+ # -- public methods ----------------------------------------------------
486
+
487
+ def json(self, **kwargs: Any) -> Any:
488
+ """解析 JSON 响应体。 / Parse response body as JSON.
489
+
490
+ Parameters are forwarded to :func:`json.loads`.
491
+ """
492
+ import json
493
+ return json.loads(self._text, **kwargs)
494
+
495
+ def raise_for_status(self) -> None:
496
+ """若状态码 ≥ 400,抛出 :exc:`RuntimeError`。
497
+
498
+ Raise :exc:`RuntimeError` if the status code indicates an error
499
+ (4xx client error or 5xx server error).
500
+ """
501
+ if self._status_code >= 400:
502
+ raise RuntimeError(
503
+ f"{self._status_code} {self.reason} for url: {self._url or '(unknown)'}"
504
+ )
505
+
506
+ # -- dunder methods ----------------------------------------------------
507
+
508
+ def __bool__(self) -> bool:
509
+ """``bool(resp)`` → ``resp.ok``。"""
510
+ return self.ok
511
+
512
+ def __repr__(self) -> str:
513
+ return f"<Response [{self._status_code}]>"
514
+
515
+ def __str__(self) -> str:
516
+ return self.__repr__()
517
+
518
+
519
+ def _merge_url_params(url: str, params: Dict[str, str]) -> str:
520
+ query = urlencode(params)
521
+ if not query:
522
+ return url
523
+
524
+ base, marker, fragment = url.partition("#")
525
+ if "?" not in base:
526
+ merged = f"{base}?{query}"
527
+ elif base.endswith("?") or base.endswith("&"):
528
+ merged = f"{base}{query}"
529
+ else:
530
+ merged = f"{base}&{query}"
531
+
532
+ if not marker:
533
+ return merged
534
+ return f"{merged}#{fragment}"
535
+
536
+
537
+ def _ensure_header(
538
+ headers: Optional[Dict[str, str]],
539
+ header_name: str,
540
+ value: str,
541
+ *,
542
+ owned: bool = False,
543
+ ) -> Tuple[Dict[str, str], bool]:
544
+ if headers is None:
545
+ return {header_name: value}, True
546
+
547
+ needle = header_name.lower()
548
+ for key in headers:
549
+ if key.lower() == needle:
550
+ return headers, owned
551
+
552
+ if owned:
553
+ headers[header_name] = value
554
+ return headers, True
555
+
556
+ merged = dict(headers)
557
+ merged[header_name] = value
558
+ return merged, True
559
+
560
+
561
+ ProxyConfig = Union[str, Dict[str, str]]
562
+ _MISSING = object()
563
+
564
+
565
+ def _resolve_proxy_url(
566
+ proxy: Optional[ProxyConfig],
567
+ url: str,
568
+ ) -> Optional[str]:
569
+ if proxy is None:
570
+ return None
571
+ if isinstance(proxy, str):
572
+ return proxy
573
+ scheme = url.split(":", 1)[0].lower()
574
+ return (
575
+ proxy.get(scheme)
576
+ or proxy.get(f"{scheme}://")
577
+ or proxy.get("all")
578
+ or proxy.get("all://")
579
+ or next(iter(proxy.values()), None)
580
+ )
581
+
582
+
583
+ def _clone_default_value(value: Any) -> Any:
584
+ if isinstance(value, dict):
585
+ if any(isinstance(v, (dict, list, set, tuple)) for v in value.values()):
586
+ return copy.deepcopy(value)
587
+ return dict(value)
588
+ if isinstance(value, list):
589
+ if any(isinstance(v, (dict, list, set, tuple)) for v in value):
590
+ return copy.deepcopy(value)
591
+ return list(value)
592
+ if isinstance(value, set):
593
+ if any(isinstance(v, (dict, list, set, tuple)) for v in value):
594
+ return copy.deepcopy(value)
595
+ return set(value)
596
+ if isinstance(value, tuple):
597
+ if any(isinstance(v, (dict, list, set, tuple)) for v in value):
598
+ return copy.deepcopy(value)
599
+ return tuple(value)
600
+ return value
601
+
602
+
603
+ def _load_client_certificates(
604
+ cert: Union[str, Tuple[str, str]],
605
+ ) -> Optional[List[Dict[str, bytes]]]:
606
+ if isinstance(cert, str):
607
+ with open(cert, "rb") as f:
608
+ cert_bytes = f.read()
609
+ return [{"cert_pem": cert_bytes, "key_pem": cert_bytes}]
610
+
611
+ if isinstance(cert, tuple) and len(cert) == 2:
612
+ with open(cert[0], "rb") as f:
613
+ cert_bytes = f.read()
614
+ with open(cert[1], "rb") as f:
615
+ key_bytes = f.read()
616
+ return [{"cert_pem": cert_bytes, "key_pem": key_bytes}]
617
+
618
+ return None
619
+
620
+
621
+ def _prepare_request_compat(
622
+ *,
623
+ get_default,
624
+ url: str,
625
+ params: Optional[Dict[str, str]],
626
+ data: Union[bytes, str, Dict[str, str], None],
627
+ json_data: Any,
628
+ headers: Optional[Dict[str, str]],
629
+ auth: Optional[Tuple[str, str]],
630
+ cookies: Optional[Dict[str, str]],
631
+ stream: Optional[bool],
632
+ cert: Optional[Union[str, Tuple[str, str]]],
633
+ timeout: Optional[int],
634
+ allow_redirects: Optional[bool],
635
+ proxies: Optional[Dict[str, str]],
636
+ verify: Optional[bool],
637
+ kwargs: Dict[str, Any],
638
+ ) -> Tuple[str, Optional[bytes], Optional[Dict[str, str]], Optional[Dict[str, str]], Optional[List[Dict[str, bytes]]]]:
639
+ if params:
640
+ url = _merge_url_params(url, params)
641
+
642
+ body = kwargs.pop("body", None)
643
+ headers_owned = False
644
+
645
+ if body is None and data is not None:
646
+ if isinstance(data, dict):
647
+ body = urlencode(data).encode("utf-8")
648
+ headers, headers_owned = _ensure_header(
649
+ headers,
650
+ "Content-Type",
651
+ "application/x-www-form-urlencoded",
652
+ owned=headers_owned,
653
+ )
654
+ elif isinstance(data, str):
655
+ body = data.encode("utf-8")
656
+ else:
657
+ body = data
658
+
659
+ if json_data is not None:
660
+ body = _json.dumps(json_data, ensure_ascii=False).encode("utf-8")
661
+ headers, headers_owned = _ensure_header(
662
+ headers,
663
+ "Content-Type",
664
+ "application/json",
665
+ owned=headers_owned,
666
+ )
667
+
668
+ effective_auth = auth if auth is not None else get_default("auth")
669
+ if effective_auth is not None:
670
+ user, pwd = effective_auth
671
+ encoded = base64.b64encode(f"{user}:{pwd}".encode("utf-8")).decode("ascii")
672
+ headers, headers_owned = _ensure_header(
673
+ headers,
674
+ "Authorization",
675
+ f"Basic {encoded}",
676
+ owned=headers_owned,
677
+ )
678
+
679
+ client_certificates = kwargs.pop("client_certificates", None)
680
+ effective_cert = cert if cert is not None else get_default("cert")
681
+ if client_certificates is None and effective_cert is not None:
682
+ client_certificates = _load_client_certificates(effective_cert)
683
+
684
+ if cookies is not None:
685
+ request_cookies = cookies
686
+ kwargs.pop("request_cookies", None)
687
+ else:
688
+ request_cookies = kwargs.pop("request_cookies", None)
689
+
690
+ if proxies is not None:
691
+ proxy_source = proxies
692
+ else:
693
+ proxy_source = kwargs["proxy"] if "proxy" in kwargs else _MISSING
694
+ if proxy_source is _MISSING:
695
+ proxy_source = get_default("proxy")
696
+
697
+ effective_proxy = _resolve_proxy_url(proxy_source, url)
698
+ if effective_proxy is not None:
699
+ kwargs["proxy"] = effective_proxy
700
+
701
+ if allow_redirects is not None and "follow_redirects" not in kwargs:
702
+ kwargs["follow_redirects"] = allow_redirects
703
+ if timeout is not None and "timeout" not in kwargs:
704
+ kwargs["timeout"] = timeout
705
+ if verify is not None and "verify" not in kwargs:
706
+ kwargs["verify"] = verify
707
+ if stream is not None and "stream" not in kwargs:
708
+ kwargs["stream"] = stream
709
+
710
+ return url, body, headers, request_cookies, client_certificates
711
+
712
+
713
+ def _copy_snapshot_value(value: Any) -> Any:
714
+ if isinstance(value, dict):
715
+ return dict(value)
716
+ if isinstance(value, list):
717
+ return list(value)
718
+ if isinstance(value, set):
719
+ return set(value)
720
+ if isinstance(value, tuple):
721
+ return tuple(value)
722
+ return value
723
+
724
+
725
+ # Integer-typed request fields. cffi raises TypeError when ``None`` or a
726
+ # str is assigned to any of these C int fields, but the requests-compatible
727
+ # API allows e.g. ``session.timeout = None`` (a common way to write "no
728
+ # explicit timeout"). Values are normalised right after the per-request
729
+ # dict is resolved and BEFORE the cache-key hash is computed: the Go engine
730
+ # renders these fields with ``%d``, so ``None``→0 and ``True``→1 must be
731
+ # applied on the Python side too or the pre-computed hash diverges from
732
+ # Go's buildCacheKey and silently poisons the client pool.
733
+ _INT_REQUEST_KEYS = frozenset((
734
+ "timeout_seconds",
735
+ "timeout_milliseconds",
736
+ "max_idle_connections",
737
+ "max_idle_connections_per_host",
738
+ "max_connections_per_host",
739
+ "max_response_header_bytes",
740
+ "write_buffer_size",
741
+ "read_buffer_size",
742
+ "idle_conn_timeout_seconds",
743
+ "tcp_ttl",
744
+ "tcp_window_size",
745
+ "tcp_window_scale",
746
+ "tcp_mss",
747
+ "disable_session_tickets",
748
+ "h2_max_data_frame_size",
749
+ "preface_ping_idle_ms",
750
+ "cookie_crumb",
751
+ # ABI 3 — deep fingerprint controls
752
+ "extension_permute_mode",
753
+ "extension_permute_prefix",
754
+ "h2_disable_priority_frames",
755
+ "header_order_by_dest",
756
+ "tcp_dont_fragment",
757
+ "tcp_tos",
758
+ "tcp_no_delay",
759
+ "tcp_window_clamp",
760
+ ))
761
+
762
+ # ABI 3 tri-state TCP fields. Unlike the plain int fields above (where 0
763
+ # means "unset"), these use -1 as the "leave the profile default alone"
764
+ # sentinel, mirroring Go's ``cfg.tcpX >= 0`` guards. A bare ``None`` must
765
+ # therefore become -1, never 0 — 0 is a *meaningful* value (DF cleared,
766
+ # TOS 0 / CS0, Nagle off).
767
+ _TRISTATE_REQUEST_KEYS = frozenset((
768
+ "tcp_dont_fragment",
769
+ "tcp_tos",
770
+ "tcp_no_delay",
771
+ ))
772
+
773
+
774
+ def _normalize_int_fields(resolved: Dict[str, Any]) -> None:
775
+ """Coerce None→0 and bool→int for the C int fields of *resolved*.
776
+
777
+ 0 means "unset" to the Go engine (e.g. timeout_seconds=0 falls back to
778
+ the engine default), which is the closest safe mapping for the requests
779
+ idiom ``timeout=None``. Other invalid types (str, float) are left
780
+ untouched so cffi still raises its strict TypeError.
781
+
782
+ ABI 3 tri-state fields (``_TRISTATE_REQUEST_KEYS``) instead map None→-1
783
+ because 0 is a meaningful value for them; see ``_TRISTATE_REQUEST_KEYS``.
784
+ """
785
+ for key in _INT_REQUEST_KEYS:
786
+ value = resolved.get(key)
787
+ if value is None:
788
+ resolved[key] = -1 if key in _TRISTATE_REQUEST_KEYS else 0
789
+ elif isinstance(value, bool):
790
+ resolved[key] = int(value)
791
+
792
+
793
+ SYNC_REQUEST_DEFAULT_KEYS = (
794
+ "proxy",
795
+ "pseudo_header_order",
796
+ "h3_pseudo_header_order",
797
+ "default_headers",
798
+ "connect_headers",
799
+ "certificate_pinning_hosts",
800
+ "client_certificates",
801
+ "custom_tls_client",
802
+ "client_identifier",
803
+ "server_name_overwrite",
804
+ "local_address",
805
+ "insecure_skip_verify",
806
+ "force_http1",
807
+ "with_random_tls_extension_order",
808
+ "with_protocol_racing",
809
+ "max_idle_connections",
810
+ "max_idle_connections_per_host",
811
+ "max_connections_per_host",
812
+ "max_response_header_bytes",
813
+ "write_buffer_size",
814
+ "read_buffer_size",
815
+ "idle_conn_timeout_seconds",
816
+ "disable_keep_alives",
817
+ "disable_compression",
818
+ "disable_http3",
819
+ "disable_ipv4",
820
+ "disable_ipv6",
821
+ "follow_redirects",
822
+ "without_cookie_jar",
823
+ "allow_empty_cookies",
824
+ "with_default_bad_pin_handler",
825
+ "timeout_seconds",
826
+ "timeout_milliseconds",
827
+ "tcp_ttl",
828
+ "tcp_window_size",
829
+ "tcp_window_scale",
830
+ "tcp_mss",
831
+ "catch_panics",
832
+ "with_debug",
833
+ "request_host_override",
834
+ "request_cookies",
835
+ "disable_session_tickets",
836
+ "tls_keylog_path",
837
+ "root_ca_pem",
838
+ "h2_max_data_frame_size",
839
+ "preface_ping_idle_ms",
840
+ "hpack_indexing_policy",
841
+ "cookie_crumb",
842
+ # ABI 3 — deep fingerprint controls
843
+ "extension_permute_mode",
844
+ "extension_permute_prefix",
845
+ "h2_disable_priority_frames",
846
+ "header_order_by_dest",
847
+ "header_order_dest",
848
+ "tcp_dont_fragment",
849
+ "tcp_tos",
850
+ "tcp_no_delay",
851
+ "tcp_window_clamp",
852
+ "tcp_ip_id_mode",
853
+ )
854
+
855
+
856
+ ASYNC_REQUEST_DEFAULT_KEYS = (
857
+ "proxy",
858
+ "client_identifier",
859
+ "server_name_overwrite",
860
+ "local_address",
861
+ "insecure_skip_verify",
862
+ "force_http1",
863
+ "with_random_tls_extension_order",
864
+ "with_protocol_racing",
865
+ "max_idle_connections",
866
+ "max_idle_connections_per_host",
867
+ "max_connections_per_host",
868
+ "max_response_header_bytes",
869
+ "write_buffer_size",
870
+ "read_buffer_size",
871
+ "idle_conn_timeout_seconds",
872
+ "disable_keep_alives",
873
+ "disable_compression",
874
+ "disable_http3",
875
+ "disable_ipv4",
876
+ "disable_ipv6",
877
+ "tcp_ttl",
878
+ "tcp_window_size",
879
+ "tcp_window_scale",
880
+ "tcp_mss",
881
+ "follow_redirects",
882
+ "without_cookie_jar",
883
+ "allow_empty_cookies",
884
+ "with_default_bad_pin_handler",
885
+ "timeout_seconds",
886
+ "timeout_milliseconds",
887
+ "pseudo_header_order",
888
+ "h3_pseudo_header_order",
889
+ "default_headers",
890
+ "connect_headers",
891
+ "certificate_pinning_hosts",
892
+ "client_certificates",
893
+ "custom_tls_client",
894
+ "request_host_override",
895
+ "request_cookies",
896
+ "catch_panics",
897
+ "with_debug",
898
+ "disable_session_tickets",
899
+ "tls_keylog_path",
900
+ "root_ca_pem",
901
+ "h2_max_data_frame_size",
902
+ "preface_ping_idle_ms",
903
+ "hpack_indexing_policy",
904
+ "cookie_crumb",
905
+ # ABI 3 — deep fingerprint controls
906
+ "extension_permute_mode",
907
+ "extension_permute_prefix",
908
+ "h2_disable_priority_frames",
909
+ "header_order_by_dest",
910
+ "header_order_dest",
911
+ "tcp_dont_fragment",
912
+ "tcp_tos",
913
+ "tcp_no_delay",
914
+ "tcp_window_clamp",
915
+ "tcp_ip_id_mode",
916
+ )
917
+
918
+
919
+ # ---------------------------------------------------------------------------
920
+ # CFFI cdef – must stay byte‑identical with main.go `import "C"` block
921
+ # ---------------------------------------------------------------------------
922
+
923
+ CDEF = """
924
+ typedef struct {
925
+ const char* key;
926
+ const char* value;
927
+ } HttpHeader;
928
+
929
+ typedef struct {
930
+ const char* host;
931
+ const char** pins;
932
+ int pins_len;
933
+ } PinEntry;
934
+
935
+ typedef struct {
936
+ unsigned int streamDep;
937
+ int exclusive;
938
+ unsigned char weight;
939
+ } PriorityParam;
940
+
941
+ typedef struct {
942
+ PriorityParam priorityParam;
943
+ unsigned int streamID;
944
+ } PriorityFrame;
945
+
946
+ typedef struct {
947
+ const char* kdfId;
948
+ const char* aeadId;
949
+ } CandidateCipherSuite;
950
+
951
+ typedef struct {
952
+ const char* cert_pem;
953
+ int cert_pem_len;
954
+ const char* key_pem;
955
+ int key_pem_len;
956
+ } ClientCertificate;
957
+
958
+ typedef struct {
959
+ const char** h2_settings_keys;
960
+ unsigned int* h2_settings_values;
961
+ int h2_settings_len;
962
+ const char** h2_settings_order;
963
+ int h2_settings_order_len;
964
+ const char** h3_settings_keys;
965
+ unsigned long long* h3_settings_values;
966
+ int h3_settings_len;
967
+ const char** h3_settings_order;
968
+ int h3_settings_order_len;
969
+ const char** h3_pseudo_header_order;
970
+ int h3_pseudo_header_order_len;
971
+ PriorityParam* header_priority;
972
+ const char** cert_compression_algos;
973
+ int cert_compression_algos_len;
974
+ const char* ja3_string;
975
+ const char** key_share_curves;
976
+ int key_share_curves_len;
977
+ const char** alpn_protocols;
978
+ int alpn_protocols_len;
979
+ const char** alps_protocols;
980
+ int alps_protocols_len;
981
+ unsigned short* ech_candidate_payloads;
982
+ int ech_candidate_payloads_len;
983
+ CandidateCipherSuite* ech_candidate_cipher_suites;
984
+ int ech_candidate_cipher_suites_len;
985
+ PriorityFrame* priority_frames;
986
+ int priority_frames_len;
987
+ const char** pseudo_header_order;
988
+ int pseudo_header_order_len;
989
+ const char** supported_delegated_credentials_algorithms;
990
+ int supported_delegated_credentials_algorithms_len;
991
+ const char** supported_signature_algorithms;
992
+ int supported_signature_algorithms_len;
993
+ const char** supported_versions;
994
+ int supported_versions_len;
995
+ unsigned int connection_flow;
996
+ unsigned short record_size_limit;
997
+ unsigned int stream_id;
998
+ unsigned int h3_priority_param;
999
+ int h3_send_grease_frames;
1000
+ int allow_http;
1001
+ const char* trust_anchors_payload;
1002
+ } CustomTlsClient;
1003
+
1004
+ typedef struct {
1005
+ const char* method;
1006
+ const char* url;
1007
+ const char* body;
1008
+ int body_len;
1009
+ const char* proxy;
1010
+ const char* client_identifier;
1011
+ HttpHeader* headers;
1012
+ int headers_len;
1013
+ const char** header_order;
1014
+ int header_order_len;
1015
+ const char** pseudo_header_order;
1016
+ int pseudo_header_order_len;
1017
+ const char** h3_pseudo_header_order;
1018
+ int h3_pseudo_header_order_len;
1019
+ int timeout_seconds;
1020
+ int timeout_milliseconds;
1021
+ int follow_redirects;
1022
+ int insecure_skip_verify;
1023
+ int force_http1;
1024
+ int with_random_tls_extension_order;
1025
+ int with_protocol_racing;
1026
+ const char* server_name_overwrite;
1027
+ const char* request_host_override;
1028
+ const char* local_address;
1029
+ int max_idle_connections;
1030
+ int max_idle_connections_per_host;
1031
+ int max_connections_per_host;
1032
+ int max_response_header_bytes;
1033
+ int write_buffer_size;
1034
+ int read_buffer_size;
1035
+ int idle_conn_timeout_seconds;
1036
+ int disable_keep_alives;
1037
+ int disable_compression;
1038
+ int allow_empty_cookies;
1039
+ int disable_http3;
1040
+ int disable_ipv4;
1041
+ int disable_ipv6;
1042
+ int tcp_ttl;
1043
+ int tcp_window_size;
1044
+ int tcp_window_scale;
1045
+ int tcp_mss;
1046
+ int without_cookie_jar;
1047
+ int catch_panics;
1048
+ int with_debug;
1049
+ const char* stream_output_path;
1050
+ int stream_output_block_size;
1051
+ const char* stream_output_eof_symbol;
1052
+ HttpHeader* default_headers;
1053
+ int default_headers_len;
1054
+ HttpHeader* connect_headers;
1055
+ int connect_headers_len;
1056
+ PinEntry* certificate_pinning_hosts;
1057
+ int certificate_pinning_hosts_len;
1058
+ int with_default_bad_pin_handler;
1059
+ HttpHeader* request_cookies;
1060
+ int request_cookies_len;
1061
+ ClientCertificate* client_certificates;
1062
+ int client_certificates_len;
1063
+ CustomTlsClient* custom_tls_client;
1064
+ const char* cache_key_hash;
1065
+ int disable_session_tickets;
1066
+ const char* tls_keylog_path;
1067
+ const char* root_ca_pem;
1068
+ int root_ca_pem_len;
1069
+ int h2_max_data_frame_size;
1070
+ int preface_ping_idle_ms;
1071
+ const char* hpack_indexing_policy;
1072
+ int cookie_crumb;
1073
+ int extension_permute_mode;
1074
+ int extension_permute_prefix;
1075
+ int h2_disable_priority_frames;
1076
+ int header_order_by_dest;
1077
+ const char* header_order_dest;
1078
+ int tcp_dont_fragment;
1079
+ int tcp_tos;
1080
+ int tcp_no_delay;
1081
+ int tcp_window_clamp;
1082
+ const char* tcp_ip_id_mode;
1083
+ } RequestOptions;
1084
+
1085
+ typedef struct {
1086
+ int status_code;
1087
+ char* body;
1088
+ int body_len;
1089
+ char* err_msg;
1090
+ char* target_url;
1091
+ char* used_protocol;
1092
+ HttpHeader* response_headers;
1093
+ int response_headers_len;
1094
+ HttpHeader* cookies;
1095
+ int cookies_len;
1096
+ char* _resp_strings;
1097
+ } ResponseResult;
1098
+
1099
+ ResponseResult* ExecuteRequest(RequestOptions* opts);
1100
+ void FreeResponse(ResponseResult* res);
1101
+ void ClearClientPool(void);
1102
+
1103
+ void SetPoolTTL(int seconds);
1104
+ void SetPoolScanInterval(int seconds);
1105
+ void SetPoolMaxEntries(int entries);
1106
+ int GetAbiVersion(void);
1107
+ char* ResolveECHConfig(char* host);
1108
+
1109
+ typedef void (*async_callback_fn)(uintptr_t request_id, ResponseResult* response);
1110
+ int RequestAsync(RequestOptions* opts, uintptr_t request_id, async_callback_fn cb);
1111
+ """
1112
+
1113
+ # ---------------------------------------------------------------------------
1114
+ # Platform-native shared library dynamic discovery (Git-Sync & Wheel Optimized)
1115
+ # ---------------------------------------------------------------------------
1116
+
1117
+ def _detect_libc() -> str:
1118
+ """在 Linux 系统上检测 C 运行库类型(glibc 或 musl)。"""
1119
+ if sys.platform != "linux":
1120
+ return "glibc"
1121
+ try:
1122
+ libc = ctypes.CDLL(None)
1123
+ try:
1124
+ libc.__musl__ # pylint: disable=pointless-statement
1125
+ return "musl"
1126
+ except AttributeError:
1127
+ return "glibc"
1128
+ except Exception:
1129
+ for entry in Path("/lib").glob("ld-musl-*"):
1130
+ if entry.is_file():
1131
+ return "musl"
1132
+ return "unknown"
1133
+
1134
+
1135
+ def _libc_suffix() -> str:
1136
+ """如果是 Alpine (musl) 系统,返回 -musl 后缀。"""
1137
+ if sys.platform == "linux" and _detect_libc() == "musl":
1138
+ return "-musl"
1139
+ return ""
1140
+
1141
+
1142
+ def _go_os() -> str:
1143
+ return {"darwin": "darwin", "linux": "linux", "win32": "windows"}.get(
1144
+ sys.platform, sys.platform
1145
+ )
1146
+
1147
+
1148
+ def _go_arch() -> str:
1149
+ m = platform.machine().lower()
1150
+ return {
1151
+ "x86_64": "amd64", "amd64": "amd64",
1152
+ "arm64": "arm64", "aarch64": "arm64",
1153
+ "armv7l": "arm", "armv6l": "arm", "armv8l": "arm",
1154
+ "i386": "386", "i686": "386",
1155
+ # 32-bit Windows reports "x86" (not "i386"); other 32-bit x86 spellings.
1156
+ "x86": "386", "x86pc": "386", "win32": "386", "intel": "386",
1157
+ }.get(m, m)
1158
+
1159
+
1160
+ def _shared_lib_ext() -> str:
1161
+ if sys.platform == "darwin":
1162
+ return ".dylib"
1163
+ elif sys.platform == "win32":
1164
+ return ".dll"
1165
+ return ".so"
1166
+
1167
+
1168
+ def _shared_lib_name() -> str:
1169
+ ext = _shared_lib_ext()
1170
+ goos = _go_os()
1171
+ goarch = _go_arch()
1172
+ lc = _libc_suffix()
1173
+ return f"tls-client-{goos}-{goarch}{lc}{ext}"
1174
+
1175
+
1176
+ def _find_library() -> str:
1177
+ """定位平台对应的动态链接库。
1178
+
1179
+ 搜索顺序:
1180
+ 1. 读取 ``TLS_CLIENT_LIB`` 环境变量(显式用户覆盖)。
1181
+ 2. 寻找包目录内 ``tls_client/bin/`` 下的带架构后缀文件(如 tls-client-windows-amd64.dll)。
1182
+ 3. 寻找同级开发目录 ``dist/`` 下的文件。
1183
+ """
1184
+ # 1. 环境变量显式覆盖
1185
+ env_lib = os.environ.get("TLS_CLIENT_LIB")
1186
+ if env_lib:
1187
+ p = Path(env_lib)
1188
+ if p.exists():
1189
+ return str(p)
1190
+ raise FileNotFoundError(
1191
+ f"TLS_CLIENT_LIB is set to '{env_lib}' but the file does not exist."
1192
+ )
1193
+
1194
+ name = _shared_lib_name()
1195
+ here = Path(__file__).resolve().parent
1196
+
1197
+ candidates = [here / "bin" / name, here / "dist" / name]
1198
+
1199
+ for candidate in candidates:
1200
+ if candidate.exists():
1201
+ return str(candidate)
1202
+
1203
+ parts = [
1204
+ f"Cannot locate shared library '{name}' inside the package.",
1205
+ "",
1206
+ " Searched:",
1207
+ ]
1208
+ parts.extend(f" {c}" for c in candidates)
1209
+ parts.extend([
1210
+ "",
1211
+ " Set the 'TLS_CLIENT_LIB' environment variable to point directly to your binary.",
1212
+ ])
1213
+ raise FileNotFoundError("\n".join(parts))
1214
+
1215
+
1216
+ def _load_ffi():
1217
+ """Lazy‑import cffi so the wrapper is importable without it installed."""
1218
+ from cffi import FFI
1219
+
1220
+ ffi = FFI()
1221
+ ffi.cdef(CDEF)
1222
+ libpath = _find_library()
1223
+
1224
+ try:
1225
+ lib = ffi.dlopen(libpath)
1226
+ except OSError as exc:
1227
+ raise OSError(
1228
+ f"Shared library at '{libpath}' failed to load. "
1229
+ f"The binary may be corrupt, built for a different architecture, "
1230
+ f"or missing system dependencies.\n"
1231
+ f"Underlying error: {exc}"
1232
+ ) from exc
1233
+
1234
+ return ffi, lib
1235
+
1236
+
1237
+ # Global singletons – initialised on first use
1238
+ _ffi = None
1239
+ _lib = None
1240
+ _ffi_lock = threading.Lock()
1241
+ # True when this process is a fork child whose parent had already loaded the
1242
+ # native Go library — see _after_fork_in_child() and the _get_ffi() guard.
1243
+ _forked_after_load = False
1244
+ _abi_version = 1 # 1 = legacy pre-rebuild library; 2 = GetAbiVersion() export present
1245
+
1246
+ def _require_abi2() -> None:
1247
+ if _abi_version < 2:
1248
+ raise RuntimeError(
1249
+ "disable_session_tickets / tls_keylog_path / root_ca_pem and the "
1250
+ "custom_tls_client 'trust_anchors_payload' field require a native "
1251
+ "tls-client library with ABI >= 2 — rebuild the shared libraries "
1252
+ "from current source (see UPSTREAM_SYNC.md)."
1253
+ )
1254
+
1255
+
1256
+ # Fields introduced by ABI 3 together with their "feature disabled" value.
1257
+ # Dropping a field back to its sentinel keeps the Python-side cache key in
1258
+ # sync with what Go will actually receive.
1259
+ _ABI3_REQUEST_FIELDS = {
1260
+ "extension_permute_mode": 0,
1261
+ "extension_permute_prefix": 0,
1262
+ "h2_disable_priority_frames": 0,
1263
+ "header_order_by_dest": 0,
1264
+ "header_order_dest": "",
1265
+ "tcp_dont_fragment": -1,
1266
+ "tcp_tos": -1,
1267
+ "tcp_no_delay": -1,
1268
+ "tcp_window_clamp": 0,
1269
+ "tcp_ip_id_mode": "",
1270
+ }
1271
+
1272
+ _abi3_warned = False
1273
+
1274
+
1275
+ def _degrade_abi3_fields(resolved: Dict[str, Any]) -> bool:
1276
+ """Reset ABI 3 fields to their sentinels when the library predates ABI 3.
1277
+
1278
+ Returns True when a degradation actually happened. A one-time warning is
1279
+ emitted so the operator knows the requested refinements were dropped rather
1280
+ than silently ignored. On an ABI >= 3 library this is a cheap no-op.
1281
+ """
1282
+ global _abi3_warned
1283
+
1284
+ if _abi_version >= 3:
1285
+ return False
1286
+
1287
+ requested = [
1288
+ key for key, sentinel in _ABI3_REQUEST_FIELDS.items()
1289
+ if resolved.get(key) not in (None, sentinel)
1290
+ ]
1291
+ if not requested:
1292
+ return False
1293
+
1294
+ for key, sentinel in _ABI3_REQUEST_FIELDS.items():
1295
+ resolved[key] = sentinel
1296
+
1297
+ if not _abi3_warned:
1298
+ _abi3_warned = True
1299
+ import warnings
1300
+
1301
+ warnings.warn(
1302
+ "the loaded tls-client library predates ABI 3; the following "
1303
+ "deep-fingerprint controls were dropped: %s. Rebuild the shared "
1304
+ "libraries from current source to enable them (see "
1305
+ "UPSTREAM_SYNC.md)." % ", ".join(sorted(requested)),
1306
+ RuntimeWarning,
1307
+ stacklevel=3,
1308
+ )
1309
+ return True
1310
+
1311
+
1312
+ def _get_ffi():
1313
+ global _ffi, _lib, _abi_version
1314
+ if _forked_after_load:
1315
+ raise RuntimeError(
1316
+ "tls_client: the native Go library was loaded in the parent "
1317
+ "process before this process was forked. The Go runtime does not "
1318
+ "survive fork() — its threads (GC, evictor, HTTP workers) exist "
1319
+ "only in the parent, so calling into it here would deadlock or "
1320
+ "crash. Use the 'spawn' or 'forkserver' start method for process "
1321
+ "pools, or import/use tls_client only after forking."
1322
+ )
1323
+ if _ffi is None:
1324
+ with _ffi_lock:
1325
+ if _ffi is None:
1326
+ _ffi, _lib = _load_ffi()
1327
+ # Legacy libraries predate the export; treat them as ABI 1.
1328
+ _abi_version = int(getattr(_lib, "GetAbiVersion", lambda: 1)())
1329
+ return _ffi, _lib
1330
+
1331
+
1332
+ # ---------------------------------------------------------------------------
1333
+ # Helpers
1334
+ # ---------------------------------------------------------------------------
1335
+
1336
+ def _charset_from_content_type(content_type: str) -> str:
1337
+ """Extract charset from Content-Type header, default to ``"utf-8"``.
1338
+
1339
+ Mirrors ``golang.org/x/net/html/charset.NewReader`` behaviour.
1340
+ """
1341
+ if not content_type:
1342
+ return "utf-8"
1343
+ # Parse 'text/html; charset=gbk' → 'gbk'
1344
+ for part in content_type.lower().split(";"):
1345
+ part = part.strip()
1346
+ if part.startswith("charset=") or part.startswith("charset ="):
1347
+ enc = part.split("=", 1)[1].strip().strip('"').strip("'")
1348
+ if enc:
1349
+ return enc
1350
+ return "utf-8"
1351
+
1352
+
1353
+ def _c_string(ffi, value: Optional[str]) -> Any:
1354
+ """Allocate a null‑terminated C string (or ``ffi.NULL``)."""
1355
+ if value is None:
1356
+ return ffi.NULL
1357
+ return ffi.new("char[]", value.encode("utf-8"))
1358
+
1359
+
1360
+ def _build_headers(ffi, headers: Optional[Dict[str, str]], keep_alive: list):
1361
+ """Convert a Python dict → C HttpHeader[]. Returns ``(ptr, length)``."""
1362
+ if not headers:
1363
+ return ffi.NULL, 0
1364
+
1365
+ n = len(headers)
1366
+ arr = ffi.new("HttpHeader[]", n)
1367
+ keep_alive.append(arr)
1368
+
1369
+ for i, (k, v) in enumerate(headers.items()):
1370
+ ck = ffi.new("char[]", k.encode("utf-8"))
1371
+ cv = ffi.new("char[]", v.encode("utf-8"))
1372
+ keep_alive.extend([ck, cv])
1373
+ arr[i].key = ck
1374
+ arr[i].value = cv
1375
+
1376
+ return arr, n
1377
+
1378
+
1379
+ def _identifier_browser(identifier: str) -> str:
1380
+ """Map a client identifier to its browser family (context headers).
1381
+
1382
+ Mirrors Go's ``browserFamilyForIdentifier`` in cffi_binding/main.go so a
1383
+ request's context headers do not depend on which engine side built them.
1384
+ An unrecognised identifier yields "" — callers must treat that as
1385
+ "unknown, apply no browser-specific context" rather than assuming Chrome.
1386
+ """
1387
+ lower = (identifier or "").lower()
1388
+ if lower.startswith(("chrome", "cloudscraper", "brave", "opera")):
1389
+ return "chrome"
1390
+ if lower.startswith("firefox"):
1391
+ return "firefox"
1392
+ if lower.startswith("safari"):
1393
+ return "safari"
1394
+ return ""
1395
+
1396
+
1397
+ def _apply_request_context(session, headers, header_order, context, identifier,
1398
+ user_headers=None):
1399
+ """Merge an opt-in ``RequestContext`` into the request headers.
1400
+
1401
+ Also selects the navigation/XHR header-order template recorded by a
1402
+ fingerprint preset (when the caller did not pass an explicit
1403
+ ``header_order``). *user_headers* are the request-level headers —
1404
+ they always win over context-derived values, while values inherited
1405
+ from the profile defaults are overridden to stay context-coherent.
1406
+ """
1407
+ from tls_client import context as _ctx_mod
1408
+
1409
+ browser = _identifier_browser(identifier)
1410
+ user_keys = {key.casefold() for key in (user_headers or {})}
1411
+ merged = _ctx_mod.apply_context(headers, context, browser=browser,
1412
+ user_keys=user_keys)
1413
+ if header_order is None:
1414
+ if context.dest in ("document", "iframe"):
1415
+ template = getattr(session, "_fingerprint_header_order", None)
1416
+ else:
1417
+ template = getattr(session, "_fingerprint_header_order_xhr", None)
1418
+ if template:
1419
+ header_order = list(template)
1420
+ return merged, header_order
1421
+
1422
+
1423
+ def _merge_default_headers(
1424
+ default_headers: Optional[Dict[str, str]],
1425
+ request_headers: Optional[Dict[str, str]],
1426
+ header_order: Optional[List[str]],
1427
+ ) -> Tuple[Optional[Dict[str, str]], Optional[List[str]]]:
1428
+ """Fold the profile default header block into the per-request headers.
1429
+
1430
+ The Go engine assigns ``req.Header = cfg.headers`` wholesale whenever
1431
+ per-request headers are present, so a request carrying e.g. only
1432
+ ``{"X-Mark": "1"}`` would otherwise go out with NO User-Agent or any
1433
+ other profile header at all (Go's "Go-http-client/1.1" default) —
1434
+ the client-level default_headers are silently dropped. Merging per
1435
+ key with a case-insensitive match lets a request header override the
1436
+ profile value without emitting duplicate headers.
1437
+
1438
+ A deterministic wire order is derived for the merged map: Go
1439
+ randomises HTTP/1.1 header order when no HeaderOrderKey is set, and
1440
+ a randomized order is itself a fingerprinting signal.
1441
+ """
1442
+ if not default_headers:
1443
+ return request_headers, header_order
1444
+
1445
+ merged = dict(default_headers)
1446
+ folded: Dict[str, str] = {}
1447
+ for key in merged:
1448
+ folded.setdefault(key.casefold(), key)
1449
+ for key, value in (request_headers or {}).items():
1450
+ existing = folded.get(key.casefold())
1451
+ if existing is not None:
1452
+ merged[existing] = value
1453
+ else:
1454
+ merged[key] = value
1455
+ folded[key.casefold()] = key
1456
+
1457
+ if header_order:
1458
+ order = list(header_order)
1459
+ listed = {key.casefold() for key in order}
1460
+ order.extend(key for key in merged if key.casefold() not in listed)
1461
+ else:
1462
+ order = list(merged.keys())
1463
+ return merged, order
1464
+
1465
+
1466
+ def _build_string_array(ffi, items: Optional[List[str]], keep_alive: list):
1467
+ """Convert a Python list[str] → C const char**. Returns ``(ptr, length)``."""
1468
+ if not items:
1469
+ return ffi.NULL, 0
1470
+
1471
+ n = len(items)
1472
+ arr = ffi.new("const char*[]", n)
1473
+ keep_alive.append(arr)
1474
+
1475
+ for i, s in enumerate(items):
1476
+ cs = ffi.new("char[]", s.encode("utf-8"))
1477
+ keep_alive.append(cs)
1478
+ arr[i] = cs
1479
+
1480
+ return arr, n
1481
+
1482
+
1483
+ def _build_pin_entries(ffi, pins: Optional[Dict[str, List[str]]], keep_alive: list):
1484
+ """Convert a Python dict[str, list[str]] → C PinEntry[]. Returns ``(ptr, length)``."""
1485
+ if not pins:
1486
+ return ffi.NULL, 0
1487
+
1488
+ n = len(pins)
1489
+ arr = ffi.new("PinEntry[]", n)
1490
+ keep_alive.append(arr)
1491
+
1492
+ for i, (host, pin_list) in enumerate(pins.items()):
1493
+ ch = ffi.new("char[]", host.encode("utf-8"))
1494
+ keep_alive.append(ch)
1495
+ arr[i].host = ch
1496
+
1497
+ if pin_list:
1498
+ pn = len(pin_list)
1499
+ parr = ffi.new("const char*[]", pn)
1500
+ keep_alive.append(parr)
1501
+ for j, pin in enumerate(pin_list):
1502
+ cp = ffi.new("char[]", pin.encode("utf-8"))
1503
+ keep_alive.append(cp)
1504
+ parr[j] = cp
1505
+ arr[i].pins = parr
1506
+ arr[i].pins_len = pn
1507
+ else:
1508
+ arr[i].pins = ffi.NULL
1509
+ arr[i].pins_len = 0
1510
+
1511
+ return arr, n
1512
+
1513
+
1514
+ def _build_client_certificates(ffi, certs: Optional[List[Dict[str, bytes]]], keep_alive: list):
1515
+ """Convert a Python list[dict] → C ClientCertificate[]. Returns ``(ptr, length)``.
1516
+
1517
+ Each dict must have ``"cert_pem"`` and ``"key_pem"`` keys with bytes values.
1518
+ """
1519
+ if not certs:
1520
+ return ffi.NULL, 0
1521
+
1522
+ n = len(certs)
1523
+ arr = ffi.new("ClientCertificate[]", n)
1524
+ keep_alive.append(arr)
1525
+
1526
+ for i, c in enumerate(certs):
1527
+ cert_bytes = c.get("cert_pem", b"")
1528
+ key_bytes = c.get("key_pem", b"")
1529
+
1530
+ cc = ffi.new("char[]", cert_bytes)
1531
+ ck = ffi.new("char[]", key_bytes)
1532
+ keep_alive.extend([cc, ck])
1533
+ arr[i].cert_pem = cc
1534
+ arr[i].cert_pem_len = len(cert_bytes)
1535
+ arr[i].key_pem = ck
1536
+ arr[i].key_pem_len = len(key_bytes)
1537
+
1538
+ return arr, n
1539
+
1540
+
1541
+ def _build_custom_tls_client(ffi, cfg: Optional[Dict[str, Any]], keep_alive: list):
1542
+ """Convert a Python dict → C CustomTlsClient*. Returns ``ffi.NULL`` when
1543
+ *cfg* is None or empty."""
1544
+ if not cfg:
1545
+ return ffi.NULL
1546
+
1547
+ ctc = ffi.new("CustomTlsClient *")
1548
+ keep_alive.append(ctc)
1549
+
1550
+ # JA3 string
1551
+ ja3 = _c_string(ffi, cfg.get("ja3_string"))
1552
+ if ja3 != ffi.NULL:
1553
+ keep_alive.append(ja3)
1554
+ ctc.ja3_string = ja3
1555
+
1556
+ # Simple scalar fields
1557
+ ctc.connection_flow = cfg.get("connection_flow", 0)
1558
+ ctc.record_size_limit = cfg.get("record_size_limit", 0)
1559
+ ctc.stream_id = cfg.get("stream_id", 0)
1560
+ ctc.h3_priority_param = cfg.get("h3_priority_param", 0)
1561
+ ctc.h3_send_grease_frames = 1 if cfg.get("h3_send_grease_frames") else 0
1562
+ ctc.allow_http = 1 if cfg.get("allow_http") else 0
1563
+
1564
+ # String arrays
1565
+ ctc.h2_settings_order, ctc.h2_settings_order_len = _build_string_array(
1566
+ ffi, cfg.get("h2_settings_order"), keep_alive
1567
+ )
1568
+ ctc.h3_settings_order, ctc.h3_settings_order_len = _build_string_array(
1569
+ ffi, cfg.get("h3_settings_order"), keep_alive
1570
+ )
1571
+ ctc.h3_pseudo_header_order, ctc.h3_pseudo_header_order_len = _build_string_array(
1572
+ ffi, cfg.get("h3_pseudo_header_order"), keep_alive
1573
+ )
1574
+ ctc.cert_compression_algos, ctc.cert_compression_algos_len = _build_string_array(
1575
+ ffi, cfg.get("cert_compression_algos"), keep_alive
1576
+ )
1577
+ ctc.key_share_curves, ctc.key_share_curves_len = _build_string_array(
1578
+ ffi, cfg.get("key_share_curves"), keep_alive
1579
+ )
1580
+ ctc.alpn_protocols, ctc.alpn_protocols_len = _build_string_array(
1581
+ ffi, cfg.get("alpn_protocols"), keep_alive
1582
+ )
1583
+ ctc.alps_protocols, ctc.alps_protocols_len = _build_string_array(
1584
+ ffi, cfg.get("alps_protocols"), keep_alive
1585
+ )
1586
+ ctc.pseudo_header_order, ctc.pseudo_header_order_len = _build_string_array(
1587
+ ffi, cfg.get("pseudo_header_order"), keep_alive
1588
+ )
1589
+ ctc.supported_delegated_credentials_algorithms, ctc.supported_delegated_credentials_algorithms_len = _build_string_array(
1590
+ ffi, cfg.get("supported_delegated_credentials_algorithms"), keep_alive
1591
+ )
1592
+ ctc.supported_signature_algorithms, ctc.supported_signature_algorithms_len = _build_string_array(
1593
+ ffi, cfg.get("supported_signature_algorithms"), keep_alive
1594
+ )
1595
+ ctc.supported_versions, ctc.supported_versions_len = _build_string_array(
1596
+ ffi, cfg.get("supported_versions"), keep_alive
1597
+ )
1598
+
1599
+ # H2/H3 settings key-value pairs
1600
+ h2_settings = cfg.get("h2_settings")
1601
+ if h2_settings:
1602
+ n = len(h2_settings)
1603
+ keys = ffi.new("const char*[]", n)
1604
+ vals = ffi.new("unsigned int[]", n)
1605
+ keep_alive.extend([keys, vals])
1606
+ for i, (k, v) in enumerate(h2_settings.items()):
1607
+ ck = ffi.new("char[]", k.encode("utf-8"))
1608
+ keep_alive.append(ck)
1609
+ keys[i] = ck
1610
+ vals[i] = v
1611
+ ctc.h2_settings_keys = keys
1612
+ ctc.h2_settings_values = vals
1613
+ ctc.h2_settings_len = n
1614
+
1615
+ h3_settings = cfg.get("h3_settings")
1616
+ if h3_settings:
1617
+ n = len(h3_settings)
1618
+ keys = ffi.new("const char*[]", n)
1619
+ vals = ffi.new("unsigned long long[]", n)
1620
+ keep_alive.extend([keys, vals])
1621
+ for i, (k, v) in enumerate(h3_settings.items()):
1622
+ ck = ffi.new("char[]", k.encode("utf-8"))
1623
+ keep_alive.append(ck)
1624
+ keys[i] = ck
1625
+ vals[i] = v
1626
+ ctc.h3_settings_keys = keys
1627
+ ctc.h3_settings_values = vals
1628
+ ctc.h3_settings_len = n
1629
+
1630
+ # ECH candidate payloads
1631
+ ech_payloads = cfg.get("ech_candidate_payloads")
1632
+ if ech_payloads:
1633
+ n = len(ech_payloads)
1634
+ arr = ffi.new("unsigned short[]", ech_payloads)
1635
+ keep_alive.append(arr)
1636
+ ctc.ech_candidate_payloads = arr
1637
+ ctc.ech_candidate_payloads_len = n
1638
+
1639
+ # ECH candidate cipher suites
1640
+ ech_suites = cfg.get("ech_candidate_cipher_suites")
1641
+ if ech_suites:
1642
+ n = len(ech_suites)
1643
+ arr = ffi.new("CandidateCipherSuite[]", n)
1644
+ keep_alive.append(arr)
1645
+ for i, suite in enumerate(ech_suites):
1646
+ kdf = _c_string(ffi, suite.get("kdfId"))
1647
+ aead = _c_string(ffi, suite.get("aeadId"))
1648
+ if kdf != ffi.NULL:
1649
+ keep_alive.append(kdf)
1650
+ if aead != ffi.NULL:
1651
+ keep_alive.append(aead)
1652
+ arr[i].kdfId = kdf
1653
+ arr[i].aeadId = aead
1654
+ ctc.ech_candidate_cipher_suites = arr
1655
+ ctc.ech_candidate_cipher_suites_len = n
1656
+
1657
+ # Priority frames
1658
+ pri_frames = cfg.get("priority_frames")
1659
+ if pri_frames:
1660
+ n = len(pri_frames)
1661
+ arr = ffi.new("PriorityFrame[]", n)
1662
+ keep_alive.append(arr)
1663
+ for i, pf in enumerate(pri_frames):
1664
+ pp = pf.get("priorityParam", {})
1665
+ arr[i].priorityParam.streamDep = pp.get("streamDep", 0)
1666
+ arr[i].priorityParam.exclusive = 1 if pp.get("exclusive") else 0
1667
+ arr[i].priorityParam.weight = pp.get("weight", 0)
1668
+ arr[i].streamID = pf.get("streamID", 0)
1669
+ ctc.priority_frames = arr
1670
+ ctc.priority_frames_len = n
1671
+
1672
+ # Header priority (single optional struct)
1673
+ hp = cfg.get("header_priority")
1674
+ if hp:
1675
+ chp = ffi.new("PriorityParam *")
1676
+ keep_alive.append(chp)
1677
+ chp.streamDep = hp.get("streamDep", 0)
1678
+ chp.exclusive = 1 if hp.get("exclusive") else 0
1679
+ chp.weight = hp.get("weight", 0)
1680
+ ctc.header_priority = chp
1681
+
1682
+ # Trust anchors payload (ABI 2) — encoded ROIDs for the
1683
+ # draft-ietf-tls-trust-anchor-ids extension (Chrome 152+).
1684
+ ta = cfg.get("trust_anchors_payload")
1685
+ if ta:
1686
+ _require_abi2()
1687
+ c_ta = _c_string(ffi, ta)
1688
+ keep_alive.append(c_ta)
1689
+ ctc.trust_anchors_payload = c_ta
1690
+
1691
+ # Per-handshake extension permutation lives on RequestOptions
1692
+ # (extension_permute_mode / extension_permute_prefix), NOT here: the
1693
+ # permutation is a per-request transport policy, while a CustomTlsClient
1694
+ # describes a reusable ClientHello shape. Set it via the Session kwargs.
1695
+
1696
+ return ctc
1697
+
1698
+
1699
+ # ---------------------------------------------------------------------------
1700
+ # Cache-key pre-computation — mirrors Go's buildCacheKey format EXACTLY.
1701
+ # Python computes the SHA-256 hash natively so Go can skip 50–200 C.GoString()
1702
+ # CGO calls on every cache hit. The hash is passed to Go via
1703
+ # RequestOptions.cache_key_hash — if non-empty, Go uses it directly for
1704
+ # clientPool.Load, bypassing buildCacheKey entirely.
1705
+ #
1706
+ # WARNING: This function must produce byte-for-byte identical output to
1707
+ # Go's buildCacheKey in cffi_binding/main.go. If either side drifts,
1708
+ # cache entries will be stored under different keys, causing silent
1709
+ # cache poisoning (duplicate clients). The test_cache_key_parity.py
1710
+ # test catches format drift BEFORE it reaches production.
1711
+ # ---------------------------------------------------------------------------
1712
+
1713
+
1714
+ def _as_int(v) -> int:
1715
+ """Coerce a resolved config value to the int Go would hash.
1716
+
1717
+ Go stores these fields as plain ints and hashes them with %d, so the
1718
+ Python side must emit the same integer — including negative sentinels
1719
+ such as the -1 used by the tri-state TCP fields. None means "the caller
1720
+ is not using cache-key pre-computation"; map it to 0 rather than raising
1721
+ so a partially-populated dict still produces a deterministic hash.
1722
+ """
1723
+ return 0 if v is None else int(v)
1724
+
1725
+
1726
+ def _compute_cache_key_hash(r: dict) -> str:
1727
+ """Return the SHA-256 hex digest of resolved config values.
1728
+
1729
+ The format matches Go's buildCacheKey exactly — same field order,
1730
+ same separators, same sort order for maps, same hex encoding.
1731
+
1732
+ FORMAT VERSION: 5
1733
+ If you change the hash format below, increment the version AND update
1734
+ Go's buildCacheKey / buildCacheKeyFromConfig in cffi_binding/main.go
1735
+ and the corresponding test in test_cache_key_parity.py. Format drift
1736
+ causes silent cache poisoning (different keys → duplicate clients).
1737
+ """
1738
+ h = hashlib.sha256()
1739
+ update = h.update
1740
+
1741
+ ci = r["client_identifier"] or ""
1742
+ px = r["proxy"] or ""
1743
+ sn = r["server_name_overwrite"] or ""
1744
+ la = r["local_address"] or ""
1745
+
1746
+ # ── 22 int fields (matching Go's 22 %%d format verbs) ──────────────
1747
+ main = (
1748
+ f"{ci}|{px}|{sn}|{la}|"
1749
+ f"{r['insecure_skip_verify']}|{r['force_http1']}|"
1750
+ f"{r['with_random_tls_extension_order']}|{r['with_protocol_racing']}|"
1751
+ f"{r['max_idle_connections']}|{r['max_idle_connections_per_host']}|"
1752
+ f"{r['max_connections_per_host']}|{r['max_response_header_bytes']}|"
1753
+ f"{r['write_buffer_size']}|{r['read_buffer_size']}|"
1754
+ f"{r['idle_conn_timeout_seconds']}|{r['disable_keep_alives']}|"
1755
+ f"{r['disable_compression']}|{r['disable_http3']}|"
1756
+ f"{r['disable_ipv4']}|{r['disable_ipv6']}|{r['follow_redirects']}|"
1757
+ f"{r['without_cookie_jar']}|{r['allow_empty_cookies']}|"
1758
+ f"{r['with_default_bad_pin_handler']}|"
1759
+ f"{r['timeout_seconds']}|{r['timeout_milliseconds']}|"
1760
+ f"{r['tcp_ttl']}|{r['tcp_window_size']}|{r['tcp_window_scale']}|{r['tcp_mss']}"
1761
+ )
1762
+ update(main.encode("utf-8"))
1763
+
1764
+ # ── ABI 2 / format-version 3 additions — mirror buildCacheKeyFromConfig
1765
+ update(("|%d|%s" % (1 if r.get("disable_session_tickets") else 0,
1766
+ r.get("tls_keylog_path") or "")).encode("utf-8"))
1767
+ rc = r.get("root_ca_pem")
1768
+ if rc:
1769
+ update(("|rc:" + hashlib.sha256(rc).hexdigest()).encode("utf-8"))
1770
+ else:
1771
+ update(b"|rc:")
1772
+ # ABI 2.1 / format-version 4: engine-level HTTP/2 realism knobs.
1773
+ # cookie_crumb is per-request wire behaviour and NOT part of the key.
1774
+ update(("|mdf=%d|pp=%d|hip=%s" % (
1775
+ r.get("h2_max_data_frame_size") or 0,
1776
+ r.get("preface_ping_idle_ms") or 0,
1777
+ r.get("hpack_indexing_policy") or "",
1778
+ )).encode("utf-8"))
1779
+ # ABI 3 / format-version 5: extension-order policy, PRIORITY-frame
1780
+ # suppression and the deep TCP fingerprint fields. header_order_by_dest /
1781
+ # header_order_dest and cookie_crumb are per-request wire behaviour that
1782
+ # does not change the transport, so they are not keyed (mirrors Go).
1783
+ #
1784
+ # The integers are emitted RAW — never collapsed through a truthiness
1785
+ # test — because Go's %d verbs hash the stored int verbatim. Two traps
1786
+ # this avoids:
1787
+ # * the tri-state TCP fields use -1 for "unset", which is truthy in
1788
+ # Python; `1 if x else 0` would emit 1 where Go emits -1;
1789
+ # * extension_permute_mode is a 4-valued enum (0=off, 1=chrome, 2=all,
1790
+ # 3=prefix); a truthiness test collapses 2 and 3 onto 1, hashing
1791
+ # distinct transports to the same key.
1792
+ update(("|epm=%d|epp=%d|hdpf=%d|df=%d|tos=%d|nd=%d|wc=%d|ipid=%s" % (
1793
+ _as_int(r.get("extension_permute_mode")),
1794
+ _as_int(r.get("extension_permute_prefix")),
1795
+ _as_int(r.get("h2_disable_priority_frames")),
1796
+ _as_int(r.get("tcp_dont_fragment")),
1797
+ _as_int(r.get("tcp_tos")),
1798
+ _as_int(r.get("tcp_no_delay")),
1799
+ _as_int(r.get("tcp_window_clamp")),
1800
+ r.get("tcp_ip_id_mode") or "",
1801
+ )).encode("utf-8"))
1802
+
1803
+ # ── Pseudo-header orders ──────────────────────────────────────────
1804
+ ph = r["pseudo_header_order"]
1805
+ if ph:
1806
+ for s in ph:
1807
+ update(f":{s}".encode("utf-8"))
1808
+ else:
1809
+ update(b":<default>")
1810
+
1811
+ h3ph = r["h3_pseudo_header_order"]
1812
+ if h3ph:
1813
+ for s in h3ph:
1814
+ update(f"#{s}".encode("utf-8"))
1815
+ else:
1816
+ update(b"#<default>")
1817
+
1818
+ # ── Default / connect headers (sorted by key) ─────────────────────
1819
+ for prefix, key in (("~dh:", "default_headers"), ("~ch:", "connect_headers")):
1820
+ headers = r[key]
1821
+ if headers:
1822
+ for k, v in sorted(headers.items()):
1823
+ update(f"{prefix}{k}={v}".encode("utf-8"))
1824
+
1825
+ # ── Certificate pinning (sorted by host) ──────────────────────────
1826
+ cp = r["certificate_pinning_hosts"]
1827
+ if cp:
1828
+ for host, pins in sorted(cp.items()):
1829
+ update(f"^cp:{host}=".encode("utf-8"))
1830
+ for pin in pins:
1831
+ update(f"{pin},".encode("utf-8"))
1832
+
1833
+ # ── Client certificates ───────────────────────────────────────────
1834
+ cc = r["client_certificates"]
1835
+ if cc:
1836
+ for cert in cc:
1837
+ cert_pem = cert.get("cert_pem", b"")
1838
+ key_pem = cert.get("key_pem", b"")
1839
+ update(f"|cc:{hashlib.sha256(cert_pem).hexdigest()}".encode("utf-8"))
1840
+ update(f"|ck:{hashlib.sha256(key_pem).hexdigest()}".encode("utf-8"))
1841
+
1842
+ # ── Custom TLS client profile ─────────────────────────────────────
1843
+ ctc = r["custom_tls_client"]
1844
+ if ctc:
1845
+ update(f"|ja3={ctc.get('ja3_string', '')}".encode("utf-8"))
1846
+ update(f"|cf={ctc.get('connection_flow', 0)}".encode("utf-8"))
1847
+ update(f"|rsl={ctc.get('record_size_limit', 0)}".encode("utf-8"))
1848
+ update(f"|sid={ctc.get('stream_id', 0)}".encode("utf-8"))
1849
+ update(f"|h3pp={ctc.get('h3_priority_param', 0)}".encode("utf-8"))
1850
+ update(f"|h3sgf={1 if ctc.get('h3_send_grease_frames') else 0}".encode("utf-8"))
1851
+ update(f"|ah={1 if ctc.get('allow_http') else 0}".encode("utf-8"))
1852
+ update(f"|ta={ctc.get('trust_anchors_payload') or ''}".encode("utf-8"))
1853
+
1854
+ str_arrays = {
1855
+ "h2_settings_order": "|h2so=", "h3_settings_order": "|h3so=",
1856
+ "h3_pseudo_header_order": "|h3ph=", "cert_compression_algos": "|cca=",
1857
+ "key_share_curves": "|ksc=", "alpn_protocols": "|alpn=",
1858
+ "alps_protocols": "|alps=", "pseudo_header_order": "|ph=",
1859
+ "supported_delegated_credentials_algorithms": "|sdca=",
1860
+ "supported_signature_algorithms": "|ssa=", "supported_versions": "|sv=",
1861
+ }
1862
+ for key, pfx in str_arrays.items():
1863
+ arr = ctc.get(key)
1864
+ if arr:
1865
+ update(pfx.encode("utf-8"))
1866
+ for i, s in enumerate(arr):
1867
+ if i > 0:
1868
+ update(b",")
1869
+ update(str(s).encode("utf-8"))
1870
+
1871
+ for skey, pfx in [("h2_settings", "|h2s:"), ("h3_settings", "|h3s:")]:
1872
+ settings = ctc.get(skey)
1873
+ if settings:
1874
+ for k, v in sorted(settings.items()):
1875
+ update(f"{pfx}{k}={v}".encode("utf-8"))
1876
+
1877
+ ech_payloads = ctc.get("ech_candidate_payloads")
1878
+ if ech_payloads:
1879
+ for pld in ech_payloads:
1880
+ update(f"|echp:{pld}".encode("utf-8"))
1881
+
1882
+ ech_suites = ctc.get("ech_candidate_cipher_suites")
1883
+ if ech_suites:
1884
+ for s in sorted(ech_suites, key=lambda x: (x.get("kdfId", ""), x.get("aeadId", ""))):
1885
+ update(f"|echcs:{s.get('kdfId', '')},{s.get('aeadId', '')}".encode("utf-8"))
1886
+
1887
+ pri_frames = ctc.get("priority_frames")
1888
+ if pri_frames:
1889
+ for pf in pri_frames:
1890
+ pp = pf.get("priorityParam", {})
1891
+ update(
1892
+ f"|pf:{pf.get('streamID', 0)},{pp.get('streamDep', 0)},"
1893
+ f"{1 if pp.get('exclusive') else 0},{pp.get('weight', 0)}".encode("utf-8")
1894
+ )
1895
+
1896
+ hp = ctc.get("header_priority")
1897
+ if hp:
1898
+ update(
1899
+ f"|hp:{hp.get('streamDep', 0)},{1 if hp.get('exclusive') else 0},"
1900
+ f"{hp.get('weight', 0)}".encode("utf-8")
1901
+ )
1902
+
1903
+ return h.hexdigest()
1904
+
1905
+
1906
+ # ---------------------------------------------------------------------------
1907
+ # Response unpacking — shared between sync ExecuteRequest and async callback
1908
+ # ---------------------------------------------------------------------------
1909
+
1910
+ def _unpack_c_response(ffi, raw_res) -> Response:
1911
+ """Unpack a C ResponseResult* into a Python Response object.
1912
+
1913
+ Used by both the synchronous execute_request path and the async
1914
+ CFFI callback path. Does NOT call FreeResponse — the caller is
1915
+ responsible for that.
1916
+ """
1917
+ status = raw_res.status_code
1918
+ blen = raw_res.body_len
1919
+
1920
+ if blen > 0 and raw_res.body != ffi.NULL:
1921
+ body_bytes = ffi.buffer(raw_res.body, blen)[:]
1922
+ else:
1923
+ body_bytes = b""
1924
+
1925
+ response_headers: Dict[str, List[str]] = {}
1926
+ rh_len = raw_res.response_headers_len
1927
+ if rh_len > 0 and raw_res.response_headers != ffi.NULL:
1928
+ for i in range(rh_len):
1929
+ h = raw_res.response_headers[i]
1930
+ if h.key != ffi.NULL and h.value != ffi.NULL:
1931
+ k = ffi.string(h.key).decode("utf-8", errors="replace")
1932
+ v = ffi.string(h.value).decode("utf-8", errors="replace")
1933
+ response_headers.setdefault(k, []).append(v)
1934
+
1935
+ ct = ""
1936
+ for k, v in response_headers.items():
1937
+ if k.lower() == "content-type":
1938
+ ct = v[0] if v else ""
1939
+ break
1940
+ encoding = _charset_from_content_type(ct)
1941
+ try:
1942
+ text = body_bytes.decode(encoding)
1943
+ except (UnicodeDecodeError, LookupError):
1944
+ encoding = "utf-8"
1945
+ text = body_bytes.decode("utf-8", errors="replace")
1946
+
1947
+ response_cookies: Dict[str, str] = {}
1948
+ ck_len = raw_res.cookies_len
1949
+ if ck_len > 0 and raw_res.cookies != ffi.NULL:
1950
+ for i in range(ck_len):
1951
+ ck_entry = raw_res.cookies[i]
1952
+ if ck_entry.key != ffi.NULL and ck_entry.value != ffi.NULL:
1953
+ cn = ffi.string(ck_entry.key).decode("utf-8", errors="replace")
1954
+ cv = ffi.string(ck_entry.value).decode("utf-8", errors="replace")
1955
+ response_cookies[cn] = cv
1956
+
1957
+ target_url: Optional[str] = None
1958
+ if raw_res.target_url != ffi.NULL:
1959
+ target_url = ffi.string(raw_res.target_url).decode("utf-8", errors="replace")
1960
+
1961
+ used_protocol: Optional[str] = None
1962
+ if raw_res.used_protocol != ffi.NULL:
1963
+ used_protocol = ffi.string(raw_res.used_protocol).decode("utf-8", errors="replace")
1964
+
1965
+ return Response(
1966
+ status_code=status,
1967
+ headers=response_headers,
1968
+ content=body_bytes,
1969
+ text=text,
1970
+ encoding=encoding,
1971
+ url=target_url,
1972
+ cookies=response_cookies,
1973
+ used_protocol=used_protocol,
1974
+ )
1975
+
1976
+ # ---------------------------------------------------------------------------
1977
+ # Synchronous Session
1978
+ # ---------------------------------------------------------------------------
1979
+
1980
+ class Session:
1981
+ """同步 HTTP 客户端,封装 Go tls-client 引擎。
1982
+
1983
+ Synchronous HTTP client wrapping the Go tls-client engine.
1984
+ """
1985
+
1986
+ defaults: Dict[str, Any]
1987
+ _defaults_lock: threading.RLock
1988
+ _closed: bool
1989
+ _defaults_version: int
1990
+ _selected_snapshot_cache: Dict[Tuple[str, ...], Tuple[int, Dict[str, Any]]]
1991
+
1992
+ def _get_default(self, name: str, default: Any = None) -> Any:
1993
+ with self._defaults_lock:
1994
+ if name in self.defaults:
1995
+ return _clone_default_value(self.defaults[name])
1996
+ return _clone_default_value(default)
1997
+
1998
+ def _set_default(self, name: str, value: Any) -> None:
1999
+ with self._defaults_lock:
2000
+ self.defaults[name] = _clone_default_value(value)
2001
+ self._defaults_version += 1
2002
+ self._selected_snapshot_cache.clear()
2003
+
2004
+ def _snapshot_selected_defaults(self, names: List[str]) -> Dict[str, Any]:
2005
+ cache_key = tuple(names)
2006
+ with self._defaults_lock:
2007
+ cached = self._selected_snapshot_cache.get(cache_key)
2008
+ if cached is not None:
2009
+ version, snapshot = cached
2010
+ if version == self._defaults_version:
2011
+ return {k: _copy_snapshot_value(v) for k, v in snapshot.items()}
2012
+
2013
+ snapshot = {
2014
+ name: _clone_default_value(self.defaults[name])
2015
+ for name in names
2016
+ if name in self.defaults
2017
+ }
2018
+ self._selected_snapshot_cache[cache_key] = (
2019
+ self._defaults_version,
2020
+ snapshot,
2021
+ )
2022
+ return {k: _copy_snapshot_value(v) for k, v in snapshot.items()}
2023
+
2024
+ # ------------------------------------------------------------------
2025
+ # Writable session properties — users can read/write after construction.
2026
+ # e.g. session.headers = {"User-Agent": "..."}
2027
+ # session.cookies = {"foo": "bar"}
2028
+ # session.proxy = "http://127.0.0.1:8080"
2029
+ # session.timeout = 10
2030
+ # ------------------------------------------------------------------
2031
+
2032
+ # -- fingerprint / protocol --------------------------------------------
2033
+
2034
+ @property
2035
+ def client_identifier(self) -> str:
2036
+ """TLS 指纹标识 / TLS fingerprint identifier."""
2037
+ return self._get_default("client_identifier")
2038
+
2039
+ @client_identifier.setter
2040
+ def client_identifier(self, value: str) -> None:
2041
+ if value not in SUPPORTED_CLIENT_IDENTIFIERS:
2042
+ raise ValueError("unsupported client_identifier %r" % value)
2043
+ with self._defaults_lock:
2044
+ previous = self.defaults.get("client_identifier")
2045
+ self.defaults["client_identifier"] = value
2046
+ self._defaults_version += 1
2047
+ self._selected_snapshot_cache.clear()
2048
+ # Keep the default header block in sync with the fingerprint:
2049
+ # User-Agent / sec-ch-ua / Accept belong to the same browser
2050
+ # profile as the TLS fingerprint. Switching the identifier
2051
+ # while keeping the old headers produces a detectable mismatch
2052
+ # (TLS handshake says Safari, User-Agent says Chrome). Once
2053
+ # the caller customises headers explicitly, auto-sync stops.
2054
+ if value != previous and not self._headers_customized:
2055
+ self.defaults["default_headers"] = _clone_default_value(
2056
+ DEFAULT_HEADERS.get(value)
2057
+ )
2058
+
2059
+ @property
2060
+ def force_http1(self) -> bool:
2061
+ """是否强制 HTTP/1.1 / Whether to force HTTP/1.1."""
2062
+ return bool(self._get_default("force_http1"))
2063
+
2064
+ @force_http1.setter
2065
+ def force_http1(self, value: bool) -> None:
2066
+ self._set_default("force_http1", 1 if value else 0)
2067
+
2068
+ @property
2069
+ def disable_http3(self) -> bool:
2070
+ """是否完全禁用 HTTP/3 / Whether to disable HTTP/3."""
2071
+ return bool(self._get_default("disable_http3"))
2072
+
2073
+ @disable_http3.setter
2074
+ def disable_http3(self, value: bool) -> None:
2075
+ self._set_default("disable_http3", 1 if value else 0)
2076
+
2077
+ @property
2078
+ def with_protocol_racing(self) -> bool:
2079
+ """是否启用协议竞速 / Whether to enable protocol racing."""
2080
+ return bool(self._get_default("with_protocol_racing"))
2081
+
2082
+ @with_protocol_racing.setter
2083
+ def with_protocol_racing(self, value: bool) -> None:
2084
+ self._set_default("with_protocol_racing", 1 if value else 0)
2085
+
2086
+ @property
2087
+ def random_tls_extension_order(self) -> bool:
2088
+ """是否随机 TLS 扩展顺序 / Whether to randomise TLS extension order."""
2089
+ return bool(self._get_default("with_random_tls_extension_order"))
2090
+
2091
+ @random_tls_extension_order.setter
2092
+ def random_tls_extension_order(self, value: bool) -> None:
2093
+ self._set_default("with_random_tls_extension_order", 1 if value else 0)
2094
+
2095
+ # -- timeout / redirect -------------------------------------------------
2096
+
2097
+ @property
2098
+ def timeout(self) -> int:
2099
+ """请求超时时间(秒) / Request timeout in seconds."""
2100
+ return self._get_default("timeout_seconds")
2101
+
2102
+ @timeout.setter
2103
+ def timeout(self, value: int) -> None:
2104
+ self._set_default("timeout_seconds", value)
2105
+
2106
+ @property
2107
+ def timeout_milliseconds(self) -> int:
2108
+ """请求超时时间(毫秒) / Request timeout in milliseconds."""
2109
+ return self._get_default("timeout_milliseconds")
2110
+
2111
+ @timeout_milliseconds.setter
2112
+ def timeout_milliseconds(self, value: int) -> None:
2113
+ self._set_default("timeout_milliseconds", value)
2114
+
2115
+ @property
2116
+ def follow_redirects(self) -> bool:
2117
+ """是否跟随重定向 / Whether to follow redirects."""
2118
+ return bool(self._get_default("follow_redirects"))
2119
+
2120
+ @follow_redirects.setter
2121
+ def follow_redirects(self, value: bool) -> None:
2122
+ self._set_default("follow_redirects", 1 if value else 0)
2123
+
2124
+ # -- TLS / certificate --------------------------------------------------
2125
+
2126
+ @property
2127
+ def verify(self) -> bool:
2128
+ """是否验证 TLS 证书 / Whether to verify the TLS certificate."""
2129
+ return not bool(self._get_default("insecure_skip_verify"))
2130
+
2131
+ @verify.setter
2132
+ def verify(self, value: bool) -> None:
2133
+ self._set_default("insecure_skip_verify", 0 if value else 1)
2134
+
2135
+ @property
2136
+ def server_name_overwrite(self) -> Optional[str]:
2137
+ """SNI 主机名覆盖 / SNI hostname override."""
2138
+ return self._get_default("server_name_overwrite")
2139
+
2140
+ @server_name_overwrite.setter
2141
+ def server_name_overwrite(self, value: Optional[str]) -> None:
2142
+ self._set_default("server_name_overwrite", value)
2143
+
2144
+ # -- proxy / local address ----------------------------------------------
2145
+
2146
+ @property
2147
+ def proxy(self) -> Optional[ProxyConfig]:
2148
+ """代理 URL / Proxy URL."""
2149
+ return self._get_default("proxy")
2150
+
2151
+ @proxy.setter
2152
+ def proxy(self, value: Optional[ProxyConfig]) -> None:
2153
+ self._set_default("proxy", value)
2154
+
2155
+ @property
2156
+ def proxies(self) -> Optional[ProxyConfig]:
2157
+ """代理配置(别名)/ Proxy config (alias for :attr:`proxy`)."""
2158
+ return self._get_default("proxy")
2159
+
2160
+ @proxies.setter
2161
+ def proxies(self, value: Optional[ProxyConfig]) -> None:
2162
+ self._set_default("proxy", value)
2163
+
2164
+ @property
2165
+ def local_address(self) -> Optional[str]:
2166
+ """本地绑定地址 / Local bind address."""
2167
+ return self._get_default("local_address")
2168
+
2169
+ @local_address.setter
2170
+ def local_address(self, value: Optional[str]) -> None:
2171
+ self._set_default("local_address", value)
2172
+
2173
+ # -- header control -----------------------------------------------------
2174
+
2175
+ @property
2176
+ def request_host_override(self) -> Optional[str]:
2177
+ """Host 请求头覆盖 / Host header override."""
2178
+ return self._get_default("request_host_override")
2179
+
2180
+ @request_host_override.setter
2181
+ def request_host_override(self, value: Optional[str]) -> None:
2182
+ self._set_default("request_host_override", value)
2183
+
2184
+ @property
2185
+ def pseudo_header_order(self) -> Optional[List[str]]:
2186
+ """HTTP/2 伪头顺序 / HTTP/2 pseudo-header order."""
2187
+ return self._get_default("pseudo_header_order")
2188
+
2189
+ @pseudo_header_order.setter
2190
+ def pseudo_header_order(self, value: Optional[List[str]]) -> None:
2191
+ self._set_default("pseudo_header_order", value)
2192
+
2193
+ @property
2194
+ def h3_pseudo_header_order(self) -> Optional[List[str]]:
2195
+ """HTTP/3 伪头顺序 / HTTP/3 pseudo-header order."""
2196
+ return self._get_default("h3_pseudo_header_order")
2197
+
2198
+ @h3_pseudo_header_order.setter
2199
+ def h3_pseudo_header_order(self, value: Optional[List[str]]) -> None:
2200
+ self._set_default("h3_pseudo_header_order", value)
2201
+
2202
+ @property
2203
+ def default_headers(self) -> Optional[Dict[str, str]]:
2204
+ """默认请求头字典 / Default headers dict."""
2205
+ return self._get_default("default_headers")
2206
+
2207
+ @default_headers.setter
2208
+ def default_headers(self, value: Optional[Dict[str, str]]) -> None:
2209
+ self._headers_customized = True
2210
+ self._set_default("default_headers", value)
2211
+
2212
+ @property
2213
+ def headers(self) -> Optional[Dict[str, str]]:
2214
+ """默认请求头字典(别名)/ Default headers dict (alias for :attr:`default_headers`)."""
2215
+ return self._get_default("default_headers")
2216
+
2217
+ @headers.setter
2218
+ def headers(self, value: Optional[Dict[str, str]]) -> None:
2219
+ self._headers_customized = True
2220
+ self._set_default("default_headers", value)
2221
+
2222
+ @property
2223
+ def connect_headers(self) -> Optional[Dict[str, str]]:
2224
+ """代理 CONNECT 隧道请求头字典 / Proxy CONNECT tunnel headers."""
2225
+ return self._get_default("connect_headers")
2226
+
2227
+ @connect_headers.setter
2228
+ def connect_headers(self, value: Optional[Dict[str, str]]) -> None:
2229
+ self._set_default("connect_headers", value)
2230
+
2231
+ # -- certificate pinning ------------------------------------------------
2232
+
2233
+ @property
2234
+ def certificate_pinning_hosts(self) -> Optional[Dict[str, List[str]]]:
2235
+ """SSL 证书固定字典 / SSL certificate pinning dict."""
2236
+ return self._get_default("certificate_pinning_hosts")
2237
+
2238
+ @certificate_pinning_hosts.setter
2239
+ def certificate_pinning_hosts(self, value: Optional[Dict[str, List[str]]]) -> None:
2240
+ self._set_default("certificate_pinning_hosts", value)
2241
+
2242
+ @property
2243
+ def with_default_bad_pin_handler(self) -> bool:
2244
+ """是否调用默认 Bad-Pin 处理器 / Whether to invoke the default bad-pin handler."""
2245
+ return bool(self._get_default("with_default_bad_pin_handler"))
2246
+
2247
+ @with_default_bad_pin_handler.setter
2248
+ def with_default_bad_pin_handler(self, value: bool) -> None:
2249
+ self._set_default("with_default_bad_pin_handler", 1 if value else 0)
2250
+
2251
+ # -- cookies -------------------------------------------------------------
2252
+
2253
+ @property
2254
+ def request_cookies(self) -> Optional[Dict[str, str]]:
2255
+ """预置 Cookie 字典 / Pre-populated cookie dict."""
2256
+ return self._get_default("request_cookies")
2257
+
2258
+ @request_cookies.setter
2259
+ def request_cookies(self, value: Optional[Dict[str, str]]) -> None:
2260
+ self._set_default("request_cookies", value)
2261
+
2262
+ @property
2263
+ def cookies(self) -> Optional[Dict[str, str]]:
2264
+ """预置 Cookie 字典(别名)/ Pre-populated cookie dict (alias for :attr:`request_cookies`)."""
2265
+ return self._get_default("request_cookies")
2266
+
2267
+ @cookies.setter
2268
+ def cookies(self, value: Optional[Dict[str, str]]) -> None:
2269
+ self._set_default("request_cookies", value)
2270
+
2271
+ # -- custom TLS / client certs ------------------------------------------
2272
+
2273
+ @property
2274
+ def custom_tls_client(self) -> Optional[Dict[str, Any]]:
2275
+ """完全自定义的 TLS 客户端配置 / Fully custom TLS client configuration."""
2276
+ return self._get_default("custom_tls_client")
2277
+
2278
+ @custom_tls_client.setter
2279
+ def custom_tls_client(self, value: Optional[Dict[str, Any]]) -> None:
2280
+ self._set_default("custom_tls_client", value)
2281
+
2282
+ @property
2283
+ def client_certificates(self) -> Optional[List[Dict[str, bytes]]]:
2284
+ """客户端证书列表 (mTLS) / Client certificates for mTLS."""
2285
+ return self._get_default("client_certificates")
2286
+
2287
+ @client_certificates.setter
2288
+ def client_certificates(self, value: Optional[List[Dict[str, bytes]]]) -> None:
2289
+ self._set_default("client_certificates", value)
2290
+
2291
+ # -- connection pool tuning ---------------------------------------------
2292
+
2293
+ @property
2294
+ def max_idle_connections(self) -> int:
2295
+ """全局最大空闲连接数 / Global max idle connections."""
2296
+ return self._get_default("max_idle_connections")
2297
+
2298
+ @max_idle_connections.setter
2299
+ def max_idle_connections(self, value: int) -> None:
2300
+ self._set_default("max_idle_connections", value)
2301
+
2302
+ @property
2303
+ def max_idle_connections_per_host(self) -> int:
2304
+ """每 Host 最大空闲连接数 / Max idle connections per host."""
2305
+ return self._get_default("max_idle_connections_per_host")
2306
+
2307
+ @max_idle_connections_per_host.setter
2308
+ def max_idle_connections_per_host(self, value: int) -> None:
2309
+ self._set_default("max_idle_connections_per_host", value)
2310
+
2311
+ @property
2312
+ def max_connections_per_host(self) -> int:
2313
+ """每 Host 最大总连接数 / Max total connections per host."""
2314
+ return self._get_default("max_connections_per_host")
2315
+
2316
+ @max_connections_per_host.setter
2317
+ def max_connections_per_host(self, value: int) -> None:
2318
+ self._set_default("max_connections_per_host", value)
2319
+
2320
+ @property
2321
+ def disable_keep_alives(self) -> bool:
2322
+ """是否禁用 Keep-Alive / Whether to disable Keep-Alive."""
2323
+ return bool(self._get_default("disable_keep_alives"))
2324
+
2325
+ @disable_keep_alives.setter
2326
+ def disable_keep_alives(self, value: bool) -> None:
2327
+ self._set_default("disable_keep_alives", 1 if value else 0)
2328
+
2329
+ @property
2330
+ def disable_compression(self) -> bool:
2331
+ """是否禁用响应解压 / Whether to disable decompression."""
2332
+ return bool(self._get_default("disable_compression"))
2333
+
2334
+ @disable_compression.setter
2335
+ def disable_compression(self, value: bool) -> None:
2336
+ self._set_default("disable_compression", 1 if value else 0)
2337
+
2338
+ @property
2339
+ def idle_conn_timeout_seconds(self) -> int:
2340
+ """空闲连接超时(秒) / Idle connection timeout (seconds)."""
2341
+ return self._get_default("idle_conn_timeout_seconds")
2342
+
2343
+ @idle_conn_timeout_seconds.setter
2344
+ def idle_conn_timeout_seconds(self, value: int) -> None:
2345
+ self._set_default("idle_conn_timeout_seconds", value)
2346
+
2347
+ @property
2348
+ def max_response_header_bytes(self) -> int:
2349
+ """响应头最大字节数 / Max response header bytes."""
2350
+ return self._get_default("max_response_header_bytes")
2351
+
2352
+ @max_response_header_bytes.setter
2353
+ def max_response_header_bytes(self, value: int) -> None:
2354
+ self._set_default("max_response_header_bytes", value)
2355
+
2356
+ @property
2357
+ def write_buffer_size(self) -> int:
2358
+ """写缓冲区大小 / Write buffer size."""
2359
+ return self._get_default("write_buffer_size")
2360
+
2361
+ @write_buffer_size.setter
2362
+ def write_buffer_size(self, value: int) -> None:
2363
+ self._set_default("write_buffer_size", value)
2364
+
2365
+ @property
2366
+ def read_buffer_size(self) -> int:
2367
+ """读缓冲区大小 / Read buffer size."""
2368
+ return self._get_default("read_buffer_size")
2369
+
2370
+ @read_buffer_size.setter
2371
+ def read_buffer_size(self, value: int) -> None:
2372
+ self._set_default("read_buffer_size", value)
2373
+
2374
+ # -- IP stack / cookies / debug -----------------------------------------
2375
+
2376
+ @property
2377
+ def disable_ipv4(self) -> bool:
2378
+ """是否禁用 IPv4 / Whether to disable IPv4."""
2379
+ return bool(self._get_default("disable_ipv4"))
2380
+
2381
+ @disable_ipv4.setter
2382
+ def disable_ipv4(self, value: bool) -> None:
2383
+ self._set_default("disable_ipv4", 1 if value else 0)
2384
+
2385
+ @property
2386
+ def disable_ipv6(self) -> bool:
2387
+ """是否禁用 IPv6 / Whether to disable IPv6."""
2388
+ return bool(self._get_default("disable_ipv6"))
2389
+
2390
+ @disable_ipv6.setter
2391
+ def disable_ipv6(self, value: bool) -> None:
2392
+ self._set_default("disable_ipv6", 1 if value else 0)
2393
+
2394
+ @property
2395
+ def tcp_ttl(self) -> int:
2396
+ """IP TTL / IP TTL value. 0 = auto from profile."""
2397
+ return self._get_default("tcp_ttl")
2398
+
2399
+ @tcp_ttl.setter
2400
+ def tcp_ttl(self, value: int) -> None:
2401
+ self._set_default("tcp_ttl", value)
2402
+
2403
+ @property
2404
+ def tcp_window_size(self) -> int:
2405
+ """TCP receive window size. 0 = auto from profile."""
2406
+ return self._get_default("tcp_window_size")
2407
+
2408
+ @tcp_window_size.setter
2409
+ def tcp_window_size(self, value: int) -> None:
2410
+ self._set_default("tcp_window_size", value)
2411
+
2412
+ @property
2413
+ def tcp_window_scale(self) -> int:
2414
+ """TCP window scale factor. 0 = auto from profile."""
2415
+ return self._get_default("tcp_window_scale")
2416
+
2417
+ @tcp_window_scale.setter
2418
+ def tcp_window_scale(self, value: int) -> None:
2419
+ self._set_default("tcp_window_scale", value)
2420
+
2421
+ @property
2422
+ def tcp_mss(self) -> int:
2423
+ """TCP Maximum Segment Size. 0 = auto from profile."""
2424
+ return self._get_default("tcp_mss")
2425
+
2426
+ @tcp_mss.setter
2427
+ def tcp_mss(self, value: int) -> None:
2428
+ self._set_default("tcp_mss", value)
2429
+
2430
+ @property
2431
+ def allow_empty_cookies(self) -> bool:
2432
+ """是否允许空 Cookie / Whether to allow empty cookies."""
2433
+ return bool(self._get_default("allow_empty_cookies"))
2434
+
2435
+ @allow_empty_cookies.setter
2436
+ def allow_empty_cookies(self, value: bool) -> None:
2437
+ self._set_default("allow_empty_cookies", 1 if value else 0)
2438
+
2439
+ @property
2440
+ def without_cookie_jar(self) -> bool:
2441
+ """是否禁用 Cookie Jar / Whether to disable Cookie Jar."""
2442
+ return bool(self._get_default("without_cookie_jar"))
2443
+
2444
+ @without_cookie_jar.setter
2445
+ def without_cookie_jar(self, value: bool) -> None:
2446
+ self._set_default("without_cookie_jar", 1 if value else 0)
2447
+
2448
+ @property
2449
+ def catch_panics(self) -> bool:
2450
+ """是否捕获 Go panic / Whether to catch Go panics."""
2451
+ return bool(self._get_default("catch_panics"))
2452
+
2453
+ @catch_panics.setter
2454
+ def catch_panics(self, value: bool) -> None:
2455
+ self._set_default("catch_panics", 1 if value else 0)
2456
+
2457
+ @property
2458
+ def with_debug(self) -> bool:
2459
+ """是否启用调试日志 / Whether to enable debug logging."""
2460
+ return bool(self._get_default("with_debug"))
2461
+
2462
+ @with_debug.setter
2463
+ def with_debug(self, value: bool) -> None:
2464
+ self._set_default("with_debug", 1 if value else 0)
2465
+
2466
+ # -- auth ----------------------------------------------------------------
2467
+
2468
+ @property
2469
+ def auth(self) -> Optional[Tuple[str, str]]:
2470
+ """HTTP 认证元组 ``(username, password)`` / HTTP auth tuple ``(username, password)``."""
2471
+ return self._get_default("auth")
2472
+
2473
+ @auth.setter
2474
+ def auth(self, value: Optional[Tuple[str, str]]) -> None:
2475
+ self._set_default("auth", value)
2476
+
2477
+ # -- params (query string) ----------------------------------------------
2478
+
2479
+ @property
2480
+ def params(self) -> Optional[Dict[str, str]]:
2481
+ """查询字符串参数字典 / Query-string parameter dict."""
2482
+ return self._get_default("params")
2483
+
2484
+ @params.setter
2485
+ def params(self, value: Optional[Dict[str, str]]) -> None:
2486
+ self._set_default("params", value)
2487
+
2488
+ # -- cert (client SSL certificate) --------------------------------------
2489
+
2490
+ @property
2491
+ def cert(self) -> Optional[Union[str, Tuple[str, str]]]:
2492
+ """客户端 SSL 证书路径 / Client SSL cert path.
2493
+
2494
+ ``str``: 单独 cert 文件 ; ``(cert_path, key_path)``: cert + key 文件。
2495
+ """
2496
+ return self._get_default("cert")
2497
+
2498
+ @cert.setter
2499
+ def cert(self, value: Optional[Union[str, Tuple[str, str]]]) -> None:
2500
+ self._set_default("cert", value)
2501
+
2502
+ # -- stream (response streaming mode) -----------------------------------
2503
+
2504
+ @property
2505
+ def stream(self) -> bool:
2506
+ """是否流式读取响应体 / Whether to stream the response body."""
2507
+ return bool(self._get_default("stream", False))
2508
+
2509
+ @stream.setter
2510
+ def stream(self, value: bool) -> None:
2511
+ self._set_default("stream", 1 if value else 0)
2512
+
2513
+ def __init__(
2514
+ self,
2515
+ *,
2516
+ # ── 指纹 / 协议 ── / Fingerprint / Protocol ──
2517
+ # TLS 指纹标识 / TLS fingerprint identifier
2518
+ client_identifier: ClientIdentifiers = "chrome_120",
2519
+ # 强制使用 HTTP/1.1 / Force HTTP/1.1
2520
+ force_http1: bool = False,
2521
+ # 完全禁用 HTTP/3(QUIC) / Completely disable HTTP/3 (QUIC)
2522
+ disable_http3: bool = False,
2523
+ # 启用协议竞速 / Enable protocol racing
2524
+ with_protocol_racing: bool = False,
2525
+ # 随机打乱 TLS 扩展的发送顺序 / Randomize TLS extension send order
2526
+ random_tls_extension_order: bool = True,
2527
+ # ── 超时 / 重定向 ── / Timeout / Redirect ──
2528
+ # 请求整体超时时间(秒) / Total request timeout in seconds
2529
+ timeout: int = 30,
2530
+ # 请求超时时间(毫秒) / Request timeout in milliseconds
2531
+ timeout_milliseconds: int = 0,
2532
+ # 是否自动跟随 HTTP 重定向 / Whether to automatically follow HTTP redirects
2533
+ follow_redirects: bool = False,
2534
+ # ── TLS / 证书 ── / TLS / Cert ──
2535
+ # 是否验证服务端 TLS 证书 / Whether to verify the server TLS certificate
2536
+ verify: bool = True,
2537
+ # 自定义 SNI / Custom SNI
2538
+ server_name_overwrite: Optional[str] = None,
2539
+ # ── 代理 ── / Proxy ──
2540
+ # 代理 URL / Proxy URL
2541
+ proxy: Optional[ProxyConfig] = None,
2542
+ # requests 风格代理字典 / requests-style proxies mapping
2543
+ proxies: Optional[ProxyConfig] = None,
2544
+ # 绑定到指定的本地 IP 地址 / Bind to a specific local IP address
2545
+ local_address: Optional[str] = None,
2546
+ # ── 请求头控制 ── / Header Control ──
2547
+ # 覆盖 HTTP Host 请求头 / Override the HTTP Host header
2548
+ request_host_override: Optional[str] = None,
2549
+ # HTTP/2 伪头发送顺序 / HTTP/2 pseudo-header send order
2550
+ pseudo_header_order: Optional[List[str]] = None,
2551
+ # HTTP/3 伪头的发送顺序 / HTTP/3 pseudo-header send order
2552
+ h3_pseudo_header_order: Optional[List[str]] = None,
2553
+ # 默认请求头字典 / Default headers dict
2554
+ default_headers: Optional[Dict[str, str]] = None,
2555
+ # 默认请求头字典(别名)/ Default headers dict alias
2556
+ headers: Optional[Dict[str, str]] = None,
2557
+ # 代理 CONNECT 隧道请求头字典 / Proxy CONNECT tunnel headers dict
2558
+ connect_headers: Optional[Dict[str, str]] = None,
2559
+ # ── 证书固定 ── / Certificate Pinning ──
2560
+ # SSL 证书固定字典 / SSL certificate pinning dict
2561
+ certificate_pinning_hosts: Optional[Dict[str, List[str]]] = None,
2562
+ # 是否调用默认 Bad-Pin 处理器 / Whether to invoke the default bad-pin handler
2563
+ with_default_bad_pin_handler: bool = False,
2564
+ # ── Cookie ──
2565
+ # 预置 Cookie 字典 / Pre-populated cookie dict
2566
+ request_cookies: Optional[Dict[str, str]] = None,
2567
+ # 预置 Cookie 字典(别名)/ Pre-populated cookie dict alias
2568
+ cookies: Optional[Dict[str, str]] = None,
2569
+ # ── 自定义 TLS ── / Custom TLS ──
2570
+ # 完全自定义的 TLS 客户端配置 (26 fields) / Fully custom TLS client configuration
2571
+ custom_tls_client: Optional[Dict[str, Any]] = None,
2572
+ # 客户端证书 (mTLS) / Client certificates for mTLS
2573
+ client_certificates: Optional[List[Dict[str, bytes]]] = None,
2574
+ # ── 连接池调优 ── / Connection Pool Tuning ──
2575
+ # 全局最大空闲连接数 / Global max idle connections
2576
+ max_idle_connections: int = 0,
2577
+ # 每个 Host 的最大空闲连接数 / Max idle connections per host
2578
+ max_idle_connections_per_host: int = 0,
2579
+ # 每个 Host 的最大总连接数 / Max total connections per host
2580
+ max_connections_per_host: int = 0,
2581
+ # 禁用 HTTP Keep-Alive / Disable HTTP Keep-Alive
2582
+ disable_keep_alives: bool = False,
2583
+ # 禁用响应体自动解压 / Disable automatic response body decompression
2584
+ disable_compression: bool = False,
2585
+ # 空闲连接的最大保持时间(秒) / Max idle time for keep-alive connections
2586
+ idle_conn_timeout_seconds: int = 0,
2587
+ # HTTP 响应头的最大字节数限制 / Max response header bytes limit
2588
+ max_response_header_bytes: int = 0,
2589
+ # Socket 写缓冲区大小(字节) / Socket write buffer size (bytes)
2590
+ write_buffer_size: int = 0,
2591
+ # Socket 读缓冲区大小(字节) / Socket read buffer size (bytes)
2592
+ read_buffer_size: int = 0,
2593
+ # ── IP 协议栈控制 ── / IP Stack Control ──
2594
+ # 禁用 IPv4 / Disable IPv4
2595
+ disable_ipv4: bool = False,
2596
+ # 禁用 IPv6 / Disable IPv6
2597
+ disable_ipv6: bool = False,
2598
+ # ── TCP/IP Fingerprint ──
2599
+ # IP TTL (Time To Live). Windows=128, Linux/macOS=64. 0=auto from profile
2600
+ tcp_ttl: int = 0,
2601
+ # TCP receive window size. Windows=64240, Linux/macOS=65535. 0=auto
2602
+ tcp_window_size: int = 0,
2603
+ # TCP window scale factor. Windows=8, Linux=7, macOS=6. 0=auto
2604
+ tcp_window_scale: int = 0,
2605
+ # TCP Maximum Segment Size. Standard Ethernet=1460. 0=auto
2606
+ tcp_mss: int = 0,
2607
+ # ── Cookie ──
2608
+ # 是否允许空 Cookie / Whether to allow empty-value cookies
2609
+ allow_empty_cookies: bool = False,
2610
+ # 完全禁用 Cookie Jar / Completely disable Cookie Jar
2611
+ without_cookie_jar: bool = False,
2612
+ # ── requests 兼容属性 ── / requests-compatible properties ──
2613
+ # HTTP 认证元组 (username, password) / HTTP auth tuple
2614
+ auth: Optional[Tuple[str, str]] = None,
2615
+ # 查询字符串参数字典 / Query-string parameter dict
2616
+ params: Optional[Dict[str, str]] = None,
2617
+ # 客户端 SSL 证书路径 / Client SSL cert path
2618
+ cert: Optional[Union[str, Tuple[str, str]]] = None,
2619
+ # 是否流式读取响应体 / Whether to stream the response body
2620
+ stream: bool = False,
2621
+ # ── 调试 / 安全 ── / Debug / Safety ──
2622
+ # 是否在 Go 侧捕获 panic / Whether to catch Go panics
2623
+ catch_panics: bool = True,
2624
+ # 启用调试日志输出 / Enable debug log output
2625
+ with_debug: bool = False,
2626
+ # 禁用 TLS session tickets / Disable TLS session tickets (ABI 2)
2627
+ disable_session_tickets: bool = False,
2628
+ # TLS keylog 文件路径(Wireshark 指纹调试)/ TLS keylog path (ABI 2)
2629
+ tls_keylog_path: Optional[str] = None,
2630
+ # 自定义 CA PEM 内容 / Custom CA PEM bytes for TLS verification (ABI 2)
2631
+ root_ca_pem: Optional[bytes] = None,
2632
+ # HTTP/2 DATA 帧上限 (ABI 2.1) / Cap per-DATA-frame payload
2633
+ h2_max_data_frame_size: int = 0,
2634
+ # 空闲 H2 连接 PING 阈值毫秒 (ABI 2.1) / Preface-ping idle threshold ms
2635
+ preface_ping_idle_ms: int = 0,
2636
+ # HPACK 索引策略 ("chrome") (ABI 2.1) / HPACK indexing policy
2637
+ hpack_indexing_policy: str = "",
2638
+ # Cookie 按对拆分 (ABI 2.1) / Split Cookie header per cookie-pair
2639
+ cookie_crumb: bool = False,
2640
+ # ── ABI 3 — 细粒度指纹控制 / fine-grained fingerprint control ──
2641
+ # 扩展乱序策略: 0=off, 1=chrome, 2=all, 3=prefix (ABI 3)
2642
+ # Extension-order permutation policy (per-handshake, Chromium-style)
2643
+ extension_permute_mode: int = 0,
2644
+ # 前缀长度(仅 mode=3): 前 N 个扩展保持原位不乱序 / prefix length
2645
+ extension_permute_prefix: int = 0,
2646
+ # 抑制 HTTP/2 PRIORITY 帧与 HEADERS 优先级标志 (ABI 3)
2647
+ # Suppress RFC 7540 PRIORITY frames / HEADERS priority flag
2648
+ h2_disable_priority_frames: bool = False,
2649
+ # 按 Sec-Fetch-Dest 选择浏览器真实头序 (ABI 3)
2650
+ # Derive the header order from Sec-Fetch-Dest instead of header_order
2651
+ header_order_by_dest: bool = False,
2652
+ # 显式指定目的类型(留空则由请求头推断)/ Explicit Sec-Fetch-Dest value
2653
+ header_order_dest: Optional[str] = None,
2654
+ # 深度 TCP 指纹: DF 位 / TOS / Nagle / 窗口钳制 / IP ID 模式 (ABI 3)
2655
+ # -1/None 表示沿用指纹预设值 / -1 or None keeps the profile default
2656
+ tcp_dont_fragment: int = -1,
2657
+ tcp_tos: int = -1,
2658
+ tcp_no_delay: int = -1,
2659
+ tcp_window_clamp: int = 0,
2660
+ tcp_ip_id_mode: str = "",
2661
+ # 指纹预设名 / Fingerprint preset name (tls_client.fingerprints)
2662
+ fingerprint: Optional[str] = None,
2663
+ ) -> None:
2664
+ if client_identifier not in SUPPORTED_CLIENT_IDENTIFIERS:
2665
+ raise ValueError(
2666
+ "unsupported client_identifier %r; supported values: %s"
2667
+ % (client_identifier, ", ".join(sorted(SUPPORTED_CLIENT_IDENTIFIERS)))
2668
+ )
2669
+ self._defaults_lock = threading.RLock()
2670
+ self._closed = False
2671
+ self._defaults_version = 0
2672
+ self._selected_snapshot_cache = {}
2673
+ self.defaults = {
2674
+ "client_identifier": client_identifier,
2675
+ "timeout_seconds": timeout,
2676
+ "timeout_milliseconds": timeout_milliseconds,
2677
+ "follow_redirects": 1 if follow_redirects else 0,
2678
+ "insecure_skip_verify": 0 if verify else 1,
2679
+ "force_http1": 1 if force_http1 else 0,
2680
+ "with_random_tls_extension_order": (
2681
+ 1 if random_tls_extension_order else 0
2682
+ ),
2683
+ "with_protocol_racing": 1 if with_protocol_racing else 0,
2684
+ "server_name_overwrite": server_name_overwrite,
2685
+ "request_host_override": request_host_override,
2686
+ "local_address": local_address,
2687
+ "proxy": proxies if proxies is not None else proxy,
2688
+ "pseudo_header_order": pseudo_header_order,
2689
+ "h3_pseudo_header_order": h3_pseudo_header_order,
2690
+ "auth": auth,
2691
+ "params": params,
2692
+ "cert": cert,
2693
+ "stream": 1 if stream else 0,
2694
+ "default_headers": (
2695
+ default_headers if default_headers is not None
2696
+ else headers if headers is not None
2697
+ else DEFAULT_HEADERS.get(client_identifier)
2698
+ ),
2699
+ "connect_headers": connect_headers,
2700
+ "certificate_pinning_hosts": certificate_pinning_hosts,
2701
+ "with_default_bad_pin_handler": (
2702
+ 1 if with_default_bad_pin_handler else 0
2703
+ ),
2704
+ "request_cookies": request_cookies if request_cookies is not None else cookies,
2705
+ "custom_tls_client": custom_tls_client,
2706
+ "client_certificates": client_certificates,
2707
+ "max_idle_connections": max_idle_connections,
2708
+ "max_idle_connections_per_host": max_idle_connections_per_host,
2709
+ "max_connections_per_host": max_connections_per_host,
2710
+ "disable_keep_alives": 1 if disable_keep_alives else 0,
2711
+ "disable_compression": 1 if disable_compression else 0,
2712
+ "idle_conn_timeout_seconds": idle_conn_timeout_seconds,
2713
+ "max_response_header_bytes": max_response_header_bytes,
2714
+ "write_buffer_size": write_buffer_size,
2715
+ "read_buffer_size": read_buffer_size,
2716
+ "allow_empty_cookies": 1 if allow_empty_cookies else 0,
2717
+ "without_cookie_jar": 1 if without_cookie_jar else 0,
2718
+ "disable_http3": 1 if disable_http3 else 0,
2719
+ "disable_ipv4": 1 if disable_ipv4 else 0,
2720
+ "disable_ipv6": 1 if disable_ipv6 else 0,
2721
+ "tcp_ttl": tcp_ttl,
2722
+ "tcp_window_size": tcp_window_size,
2723
+ "tcp_window_scale": tcp_window_scale,
2724
+ "tcp_mss": tcp_mss,
2725
+ "catch_panics": 1 if catch_panics else 0,
2726
+ "with_debug": 1 if with_debug else 0,
2727
+ "disable_session_tickets": 1 if disable_session_tickets else 0,
2728
+ "tls_keylog_path": tls_keylog_path,
2729
+ "root_ca_pem": root_ca_pem,
2730
+ "h2_max_data_frame_size": h2_max_data_frame_size,
2731
+ "preface_ping_idle_ms": preface_ping_idle_ms,
2732
+ "hpack_indexing_policy": hpack_indexing_policy,
2733
+ "cookie_crumb": 1 if cookie_crumb else 0,
2734
+ # ── ABI 3 — 细粒度指纹控制 / fine-grained fingerprint control ──
2735
+ "extension_permute_mode": extension_permute_mode,
2736
+ "extension_permute_prefix": extension_permute_prefix,
2737
+ "h2_disable_priority_frames": 1 if h2_disable_priority_frames else 0,
2738
+ "header_order_by_dest": 1 if header_order_by_dest else 0,
2739
+ "header_order_dest": header_order_dest or "",
2740
+ "tcp_dont_fragment": tcp_dont_fragment,
2741
+ "tcp_tos": tcp_tos,
2742
+ "tcp_no_delay": tcp_no_delay,
2743
+ "tcp_window_clamp": tcp_window_clamp,
2744
+ "tcp_ip_id_mode": tcp_ip_id_mode or "",
2745
+ }
2746
+ # True once the caller overrides the profile's default header block
2747
+ # (via the default_headers/headers property or constructor kwargs);
2748
+ # while False, switching client_identifier also switches the
2749
+ # default headers so TLS fingerprint and headers stay consistent.
2750
+ self._headers_customized = default_headers is not None or headers is not None
2751
+ if fingerprint is not None:
2752
+ from tls_client.fingerprints import apply as _apply_fingerprint
2753
+
2754
+ _apply_fingerprint(self, fingerprint)
2755
+
2756
+ def stream_to_file(
2757
+ self,
2758
+ # HTTP 方法 / HTTP method
2759
+ method: str,
2760
+ # 请求 URL / Request URL
2761
+ url: str,
2762
+ # 输出文件路径 / Output file path
2763
+ output_path: str,
2764
+ *,
2765
+ # 请求头字典 / Request headers dict
2766
+ headers: Optional[Dict[str, str]] = None,
2767
+ # 请求头发送顺序 / Header send order
2768
+ header_order: Optional[List[str]] = None,
2769
+ # 请求体原始字节串 / Request body as raw bytes
2770
+ body: Optional[bytes] = None,
2771
+ # 块大小(字节) / Chunk size per read (bytes)
2772
+ chunk_size: int = 8192,
2773
+ # 可选的 EOF 标记字符串 / Optional EOF marker string
2774
+ eof_marker: Optional[str] = None,
2775
+ **kwargs: Any,
2776
+ ) -> Response:
2777
+ """执行请求并将响应体流式写入磁盘。
2778
+
2779
+ Execute a request and stream the response body to disk.
2780
+ """
2781
+
2782
+ ffi, _ = _get_ffi()
2783
+
2784
+ keep_alive: list = []
2785
+ c_path = _c_string(ffi, output_path)
2786
+ keep_alive.append(c_path)
2787
+
2788
+ c_eof = _c_string(ffi, eof_marker)
2789
+ if c_eof != ffi.NULL:
2790
+ keep_alive.append(c_eof)
2791
+
2792
+ return self.execute_request(
2793
+ method,
2794
+ url,
2795
+ headers=headers,
2796
+ header_order=header_order,
2797
+ body=body,
2798
+ _stream_output_path=c_path,
2799
+ _stream_output_block_size=chunk_size,
2800
+ _stream_output_eof_symbol=c_eof,
2801
+ _stream_keep_alive=keep_alive,
2802
+ **kwargs,
2803
+ )
2804
+
2805
+ def __enter__(self) -> "Session":
2806
+ return self
2807
+
2808
+ def __exit__(self, *args: Any) -> None:
2809
+ pass
2810
+
2811
+ def execute_request(
2812
+ self,
2813
+ # HTTP 方法 / HTTP method
2814
+ method: str,
2815
+ # 完整的请求 URL / Full request URL including scheme and hostname
2816
+ url: str,
2817
+ *,
2818
+ # 请求头字典 / Request headers dict
2819
+ headers: Optional[Dict[str, str]] = None,
2820
+ # 请求头的发送顺序列表 / Header send-order list
2821
+ header_order: Optional[List[str]] = None,
2822
+ # 请求体原始字节串 / Request body as raw bytes
2823
+ body: Optional[bytes] = None,
2824
+ # ── 每请求覆盖参数 / Per-request overrides ──
2825
+ # 覆盖 TLS 指纹标识 / Override TLS fingerprint identifier
2826
+ client_identifier: Optional[str] = None,
2827
+ # 覆盖超时时间(秒) / Override timeout (seconds)
2828
+ timeout: Optional[int] = None,
2829
+ # 覆盖超时时间(毫秒) / Override timeout (milliseconds)
2830
+ timeout_milliseconds: Optional[int] = None,
2831
+ # 覆盖重定向跟随策略 / Override redirect-following policy
2832
+ follow_redirects: Optional[bool] = None,
2833
+ # 覆盖 TLS 证书校验 / Override TLS certificate verification
2834
+ verify: Optional[bool] = None,
2835
+ # 覆盖 HTTP/1.1 强制开关 / Override force HTTP/1.1
2836
+ force_http1: Optional[bool] = None,
2837
+ # 覆盖 TLS 扩展随机化 / Override TLS extension randomisation
2838
+ random_tls_extension_order: Optional[bool] = None,
2839
+ # 覆盖协议竞速开关 / Override protocol racing
2840
+ with_protocol_racing: Optional[bool] = None,
2841
+ # 覆盖 SNI 主机名 / Override SNI hostname
2842
+ server_name_overwrite: Optional[str] = None,
2843
+ # 覆盖 HTTP Host 请求头 / Override HTTP Host header
2844
+ request_host_override: Optional[str] = None,
2845
+ # 覆盖代理 URL / Override proxy URL
2846
+ proxy: Optional[str] = None,
2847
+ # 覆盖本地绑定地址 / Override local bind address
2848
+ local_address: Optional[str] = None,
2849
+ # 覆盖 HTTP/2 伪头顺序 / Override HTTP/2 pseudo-header order
2850
+ pseudo_header_order: Optional[List[str]] = None,
2851
+ # 覆盖 HTTP/3 伪头顺序 / Override HTTP/3 pseudo-header order
2852
+ h3_pseudo_header_order: Optional[List[str]] = None,
2853
+ # 覆盖默认请求头字典 / Override default headers dict
2854
+ default_headers: Optional[Dict[str, str]] = None,
2855
+ # 覆盖代理 CONNECT 隧道请求头 / Override proxy CONNECT tunnel headers
2856
+ connect_headers: Optional[Dict[str, str]] = None,
2857
+ # 覆盖 SSL 证书固定字典 / Override SSL certificate pinning dict
2858
+ certificate_pinning_hosts: Optional[Dict[str, List[str]]] = None,
2859
+ # 覆盖 Bad-Pin 处理器开关 / Override default bad-pin handler toggle
2860
+ with_default_bad_pin_handler: Optional[bool] = None,
2861
+ # 覆盖预置 Cookie 字典 / Override pre-populated cookie dict
2862
+ request_cookies: Optional[Dict[str, str]] = None,
2863
+ # 覆盖客户端证书列表 / Override client certificate list
2864
+ client_certificates: Optional[List[Dict[str, bytes]]] = None,
2865
+ # 覆盖自定义 TLS 客户端配置 / Override custom TLS client configuration
2866
+ custom_tls_client: Optional[Dict[str, Any]] = None,
2867
+ # 覆盖全局最大空闲连接数 / Override global max idle connections
2868
+ max_idle_connections: Optional[int] = None,
2869
+ # 覆盖每 Host 最大空闲连接数 / Override max idle connections per host
2870
+ max_idle_connections_per_host: Optional[int] = None,
2871
+ # 覆盖每 Host 最大总连接数 / Override max total connections per host
2872
+ max_connections_per_host: Optional[int] = None,
2873
+ # 覆盖 Keep-Alive 禁用 / Override disable Keep-Alive
2874
+ disable_keep_alives: Optional[bool] = None,
2875
+ # 覆盖压缩禁用 / Override disable compression
2876
+ disable_compression: Optional[bool] = None,
2877
+ # 覆盖空闲连接超时 / Override idle connection timeout
2878
+ idle_conn_timeout_seconds: Optional[int] = None,
2879
+ # 覆盖响应头最大字节数 / Override max response header bytes
2880
+ max_response_header_bytes: Optional[int] = None,
2881
+ # 覆盖写缓冲区大小 / Override write buffer size
2882
+ write_buffer_size: Optional[int] = None,
2883
+ # 覆盖读缓冲区大小 / Override read buffer size
2884
+ read_buffer_size: Optional[int] = None,
2885
+ # 覆盖空 Cookie 允许 / Override allow-empty-cookies
2886
+ allow_empty_cookies: Optional[bool] = None,
2887
+ # 覆盖禁用 Cookie Jar / Override disable Cookie Jar
2888
+ without_cookie_jar: Optional[bool] = None,
2889
+ # 覆盖 HTTP/3 禁用 / Override disable HTTP/3
2890
+ disable_http3: Optional[bool] = None,
2891
+ # 覆盖 IPv4 禁用 / Override disable IPv4
2892
+ disable_ipv4: Optional[bool] = None,
2893
+ # 覆盖 IPv6 禁用 / Override disable IPv6
2894
+ disable_ipv6: Optional[bool] = None,
2895
+ # 覆盖 TCP TTL / Override TCP TTL
2896
+ tcp_ttl: Optional[int] = None,
2897
+ # 覆盖 TCP 窗口大小 / Override TCP window size
2898
+ tcp_window_size: Optional[int] = None,
2899
+ # 覆盖 TCP 窗口缩放 / Override TCP window scale
2900
+ tcp_window_scale: Optional[int] = None,
2901
+ # 覆盖 TCP MSS / Override TCP MSS
2902
+ tcp_mss: Optional[int] = None,
2903
+ # 覆盖 panic 捕获 / Override catch-panics
2904
+ catch_panics: Optional[bool] = None,
2905
+ # 覆盖调试日志 / Override debug logging
2906
+ with_debug: Optional[bool] = None,
2907
+ # 覆盖 TLS session tickets 禁用 (ABI 2) / Override session-ticket disabling
2908
+ disable_session_tickets: Optional[bool] = None,
2909
+ # 覆盖 TLS keylog 路径 (ABI 2) / Override TLS keylog path
2910
+ tls_keylog_path: Optional[str] = None,
2911
+ # 覆盖自定义 CA PEM (ABI 2) / Override custom CA PEM bytes
2912
+ root_ca_pem: Optional[bytes] = None,
2913
+ # 覆盖 HTTP/2 DATA 帧上限 (ABI 2.1) / Override DATA frame cap
2914
+ h2_max_data_frame_size: Optional[int] = None,
2915
+ # 覆盖空闲 PING 阈值 (ABI 2.1) / Override preface-ping threshold
2916
+ preface_ping_idle_ms: Optional[int] = None,
2917
+ # 覆盖 HPACK 索引策略 (ABI 2.1) / Override HPACK indexing policy
2918
+ hpack_indexing_policy: Optional[str] = None,
2919
+ # 覆盖 Cookie 拆分 (ABI 2.1) / Override cookie crumble
2920
+ cookie_crumb: Optional[bool] = None,
2921
+ # ── ABI 3 — 细粒度指纹控制 / fine-grained fingerprint control ──
2922
+ # 扩展乱序策略: 0=off, 1=chrome, 2=all, 3=prefix
2923
+ extension_permute_mode: Optional[int] = None,
2924
+ # 前缀长度(仅 mode=3)/ Prefix length (mode=3 only)
2925
+ extension_permute_prefix: Optional[int] = None,
2926
+ # 抑制 HTTP/2 PRIORITY 帧 / Suppress PRIORITY frames
2927
+ h2_disable_priority_frames: Optional[bool] = None,
2928
+ # 按 Sec-Fetch-Dest 选择浏览器真实头序 / Destination-aware header order
2929
+ header_order_by_dest: Optional[bool] = None,
2930
+ # 显式目的类型(留空自动推断)/ Explicit Sec-Fetch-Dest value
2931
+ header_order_dest: Optional[str] = None,
2932
+ # 深度 TCP 指纹 / Deep TCP fingerprint (ABI 3)
2933
+ tcp_dont_fragment: Optional[int] = None,
2934
+ tcp_tos: Optional[int] = None,
2935
+ tcp_no_delay: Optional[int] = None,
2936
+ tcp_window_clamp: Optional[int] = None,
2937
+ tcp_ip_id_mode: Optional[str] = None,
2938
+ **kwargs: Any,
2939
+ ) -> Response:
2940
+ """通过 Go 引擎执行单次 HTTP 请求。
2941
+
2942
+ Execute a single HTTP request through the Go engine.
2943
+ """
2944
+ selected_identifier = client_identifier or self.client_identifier
2945
+ if selected_identifier not in SUPPORTED_CLIENT_IDENTIFIERS:
2946
+ raise ValueError("unsupported client_identifier %r" % selected_identifier)
2947
+ if self._closed:
2948
+ raise RuntimeError("Session is closed")
2949
+ ffi, lib = _get_ffi()
2950
+ context = kwargs.pop("context", None)
2951
+ defaults = self._snapshot_selected_defaults(SYNC_REQUEST_DEFAULT_KEYS)
2952
+
2953
+ effective_proxy = _resolve_proxy_url(
2954
+ proxy if proxy is not None else defaults.get("proxy"),
2955
+ url,
2956
+ )
2957
+
2958
+ def _val(name: str, override, as_bool: bool = False):
2959
+ if name == "proxy":
2960
+ v = effective_proxy
2961
+ else:
2962
+ v = override if override is not None else defaults.get(name)
2963
+ if as_bool:
2964
+ return 1 if v else 0
2965
+ return v
2966
+
2967
+ resolved = {
2968
+ "client_identifier": _val("client_identifier", client_identifier),
2969
+ "proxy": _val("proxy", proxy),
2970
+ "server_name_overwrite": _val("server_name_overwrite", server_name_overwrite),
2971
+ "request_host_override": _val("request_host_override", request_host_override),
2972
+ "local_address": _val("local_address", local_address),
2973
+ "pseudo_header_order": _val("pseudo_header_order", pseudo_header_order),
2974
+ "h3_pseudo_header_order": _val("h3_pseudo_header_order", h3_pseudo_header_order),
2975
+ "default_headers": _val("default_headers", default_headers),
2976
+ "connect_headers": _val("connect_headers", connect_headers),
2977
+ "certificate_pinning_hosts": _val("certificate_pinning_hosts", certificate_pinning_hosts),
2978
+ "request_cookies": _val("request_cookies", request_cookies),
2979
+ "client_certificates": _val("client_certificates", client_certificates),
2980
+ "custom_tls_client": _val("custom_tls_client", custom_tls_client),
2981
+ "timeout_seconds": _val("timeout_seconds", timeout),
2982
+ "timeout_milliseconds": _val("timeout_milliseconds", timeout_milliseconds),
2983
+ "follow_redirects": _val("follow_redirects", follow_redirects, True),
2984
+ "force_http1": _val("force_http1", force_http1, True),
2985
+ "with_random_tls_extension_order": _val(
2986
+ "with_random_tls_extension_order", random_tls_extension_order, True
2987
+ ),
2988
+ "with_protocol_racing": _val("with_protocol_racing", with_protocol_racing, True),
2989
+ "max_idle_connections": _val("max_idle_connections", max_idle_connections),
2990
+ "max_idle_connections_per_host": _val(
2991
+ "max_idle_connections_per_host", max_idle_connections_per_host
2992
+ ),
2993
+ "max_connections_per_host": _val(
2994
+ "max_connections_per_host", max_connections_per_host
2995
+ ),
2996
+ "max_response_header_bytes": _val(
2997
+ "max_response_header_bytes", max_response_header_bytes
2998
+ ),
2999
+ "write_buffer_size": _val("write_buffer_size", write_buffer_size),
3000
+ "read_buffer_size": _val("read_buffer_size", read_buffer_size),
3001
+ "idle_conn_timeout_seconds": _val(
3002
+ "idle_conn_timeout_seconds", idle_conn_timeout_seconds
3003
+ ),
3004
+ "disable_keep_alives": _val("disable_keep_alives", disable_keep_alives, True),
3005
+ "disable_compression": _val("disable_compression", disable_compression, True),
3006
+ "disable_http3": _val("disable_http3", disable_http3, True),
3007
+ "disable_ipv4": _val("disable_ipv4", disable_ipv4, True),
3008
+ "disable_ipv6": _val("disable_ipv6", disable_ipv6, True),
3009
+ "without_cookie_jar": _val("without_cookie_jar", without_cookie_jar, True),
3010
+ "allow_empty_cookies": _val("allow_empty_cookies", allow_empty_cookies, True),
3011
+ "with_default_bad_pin_handler": _val(
3012
+ "with_default_bad_pin_handler", with_default_bad_pin_handler, True
3013
+ ),
3014
+ "catch_panics": _val("catch_panics", catch_panics, True),
3015
+ "with_debug": _val("with_debug", with_debug, True),
3016
+ "disable_session_tickets": _val(
3017
+ "disable_session_tickets", disable_session_tickets, True
3018
+ ),
3019
+ "tls_keylog_path": _val("tls_keylog_path", tls_keylog_path),
3020
+ "root_ca_pem": _val("root_ca_pem", root_ca_pem),
3021
+ "h2_max_data_frame_size": _val(
3022
+ "h2_max_data_frame_size", h2_max_data_frame_size
3023
+ ),
3024
+ "preface_ping_idle_ms": _val("preface_ping_idle_ms", preface_ping_idle_ms),
3025
+ "hpack_indexing_policy": _val("hpack_indexing_policy", hpack_indexing_policy),
3026
+ "cookie_crumb": _val("cookie_crumb", cookie_crumb, True),
3027
+ "tcp_ttl": _val("tcp_ttl", tcp_ttl),
3028
+ "tcp_window_size": _val("tcp_window_size", tcp_window_size),
3029
+ "tcp_window_scale": _val("tcp_window_scale", tcp_window_scale),
3030
+ "tcp_mss": _val("tcp_mss", tcp_mss),
3031
+ # ── ABI 3 — 细粒度指纹控制 / fine-grained fingerprint control ──
3032
+ "extension_permute_mode": _val(
3033
+ "extension_permute_mode", extension_permute_mode
3034
+ ),
3035
+ "extension_permute_prefix": _val(
3036
+ "extension_permute_prefix", extension_permute_prefix
3037
+ ),
3038
+ "h2_disable_priority_frames": _val(
3039
+ "h2_disable_priority_frames", h2_disable_priority_frames, True
3040
+ ),
3041
+ "header_order_by_dest": _val(
3042
+ "header_order_by_dest", header_order_by_dest, True
3043
+ ),
3044
+ "header_order_dest": _val("header_order_dest", header_order_dest),
3045
+ "tcp_dont_fragment": _val("tcp_dont_fragment", tcp_dont_fragment),
3046
+ "tcp_tos": _val("tcp_tos", tcp_tos),
3047
+ "tcp_no_delay": _val("tcp_no_delay", tcp_no_delay),
3048
+ "tcp_window_clamp": _val("tcp_window_clamp", tcp_window_clamp),
3049
+ "tcp_ip_id_mode": _val("tcp_ip_id_mode", tcp_ip_id_mode),
3050
+ }
3051
+ if verify is not None:
3052
+ resolved["insecure_skip_verify"] = 0 if verify else 1
3053
+ else:
3054
+ resolved["insecure_skip_verify"] = _val("insecure_skip_verify", None, True)
3055
+ _normalize_int_fields(resolved)
3056
+
3057
+ # ABI 2 features need the rebuilt shared library.
3058
+ if (resolved["disable_session_tickets"] or resolved["tls_keylog_path"]
3059
+ or resolved["root_ca_pem"]):
3060
+ _require_abi2()
3061
+ # ABI 3 deep-fingerprint knobs. Unlike the ABI 2 gate (which raises),
3062
+ # these degrade: a preset or an implicit default may enable them on a
3063
+ # library that predates ABI 3, and failing the whole request would be
3064
+ # worse than dropping the refinement. Explicit caller intent is
3065
+ # reported through the warning instead.
3066
+ _degrade_abi3_fields(resolved)
3067
+
3068
+ # Per-request client_identifier override: pair the request with the
3069
+ # profile's default headers unless the caller manages headers
3070
+ # explicitly (per-request default_headers kwarg or a customised
3071
+ # session header block). Prevents a Safari TLS fingerprint from
3072
+ # going out with the session profile's Chrome User-Agent. Applied
3073
+ # before the cache-key hash so the key reflects the actual headers.
3074
+ if (
3075
+ default_headers is None
3076
+ and not self._headers_customized
3077
+ and resolved["client_identifier"] != defaults.get("client_identifier")
3078
+ ):
3079
+ resolved["default_headers"] = _clone_default_value(
3080
+ DEFAULT_HEADERS.get(resolved["client_identifier"])
3081
+ )
3082
+
3083
+ keep_alive: list = []
3084
+
3085
+ # Fold the profile default headers into the per-request headers
3086
+ # (see _merge_default_headers — Go drops client-level defaults
3087
+ # whenever request headers are present).
3088
+ merged_headers, merged_order = _merge_default_headers(
3089
+ resolved["default_headers"], headers, header_order
3090
+ )
3091
+ if context is not None:
3092
+ merged_headers, merged_order = _apply_request_context(
3093
+ self, merged_headers, merged_order, context,
3094
+ resolved["client_identifier"], headers,
3095
+ )
3096
+
3097
+ # ---- build C HttpHeader array -------------------------------------
3098
+ hdr_ptr, hdr_len = _build_headers(ffi, merged_headers, keep_alive)
3099
+
3100
+ # ---- build header_order array -------------------------------------
3101
+ ho_ptr, ho_len = _build_string_array(ffi, merged_order, keep_alive)
3102
+
3103
+ # ---- build pseudo_header_order array ------------------------------
3104
+ ph_ptr, ph_len = _build_string_array(
3105
+ ffi, resolved["pseudo_header_order"], keep_alive
3106
+ )
3107
+
3108
+ # ---- build h3_pseudo_header_order array ---------------------------
3109
+ h3ph_ptr, h3ph_len = _build_string_array(
3110
+ ffi, resolved["h3_pseudo_header_order"], keep_alive
3111
+ )
3112
+
3113
+ # ---- build default_headers array ----------------------------------
3114
+ dh_ptr, dh_len = _build_headers(
3115
+ ffi, resolved["default_headers"], keep_alive
3116
+ )
3117
+
3118
+ # ---- build connect_headers array ----------------------------------
3119
+ ch_ptr, ch_len = _build_headers(
3120
+ ffi, resolved["connect_headers"], keep_alive
3121
+ )
3122
+
3123
+ # ---- build certificate_pinning_hosts array -------------------------
3124
+ cp_ptr, cp_len = _build_pin_entries(
3125
+ ffi, resolved["certificate_pinning_hosts"], keep_alive
3126
+ )
3127
+
3128
+ # ---- build request_cookies array -----------------------------------
3129
+ rc_ptr, rc_len = _build_headers(
3130
+ ffi, resolved["request_cookies"], keep_alive
3131
+ )
3132
+
3133
+ # ---- build client_certificates array --------------------------------
3134
+ cc_ptr, cc_len = _build_client_certificates(
3135
+ ffi, resolved["client_certificates"], keep_alive
3136
+ )
3137
+
3138
+ # ---- build custom_tls_client --------------------------------------
3139
+ ctc_ptr = _build_custom_tls_client(
3140
+ ffi, resolved["custom_tls_client"], keep_alive
3141
+ )
3142
+
3143
+ # ---- pre-compute cache key hash (avoids ~50 CGO calls on cache hit) --------
3144
+ ck_hash = _compute_cache_key_hash(resolved)
3145
+ c_ck = _c_string(ffi, ck_hash)
3146
+ if c_ck != ffi.NULL:
3147
+ keep_alive.append(c_ck)
3148
+
3149
+ # ---- build body (zero-copy) ---------------------------------------
3150
+ # ffi.from_buffer returns a pointer into Python's bytes buffer without
3151
+ # copying. keep_alive anchors the pointer so Python does not GC the
3152
+ # buffer while Go reads from it (sync: blocked; async: _pending_requests).
3153
+ if body is not None:
3154
+ body_ptr = ffi.from_buffer(body)
3155
+ keep_alive.append(body_ptr)
3156
+ body_len = len(body)
3157
+ else:
3158
+ body_ptr = ffi.NULL
3159
+ body_len = 0
3160
+
3161
+ # ---- build RequestOptions -----------------------------------------
3162
+ opts = ffi.new("RequestOptions *")
3163
+ keep_alive.append(opts)
3164
+
3165
+ c_method = ffi.new("char[]", method.encode("utf-8"))
3166
+ c_url = ffi.new("char[]", url.encode("utf-8"))
3167
+ keep_alive.extend([c_method, c_url])
3168
+
3169
+ opts.method = c_method
3170
+ opts.url = c_url
3171
+ opts.body = body_ptr
3172
+ opts.body_len = body_len
3173
+
3174
+ c_proxy = _c_string(ffi, resolved["proxy"])
3175
+ c_ci = _c_string(ffi, resolved["client_identifier"])
3176
+ c_sni = _c_string(ffi, resolved["server_name_overwrite"])
3177
+ c_host_override = _c_string(ffi, resolved["request_host_override"])
3178
+ c_local_addr = _c_string(ffi, resolved["local_address"])
3179
+ for c in (c_proxy, c_ci, c_sni, c_host_override, c_local_addr):
3180
+ if c != ffi.NULL:
3181
+ keep_alive.append(c)
3182
+
3183
+ opts.proxy = c_proxy
3184
+ opts.client_identifier = c_ci
3185
+ opts.headers = hdr_ptr
3186
+ opts.headers_len = hdr_len
3187
+ opts.header_order = ho_ptr
3188
+ opts.header_order_len = ho_len
3189
+ opts.pseudo_header_order = ph_ptr
3190
+ opts.pseudo_header_order_len = ph_len
3191
+ opts.h3_pseudo_header_order = h3ph_ptr
3192
+ opts.h3_pseudo_header_order_len = h3ph_len
3193
+ opts.default_headers = dh_ptr
3194
+ opts.default_headers_len = dh_len
3195
+ opts.connect_headers = ch_ptr
3196
+ opts.connect_headers_len = ch_len
3197
+ opts.certificate_pinning_hosts = cp_ptr
3198
+ opts.certificate_pinning_hosts_len = cp_len
3199
+ opts.with_default_bad_pin_handler = resolved["with_default_bad_pin_handler"]
3200
+ opts.request_cookies = rc_ptr
3201
+ opts.request_cookies_len = rc_len
3202
+ opts.client_certificates = cc_ptr
3203
+ opts.client_certificates_len = cc_len
3204
+ opts.custom_tls_client = ctc_ptr
3205
+ opts.cache_key_hash = c_ck
3206
+
3207
+ # ABI 2 fields
3208
+ opts.disable_session_tickets = resolved["disable_session_tickets"]
3209
+ if resolved["tls_keylog_path"]:
3210
+ c_keylog = _c_string(ffi, resolved["tls_keylog_path"])
3211
+ keep_alive.append(c_keylog)
3212
+ opts.tls_keylog_path = c_keylog
3213
+ if resolved["root_ca_pem"]:
3214
+ rc_ptr = ffi.from_buffer(resolved["root_ca_pem"])
3215
+ keep_alive.append(rc_ptr)
3216
+ opts.root_ca_pem = rc_ptr
3217
+ opts.root_ca_pem_len = len(resolved["root_ca_pem"])
3218
+ opts.h2_max_data_frame_size = resolved["h2_max_data_frame_size"]
3219
+ opts.preface_ping_idle_ms = resolved["preface_ping_idle_ms"]
3220
+ if resolved["hpack_indexing_policy"]:
3221
+ c_hip = _c_string(ffi, resolved["hpack_indexing_policy"])
3222
+ keep_alive.append(c_hip)
3223
+ opts.hpack_indexing_policy = c_hip
3224
+ opts.cookie_crumb = resolved["cookie_crumb"]
3225
+
3226
+ # ABI 3 fields — extension-order policy, PRIORITY-frame suppression,
3227
+ # destination-aware header ordering and the deep TCP fingerprint.
3228
+ opts.extension_permute_mode = resolved["extension_permute_mode"]
3229
+ opts.extension_permute_prefix = resolved["extension_permute_prefix"]
3230
+ opts.h2_disable_priority_frames = resolved["h2_disable_priority_frames"]
3231
+ opts.header_order_by_dest = resolved["header_order_by_dest"]
3232
+ if resolved["header_order_dest"]:
3233
+ c_hod = _c_string(ffi, resolved["header_order_dest"])
3234
+ keep_alive.append(c_hod)
3235
+ opts.header_order_dest = c_hod
3236
+ opts.tcp_dont_fragment = resolved["tcp_dont_fragment"]
3237
+ opts.tcp_tos = resolved["tcp_tos"]
3238
+ opts.tcp_no_delay = resolved["tcp_no_delay"]
3239
+ opts.tcp_window_clamp = resolved["tcp_window_clamp"]
3240
+ if resolved["tcp_ip_id_mode"]:
3241
+ c_ipid = _c_string(ffi, resolved["tcp_ip_id_mode"])
3242
+ keep_alive.append(c_ipid)
3243
+ opts.tcp_ip_id_mode = c_ipid
3244
+
3245
+ opts.timeout_seconds = resolved["timeout_seconds"]
3246
+ opts.timeout_milliseconds = resolved["timeout_milliseconds"]
3247
+ opts.follow_redirects = resolved["follow_redirects"]
3248
+ opts.insecure_skip_verify = resolved["insecure_skip_verify"]
3249
+ opts.force_http1 = resolved["force_http1"]
3250
+ opts.with_random_tls_extension_order = resolved["with_random_tls_extension_order"]
3251
+ opts.with_protocol_racing = resolved["with_protocol_racing"]
3252
+ opts.server_name_overwrite = c_sni
3253
+ opts.request_host_override = c_host_override
3254
+ opts.local_address = c_local_addr
3255
+ opts.max_idle_connections = resolved["max_idle_connections"]
3256
+ opts.max_idle_connections_per_host = resolved["max_idle_connections_per_host"]
3257
+ opts.max_connections_per_host = resolved["max_connections_per_host"]
3258
+ opts.disable_keep_alives = resolved["disable_keep_alives"]
3259
+ opts.disable_compression = resolved["disable_compression"]
3260
+ opts.idle_conn_timeout_seconds = resolved["idle_conn_timeout_seconds"]
3261
+ opts.max_response_header_bytes = resolved["max_response_header_bytes"]
3262
+ opts.write_buffer_size = resolved["write_buffer_size"]
3263
+ opts.read_buffer_size = resolved["read_buffer_size"]
3264
+ opts.allow_empty_cookies = resolved["allow_empty_cookies"]
3265
+ opts.without_cookie_jar = resolved["without_cookie_jar"]
3266
+ opts.disable_http3 = resolved["disable_http3"]
3267
+ opts.disable_ipv4 = resolved["disable_ipv4"]
3268
+ opts.disable_ipv6 = resolved["disable_ipv6"]
3269
+ opts.tcp_ttl = resolved["tcp_ttl"]
3270
+ opts.tcp_window_size = resolved["tcp_window_size"]
3271
+ opts.tcp_window_scale = resolved["tcp_window_scale"]
3272
+ opts.tcp_mss = resolved["tcp_mss"]
3273
+ opts.catch_panics = resolved["catch_panics"]
3274
+ opts.with_debug = resolved["with_debug"]
3275
+
3276
+ # ---- streaming fields (injected by stream_to_file) -----------------
3277
+ stream_path = kwargs.pop("_stream_output_path", ffi.NULL)
3278
+ stream_bs = kwargs.pop("_stream_output_block_size", 0)
3279
+ stream_eof = kwargs.pop("_stream_output_eof_symbol", ffi.NULL)
3280
+ stream_keep = kwargs.pop("_stream_keep_alive", None)
3281
+ if stream_keep is not None:
3282
+ keep_alive.extend(stream_keep)
3283
+ opts.stream_output_path = stream_path
3284
+ opts.stream_output_block_size = stream_bs
3285
+ opts.stream_output_eof_symbol = stream_eof
3286
+
3287
+ # ---- call Go ------------------------------------------------------
3288
+ raw_res = lib.ExecuteRequest(opts)
3289
+
3290
+ if raw_res == ffi.NULL:
3291
+ raise RuntimeError("Go engine returned NULL – likely memory allocation failure")
3292
+
3293
+ raw_res = ffi.gc(raw_res, lib.FreeResponse)
3294
+
3295
+ if raw_res.err_msg != ffi.NULL:
3296
+ err = ffi.string(raw_res.err_msg).decode("utf-8", errors="replace")
3297
+ raise RuntimeError(err)
3298
+
3299
+ return _unpack_c_response(ffi, raw_res)
3300
+
3301
+ def typed_request(self, req: Request) -> Response:
3302
+ """使用 :class:`Request` 强类型对象执行 HTTP 请求。
3303
+
3304
+ Execute an HTTP request using a :class:`Request` strongly-typed object.
3305
+ """
3306
+ method = req["method"]
3307
+ url = req["url"]
3308
+ kwargs = {k: v for k, v in req.items() if k not in ("method", "url")}
3309
+ return self.execute_request(method, url, **kwargs)
3310
+
3311
+ def get(self, url: str, *, headers: Optional[Dict[str, str]] = None, **kwargs: Any) -> Response:
3312
+ return self.request("GET", url, headers=headers, **kwargs)
3313
+
3314
+ def post(self, url: str, *, headers: Optional[Dict[str, str]] = None, body: Optional[bytes] = None, **kwargs: Any) -> Response:
3315
+ if body is not None:
3316
+ kwargs.setdefault("data", body)
3317
+ return self.request("POST", url, headers=headers, **kwargs)
3318
+
3319
+ def head(self, url: str, *, headers: Optional[Dict[str, str]] = None, **kwargs: Any) -> Response:
3320
+ return self.request("HEAD", url, headers=headers, **kwargs)
3321
+
3322
+ def put(self, url: str, *, headers: Optional[Dict[str, str]] = None, body: Optional[bytes] = None, **kwargs: Any) -> Response:
3323
+ if body is not None:
3324
+ kwargs.setdefault("data", body)
3325
+ return self.request("PUT", url, headers=headers, **kwargs)
3326
+
3327
+ def delete(self, url: str, *, headers: Optional[Dict[str, str]] = None, **kwargs: Any) -> Response:
3328
+ return self.request("DELETE", url, headers=headers, **kwargs)
3329
+
3330
+ def patch(self, url: str, *, headers: Optional[Dict[str, str]] = None, body: Optional[bytes] = None, **kwargs: Any) -> Response:
3331
+ if body is not None:
3332
+ kwargs.setdefault("data", body)
3333
+ return self.request("PATCH", url, headers=headers, **kwargs)
3334
+
3335
+ def request(
3336
+ self,
3337
+ method: str,
3338
+ url: str,
3339
+ *,
3340
+ params: Optional[Dict[str, str]] = None,
3341
+ data: Union[bytes, str, Dict[str, str], None] = None,
3342
+ json: Any = None,
3343
+ headers: Optional[Dict[str, str]] = None,
3344
+ auth: Optional[Tuple[str, str]] = None,
3345
+ cookies: Optional[Dict[str, str]] = None,
3346
+ stream: Optional[bool] = None,
3347
+ cert: Optional[Union[str, Tuple[str, str]]] = None,
3348
+ timeout: Optional[int] = None,
3349
+ allow_redirects: Optional[bool] = None,
3350
+ proxies: Optional[Dict[str, str]] = None,
3351
+ verify: Optional[bool] = None,
3352
+ **kwargs: Any,
3353
+ ) -> Response:
3354
+ """``requests`` ????? HTTP ?????
3355
+
3356
+ ``requests``-compatible universal HTTP request method.
3357
+
3358
+ ?? ``params``?``data``?``json``?``auth``?``cookies``?``cert``?
3359
+ ``proxies``?``allow_redirects``?``timeout``?``verify`` ??????
3360
+ ????????? ``execute_request`` ???????
3361
+ """
3362
+ url, body, headers, request_cookies, client_certificates = _prepare_request_compat(
3363
+ get_default=self._get_default,
3364
+ url=url,
3365
+ params=params,
3366
+ data=data,
3367
+ json_data=json,
3368
+ headers=headers,
3369
+ auth=auth,
3370
+ cookies=cookies,
3371
+ stream=stream,
3372
+ cert=cert,
3373
+ timeout=timeout,
3374
+ allow_redirects=allow_redirects,
3375
+ proxies=proxies,
3376
+ verify=verify,
3377
+ kwargs=kwargs,
3378
+ )
3379
+ return self.execute_request(
3380
+ method,
3381
+ url,
3382
+ headers=headers,
3383
+ body=body,
3384
+ request_cookies=request_cookies,
3385
+ client_certificates=client_certificates,
3386
+ **kwargs,
3387
+ )
3388
+
3389
+ def options(self, url: str, **kwargs: Any) -> Response:
3390
+ """发送 HTTP OPTIONS 请求 / Send an HTTP OPTIONS request."""
3391
+ return self.request("OPTIONS", url, **kwargs)
3392
+
3393
+ def close(self) -> None:
3394
+ """关闭会话,释放 Go 客户端池中的空闲连接。
3395
+
3396
+ Close the session and release idle connections in the Go client pool.
3397
+ """
3398
+ self._closed = True
3399
+ _, lib = _get_ffi()
3400
+ lib.ClearClientPool()
3401
+
3402
+ @staticmethod
3403
+ def clear_client_pool() -> None:
3404
+ """Close all idle connections in the global Go client pool."""
3405
+ _, lib = _get_ffi()
3406
+ lib.ClearClientPool()
3407
+
3408
+ @staticmethod
3409
+ def set_pool_ttl(seconds: int) -> None:
3410
+ """Set the TTL for cached HttpClient entries (default 300 s = 5 min).
3411
+
3412
+ Entries not accessed within this duration are evicted by the
3413
+ background scanner. Set to a large value to keep clients longer;
3414
+ set lower for memory-constrained environments.
3415
+ """
3416
+ _, lib = _get_ffi()
3417
+ lib.SetPoolTTL(seconds)
3418
+
3419
+ @staticmethod
3420
+ def set_pool_scan_interval(seconds: int) -> None:
3421
+ """Set the interval for the background eviction scanner (default 60 s).
3422
+
3423
+ Shorter intervals catch stale entries sooner but consume more CPU.
3424
+ """
3425
+ _, lib = _get_ffi()
3426
+ lib.SetPoolScanInterval(seconds)
3427
+
3428
+ @staticmethod
3429
+ def set_pool_max_entries(entries: int) -> None:
3430
+ """Cap the number of cached Go HttpClient entries (default 1024).
3431
+
3432
+ Bounds memory when configurations rotate faster than the TTL
3433
+ evicts them (e.g. a distinct TLS fingerprint per request): once the
3434
+ pool exceeds *entries*, the least-recently-used clients are evicted
3435
+ (losing only idle connections; in-flight requests complete). Pass
3436
+ 0 to disable the cap entirely (unbounded legacy behaviour), or a
3437
+ negative value to restore the default.
3438
+ """
3439
+ _, lib = _get_ffi()
3440
+ setter = getattr(lib, "SetPoolMaxEntries", None)
3441
+ if setter is None:
3442
+ raise RuntimeError(
3443
+ "set_pool_max_entries requires a native tls-client library "
3444
+ "rebuilt from current source (the loaded binary predates the "
3445
+ "SetPoolMaxEntries export; see UPSTREAM_SYNC.md)."
3446
+ )
3447
+ setter(entries)
3448
+
3449
+
3450
+ # ---------------------------------------------------------------------------
3451
+ # Async callback bridge — Go goroutine → Python CFFI callback → asyncio Future
3452
+ # ---------------------------------------------------------------------------
3453
+
3454
+ # Registry of pending async requests.
3455
+ # request_id → (future, keep_alive, timeout_handle, owner)
3456
+ # future – asyncio.Future resolved by the CFFI callback
3457
+ # keep_alive – list of CFFI pointers that must outlive the Go goroutine
3458
+ # timeout_handle – asyncio.Handle; cancelled when callback fires, fires a
3459
+ # defensive cleanup if the Go goroutine never responds
3460
+ # owner – AsyncSession instance that created the request
3461
+ _pending_requests: Dict[int, tuple] = {}
3462
+ _pending_lock = threading.Lock()
3463
+ _request_counter = 0
3464
+ _request_counter_lock = threading.Lock()
3465
+
3466
+
3467
+ def _next_request_id() -> int:
3468
+ global _request_counter
3469
+ with _request_counter_lock:
3470
+ _request_counter += 1
3471
+ return _request_counter
3472
+
3473
+
3474
+ def _apply_future_state(future: "asyncio.Future", is_exc: bool, value: Any) -> None:
3475
+ """Apply set_result/set_exception to *future* on its own loop thread.
3476
+
3477
+ Guarded with done() so racing completions (user cancellation, the
3478
+ zombie timer, AsyncSession.close(), and the Go callback firing after
3479
+ any of them) never raise InvalidStateError inside a loop callback —
3480
+ under high concurrency those races are routine, and an unguarded
3481
+ InvalidStateError would spam the loop's exception handler.
3482
+ """
3483
+ if future.done():
3484
+ return
3485
+ try:
3486
+ if is_exc:
3487
+ future.set_exception(value)
3488
+ else:
3489
+ future.set_result(value)
3490
+ except asyncio.InvalidStateError:
3491
+ pass # cancelled/resolved between the done() check and now
3492
+
3493
+
3494
+ def _apply_future_exception(future: "asyncio.Future", exc: BaseException) -> None:
3495
+ """Fail *future* with *exc* from a possibly non-loop thread."""
3496
+ try:
3497
+ future.get_loop().call_soon_threadsafe(
3498
+ _apply_future_state, future, True, exc
3499
+ )
3500
+ except RuntimeError:
3501
+ pass # event loop already closed — graceful shutdown
3502
+
3503
+
3504
+ def _cancel_timeout_handle(future, timeout_handle) -> None:
3505
+ """Cancel a defensive-timeout Handle safely from any thread.
3506
+
3507
+ ``asyncio.Handle.cancel()`` mutates loop-internal scheduler state (the
3508
+ ``_scheduled`` timer heap) without synchronisation, so calling it from
3509
+ the Go-managed callback thread races the event loop thread. Deferring
3510
+ the cancel through ``call_soon_threadsafe`` runs it on the loop thread,
3511
+ where it is safe. Best-effort by design: when the loop is already
3512
+ closed the timer can never fire anyway — a stray ``_on_zombie_timeout``
3513
+ pops a missing entry and returns — so the ``RuntimeError`` raised by a
3514
+ dead loop is swallowed.
3515
+ """
3516
+ if timeout_handle is None or future is None:
3517
+ return
3518
+ try:
3519
+ future.get_loop().call_soon_threadsafe(timeout_handle.cancel)
3520
+ except RuntimeError:
3521
+ pass # event loop already closed — graceful shutdown
3522
+
3523
+
3524
+ def _drop_pending_request(request_id: int) -> Optional[tuple]:
3525
+ """Pop a pending request entry and cancel its defensive timer.
3526
+
3527
+ Returns the popped entry (or None if the callback already resolved it).
3528
+ Safe to call from any thread.
3529
+ """
3530
+ with _pending_lock:
3531
+ entry = _pending_requests.pop(request_id, None)
3532
+ if entry is not None:
3533
+ _future, _keep_alive, timeout_handle, _owner = entry
3534
+ _cancel_timeout_handle(_future, timeout_handle)
3535
+ return entry
3536
+
3537
+
3538
+ def _defensive_timeout_seconds(timeout_seconds: Any, timeout_milliseconds: Any) -> float:
3539
+ """Bound for the async zombie-cleanup timer.
3540
+
3541
+ Mirrors the Go engine's timeout fallback: timeout_milliseconds > 0
3542
+ wins, else timeout_seconds > 0, else the engine default (30 s — Go
3543
+ maps 0 to tls_client.DefaultTimeoutSeconds, NOT to "no timeout").
3544
+ The defensive timer is 2× the Go timeout + 2 s grace, clamped to
3545
+ [60, 600] seconds.
3546
+ """
3547
+ if timeout_milliseconds and timeout_milliseconds > 0:
3548
+ go_timeout = timeout_milliseconds / 1000.0
3549
+ elif timeout_seconds and timeout_seconds > 0:
3550
+ go_timeout = float(timeout_seconds)
3551
+ else:
3552
+ go_timeout = 30.0
3553
+ return max(60.0, min(go_timeout * 2.0 + 2.0, 600.0))
3554
+
3555
+
3556
+ def _on_zombie_timeout(request_id: int, safe_timeout: float) -> None:
3557
+ """Defensive cleanup when the Go goroutine never fires the callback.
3558
+
3559
+ Runs on the event loop thread. If the callback already completed the
3560
+ request, the entry is gone and this is a no-op. Otherwise the entry
3561
+ (future + keep_alive C pointers) would leak forever, so it is dropped
3562
+ and the future is failed with a TimeoutError. Releasing keep_alive is
3563
+ safe here even if the goroutine is still hung: RequestAsync deep-copies
3564
+ all C data into the Go heap before returning, so the goroutine never
3565
+ reads the Python-owned buffers again.
3566
+ """
3567
+ with _pending_lock:
3568
+ entry = _pending_requests.pop(request_id, None)
3569
+ if entry is None:
3570
+ return # already resolved via callback
3571
+ future, _keep_alive, timeout_handle, _owner = entry
3572
+ if timeout_handle is not None:
3573
+ timeout_handle.cancel()
3574
+ _apply_future_exception(
3575
+ future,
3576
+ asyncio.TimeoutError(
3577
+ f"Async request {request_id} did not complete within "
3578
+ f"{safe_timeout:.0f}s — Go goroutine may be hung"
3579
+ ),
3580
+ )
3581
+
3582
+
3583
+ def _resolve_async_response(ffi, future, raw_gc):
3584
+ """Unpack C response and resolve future ON THE EVENT LOOP THREAD.
3585
+
3586
+ Called via loop.call_soon_threadsafe from the CFFI callback bridge.
3587
+ By deferring all ffi.string / ffi.buffer / .decode() operations to the
3588
+ event loop thread, the Go OS thread callback releases the GIL in
3589
+ microseconds instead of milliseconds — eliminating GIL contention at
3590
+ high concurrency (>10K req/s).
3591
+
3592
+ C memory is kept alive by ffi.gc(raw_res, lib.FreeResponse) until
3593
+ this function completes and the reference to raw_gc is dropped.
3594
+ """
3595
+ try:
3596
+ if not future.done():
3597
+ if raw_gc.err_msg != ffi.NULL:
3598
+ err = ffi.string(raw_gc.err_msg).decode("utf-8", errors="replace")
3599
+ future.set_exception(RuntimeError(err))
3600
+ else:
3601
+ response = _unpack_c_response(ffi, raw_gc)
3602
+ future.set_result(response)
3603
+ except BaseException as exc:
3604
+ if not future.done():
3605
+ future.set_exception(exc)
3606
+
3607
+
3608
+ def _make_async_callback(ffi, lib):
3609
+ """Create a CFFI callback that Go goroutines invoke with results.
3610
+
3611
+ The callback is called from a Go-managed OS thread (not the Python main
3612
+ thread). CFFI internally calls PyGILState_Ensure to safely acquire the
3613
+ GIL before entering Python code.
3614
+
3615
+ Lifecycle (per the 9-step user blueprint):
3616
+ 1. Python calls RequestAsync → Go deep-copies → returns immediately
3617
+ 2. Go goroutine executes HTTP request
3618
+ 3. Go allocates CResponseResult on C heap via C.malloc
3619
+ 4. Go calls this callback with (request_id, CResponseResult*)
3620
+ 5. Python unpacks CResponseResult → Response object
3621
+ 6. Python calls FreeResponse to release C memory
3622
+ 7. Python uses loop.call_soon_threadsafe to resolve the Future
3623
+ """
3624
+
3625
+ @ffi.callback("void(uintptr_t, ResponseResult*)")
3626
+ def _on_async_response(request_id: int, raw_res: Any) -> None:
3627
+ # This callback executes on a Go-managed OS thread. If any Python
3628
+ # exception escapes uncaught, the Python interpreter crashes with
3629
+ # Fatal Python error: Segmentation fault.
3630
+ #
3631
+ # GIL OPTIMIZATION: Instead of doing expensive ffi.string / ffi.buffer
3632
+ # / .decode() work here (which holds the GIL for milliseconds), we
3633
+ # immediately wrap raw_res with ffi.gc (keeping C memory alive) and
3634
+ # defer ALL unpacking to the event loop thread via call_soon_threadsafe.
3635
+ # The callback releases the GIL in microseconds, eliminating GIL
3636
+ # contention at high concurrency (>10K req/s).
3637
+ gc_bound = False # track whether ffi.gc was called — see except handler
3638
+ try:
3639
+ # Phase 1: Pop _pending_requests & cancel defensive timeout.
3640
+ with _pending_lock:
3641
+ future, _keep_alive, timeout_handle, _owner = _pending_requests.pop(
3642
+ request_id, (None, None, None, None)
3643
+ )
3644
+ # _keep_alive is now released – the goroutine has finished.
3645
+
3646
+ # Cancel the defensive timer on the loop thread: this callback
3647
+ # runs on a Go-managed OS thread, and Handle.cancel() is not
3648
+ # thread-safe against a running event loop.
3649
+ _cancel_timeout_handle(future, timeout_handle)
3650
+
3651
+ if future is None or future.done():
3652
+ # Already resolved or timed out. Free C memory and exit.
3653
+ if raw_res != ffi.NULL:
3654
+ lib.FreeResponse(raw_res)
3655
+ return
3656
+
3657
+ # Handle NULL result synchronously (no C memory to manage).
3658
+ if raw_res == ffi.NULL:
3659
+ _apply_future_exception(
3660
+ future, RuntimeError("Go engine returned NULL")
3661
+ )
3662
+ return
3663
+
3664
+ # Phase 2: Defer unpacking to event loop thread.
3665
+ # ffi.gc binds FreeResponse to the Python GC — the C memory
3666
+ # stays alive until _resolve_async_response drops raw_gc.
3667
+ raw_gc = ffi.gc(raw_res, lib.FreeResponse)
3668
+ gc_bound = True
3669
+ loop = future.get_loop()
3670
+ loop.call_soon_threadsafe(_resolve_async_response, ffi, future, raw_gc)
3671
+
3672
+ except BaseException:
3673
+ # Log swallowed exception for diagnostics before cleaning up.
3674
+ import traceback as _tb
3675
+ print("[tls-client] async callback suppressed exception:", file=sys.stderr)
3676
+ _tb.print_exc(file=sys.stderr)
3677
+ # Absolute last resort: free C memory, then swallow.
3678
+ # If ffi.gc already bound FreeResponse, release the GC binding
3679
+ # via ffi.release() to prevent double-free when raw_gc is
3680
+ # garbage-collected later (call_soon_threadsafe may raise if
3681
+ # the event loop has already been closed).
3682
+ if raw_res != ffi.NULL:
3683
+ try:
3684
+ if gc_bound:
3685
+ ffi.release(raw_gc)
3686
+ lib.FreeResponse(raw_res)
3687
+ except BaseException:
3688
+ pass
3689
+
3690
+ return _on_async_response
3691
+
3692
+
3693
+ # Lazy-initialised callback — must be created after ffi is loaded and kept alive.
3694
+ # Protected by a lock to prevent race conditions when multiple AsyncSession
3695
+ # instances are created concurrently from different threads.
3696
+ _async_callback = None
3697
+ _async_callback_lock = threading.Lock()
3698
+
3699
+
3700
+ def _get_async_callback(ffi, lib):
3701
+ """Return the singleton CFFI callback, creating it once under lock.
3702
+
3703
+ Always acquires _async_callback_lock — double‑checked locking is unsafe
3704
+ under free‑threaded Python (PEP 703) because _async_callback may be
3705
+ partially visible without a synchronisation edge. Contention is
3706
+ negligible: the callback is created once and cached thereafter.
3707
+ """
3708
+ global _async_callback
3709
+ with _async_callback_lock:
3710
+ if _async_callback is None:
3711
+ _async_callback = _make_async_callback(ffi, lib)
3712
+ return _async_callback
3713
+
3714
+
3715
+ # ---------------------------------------------------------------------------
3716
+ # Fork safety — ProcessPoolExecutor("fork") / os.fork() interop
3717
+ # ---------------------------------------------------------------------------
3718
+
3719
+ def _after_fork_in_child() -> None:
3720
+ """Reinitialise cross-thread state in a forked child (Unix only).
3721
+
3722
+ Runs via ``os.register_at_fork`` in the child, before ``os.fork()``
3723
+ returns:
3724
+
3725
+ (a) Every module-level lock is replaced with a fresh, unlocked one — a
3726
+ lock held by another thread at fork time is inherited in the locked
3727
+ state, and the owning thread does not exist in the child, so the
3728
+ first acquire would deadlock forever.
3729
+ (b) The pending-async registry is dropped: its futures, timers and
3730
+ event loops belong to the parent process.
3731
+ (c) If the Go library was already loaded, ``_forked_after_load`` is set
3732
+ so ``_get_ffi()`` fails fast with guidance instead of deadlocking on
3733
+ Go-internal locks held by threads that no longer exist.
3734
+ """
3735
+ global _forked_after_load
3736
+ global _ffi, _ffi_lock, _pending_lock, _request_counter_lock, _async_callback_lock
3737
+ global _pending_requests, _async_callback
3738
+
3739
+ if _lib is None:
3740
+ # Library not yet loaded in the parent — the child may lazily load a
3741
+ # fresh Go runtime. Reset _ffi in case a fork landed mid-assignment
3742
+ # (only the forking thread survives, so no loader is running here).
3743
+ _ffi = None
3744
+ _forked_after_load = False
3745
+ else:
3746
+ _forked_after_load = True
3747
+
3748
+ _ffi_lock = threading.Lock()
3749
+ _pending_lock = threading.Lock()
3750
+ _request_counter_lock = threading.Lock()
3751
+ _async_callback_lock = threading.Lock()
3752
+ _pending_requests = {}
3753
+ _async_callback = None
3754
+
3755
+
3756
+ if hasattr(os, "register_at_fork"):
3757
+ os.register_at_fork(after_in_child=_after_fork_in_child)
3758
+
3759
+
3760
+ class AsyncSession:
3761
+ """True async HTTP client — no thread pool, no blocking.
3762
+
3763
+ Uses Go goroutines + CFFI callbacks + asyncio Future:
3764
+ - Python calls RequestAsync (returns instantly after Go deep-copies)
3765
+ - Go goroutine executes HTTP I/O in the background
3766
+ - Go invokes CFFI callback when done
3767
+ - Python resolves asyncio.Future via call_soon_threadsafe
3768
+
3769
+ Compatible with uvloop / winloop for maximum event-loop performance.
3770
+ """
3771
+
3772
+ def __init__(
3773
+ self,
3774
+ *,
3775
+ # ── 指纹 / 协议 ── / Fingerprint / Protocol ──
3776
+ # TLS 指纹标识 / TLS fingerprint identifier
3777
+ client_identifier: ClientIdentifiers = "chrome_120",
3778
+ # 强制使用 HTTP/1.1 / Force HTTP/1.1
3779
+ force_http1: bool = False,
3780
+ # 完全禁用 HTTP/3(QUIC) / Completely disable HTTP/3 (QUIC)
3781
+ disable_http3: bool = False,
3782
+ # 启用协议竞速 / Enable protocol racing
3783
+ with_protocol_racing: bool = False,
3784
+ # 随机打乱 TLS 扩展的发送顺序 / Randomize TLS extension send order
3785
+ random_tls_extension_order: bool = True,
3786
+ # ── 超时 / 重定向 ── / Timeout / Redirect ──
3787
+ # 请求整体超时时间(秒) / Total request timeout in seconds
3788
+ timeout: int = 30,
3789
+ # 请求超时时间(毫秒) / Request timeout in milliseconds
3790
+ timeout_milliseconds: int = 0,
3791
+ # 是否自动跟随 HTTP 重定向 / Whether to automatically follow HTTP redirects
3792
+ follow_redirects: bool = False,
3793
+ # ── TLS / 证书 ── / TLS / Cert ──
3794
+ # 是否验证服务端 TLS 证书 / Whether to verify the server TLS certificate
3795
+ verify: bool = True,
3796
+ # 自定义 SNI / Custom SNI
3797
+ server_name_overwrite: Optional[str] = None,
3798
+ # ── 代理 ── / Proxy ──
3799
+ # 代理 URL / Proxy URL
3800
+ proxy: Optional[ProxyConfig] = None,
3801
+ # requests 风格代理字典 / requests-style proxies mapping
3802
+ proxies: Optional[ProxyConfig] = None,
3803
+ # 绑定到指定的本地 IP 地址 / Bind to a specific local IP address
3804
+ local_address: Optional[str] = None,
3805
+ # ── 请求头控制 ── / Header Control ──
3806
+ # 覆盖 HTTP Host 请求头 / Override the HTTP Host header
3807
+ request_host_override: Optional[str] = None,
3808
+ # HTTP/2 伪头发送顺序 / HTTP/2 pseudo-header send order
3809
+ pseudo_header_order: Optional[List[str]] = None,
3810
+ # HTTP/3 伪头的发送顺序 / HTTP/3 pseudo-header send order
3811
+ h3_pseudo_header_order: Optional[List[str]] = None,
3812
+ # 默认请求头字典 / Default headers dict
3813
+ default_headers: Optional[Dict[str, str]] = None,
3814
+ # 默认请求头字典(别名)/ Default headers dict alias
3815
+ headers: Optional[Dict[str, str]] = None,
3816
+ # 代理 CONNECT 隧道请求头字典 / Proxy CONNECT tunnel headers dict
3817
+ connect_headers: Optional[Dict[str, str]] = None,
3818
+ # ── 证书固定 ── / Certificate Pinning ──
3819
+ # SSL 证书固定字典 / SSL certificate pinning dict
3820
+ certificate_pinning_hosts: Optional[Dict[str, List[str]]] = None,
3821
+ # 是否调用默认 Bad-Pin 处理器 / Whether to invoke the default bad-pin handler
3822
+ with_default_bad_pin_handler: bool = False,
3823
+ # ── Cookie ──
3824
+ # 预置 Cookie 字典 / Pre-populated cookie dict
3825
+ request_cookies: Optional[Dict[str, str]] = None,
3826
+ # 预置 Cookie 字典(别名)/ Pre-populated cookie dict alias
3827
+ cookies: Optional[Dict[str, str]] = None,
3828
+ # ── 自定义 TLS ── / Custom TLS ──
3829
+ # 完全自定义的 TLS 客户端配置 (26 fields) / Fully custom TLS client configuration
3830
+ custom_tls_client: Optional[Dict[str, Any]] = None,
3831
+ # 客户端证书 (mTLS) / Client certificates for mTLS
3832
+ client_certificates: Optional[List[Dict[str, bytes]]] = None,
3833
+ # ── 连接池调优 ── / Connection Pool Tuning ──
3834
+ # 全局最大空闲连接数 / Global max idle connections
3835
+ max_idle_connections: int = 0,
3836
+ # 每个 Host 的最大空闲连接数 / Max idle connections per host
3837
+ max_idle_connections_per_host: int = 0,
3838
+ # 每个 Host 的最大总连接数 / Max total connections per host
3839
+ max_connections_per_host: int = 0,
3840
+ # 禁用 HTTP Keep-Alive / Disable HTTP Keep-Alive
3841
+ disable_keep_alives: bool = False,
3842
+ # 禁用响应体自动解压 / Disable automatic response body decompression
3843
+ disable_compression: bool = False,
3844
+ # 空闲连接的最大保持时间(秒) / Max idle time for keep-alive connections
3845
+ idle_conn_timeout_seconds: int = 0,
3846
+ # HTTP 响应头的最大字节数限制 / Max response header bytes limit
3847
+ max_response_header_bytes: int = 0,
3848
+ # Socket 写缓冲区大小(字节) / Socket write buffer size (bytes)
3849
+ write_buffer_size: int = 0,
3850
+ # Socket 读缓冲区大小(字节) / Socket read buffer size (bytes)
3851
+ read_buffer_size: int = 0,
3852
+ # ── IP 协议栈控制 ── / IP Stack Control ──
3853
+ # 禁用 IPv4 / Disable IPv4
3854
+ disable_ipv4: bool = False,
3855
+ # 禁用 IPv6 / Disable IPv6
3856
+ disable_ipv6: bool = False,
3857
+ # ── TCP/IP Fingerprint ──
3858
+ # IP TTL (Time To Live). Windows=128, Linux/macOS=64. 0=auto from profile
3859
+ tcp_ttl: int = 0,
3860
+ # TCP receive window size. Windows=64240, Linux/macOS=65535. 0=auto
3861
+ tcp_window_size: int = 0,
3862
+ # TCP window scale factor. Windows=8, Linux=7, macOS=6. 0=auto
3863
+ tcp_window_scale: int = 0,
3864
+ # TCP Maximum Segment Size. Standard Ethernet=1460. 0=auto
3865
+ tcp_mss: int = 0,
3866
+ # ── Cookie ──
3867
+ # 是否允许空 Cookie / Whether to allow empty-value cookies
3868
+ allow_empty_cookies: bool = False,
3869
+ # 完全禁用 Cookie Jar / Completely disable Cookie Jar
3870
+ without_cookie_jar: bool = False,
3871
+ # ── requests 兼容属性 ── / requests-compatible properties ──
3872
+ # HTTP 认证元组 (username, password) / HTTP auth tuple
3873
+ auth: Optional[Tuple[str, str]] = None,
3874
+ # 查询字符串参数字典 / Query-string parameter dict
3875
+ params: Optional[Dict[str, str]] = None,
3876
+ # 客户端 SSL 证书路径 / Client SSL cert path
3877
+ cert: Optional[Union[str, Tuple[str, str]]] = None,
3878
+ # 是否流式读取响应体 / Whether to stream the response body
3879
+ stream: bool = False,
3880
+ # ── 调试 / 安全 ── / Debug / Safety ──
3881
+ # 是否在 Go 侧捕获 panic / Whether to catch Go panics
3882
+ catch_panics: bool = True,
3883
+ # 启用调试日志输出 / Enable debug log output
3884
+ with_debug: bool = False,
3885
+ # 禁用 TLS session tickets / Disable TLS session tickets (ABI 2)
3886
+ disable_session_tickets: bool = False,
3887
+ # TLS keylog 文件路径 / TLS keylog path (ABI 2)
3888
+ tls_keylog_path: Optional[str] = None,
3889
+ # 自定义 CA PEM 内容 / Custom CA PEM bytes (ABI 2)
3890
+ root_ca_pem: Optional[bytes] = None,
3891
+ # HTTP/2 DATA 帧上限 (ABI 2.1) / Cap per-DATA-frame payload
3892
+ h2_max_data_frame_size: int = 0,
3893
+ # 空闲 H2 连接 PING 阈值毫秒 (ABI 2.1) / Preface-ping idle threshold ms
3894
+ preface_ping_idle_ms: int = 0,
3895
+ # HPACK 索引策略 ("chrome") (ABI 2.1) / HPACK indexing policy
3896
+ hpack_indexing_policy: str = "",
3897
+ # Cookie 按对拆分 (ABI 2.1) / Split Cookie header per cookie-pair
3898
+ cookie_crumb: bool = False,
3899
+ # ── ABI 3 — 细粒度指纹控制 / fine-grained fingerprint control ──
3900
+ # 扩展乱序策略: 0=off, 1=chrome, 2=all, 3=prefix (ABI 3)
3901
+ # Extension-order permutation policy (per-handshake, Chromium-style)
3902
+ extension_permute_mode: int = 0,
3903
+ # 前缀长度(仅 mode=3): 前 N 个扩展保持原位不乱序 / prefix length
3904
+ extension_permute_prefix: int = 0,
3905
+ # 抑制 HTTP/2 PRIORITY 帧与 HEADERS 优先级标志 (ABI 3)
3906
+ # Suppress RFC 7540 PRIORITY frames / HEADERS priority flag
3907
+ h2_disable_priority_frames: bool = False,
3908
+ # 按 Sec-Fetch-Dest 选择浏览器真实头序 (ABI 3)
3909
+ # Derive the header order from Sec-Fetch-Dest instead of header_order
3910
+ header_order_by_dest: bool = False,
3911
+ # 显式指定目的类型(留空则由请求头推断)/ Explicit Sec-Fetch-Dest value
3912
+ header_order_dest: Optional[str] = None,
3913
+ # 深度 TCP 指纹: DF 位 / TOS / Nagle / 窗口钳制 / IP ID 模式 (ABI 3)
3914
+ # -1/None 表示沿用指纹预设值 / -1 or None keeps the profile default
3915
+ tcp_dont_fragment: int = -1,
3916
+ tcp_tos: int = -1,
3917
+ tcp_no_delay: int = -1,
3918
+ tcp_window_clamp: int = 0,
3919
+ tcp_ip_id_mode: str = "",
3920
+ # 指纹预设名 / Fingerprint preset name (tls_client.fingerprints)
3921
+ fingerprint: Optional[str] = None,
3922
+ ) -> None:
3923
+ if client_identifier not in SUPPORTED_CLIENT_IDENTIFIERS:
3924
+ raise ValueError("unsupported client_identifier %r" % client_identifier)
3925
+ self._session = Session(
3926
+ client_identifier=client_identifier,
3927
+ force_http1=force_http1,
3928
+ disable_http3=disable_http3,
3929
+ with_protocol_racing=with_protocol_racing,
3930
+ random_tls_extension_order=random_tls_extension_order,
3931
+ timeout=timeout,
3932
+ timeout_milliseconds=timeout_milliseconds,
3933
+ follow_redirects=follow_redirects,
3934
+ verify=verify,
3935
+ server_name_overwrite=server_name_overwrite,
3936
+ proxy=proxy,
3937
+ proxies=proxies,
3938
+ local_address=local_address,
3939
+ request_host_override=request_host_override,
3940
+ pseudo_header_order=pseudo_header_order,
3941
+ h3_pseudo_header_order=h3_pseudo_header_order,
3942
+ default_headers=default_headers,
3943
+ headers=headers,
3944
+ connect_headers=connect_headers,
3945
+ certificate_pinning_hosts=certificate_pinning_hosts,
3946
+ with_default_bad_pin_handler=with_default_bad_pin_handler,
3947
+ request_cookies=request_cookies,
3948
+ cookies=cookies,
3949
+ custom_tls_client=custom_tls_client,
3950
+ client_certificates=client_certificates,
3951
+ max_idle_connections=max_idle_connections,
3952
+ max_idle_connections_per_host=max_idle_connections_per_host,
3953
+ max_connections_per_host=max_connections_per_host,
3954
+ disable_keep_alives=disable_keep_alives,
3955
+ disable_compression=disable_compression,
3956
+ idle_conn_timeout_seconds=idle_conn_timeout_seconds,
3957
+ max_response_header_bytes=max_response_header_bytes,
3958
+ write_buffer_size=write_buffer_size,
3959
+ read_buffer_size=read_buffer_size,
3960
+ disable_ipv4=disable_ipv4,
3961
+ disable_ipv6=disable_ipv6,
3962
+ tcp_ttl=tcp_ttl,
3963
+ tcp_window_size=tcp_window_size,
3964
+ tcp_window_scale=tcp_window_scale,
3965
+ tcp_mss=tcp_mss,
3966
+ allow_empty_cookies=allow_empty_cookies,
3967
+ without_cookie_jar=without_cookie_jar,
3968
+ auth=auth,
3969
+ params=params,
3970
+ cert=cert,
3971
+ stream=stream,
3972
+ catch_panics=catch_panics,
3973
+ with_debug=with_debug,
3974
+ disable_session_tickets=disable_session_tickets,
3975
+ tls_keylog_path=tls_keylog_path,
3976
+ root_ca_pem=root_ca_pem,
3977
+ h2_max_data_frame_size=h2_max_data_frame_size,
3978
+ preface_ping_idle_ms=preface_ping_idle_ms,
3979
+ hpack_indexing_policy=hpack_indexing_policy,
3980
+ cookie_crumb=cookie_crumb,
3981
+ extension_permute_mode=extension_permute_mode,
3982
+ extension_permute_prefix=extension_permute_prefix,
3983
+ h2_disable_priority_frames=h2_disable_priority_frames,
3984
+ header_order_by_dest=header_order_by_dest,
3985
+ header_order_dest=header_order_dest,
3986
+ tcp_dont_fragment=tcp_dont_fragment,
3987
+ tcp_tos=tcp_tos,
3988
+ tcp_no_delay=tcp_no_delay,
3989
+ tcp_window_clamp=tcp_window_clamp,
3990
+ tcp_ip_id_mode=tcp_ip_id_mode,
3991
+ fingerprint=fingerprint,
3992
+ )
3993
+
3994
+ # -- attribute delegation → underlying Session ------------------------
3995
+ # Allows: async_session.headers = {...}
3996
+ # async_session.proxy = "http://..."
3997
+ # async_session.cookies = {...}
3998
+ # All readable/writable Session properties are transparently delegated.
3999
+
4000
+ def __getattr__(self, name: str) -> Any:
4001
+ # Delegate non-private attribute access to the underlying Session.
4002
+ if name.startswith("_"):
4003
+ raise AttributeError(name)
4004
+ return getattr(self._session, name)
4005
+
4006
+ def __setattr__(self, name: str, value: Any) -> None:
4007
+ # Delegate non-private attribute writes to the underlying Session.
4008
+ if name.startswith("_"):
4009
+ super().__setattr__(name, value)
4010
+ else:
4011
+ setattr(self._session, name, value)
4012
+
4013
+ async def __aenter__(self) -> "AsyncSession":
4014
+ return self
4015
+
4016
+ async def __aexit__(self, *args: Any) -> None:
4017
+ pass
4018
+
4019
+ async def _execute_async(self, method: str, url: str, **kwargs: Any) -> Response:
4020
+ if self._session._closed:
4021
+ raise RuntimeError("AsyncSession is closed")
4022
+ ffi, lib = _get_ffi()
4023
+ callback = _get_async_callback(ffi, lib)
4024
+ get_running_loop = getattr(asyncio, "get_running_loop", asyncio.get_event_loop)
4025
+ loop = get_running_loop()
4026
+ defaults = self._session._snapshot_selected_defaults(ASYNC_REQUEST_DEFAULT_KEYS)
4027
+ effective_proxy = _resolve_proxy_url(
4028
+ kwargs.get("proxy", defaults.get("proxy")),
4029
+ url,
4030
+ )
4031
+
4032
+ # Build RequestOptions (same as sync path)
4033
+ keep_alive: list = []
4034
+ opts = ffi.new("RequestOptions *")
4035
+ keep_alive.append(opts)
4036
+
4037
+ c_method = ffi.new("char[]", method.encode("utf-8"))
4038
+ c_url = ffi.new("char[]", url.encode("utf-8"))
4039
+ keep_alive.extend([c_method, c_url])
4040
+ opts.method = c_method
4041
+ opts.url = c_url
4042
+
4043
+ # Headers (built after the defaults are resolved — see the
4044
+ # _merge_default_headers call below)
4045
+ headers = kwargs.pop("headers", None)
4046
+ header_order = kwargs.pop("header_order", None)
4047
+ context = kwargs.pop("context", None)
4048
+
4049
+ # Body (zero-copy — ffi.from_buffer avoids copying Python bytes to C heap)
4050
+ body = kwargs.pop("body", None)
4051
+ if body is not None:
4052
+ body_ptr = ffi.from_buffer(body)
4053
+ keep_alive.append(body_ptr)
4054
+ opts.body = body_ptr
4055
+ opts.body_len = len(body)
4056
+
4057
+ # Overrides (use defaults from the session, overridden by kwargs)
4058
+ explicit_default_headers = kwargs.get("default_headers")
4059
+
4060
+ def _val(name: str, as_bool: bool = False):
4061
+ if name == "proxy":
4062
+ kwargs.pop(name, None)
4063
+ v = effective_proxy
4064
+ else:
4065
+ v = kwargs.pop(name, None)
4066
+ if v is None:
4067
+ v = defaults.get(name)
4068
+ if as_bool:
4069
+ return 1 if v else 0
4070
+ return v
4071
+
4072
+ resolved = {
4073
+ "client_identifier": _val("client_identifier"),
4074
+ "proxy": _val("proxy"),
4075
+ "server_name_overwrite": _val("server_name_overwrite"),
4076
+ "request_host_override": _val("request_host_override"),
4077
+ "local_address": _val("local_address"),
4078
+ "pseudo_header_order": _val("pseudo_header_order"),
4079
+ "h3_pseudo_header_order": _val("h3_pseudo_header_order"),
4080
+ "default_headers": _val("default_headers"),
4081
+ "connect_headers": _val("connect_headers"),
4082
+ "certificate_pinning_hosts": _val("certificate_pinning_hosts"),
4083
+ "request_cookies": _val("request_cookies"),
4084
+ "client_certificates": _val("client_certificates"),
4085
+ "custom_tls_client": _val("custom_tls_client"),
4086
+ "timeout_seconds": _val("timeout_seconds"),
4087
+ "timeout_milliseconds": _val("timeout_milliseconds"),
4088
+ "follow_redirects": _val("follow_redirects", True),
4089
+ "insecure_skip_verify": _val("insecure_skip_verify", True),
4090
+ "force_http1": _val("force_http1", True),
4091
+ "with_random_tls_extension_order": _val(
4092
+ "with_random_tls_extension_order", True
4093
+ ),
4094
+ "with_protocol_racing": _val("with_protocol_racing", True),
4095
+ "max_idle_connections": _val("max_idle_connections"),
4096
+ "max_idle_connections_per_host": _val("max_idle_connections_per_host"),
4097
+ "max_connections_per_host": _val("max_connections_per_host"),
4098
+ "max_response_header_bytes": _val("max_response_header_bytes"),
4099
+ "write_buffer_size": _val("write_buffer_size"),
4100
+ "read_buffer_size": _val("read_buffer_size"),
4101
+ "idle_conn_timeout_seconds": _val("idle_conn_timeout_seconds"),
4102
+ "disable_keep_alives": _val("disable_keep_alives", True),
4103
+ "disable_compression": _val("disable_compression", True),
4104
+ "disable_http3": _val("disable_http3", True),
4105
+ "disable_ipv4": _val("disable_ipv4", True),
4106
+ "disable_ipv6": _val("disable_ipv6", True),
4107
+ "without_cookie_jar": _val("without_cookie_jar", True),
4108
+ "allow_empty_cookies": _val("allow_empty_cookies", True),
4109
+ "with_default_bad_pin_handler": _val(
4110
+ "with_default_bad_pin_handler", True
4111
+ ),
4112
+ "catch_panics": _val("catch_panics", True),
4113
+ "with_debug": _val("with_debug", True),
4114
+ "disable_session_tickets": _val("disable_session_tickets", True),
4115
+ "tls_keylog_path": _val("tls_keylog_path"),
4116
+ "root_ca_pem": _val("root_ca_pem"),
4117
+ "h2_max_data_frame_size": _val("h2_max_data_frame_size"),
4118
+ "preface_ping_idle_ms": _val("preface_ping_idle_ms"),
4119
+ "hpack_indexing_policy": _val("hpack_indexing_policy"),
4120
+ "cookie_crumb": _val("cookie_crumb", True),
4121
+ "tcp_ttl": _val("tcp_ttl"),
4122
+ "tcp_window_size": _val("tcp_window_size"),
4123
+ "tcp_window_scale": _val("tcp_window_scale"),
4124
+ "tcp_mss": _val("tcp_mss"),
4125
+ # ── ABI 3 — 细粒度指纹控制 / fine-grained fingerprint control ──
4126
+ "extension_permute_mode": _val("extension_permute_mode"),
4127
+ "extension_permute_prefix": _val("extension_permute_prefix"),
4128
+ "h2_disable_priority_frames": _val("h2_disable_priority_frames", True),
4129
+ "header_order_by_dest": _val("header_order_by_dest", True),
4130
+ "header_order_dest": _val("header_order_dest"),
4131
+ "tcp_dont_fragment": _val("tcp_dont_fragment"),
4132
+ "tcp_tos": _val("tcp_tos"),
4133
+ "tcp_no_delay": _val("tcp_no_delay"),
4134
+ "tcp_window_clamp": _val("tcp_window_clamp"),
4135
+ "tcp_ip_id_mode": _val("tcp_ip_id_mode"),
4136
+ }
4137
+ _normalize_int_fields(resolved)
4138
+
4139
+ # ABI 2 features need the rebuilt shared library.
4140
+ if (resolved["disable_session_tickets"] or resolved["tls_keylog_path"]
4141
+ or resolved["root_ca_pem"]):
4142
+ _require_abi2()
4143
+ # ABI 3 deep-fingerprint knobs. Unlike the ABI 2 gate (which raises),
4144
+ # these degrade: a preset or an implicit default may enable them on a
4145
+ # library that predates ABI 3, and failing the whole request would be
4146
+ # worse than dropping the refinement. Explicit caller intent is
4147
+ # reported through the warning instead.
4148
+ _degrade_abi3_fields(resolved)
4149
+
4150
+ # Per-request client_identifier override: pair the request with the
4151
+ # profile's default headers unless the caller manages headers
4152
+ # explicitly (see the sync path in Session.execute_request).
4153
+ if (
4154
+ explicit_default_headers is None
4155
+ and not self._session._headers_customized
4156
+ and resolved["client_identifier"] != self._session.defaults.get("client_identifier")
4157
+ ):
4158
+ resolved["default_headers"] = _clone_default_value(
4159
+ DEFAULT_HEADERS.get(resolved["client_identifier"])
4160
+ )
4161
+
4162
+ # Fold the profile default headers into the per-request headers
4163
+ # (see _merge_default_headers — Go drops client-level defaults
4164
+ # whenever request headers are present).
4165
+ merged_headers, merged_order = _merge_default_headers(
4166
+ resolved["default_headers"], headers, header_order
4167
+ )
4168
+ if context is not None:
4169
+ merged_headers, merged_order = _apply_request_context(
4170
+ self._session, merged_headers, merged_order, context,
4171
+ resolved["client_identifier"], headers,
4172
+ )
4173
+ hdr_ptr, hdr_len = _build_headers(ffi, merged_headers, keep_alive)
4174
+ opts.headers = hdr_ptr
4175
+ opts.headers_len = hdr_len
4176
+ ho_ptr, ho_len = _build_string_array(ffi, merged_order, keep_alive)
4177
+ opts.header_order = ho_ptr
4178
+ opts.header_order_len = ho_len
4179
+
4180
+ ck_hash = _compute_cache_key_hash(resolved)
4181
+ c_ck = _c_string(ffi, ck_hash)
4182
+ if c_ck != ffi.NULL:
4183
+ keep_alive.append(c_ck)
4184
+ opts.cache_key_hash = c_ck
4185
+
4186
+ # ABI 2 fields
4187
+ opts.disable_session_tickets = resolved["disable_session_tickets"]
4188
+ if resolved["tls_keylog_path"]:
4189
+ c_keylog = _c_string(ffi, resolved["tls_keylog_path"])
4190
+ keep_alive.append(c_keylog)
4191
+ opts.tls_keylog_path = c_keylog
4192
+ if resolved["root_ca_pem"]:
4193
+ rc_ptr = ffi.from_buffer(resolved["root_ca_pem"])
4194
+ keep_alive.append(rc_ptr)
4195
+ opts.root_ca_pem = rc_ptr
4196
+ opts.root_ca_pem_len = len(resolved["root_ca_pem"])
4197
+ opts.h2_max_data_frame_size = resolved["h2_max_data_frame_size"]
4198
+ opts.preface_ping_idle_ms = resolved["preface_ping_idle_ms"]
4199
+ if resolved["hpack_indexing_policy"]:
4200
+ c_hip = _c_string(ffi, resolved["hpack_indexing_policy"])
4201
+ keep_alive.append(c_hip)
4202
+ opts.hpack_indexing_policy = c_hip
4203
+ opts.cookie_crumb = resolved["cookie_crumb"]
4204
+
4205
+ # ABI 3 fields — extension-order policy, PRIORITY-frame suppression,
4206
+ # destination-aware header ordering and the deep TCP fingerprint.
4207
+ opts.extension_permute_mode = resolved["extension_permute_mode"]
4208
+ opts.extension_permute_prefix = resolved["extension_permute_prefix"]
4209
+ opts.h2_disable_priority_frames = resolved["h2_disable_priority_frames"]
4210
+ opts.header_order_by_dest = resolved["header_order_by_dest"]
4211
+ if resolved["header_order_dest"]:
4212
+ c_hod = _c_string(ffi, resolved["header_order_dest"])
4213
+ keep_alive.append(c_hod)
4214
+ opts.header_order_dest = c_hod
4215
+ opts.tcp_dont_fragment = resolved["tcp_dont_fragment"]
4216
+ opts.tcp_tos = resolved["tcp_tos"]
4217
+ opts.tcp_no_delay = resolved["tcp_no_delay"]
4218
+ opts.tcp_window_clamp = resolved["tcp_window_clamp"]
4219
+ if resolved["tcp_ip_id_mode"]:
4220
+ c_ipid = _c_string(ffi, resolved["tcp_ip_id_mode"])
4221
+ keep_alive.append(c_ipid)
4222
+ opts.tcp_ip_id_mode = c_ipid
4223
+
4224
+ opts.timeout_seconds = resolved["timeout_seconds"]
4225
+ opts.timeout_milliseconds = resolved["timeout_milliseconds"]
4226
+ opts.follow_redirects = resolved["follow_redirects"]
4227
+ opts.insecure_skip_verify = resolved["insecure_skip_verify"]
4228
+ opts.force_http1 = resolved["force_http1"]
4229
+ opts.with_random_tls_extension_order = resolved["with_random_tls_extension_order"]
4230
+ opts.with_protocol_racing = resolved["with_protocol_racing"]
4231
+ opts.max_idle_connections = resolved["max_idle_connections"]
4232
+ opts.max_idle_connections_per_host = resolved["max_idle_connections_per_host"]
4233
+ opts.max_connections_per_host = resolved["max_connections_per_host"]
4234
+ opts.disable_keep_alives = resolved["disable_keep_alives"]
4235
+ opts.disable_compression = resolved["disable_compression"]
4236
+ opts.idle_conn_timeout_seconds = resolved["idle_conn_timeout_seconds"]
4237
+ opts.max_response_header_bytes = resolved["max_response_header_bytes"]
4238
+ opts.write_buffer_size = resolved["write_buffer_size"]
4239
+ opts.read_buffer_size = resolved["read_buffer_size"]
4240
+ opts.allow_empty_cookies = resolved["allow_empty_cookies"]
4241
+ opts.without_cookie_jar = resolved["without_cookie_jar"]
4242
+ opts.disable_http3 = resolved["disable_http3"]
4243
+ opts.disable_ipv4 = resolved["disable_ipv4"]
4244
+ opts.disable_ipv6 = resolved["disable_ipv6"]
4245
+ opts.tcp_ttl = resolved["tcp_ttl"]
4246
+ opts.tcp_window_size = resolved["tcp_window_size"]
4247
+ opts.tcp_window_scale = resolved["tcp_window_scale"]
4248
+ opts.tcp_mss = resolved["tcp_mss"]
4249
+ opts.catch_panics = resolved["catch_panics"]
4250
+ opts.with_debug = resolved["with_debug"]
4251
+
4252
+
4253
+ # String fields
4254
+ for name, field in [
4255
+ ("client_identifier", "client_identifier"),
4256
+ ("proxy", "proxy"),
4257
+ ("server_name_overwrite", "server_name_overwrite"),
4258
+ ("request_host_override", "request_host_override"),
4259
+ ("local_address", "local_address"),
4260
+ ]:
4261
+ c_val = _c_string(ffi, resolved[name])
4262
+ setattr(opts, field, c_val)
4263
+ if c_val != ffi.NULL:
4264
+ keep_alive.append(c_val)
4265
+
4266
+ # Pseudo-header orders
4267
+ pho = resolved["pseudo_header_order"]
4268
+ ph_ptr, ph_len = _build_string_array(ffi, pho, keep_alive)
4269
+ opts.pseudo_header_order = ph_ptr
4270
+ opts.pseudo_header_order_len = ph_len
4271
+
4272
+ h3pho = resolved["h3_pseudo_header_order"]
4273
+ h3ph_ptr, h3ph_len = _build_string_array(ffi, h3pho, keep_alive)
4274
+ opts.h3_pseudo_header_order = h3ph_ptr
4275
+ opts.h3_pseudo_header_order_len = h3ph_len
4276
+
4277
+ # Default/connect headers
4278
+ dh = resolved["default_headers"]
4279
+ dh_ptr, dh_len = _build_headers(ffi, dh, keep_alive)
4280
+ opts.default_headers = dh_ptr
4281
+ opts.default_headers_len = dh_len
4282
+
4283
+ ch = resolved["connect_headers"]
4284
+ ch_ptr, ch_len = _build_headers(ffi, ch, keep_alive)
4285
+ opts.connect_headers = ch_ptr
4286
+ opts.connect_headers_len = ch_len
4287
+
4288
+ # Certificate pinning
4289
+ cp = resolved["certificate_pinning_hosts"]
4290
+ cp_ptr, cp_len = _build_pin_entries(ffi, cp, keep_alive)
4291
+ opts.certificate_pinning_hosts = cp_ptr
4292
+ opts.certificate_pinning_hosts_len = cp_len
4293
+ opts.with_default_bad_pin_handler = resolved["with_default_bad_pin_handler"]
4294
+
4295
+ # Request cookies
4296
+ rc = resolved["request_cookies"]
4297
+ rc_ptr, rc_len = _build_headers(ffi, rc, keep_alive)
4298
+ opts.request_cookies = rc_ptr
4299
+ opts.request_cookies_len = rc_len
4300
+
4301
+ # Client certificates
4302
+ cc = resolved["client_certificates"]
4303
+ cc_ptr, cc_len = _build_client_certificates(ffi, cc, keep_alive)
4304
+ opts.client_certificates = cc_ptr
4305
+ opts.client_certificates_len = cc_len
4306
+
4307
+ # Custom TLS client
4308
+ ctc = resolved["custom_tls_client"]
4309
+ ctc_ptr = _build_custom_tls_client(ffi, ctc, keep_alive)
4310
+ opts.custom_tls_client = ctc_ptr
4311
+
4312
+ # ---- streaming fields (injected by stream_to_file) -----------------
4313
+ stream_path = kwargs.pop("_stream_output_path", ffi.NULL)
4314
+ stream_bs = kwargs.pop("_stream_output_block_size", 0)
4315
+ stream_eof = kwargs.pop("_stream_output_eof_symbol", ffi.NULL)
4316
+ stream_keep = kwargs.pop("_stream_keep_alive", None)
4317
+ if stream_keep is not None:
4318
+ keep_alive.extend(stream_keep)
4319
+ opts.stream_output_path = stream_path
4320
+ opts.stream_output_block_size = stream_bs
4321
+ opts.stream_output_eof_symbol = stream_eof
4322
+
4323
+ # ── Register Future with defensive timeout ────────────────────────
4324
+ # Go's RequestAsync has its own timeout (timeout_seconds / timeout_milliseconds,
4325
+ # falling back to the engine default when both are 0), but if the Go
4326
+ # goroutine hangs indefinitely (network partition, OS bug), the
4327
+ # _pending_requests entry would leak the Future + keep_alive forever.
4328
+ # A defensive timeout (2× Go timeout + 2 s grace, clamped [60, 600] s)
4329
+ # cleans up zombie entries so the Python process does not accumulate
4330
+ # leaked memory under high-concurrency workloads.
4331
+ safe_timeout = _defensive_timeout_seconds(
4332
+ resolved["timeout_seconds"], resolved["timeout_milliseconds"]
4333
+ )
4334
+
4335
+ request_id = _next_request_id()
4336
+ future: asyncio.Future = loop.create_future()
4337
+ timeout_handle = loop.call_later(
4338
+ safe_timeout, _on_zombie_timeout, request_id, safe_timeout
4339
+ )
4340
+
4341
+ with _pending_lock:
4342
+ # Store keep_alive alongside the Future – the goroutine reads
4343
+ # from C memory via unsafe.Slice, so Python must keep the
4344
+ # original buffers alive until the callback fires.
4345
+ _pending_requests[request_id] = (future, keep_alive, timeout_handle, self)
4346
+
4347
+ # Step 1-2: Call RequestAsync — Go deep-copies, dispatches goroutine,
4348
+ # returns immediately. Python can free keep_alive memory after return.
4349
+ try:
4350
+ ret = lib.RequestAsync(opts, request_id, callback)
4351
+ except BaseException:
4352
+ # cffi-level failure before Go took ownership — drop the entry
4353
+ # and its defensive timer so nothing leaks.
4354
+ _drop_pending_request(request_id)
4355
+ raise
4356
+
4357
+ if ret != 0:
4358
+ # RequestAsync returned an error — clean up the pending entry
4359
+ # and cancel the defensive zombie timeout. keep_alive is
4360
+ # already safe to release because RequestAsync deep-copies
4361
+ # before returning.
4362
+ _drop_pending_request(request_id)
4363
+ raise RuntimeError("RequestAsync failed — opts or callback is nil")
4364
+
4365
+ # Await the Future — event loop is free to run other tasks
4366
+ return await future
4367
+
4368
+ async def stream_to_file(
4369
+ self,
4370
+ # HTTP 方法 / HTTP method
4371
+ method: str,
4372
+ # 请求 URL / Request URL
4373
+ url: str,
4374
+ # 输出文件路径 / Output file path
4375
+ output_path: str,
4376
+ *,
4377
+ # 请求头字典 / Request headers dict
4378
+ headers: Optional[Dict[str, str]] = None,
4379
+ # 请求头发送顺序 / Header send order
4380
+ header_order: Optional[List[str]] = None,
4381
+ # 请求体原始字节串 / Request body as raw bytes
4382
+ body: Optional[bytes] = None,
4383
+ # 块大小(字节) / Chunk size per read (bytes)
4384
+ chunk_size: int = 8192,
4385
+ # 可选的 EOF 标记字符串 / Optional EOF marker string
4386
+ eof_marker: Optional[str] = None,
4387
+ **kwargs: Any,
4388
+ ) -> Response:
4389
+ """执行请求并将响应体流式写入磁盘(异步)。
4390
+
4391
+ Execute a request and stream the response body to disk (async).
4392
+ """
4393
+ ffi, _ = _get_ffi()
4394
+
4395
+ keep_alive: list = []
4396
+ c_path = _c_string(ffi, output_path)
4397
+ keep_alive.append(c_path)
4398
+
4399
+ c_eof = _c_string(ffi, eof_marker)
4400
+ if c_eof != ffi.NULL:
4401
+ keep_alive.append(c_eof)
4402
+
4403
+ return await self._execute_async(
4404
+ method,
4405
+ url,
4406
+ headers=headers,
4407
+ header_order=header_order,
4408
+ body=body,
4409
+ _stream_output_path=c_path,
4410
+ _stream_output_block_size=chunk_size,
4411
+ _stream_output_eof_symbol=c_eof,
4412
+ _stream_keep_alive=keep_alive,
4413
+ **kwargs,
4414
+ )
4415
+
4416
+ async def execute_request(
4417
+ self,
4418
+ # HTTP 方法 / HTTP method
4419
+ method: str,
4420
+ # 完整的请求 URL / Full request URL including scheme and hostname
4421
+ url: str,
4422
+ *,
4423
+ # 请求头字典 / Request headers dict
4424
+ headers: Optional[Dict[str, str]] = None,
4425
+ # 请求头的发送顺序列表 / Header send-order list
4426
+ header_order: Optional[List[str]] = None,
4427
+ # 请求体原始字节串 / Request body as raw bytes
4428
+ body: Optional[bytes] = None,
4429
+ # ── 每请求覆盖参数 / Per-request overrides ──
4430
+ # 覆盖 TLS 指纹标识 / Override TLS fingerprint identifier
4431
+ client_identifier: Optional[str] = None,
4432
+ # 覆盖超时时间(秒) / Override timeout (seconds)
4433
+ timeout: Optional[int] = None,
4434
+ # 覆盖超时时间(毫秒) / Override timeout (milliseconds)
4435
+ timeout_milliseconds: Optional[int] = None,
4436
+ # 覆盖重定向跟随策略 / Override redirect-following policy
4437
+ follow_redirects: Optional[bool] = None,
4438
+ # 覆盖 TLS 证书校验 / Override TLS certificate verification
4439
+ verify: Optional[bool] = None,
4440
+ # 覆盖 HTTP/1.1 强制开关 / Override force HTTP/1.1
4441
+ force_http1: Optional[bool] = None,
4442
+ # 覆盖 TLS 扩展随机化 / Override TLS extension randomisation
4443
+ random_tls_extension_order: Optional[bool] = None,
4444
+ # 覆盖协议竞速开关 / Override protocol racing
4445
+ with_protocol_racing: Optional[bool] = None,
4446
+ # 覆盖 SNI 主机名 / Override SNI hostname
4447
+ server_name_overwrite: Optional[str] = None,
4448
+ # 覆盖 HTTP Host 请求头 / Override HTTP Host header
4449
+ request_host_override: Optional[str] = None,
4450
+ # 覆盖代理 URL / Override proxy URL
4451
+ proxy: Optional[str] = None,
4452
+ # 覆盖本地绑定地址 / Override local bind address
4453
+ local_address: Optional[str] = None,
4454
+ # 覆盖 HTTP/2 伪头顺序 / Override HTTP/2 pseudo-header order
4455
+ pseudo_header_order: Optional[List[str]] = None,
4456
+ # 覆盖 HTTP/3 伪头顺序 / Override HTTP/3 pseudo-header order
4457
+ h3_pseudo_header_order: Optional[List[str]] = None,
4458
+ # 覆盖默认请求头字典 / Override default headers dict
4459
+ default_headers: Optional[Dict[str, str]] = None,
4460
+ # 覆盖代理 CONNECT 隧道请求头 / Override proxy CONNECT tunnel headers
4461
+ connect_headers: Optional[Dict[str, str]] = None,
4462
+ # 覆盖 SSL 证书固定字典 / Override SSL certificate pinning dict
4463
+ certificate_pinning_hosts: Optional[Dict[str, List[str]]] = None,
4464
+ # 覆盖 Bad-Pin 处理器开关 / Override default bad-pin handler toggle
4465
+ with_default_bad_pin_handler: Optional[bool] = None,
4466
+ # 覆盖预置 Cookie 字典 / Override pre-populated cookie dict
4467
+ request_cookies: Optional[Dict[str, str]] = None,
4468
+ # 覆盖客户端证书列表 / Override client certificate list
4469
+ client_certificates: Optional[List[Dict[str, bytes]]] = None,
4470
+ # 覆盖自定义 TLS 客户端配置 / Override custom TLS client configuration
4471
+ custom_tls_client: Optional[Dict[str, Any]] = None,
4472
+ # 覆盖全局最大空闲连接数 / Override global max idle connections
4473
+ max_idle_connections: Optional[int] = None,
4474
+ # 覆盖每 Host 最大空闲连接数 / Override max idle connections per host
4475
+ max_idle_connections_per_host: Optional[int] = None,
4476
+ # 覆盖每 Host 最大总连接数 / Override max total connections per host
4477
+ max_connections_per_host: Optional[int] = None,
4478
+ # 覆盖 Keep-Alive 禁用 / Override disable Keep-Alive
4479
+ disable_keep_alives: Optional[bool] = None,
4480
+ # 覆盖压缩禁用 / Override disable compression
4481
+ disable_compression: Optional[bool] = None,
4482
+ # 覆盖空闲连接超时 / Override idle connection timeout
4483
+ idle_conn_timeout_seconds: Optional[int] = None,
4484
+ # 覆盖响应头最大字节数 / Override max response header bytes
4485
+ max_response_header_bytes: Optional[int] = None,
4486
+ # 覆盖写缓冲区大小 / Override write buffer size
4487
+ write_buffer_size: Optional[int] = None,
4488
+ # 覆盖读缓冲区大小 / Override read buffer size
4489
+ read_buffer_size: Optional[int] = None,
4490
+ # 覆盖空 Cookie 允许 / Override allow-empty-cookies
4491
+ allow_empty_cookies: Optional[bool] = None,
4492
+ # 覆盖禁用 Cookie Jar / Override disable Cookie Jar
4493
+ without_cookie_jar: Optional[bool] = None,
4494
+ # 覆盖 HTTP/3 禁用 / Override disable HTTP/3
4495
+ disable_http3: Optional[bool] = None,
4496
+ # 覆盖 IPv4 禁用 / Override disable IPv4
4497
+ disable_ipv4: Optional[bool] = None,
4498
+ # 覆盖 IPv6 禁用 / Override disable IPv6
4499
+ disable_ipv6: Optional[bool] = None,
4500
+ # 覆盖 panic 捕获 / Override catch-panics
4501
+ catch_panics: Optional[bool] = None,
4502
+ # 覆盖调试日志 / Override debug logging
4503
+ with_debug: Optional[bool] = None,
4504
+ # 覆盖 TLS session tickets 禁用 (ABI 2) / Override session-ticket disabling
4505
+ disable_session_tickets: Optional[bool] = None,
4506
+ # 覆盖 TLS keylog 路径 (ABI 2) / Override TLS keylog path
4507
+ tls_keylog_path: Optional[str] = None,
4508
+ # 覆盖自定义 CA PEM (ABI 2) / Override custom CA PEM bytes
4509
+ root_ca_pem: Optional[bytes] = None,
4510
+ # 覆盖 HTTP/2 DATA 帧上限 (ABI 2.1) / Override DATA frame cap
4511
+ h2_max_data_frame_size: Optional[int] = None,
4512
+ # 覆盖空闲 PING 阈值 (ABI 2.1) / Override preface-ping threshold
4513
+ preface_ping_idle_ms: Optional[int] = None,
4514
+ # 覆盖 HPACK 索引策略 (ABI 2.1) / Override HPACK indexing policy
4515
+ hpack_indexing_policy: Optional[str] = None,
4516
+ # 覆盖 Cookie 拆分 (ABI 2.1) / Override cookie crumble
4517
+ cookie_crumb: Optional[bool] = None,
4518
+ tcp_ttl: Optional[int] = None,
4519
+ tcp_window_size: Optional[int] = None,
4520
+ tcp_window_scale: Optional[int] = None,
4521
+ tcp_mss: Optional[int] = None,
4522
+ # ── ABI 3 — 细粒度指纹控制 / fine-grained fingerprint control ──
4523
+ extension_permute_mode: Optional[int] = None,
4524
+ extension_permute_prefix: Optional[int] = None,
4525
+ h2_disable_priority_frames: Optional[bool] = None,
4526
+ header_order_by_dest: Optional[bool] = None,
4527
+ header_order_dest: Optional[str] = None,
4528
+ tcp_dont_fragment: Optional[int] = None,
4529
+ tcp_tos: Optional[int] = None,
4530
+ tcp_no_delay: Optional[int] = None,
4531
+ tcp_window_clamp: Optional[int] = None,
4532
+ tcp_ip_id_mode: Optional[str] = None,
4533
+ **kwargs: Any,
4534
+ ) -> Response:
4535
+ """通过 Go 引擎执行单次 HTTP 请求(异步)。
4536
+
4537
+ Execute a single HTTP request through the Go engine (async).
4538
+ """
4539
+ selected_identifier = client_identifier or self._session.client_identifier
4540
+ if selected_identifier not in SUPPORTED_CLIENT_IDENTIFIERS:
4541
+ raise ValueError("unsupported client_identifier %r" % selected_identifier)
4542
+ # Remap user-facing names → defaults-dict keys where they differ.
4543
+ # timeout → timeout_seconds
4544
+ # verify → insecure_skip_verify (inverted: True→0, False→1)
4545
+ # random_tls_extension_order → with_random_tls_extension_order
4546
+ return await self._execute_async(
4547
+ method, url,
4548
+ headers=headers, header_order=header_order, body=body,
4549
+ timeout_seconds=timeout,
4550
+ insecure_skip_verify=None if verify is None else (0 if verify else 1),
4551
+ with_random_tls_extension_order=random_tls_extension_order,
4552
+ client_identifier=client_identifier,
4553
+ timeout_milliseconds=timeout_milliseconds, follow_redirects=follow_redirects,
4554
+ force_http1=force_http1,
4555
+ with_protocol_racing=with_protocol_racing,
4556
+ server_name_overwrite=server_name_overwrite,
4557
+ request_host_override=request_host_override, proxy=proxy,
4558
+ local_address=local_address, pseudo_header_order=pseudo_header_order,
4559
+ h3_pseudo_header_order=h3_pseudo_header_order,
4560
+ default_headers=default_headers, connect_headers=connect_headers,
4561
+ certificate_pinning_hosts=certificate_pinning_hosts,
4562
+ with_default_bad_pin_handler=with_default_bad_pin_handler,
4563
+ request_cookies=request_cookies, client_certificates=client_certificates,
4564
+ custom_tls_client=custom_tls_client,
4565
+ max_idle_connections=max_idle_connections,
4566
+ max_idle_connections_per_host=max_idle_connections_per_host,
4567
+ max_connections_per_host=max_connections_per_host,
4568
+ disable_keep_alives=disable_keep_alives,
4569
+ disable_compression=disable_compression,
4570
+ idle_conn_timeout_seconds=idle_conn_timeout_seconds,
4571
+ max_response_header_bytes=max_response_header_bytes,
4572
+ write_buffer_size=write_buffer_size, read_buffer_size=read_buffer_size,
4573
+ allow_empty_cookies=allow_empty_cookies,
4574
+ without_cookie_jar=without_cookie_jar,
4575
+ disable_http3=disable_http3, disable_ipv4=disable_ipv4,
4576
+ disable_ipv6=disable_ipv6,
4577
+ tcp_ttl=tcp_ttl,
4578
+ tcp_window_size=tcp_window_size,
4579
+ tcp_window_scale=tcp_window_scale,
4580
+ tcp_mss=tcp_mss,
4581
+ catch_panics=catch_panics,
4582
+ with_debug=with_debug,
4583
+ disable_session_tickets=disable_session_tickets,
4584
+ tls_keylog_path=tls_keylog_path,
4585
+ root_ca_pem=root_ca_pem,
4586
+ h2_max_data_frame_size=h2_max_data_frame_size,
4587
+ preface_ping_idle_ms=preface_ping_idle_ms,
4588
+ hpack_indexing_policy=hpack_indexing_policy,
4589
+ cookie_crumb=cookie_crumb,
4590
+ extension_permute_mode=extension_permute_mode,
4591
+ extension_permute_prefix=extension_permute_prefix,
4592
+ h2_disable_priority_frames=h2_disable_priority_frames,
4593
+ header_order_by_dest=header_order_by_dest,
4594
+ header_order_dest=header_order_dest,
4595
+ tcp_dont_fragment=tcp_dont_fragment,
4596
+ tcp_tos=tcp_tos,
4597
+ tcp_no_delay=tcp_no_delay,
4598
+ tcp_window_clamp=tcp_window_clamp,
4599
+ tcp_ip_id_mode=tcp_ip_id_mode,
4600
+ **kwargs,
4601
+ )
4602
+
4603
+ async def typed_request(self, req: Request) -> Response:
4604
+ """使用 :class:`Request` 强类型对象执行 HTTP 请求(异步)。
4605
+
4606
+ Execute an HTTP request using a :class:`Request` strongly-typed object (async).
4607
+ """
4608
+ method = req["method"]
4609
+ url = req["url"]
4610
+ kwargs = {k: v for k, v in req.items() if k not in ("method", "url")}
4611
+ return await self.execute_request(method, url, **kwargs)
4612
+
4613
+ async def get(self, url: str, *, headers: Optional[Dict[str, str]] = None, **kwargs: Any) -> Response:
4614
+ return await self.request("GET", url, headers=headers, **kwargs)
4615
+
4616
+ async def post(self, url: str, *, headers: Optional[Dict[str, str]] = None, body: Optional[bytes] = None, **kwargs: Any) -> Response:
4617
+ if body is not None:
4618
+ kwargs.setdefault("data", body)
4619
+ return await self.request("POST", url, headers=headers, **kwargs)
4620
+
4621
+ async def head(self, url: str, *, headers: Optional[Dict[str, str]] = None, **kwargs: Any) -> Response:
4622
+ return await self.request("HEAD", url, headers=headers, **kwargs)
4623
+
4624
+ async def put(self, url: str, *, headers: Optional[Dict[str, str]] = None, body: Optional[bytes] = None, **kwargs: Any) -> Response:
4625
+ if body is not None:
4626
+ kwargs.setdefault("data", body)
4627
+ return await self.request("PUT", url, headers=headers, **kwargs)
4628
+
4629
+ async def delete(self, url: str, *, headers: Optional[Dict[str, str]] = None, **kwargs: Any) -> Response:
4630
+ return await self.request("DELETE", url, headers=headers, **kwargs)
4631
+
4632
+ async def patch(self, url: str, *, headers: Optional[Dict[str, str]] = None, body: Optional[bytes] = None, **kwargs: Any) -> Response:
4633
+ if body is not None:
4634
+ kwargs.setdefault("data", body)
4635
+ return await self.request("PATCH", url, headers=headers, **kwargs)
4636
+
4637
+ async def request(
4638
+ self,
4639
+ method: str,
4640
+ url: str,
4641
+ *,
4642
+ params: Optional[Dict[str, str]] = None,
4643
+ data: Union[bytes, str, Dict[str, str], None] = None,
4644
+ json: Any = None,
4645
+ headers: Optional[Dict[str, str]] = None,
4646
+ auth: Optional[Tuple[str, str]] = None,
4647
+ cookies: Optional[Dict[str, str]] = None,
4648
+ stream: Optional[bool] = None,
4649
+ cert: Optional[Union[str, Tuple[str, str]]] = None,
4650
+ timeout: Optional[int] = None,
4651
+ allow_redirects: Optional[bool] = None,
4652
+ proxies: Optional[Dict[str, str]] = None,
4653
+ verify: Optional[bool] = None,
4654
+ **kwargs: Any,
4655
+ ) -> Response:
4656
+ """``requests`` ????? HTTP ?????
4657
+
4658
+ ``requests``-compatible async HTTP request method.
4659
+
4660
+ :attr:`params` ????? URL?:attr:`data` / :attr:`json` ????????
4661
+ :attr:`auth` ???? ``Authorization`` ??:attr:`cert` ????????? mTLS ???
4662
+ ???????? Session ??????????????
4663
+ """
4664
+ url, body, headers, request_cookies, client_certificates = _prepare_request_compat(
4665
+ get_default=self._session._get_default,
4666
+ url=url,
4667
+ params=params,
4668
+ data=data,
4669
+ json_data=json,
4670
+ headers=headers,
4671
+ auth=auth,
4672
+ cookies=cookies,
4673
+ stream=stream,
4674
+ cert=cert,
4675
+ timeout=timeout,
4676
+ allow_redirects=allow_redirects,
4677
+ proxies=proxies,
4678
+ verify=verify,
4679
+ kwargs=kwargs,
4680
+ )
4681
+ return await self.execute_request(
4682
+ method,
4683
+ url,
4684
+ headers=headers,
4685
+ body=body,
4686
+ request_cookies=request_cookies,
4687
+ client_certificates=client_certificates,
4688
+ **kwargs,
4689
+ )
4690
+
4691
+ async def options(self, url: str, **kwargs: Any) -> Response:
4692
+ """发送异步 HTTP OPTIONS 请求 / Send an async HTTP OPTIONS request."""
4693
+ return await self.request("OPTIONS", url, **kwargs)
4694
+
4695
+ def close(self) -> None:
4696
+ """关闭异步会话,释放 Go 客户端池中的空闲连接。
4697
+
4698
+ Close the async session and release idle connections in the Go client pool.
4699
+ """
4700
+ self._session._closed = True
4701
+ to_cancel = []
4702
+ with _pending_lock:
4703
+ owned_ids = [
4704
+ request_id
4705
+ for request_id, entry in _pending_requests.items()
4706
+ if len(entry) == 4 and entry[3] is self
4707
+ ]
4708
+ for request_id in owned_ids:
4709
+ entry = _pending_requests.pop(request_id, None)
4710
+ if entry is not None:
4711
+ to_cancel.append(entry)
4712
+ for future, _keep_alive, timeout_handle, _owner in to_cancel:
4713
+ # close() may be called from a non-loop thread — cancel the
4714
+ # defensive timer through the loop instead of racing it.
4715
+ _cancel_timeout_handle(future, timeout_handle)
4716
+ if future is not None and not future.done():
4717
+ _apply_future_exception(
4718
+ future, RuntimeError("AsyncSession is closed")
4719
+ )
4720
+ _, lib = _get_ffi()
4721
+ lib.ClearClientPool()
4722
+
4723
+ @staticmethod
4724
+ def clear_client_pool() -> None:
4725
+ """Close all idle connections in the global Go client pool.
4726
+
4727
+ Calls the Go C function directly. ClearClientPool iterates the
4728
+ internal client map and closes idle connections — it is fast and
4729
+ non-blocking, so no thread pool is needed (Constraint 4).
4730
+ """
4731
+ _, lib = _get_ffi()
4732
+ lib.ClearClientPool()
4733
+
4734
+
4735
+ # Convenience top-level function
4736
+ def clear_client_pool() -> None:
4737
+ """Close all idle connections in the global Go client pool (synchronous)."""
4738
+ Session.clear_client_pool()