@jayyuen66/dsh-scrapling 0.0.1-rc.3 → 0.0.1
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.
- package/README.md +56 -13
- package/README.zh-CN.md +17 -8
- package/client.js +461 -98
- package/host.js +21 -17
- package/package.json +45 -40
- package/py/adapters.py +400 -64
- package/py/bridge.py +16 -9
- package/py/crawl.py +162 -31
- package/py/guard.py +142 -51
package/py/adapters.py
CHANGED
|
@@ -17,10 +17,15 @@ css/xpath。所有浏览器引擎都是**一次性 session**:每次调用开
|
|
|
17
17
|
|
|
18
18
|
from __future__ import annotations
|
|
19
19
|
|
|
20
|
+
import concurrent.futures
|
|
21
|
+
import contextlib
|
|
22
|
+
import queue
|
|
20
23
|
import re
|
|
24
|
+
import threading
|
|
21
25
|
import uuid
|
|
22
26
|
from datetime import datetime, timezone
|
|
23
|
-
from typing import Any
|
|
27
|
+
from typing import Any, Callable
|
|
28
|
+
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
|
|
24
29
|
|
|
25
30
|
import guard
|
|
26
31
|
|
|
@@ -29,7 +34,8 @@ import guard
|
|
|
29
34
|
try: # pragma: no cover —— 取决于运行环境是否装了 scrapling
|
|
30
35
|
from scrapling.fetchers import DynamicFetcher, Fetcher, StealthyFetcher
|
|
31
36
|
except ImportError: # pragma: no cover
|
|
32
|
-
|
|
37
|
+
# 两个 ignore 各管一件事:misc 是「不能给类型赋值」,assignment 是「None 不是类」。
|
|
38
|
+
Fetcher = DynamicFetcher = StealthyFetcher = None # type: ignore[misc,assignment]
|
|
33
39
|
|
|
34
40
|
SCRAPLING_AVAILABLE = Fetcher is not None
|
|
35
41
|
|
|
@@ -38,6 +44,10 @@ DEFAULT_TIMEOUT_SECONDS = 120.0
|
|
|
38
44
|
DEFAULT_TIMEOUT_MS = 30_000
|
|
39
45
|
DEFAULT_MAX_CONTENT_CHARS = 200_000
|
|
40
46
|
EXTRACTION_TYPES = ("markdown", "html", "text")
|
|
47
|
+
# adaptive 指纹库的文件名。**相对路径**:bridge 由宿主以部署侧的 dataDir 为工作目录拉起
|
|
48
|
+
# (见 host.ts 的 sidecar env),相对路径正好把库落进 dataDir —— Scrapling 自己的默认值
|
|
49
|
+
# 是包目录内的绝对路径,那在只读的 site-packages 里写不了,也不是用户该找的地方。
|
|
50
|
+
ADAPTIVE_STORAGE_FILE = "elements_storage.db"
|
|
41
51
|
|
|
42
52
|
|
|
43
53
|
class AdapterError(RuntimeError):
|
|
@@ -53,8 +63,7 @@ def _require(engine: object) -> None:
|
|
|
53
63
|
if engine is None:
|
|
54
64
|
raise AdapterError(
|
|
55
65
|
"SCRAPLING_MISSING",
|
|
56
|
-
'Scrapling is not importable in this Python environment. '
|
|
57
|
-
'Install it with: pip install "scrapling[rag]"',
|
|
66
|
+
'Scrapling is not importable in this Python environment. Install it with: pip install "scrapling[rag]"',
|
|
58
67
|
)
|
|
59
68
|
|
|
60
69
|
|
|
@@ -110,16 +119,122 @@ def _jsonable(value: Any) -> Any:
|
|
|
110
119
|
return str(value)
|
|
111
120
|
|
|
112
121
|
|
|
122
|
+
# 查询串里这些名字的参数装的是凭据而不是筛选条件。XHR 摘要是**给模型看的**——它进会话
|
|
123
|
+
# 上下文、进日志、进第三方 provider——而真实站点把 access token、会话 id、签名都放在
|
|
124
|
+
# 查询串里。抓到一条就等于把凭据抄进上下文,而模型既用不上它、也拦不住它被复述出来。
|
|
125
|
+
# 值的部分一律换成固定占位符:定位接口靠的是路径与参数名,不是那个 token。
|
|
126
|
+
_SECRET_QUERY_KEYS = frozenset(
|
|
127
|
+
{
|
|
128
|
+
"access_token",
|
|
129
|
+
"api_key",
|
|
130
|
+
"apikey",
|
|
131
|
+
"auth",
|
|
132
|
+
"auth_token",
|
|
133
|
+
"authorization",
|
|
134
|
+
"code",
|
|
135
|
+
"credential",
|
|
136
|
+
"id_token",
|
|
137
|
+
"key",
|
|
138
|
+
"password",
|
|
139
|
+
"pwd",
|
|
140
|
+
"refresh_token",
|
|
141
|
+
"secret",
|
|
142
|
+
"session",
|
|
143
|
+
"sessionid",
|
|
144
|
+
"session_id",
|
|
145
|
+
"sig",
|
|
146
|
+
"signature",
|
|
147
|
+
"sign",
|
|
148
|
+
"token",
|
|
149
|
+
}
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _redacted_query(text: str) -> str:
|
|
154
|
+
"""把一段查询串里像凭据的参数值换成占位符;没有命中时原样返回。
|
|
155
|
+
|
|
156
|
+
与 :func:`redact_url_secrets` 同一套参数名判据,片段也复用它 —— OAuth2 隐式流程把
|
|
157
|
+
令牌放在 ``#access_token=`` 里,那同样是「给模型看就等于抄进上下文」的凭据。
|
|
158
|
+
|
|
159
|
+
:param text: 查询串(或片段的查询部分)
|
|
160
|
+
:returns: 脱敏后的文本
|
|
161
|
+
"""
|
|
162
|
+
if not text:
|
|
163
|
+
return text
|
|
164
|
+
pairs: list[tuple[str, str]] = []
|
|
165
|
+
changed = False
|
|
166
|
+
for name, value in parse_qsl(text, keep_blank_values=True):
|
|
167
|
+
if name.strip().lower() in _SECRET_QUERY_KEYS:
|
|
168
|
+
pairs.append((name, "<redacted>"))
|
|
169
|
+
changed = True
|
|
170
|
+
else:
|
|
171
|
+
pairs.append((name, value))
|
|
172
|
+
if not changed:
|
|
173
|
+
return text
|
|
174
|
+
return urlencode(pairs)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _redacted_fragment(fragment: str) -> str:
|
|
178
|
+
"""把片段里像查询串的那一段脱敏;没有命中时原样返回。
|
|
179
|
+
|
|
180
|
+
片段有两种藏令牌的写法:OAuth2 隐式流程把整个片段当查询串(``#access_token=…``),
|
|
181
|
+
单页应用的路由则是先路径后查询(``#!/list?token=…``)。两种都要覆盖。
|
|
182
|
+
|
|
183
|
+
:param fragment: URL 的 fragment 段
|
|
184
|
+
:returns: 脱敏后的 fragment
|
|
185
|
+
"""
|
|
186
|
+
head, separator, query = fragment.partition("?")
|
|
187
|
+
if separator:
|
|
188
|
+
return f"{head}?{_redacted_query(query)}"
|
|
189
|
+
return _redacted_query(fragment)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def redact_url_secrets(raw: str) -> str:
|
|
193
|
+
"""把 URL 里像凭据的部分替换成占位符。
|
|
194
|
+
|
|
195
|
+
三处各藏一类凭据:查询串与片段的查询部分按**参数名**判(真实站点把 access token、
|
|
196
|
+
会话 id、签名放在那里),authority 里的 ``user:pass@`` 整段丢掉(代理与 Basic 认证
|
|
197
|
+
的接口都爱这么写)。值的部分一律换成固定占位符:定位接口靠的是路径与参数名,不是
|
|
198
|
+
那个 token。
|
|
199
|
+
|
|
200
|
+
只按参数名判断、不看值 —— 值本身无法可靠判定(短 token 与普通 id 长得一样)。
|
|
201
|
+
认不出来的参数原样保留:把 ``?page=2`` 也涂掉只会让摘要失去意义,而那不是凭据。
|
|
202
|
+
|
|
203
|
+
:param raw: 原始 URL
|
|
204
|
+
:returns: 已脱敏的 URL;解析不出或没有可脱敏的部分时原样返回
|
|
205
|
+
"""
|
|
206
|
+
try:
|
|
207
|
+
parsed = urlsplit(raw)
|
|
208
|
+
except ValueError:
|
|
209
|
+
return raw
|
|
210
|
+
# rpartition 取最后一段:IPv6 字面量与端口都留在主机那一侧,只把用户信息摘掉。
|
|
211
|
+
netloc = parsed.netloc.rpartition("@")[2]
|
|
212
|
+
query = _redacted_query(parsed.query)
|
|
213
|
+
fragment = _redacted_fragment(parsed.fragment)
|
|
214
|
+
if netloc == parsed.netloc and query == parsed.query and fragment == parsed.fragment:
|
|
215
|
+
return raw
|
|
216
|
+
return urlunsplit((parsed.scheme, netloc, parsed.path, query, fragment))
|
|
217
|
+
|
|
218
|
+
|
|
113
219
|
def _xhr_summary(responses: Any) -> list[dict[str, Any]]:
|
|
114
220
|
"""把 ``captured_xhr`` 压成轻量摘要。
|
|
115
221
|
|
|
116
222
|
XHR 响应体可能很大,全量塞回 Host 会把模型上下文撑爆;这里只给 URL、状态码与
|
|
117
223
|
字节数,模型自己决定要不要再对其中某个 URL 发一次抓取。
|
|
224
|
+
|
|
225
|
+
URL 里的凭据型查询参数在这一层就脱敏:这份摘要是给模型看的,而模型用不上一个
|
|
226
|
+
access token 却会把整条 URL 原样复述出去。
|
|
118
227
|
"""
|
|
119
228
|
summary: list[dict[str, Any]] = []
|
|
120
229
|
for item in responses or ():
|
|
121
230
|
try:
|
|
122
|
-
summary.append(
|
|
231
|
+
summary.append(
|
|
232
|
+
{
|
|
233
|
+
"url": redact_url_secrets(str(item.url)),
|
|
234
|
+
"status": item.status,
|
|
235
|
+
"bytes": len(item.body),
|
|
236
|
+
}
|
|
237
|
+
)
|
|
123
238
|
except Exception: # noqa: BLE001 —— 单条摘要失败不该拖垮整次抓取
|
|
124
239
|
continue
|
|
125
240
|
return summary
|
|
@@ -177,8 +292,11 @@ def _strip_active_content(page: Any) -> None:
|
|
|
177
292
|
attrib = getattr(element, "attrib", None)
|
|
178
293
|
if attrib is None or not hasattr(attrib, "keys"):
|
|
179
294
|
continue
|
|
180
|
-
# meta refresh 能把浏览器导航到内网地址;base
|
|
181
|
-
|
|
295
|
+
# meta refresh 能把浏览器导航到内网地址;base 的 href 指挥相对地址怎么解析、
|
|
296
|
+
# 同样只影响解析而不贡献内容,两者都整段清掉属性。meta 只清带了 http-equiv 的
|
|
297
|
+
# (charset 声明无害且有用),base 不看属性名 —— <base href> 没有 http-equiv,
|
|
298
|
+
# 按属性名判它就永远清不到。
|
|
299
|
+
if tag == "base" or (tag == "meta" and "http-equiv" in attrib):
|
|
182
300
|
attrib.clear()
|
|
183
301
|
continue
|
|
184
302
|
for name in [
|
|
@@ -238,6 +356,23 @@ def drop_data_uris(text: str, *, html: bool = False) -> str:
|
|
|
238
356
|
return "\n".join(out)
|
|
239
357
|
|
|
240
358
|
|
|
359
|
+
def _scoped_pages(page: Any, css_selector: str | None) -> list[Any]: # noqa: ANN401 —— 同上
|
|
360
|
+
"""按 ``css_selector`` 把清洗过的树收窄成若干棵子树;没给选择器就是整棵。
|
|
361
|
+
|
|
362
|
+
口径与 Scrapling 自家 ``Convertor._extract_content`` 一致:命中 0 个元素就是空表,
|
|
363
|
+
三条提取路径都据此产出空正文 —— **不回退成整页**。此前只有 markdown 那条路径
|
|
364
|
+
(``Response.markdown``)吃选择器,html/text 拿到它却悄悄忽略、返回整页,模型无从
|
|
365
|
+
发现自己要的东西没被收窄。
|
|
366
|
+
|
|
367
|
+
:param page: 已清洗的页面树
|
|
368
|
+
:param css_selector: 收窄用的 CSS 选择器;None 或空串表示不收窄
|
|
369
|
+
:returns: 待提取的元素列表
|
|
370
|
+
"""
|
|
371
|
+
if not css_selector:
|
|
372
|
+
return [page]
|
|
373
|
+
return list(page.css(css_selector))
|
|
374
|
+
|
|
375
|
+
|
|
241
376
|
def to_payload(
|
|
242
377
|
response: Any,
|
|
243
378
|
*,
|
|
@@ -256,12 +391,15 @@ def to_payload(
|
|
|
256
391
|
if extraction_type == "html":
|
|
257
392
|
page = _sanitized_page(response, main_content_only=main_content_only)
|
|
258
393
|
_strip_active_content(page)
|
|
259
|
-
content =
|
|
394
|
+
content = "\n".join(element.html_content for element in _scoped_pages(page, css_selector))
|
|
260
395
|
elif extraction_type == "text":
|
|
261
396
|
page = _sanitized_page(response, main_content_only=main_content_only)
|
|
262
|
-
content =
|
|
263
|
-
|
|
264
|
-
|
|
397
|
+
content = "\n".join(
|
|
398
|
+
element.get_all_text(
|
|
399
|
+
strip=True,
|
|
400
|
+
ignore_tags=("script", "style", "noscript", "svg", "iframe"),
|
|
401
|
+
)
|
|
402
|
+
for element in _scoped_pages(page, css_selector)
|
|
265
403
|
)
|
|
266
404
|
else:
|
|
267
405
|
content = response.markdown(css_selector=css_selector, main_content_only=main_content_only)
|
|
@@ -313,9 +451,7 @@ def _static_params(args: dict[str, Any], url: str) -> dict[str, Any]:
|
|
|
313
451
|
按自己的 trust_env 读环境 —— 与本包不介入时逐字节一致。
|
|
314
452
|
"""
|
|
315
453
|
params: dict[str, Any] = {
|
|
316
|
-
"timeout": _positive_number(
|
|
317
|
-
args.get("timeoutSeconds"), "timeoutSeconds", DEFAULT_TIMEOUT_SECONDS
|
|
318
|
-
),
|
|
454
|
+
"timeout": _positive_number(args.get("timeoutSeconds"), "timeoutSeconds", DEFAULT_TIMEOUT_SECONDS),
|
|
319
455
|
"follow_redirects": "safe",
|
|
320
456
|
"retries": _positive_int(args.get("retries"), "retries", 3),
|
|
321
457
|
}
|
|
@@ -375,6 +511,27 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
375
511
|
)
|
|
376
512
|
|
|
377
513
|
|
|
514
|
+
def _xhr_pattern(args: dict[str, Any]) -> str | None:
|
|
515
|
+
"""取 XHR 捕获正则,并确认它编译得过。
|
|
516
|
+
|
|
517
|
+
这个串由 :mod:`scrapling` 塞进响应处理器,对**每个**响应跑一次 ``re.search``。
|
|
518
|
+
写错一个字符时若不在这里拦下,报错会发生在浏览器的事件回调里 —— 表现是「页面抓到了,
|
|
519
|
+
但整次抓取冒出一串看不懂的错」,而用户看不出根因是自己正则写错了。
|
|
520
|
+
|
|
521
|
+
:param args: 协议参数
|
|
522
|
+
:returns: 正则文本;没给或为空串时给 None(Scrapling 据此不捕获)
|
|
523
|
+
:raises AdapterError: 正则编译不过
|
|
524
|
+
"""
|
|
525
|
+
raw = args.get("captureXhrPattern")
|
|
526
|
+
if not isinstance(raw, str) or not raw:
|
|
527
|
+
return None
|
|
528
|
+
try:
|
|
529
|
+
re.compile(raw)
|
|
530
|
+
except re.error as error:
|
|
531
|
+
raise AdapterError("BAD_ARGS", f"captureXhrPattern is not a valid regex: {error}") from error
|
|
532
|
+
return raw
|
|
533
|
+
|
|
534
|
+
|
|
378
535
|
def _browser_params(args: dict[str, Any], url: str) -> dict[str, Any]:
|
|
379
536
|
"""浏览器抓取的公共参数。
|
|
380
537
|
|
|
@@ -417,11 +574,15 @@ def _browser_params(args: dict[str, Any], url: str) -> dict[str, Any]:
|
|
|
417
574
|
("useragent", "useragent"),
|
|
418
575
|
("locale", "locale"),
|
|
419
576
|
("timezoneId", "timezone_id"),
|
|
420
|
-
("captureXhrPattern", "capture_xhr"),
|
|
421
577
|
):
|
|
422
578
|
value = args.get(key)
|
|
423
579
|
if isinstance(value, str) and value:
|
|
424
580
|
params[name] = value
|
|
581
|
+
# XHR 捕获正则单独走一道:它是用户手写的正则,编译不过要在发车前就报出来,
|
|
582
|
+
# 而不是等它在浏览器的事件回调里炸。
|
|
583
|
+
xhr_pattern = _xhr_pattern(args)
|
|
584
|
+
if xhr_pattern is not None:
|
|
585
|
+
params["capture_xhr"] = xhr_pattern
|
|
425
586
|
# 浏览器二进制路径与 CDP 端点只从 deployment 命名空间取,不在上面的模型可见透传表里:
|
|
426
587
|
# executable_path 等于「让 Chromium 去执行这个文件」,cdp_url 等于「把浏览器交给这个
|
|
427
588
|
# 调试端点」,两者都是部署级的强能力,但绝不能由模型入参驱动。Host 侧对应的两枚设置
|
|
@@ -521,6 +682,15 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
521
682
|
|
|
522
683
|
这正是 dsh 内置 ``web_fetch`` 结构上做不到的那部分:它只能给一整块 Markdown,
|
|
523
684
|
这里给的是选择器命中的具体内容。
|
|
685
|
+
|
|
686
|
+
``adaptive`` 打开时走 Scrapling 的自愈选择器:命中成功就把首个元素的指纹存库,
|
|
687
|
+
站点改版后同一个选择器直接命中失败时,按指纹重定位。存储文件固定在 sidecar 的
|
|
688
|
+
工作目录(部署侧的 ``dataDir``),键按 ``url`` 的注册域分桶 —— 所以重定位还要求
|
|
689
|
+
给 ``url``;不给就全落在 ``default`` 桶里,跨站点共用一份指纹。
|
|
690
|
+
|
|
691
|
+
``maxContentChars`` 是这条路径的预算,与抓取类工具同源:``limit`` 数的是**条数**,
|
|
692
|
+
而十条十万字的正文照样能把模型上下文撑爆。所以逐条累计字符,超了就地截断并置
|
|
693
|
+
``truncated`` —— 总条数与单条长度是两根独立的轴,只压一根等于没压。
|
|
524
694
|
"""
|
|
525
695
|
from scrapling.parser import Selector
|
|
526
696
|
|
|
@@ -533,25 +703,61 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
533
703
|
attribute = args.get("attribute")
|
|
534
704
|
if attribute is not None and not isinstance(attribute, str):
|
|
535
705
|
raise AdapterError("BAD_ARGS", "attribute must be a string or null")
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
706
|
+
adaptive = bool(args.get("adaptive", False))
|
|
707
|
+
url = args.get("url")
|
|
708
|
+
if url is not None and not isinstance(url, str):
|
|
709
|
+
raise AdapterError("BAD_ARGS", "url must be a string or null")
|
|
710
|
+
|
|
711
|
+
if adaptive:
|
|
712
|
+
# storage_args 必须把 url 一起带上:Scrapling 对「给了部分 storage_args」是整体
|
|
713
|
+
# 替换而不是补齐,漏了 url 全部指纹都会落进 default 桶。url 为空时也显式传空串,
|
|
714
|
+
# 存储层把它归入 default 桶(StorageSystemMixin 对空值有兜底)。
|
|
715
|
+
page = Selector(
|
|
716
|
+
html,
|
|
717
|
+
url=url or "",
|
|
718
|
+
adaptive=True,
|
|
719
|
+
storage_args={"storage_file": ADAPTIVE_STORAGE_FILE, "url": url or ""},
|
|
720
|
+
)
|
|
721
|
+
else:
|
|
722
|
+
page = Selector(html)
|
|
723
|
+
|
|
724
|
+
# 命中成功时 auto_save 存指纹,命中失败且 adaptive 打开时按存过的指纹重定位 ——
|
|
725
|
+
# 两个开关都必须在**调用**上再打开一次:Scrapling 的 adaptive 是构造器与调用两级
|
|
726
|
+
# 开关,只开构造器的话,重定位会被静默跳过。
|
|
727
|
+
use_xpath = bool(args.get("useXpath", False))
|
|
728
|
+
if use_xpath:
|
|
729
|
+
nodes = page.xpath(selector, adaptive=adaptive, auto_save=adaptive)
|
|
730
|
+
else:
|
|
731
|
+
nodes = page.css(selector, adaptive=adaptive, auto_save=adaptive)
|
|
539
732
|
limit = _positive_int(args.get("limit"), "limit", 200)
|
|
733
|
+
budget = _positive_int(args.get("maxContentChars"), "maxContentChars", DEFAULT_MAX_CONTENT_CHARS)
|
|
540
734
|
include_attributes = bool(args.get("includeAttributes", False))
|
|
541
735
|
|
|
542
736
|
matches: list[dict[str, Any]] = []
|
|
543
|
-
|
|
737
|
+
spent = 0
|
|
738
|
+
clipped = False
|
|
739
|
+
for node in nodes:
|
|
740
|
+
if len(matches) >= limit:
|
|
741
|
+
break
|
|
544
742
|
item: dict[str, Any] = {"tag": node.tag}
|
|
545
|
-
if attribute
|
|
546
|
-
|
|
547
|
-
else:
|
|
548
|
-
item["text"] = str(node.get_all_text(strip=True))
|
|
743
|
+
field = "value" if attribute else "text"
|
|
744
|
+
item[field] = str(node.attrib.get(attribute, "")) if attribute else str(node.get_all_text(strip=True))
|
|
549
745
|
if include_attributes:
|
|
550
746
|
item["attributes"] = {str(key): str(value) for key, value in node.attrib.items()}
|
|
747
|
+
# 先按剩余额度截再计入已花:一条超长正文不该把整份预算吃光,也不该在预算只剩
|
|
748
|
+
# 一位时还能整条通过。
|
|
749
|
+
room = max(0, budget - spent)
|
|
750
|
+
if len(item[field]) > room:
|
|
751
|
+
item[field] = item[field][:room]
|
|
752
|
+
clipped = True
|
|
753
|
+
spent += len(item[field])
|
|
551
754
|
matches.append(item)
|
|
755
|
+
if spent >= budget:
|
|
756
|
+
clipped = True
|
|
757
|
+
break
|
|
552
758
|
return {
|
|
553
759
|
"count": len(nodes),
|
|
554
|
-
"truncated": len(nodes) > len(matches),
|
|
760
|
+
"truncated": clipped or len(nodes) > len(matches),
|
|
555
761
|
"matches": _jsonable(matches),
|
|
556
762
|
}
|
|
557
763
|
|
|
@@ -654,9 +860,18 @@ _SESSION_CLASSES = {
|
|
|
654
860
|
}
|
|
655
861
|
|
|
656
862
|
# 会话注册表。sidecar 是常驻进程,这里就是它的内存;进程退出时全部随之消失。
|
|
657
|
-
# 值里存 {"session": <对象>, "type": <str>, "created_at": <iso8601
|
|
863
|
+
# 值里存 {"session": <对象>, "type": <str>, "created_at": <iso8601>, "lock": Lock,
|
|
864
|
+
# "worker": _SessionWorker | None};正在构造中的条目只有
|
|
865
|
+
# {"pending": True, "type": <str>, "lock": Lock},那样它就已经占了名额。
|
|
866
|
+
# lock 从占位那一刻就存在,所以构造期与使用期是同一把锁;worker 只在 browser/stealth
|
|
867
|
+
# 上出现(见下),static 为 None。
|
|
658
868
|
_SESSIONS: dict[str, dict[str, Any]] = {}
|
|
659
869
|
|
|
870
|
+
# bridge 有多个 worker 线程,注册表从它们手里并发读写。判重与判名额必须原子,否则并发
|
|
871
|
+
# 的 session_open 会各自判完再各自开出一个会话 —— id 重复时后者覆盖前者(漏一个已经在
|
|
872
|
+
# 跑的 Chromium),名额判完再开等于没判。
|
|
873
|
+
_SESSION_LOCK = threading.Lock()
|
|
874
|
+
|
|
660
875
|
# 同开几个会话。browser/stealth 每开一个就是一个真实的 Chromium 进程,而 sessionType 是
|
|
661
876
|
# **模型可选**的参数 —— 不设上限的话,「开 → 不关」重复几次就能把机器的内存吃光。
|
|
662
877
|
# 因此在登记之前就判,而不是指望模型记得调 session_close。
|
|
@@ -665,6 +880,56 @@ MAX_SESSIONS = 8
|
|
|
665
880
|
MAX_BROWSER_SESSIONS = 3
|
|
666
881
|
|
|
667
882
|
|
|
883
|
+
class _SessionWorker:
|
|
884
|
+
"""一个会话的**专属执行线程**:这份会话上的全部远端调用都在它上面排队执行。
|
|
885
|
+
|
|
886
|
+
为什么必须有它:Playwright 的同步 API 靠 greenlet 与创建线程绑定 —— sync 对象上
|
|
887
|
+
任何一次远端调用都必须发生在 ``sync_playwright()`` 所在的那个 OS 线程,换线程直接
|
|
888
|
+
``greenlet.error: cannot switch to a different thread``。而 bridge 的 worker 是
|
|
889
|
+
「谁抢到帧谁处理」,还会空闲 50ms 就退出换新线程:会话在 A 线程里开、下一个请求
|
|
890
|
+
几乎必然落在 B 线程。按会话加锁只能保证「不同时用」,保证不了「同一线程用」——
|
|
891
|
+
所以每个 browser/stealth 会话配一条专用线程,open/fetch/close 全部投递到它,
|
|
892
|
+
串行执行;调用线程原地等结果。static(curl_cffi)没有线程亲和,不走这套。
|
|
893
|
+
"""
|
|
894
|
+
|
|
895
|
+
def __init__(self) -> None:
|
|
896
|
+
self._jobs: "queue.SimpleQueue[tuple[Callable[[], Any], concurrent.futures.Future[Any]] | None]"
|
|
897
|
+
self._jobs = queue.SimpleQueue()
|
|
898
|
+
self._thread = threading.Thread(target=self._loop, daemon=True, name="session-worker")
|
|
899
|
+
self._thread.start()
|
|
900
|
+
|
|
901
|
+
def _loop(self) -> None:
|
|
902
|
+
"""取任务、执行、回填结果;收到哨兵就退出。
|
|
903
|
+
|
|
904
|
+
每个任务的异常原样塞回 Future:调用方在 ``run`` 里等到的就是它自己那次调用的错。
|
|
905
|
+
"""
|
|
906
|
+
while True:
|
|
907
|
+
job = self._jobs.get()
|
|
908
|
+
if job is None:
|
|
909
|
+
return
|
|
910
|
+
fn, done = job
|
|
911
|
+
try:
|
|
912
|
+
done.set_result(fn())
|
|
913
|
+
except BaseException as error: # noqa: BLE001 —— 任务异常必须回到调用方线程
|
|
914
|
+
done.set_exception(error)
|
|
915
|
+
|
|
916
|
+
def run(self, fn: Callable[[], Any]) -> Any: # noqa: ANN401 —— 会话调用的返回形态由引擎定
|
|
917
|
+
"""把 fn 投递到属主线程执行,并阻塞调用线程直到它结束。
|
|
918
|
+
|
|
919
|
+
:param fn: 要在属主线程上执行的调用
|
|
920
|
+
:returns: fn 的返回值
|
|
921
|
+
:raises BaseException: fn 抛什么这里就抛什么
|
|
922
|
+
"""
|
|
923
|
+
done: concurrent.futures.Future[Any] = concurrent.futures.Future()
|
|
924
|
+
self._jobs.put((fn, done))
|
|
925
|
+
return done.result()
|
|
926
|
+
|
|
927
|
+
def stop(self) -> None:
|
|
928
|
+
"""发哨兵收线程。队列里的任务会先跑完,所以 close 之后 stop 是安全的。"""
|
|
929
|
+
self._jobs.put(None)
|
|
930
|
+
self._thread.join(timeout=5.0)
|
|
931
|
+
|
|
932
|
+
|
|
668
933
|
def _new_session_id() -> str:
|
|
669
934
|
"""生成一个短的会话 id。
|
|
670
935
|
|
|
@@ -714,7 +979,7 @@ def _make_session(kind: str, args: dict[str, Any]) -> Any:
|
|
|
714
979
|
common["proxy"] = proxy
|
|
715
980
|
common["extra_flags"] = [guard.WEBRTC_NO_LEAK_FLAG]
|
|
716
981
|
if kind == "browser":
|
|
717
|
-
session = DynamicSession(**common)
|
|
982
|
+
session: DynamicSession | StealthySession = DynamicSession(**common)
|
|
718
983
|
else:
|
|
719
984
|
session = StealthySession(
|
|
720
985
|
**common,
|
|
@@ -765,44 +1030,78 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
765
1030
|
session_id = args.get("sessionId") or _new_session_id()
|
|
766
1031
|
if not isinstance(session_id, str) or not session_id:
|
|
767
1032
|
raise AdapterError("BAD_ARGS", "sessionId must be a string")
|
|
768
|
-
if session_id in _SESSIONS:
|
|
769
|
-
raise AdapterError("BAD_ARGS", f"session already exists: {session_id}")
|
|
770
|
-
_enforce_session_limits(kind)
|
|
771
1033
|
|
|
1034
|
+
# 「判重复 + 判名额 + 占位」三步必须原子。sidecar 有多个 worker 线程:并发的
|
|
1035
|
+
# session_open 各自判完再各自开 —— 于是 id 重复时后者覆盖前者(漏一个已经在跑的
|
|
1036
|
+
# Chromium),名额判完再开等于没判(开满 8 个之后还能继续开)。开一个浏览器要几百
|
|
1037
|
+
# 毫秒,这个窗口足够宽。所以先在锁里占位,真正的构造放在锁外。
|
|
1038
|
+
with _SESSION_LOCK:
|
|
1039
|
+
if session_id in _SESSIONS:
|
|
1040
|
+
raise AdapterError("BAD_ARGS", f"session already exists: {session_id}")
|
|
1041
|
+
_enforce_session_limits(kind)
|
|
1042
|
+
# 锁在占位时就建好:构造期占用的也是它,所以「造到一半」与「用着」互斥。
|
|
1043
|
+
placeholder = {"pending": True, "type": kind, "lock": threading.Lock()}
|
|
1044
|
+
_SESSIONS[session_id] = placeholder
|
|
1045
|
+
entry_lock = placeholder["lock"]
|
|
1046
|
+
|
|
1047
|
+
# browser/stealth 先起属主线程,构造(含 sync_playwright 的启动)整个发生在它上面
|
|
1048
|
+
# —— greenlet 绑定从此指向这条线程,之后每次 fetch/close 都投递回来。static 没有
|
|
1049
|
+
# 线程亲和,留在调用线程即可。
|
|
1050
|
+
worker: _SessionWorker | None = None
|
|
772
1051
|
try:
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
1052
|
+
if kind == "static":
|
|
1053
|
+
usable, closer = _make_session(kind, args)
|
|
1054
|
+
else:
|
|
1055
|
+
worker = _SessionWorker()
|
|
1056
|
+
usable, closer = worker.run(lambda: _make_session(kind, args))
|
|
1057
|
+
except BaseException as error:
|
|
1058
|
+
if worker is not None:
|
|
1059
|
+
worker.stop()
|
|
1060
|
+
with _SESSION_LOCK:
|
|
1061
|
+
_SESSIONS.pop(session_id, None)
|
|
1062
|
+
if isinstance(error, AdapterError):
|
|
1063
|
+
raise
|
|
777
1064
|
raise AdapterError("SESSION_OPEN_FAILED", f"{type(error).__name__}: {error}") from error
|
|
778
1065
|
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
1066
|
+
with _SESSION_LOCK:
|
|
1067
|
+
_SESSIONS[session_id] = {
|
|
1068
|
+
"session": usable, # 真正发请求的对象
|
|
1069
|
+
"closer": closer, # 关它用的对象(static 是 wrapper,浏览器是自身)
|
|
1070
|
+
"type": kind,
|
|
1071
|
+
# 浏览器会话是否带着代理;stealth 的 block_webrtc 要在每次 fetch 时跟着它走。
|
|
1072
|
+
"proxied": kind != "static" and guard.default_proxy() != "",
|
|
1073
|
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
|
1074
|
+
# 同一把锁:占位时建的那把,盖回来而不是新建 —— 新建会让构造期与使用期各锁各的。
|
|
1075
|
+
"lock": entry_lock,
|
|
1076
|
+
# browser/stealth 的专属执行线程;static 为 None(见 _SessionWorker 的说明)。
|
|
1077
|
+
"worker": worker,
|
|
1078
|
+
}
|
|
1079
|
+
created_at = _SESSIONS[session_id]["created_at"]
|
|
787
1080
|
return {
|
|
788
1081
|
"sessionId": session_id,
|
|
789
1082
|
"sessionType": kind,
|
|
790
|
-
"createdAt":
|
|
1083
|
+
"createdAt": created_at,
|
|
791
1084
|
}
|
|
792
1085
|
|
|
793
1086
|
|
|
794
1087
|
def _get_session(session_id: Any) -> dict[str, Any]:
|
|
795
1088
|
"""按 id 取已登记的会话。
|
|
796
1089
|
|
|
1090
|
+
正在构造中的条目也占着 id,所以「存在」不等于「可用」:拿到这种条目时明确报错,
|
|
1091
|
+
而不是让调用方在 entry["session"] 上撞 KeyError。
|
|
1092
|
+
|
|
797
1093
|
:param session_id: 会话 id
|
|
798
1094
|
:returns: 登记条目
|
|
799
|
-
:raises AdapterError: id
|
|
1095
|
+
:raises AdapterError: id 缺失、不存在,或该 id 还在构造中
|
|
800
1096
|
"""
|
|
801
1097
|
if not isinstance(session_id, str) or not session_id:
|
|
802
1098
|
raise AdapterError("BAD_ARGS", "sessionId is required")
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
1099
|
+
with _SESSION_LOCK:
|
|
1100
|
+
entry = _SESSIONS.get(session_id)
|
|
1101
|
+
if entry is None:
|
|
1102
|
+
raise AdapterError("NO_SUCH_SESSION", f"no such session: {session_id}")
|
|
1103
|
+
if entry.get("pending") is True:
|
|
1104
|
+
raise AdapterError("NO_SUCH_SESSION", f"session {session_id} is still being created; retry shortly")
|
|
806
1105
|
return entry
|
|
807
1106
|
|
|
808
1107
|
|
|
@@ -818,12 +1117,17 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
818
1117
|
extraction_type, css_selector, main_content_only, limit = _extraction(args)
|
|
819
1118
|
url = _url(args)
|
|
820
1119
|
|
|
1120
|
+
# 一份会话同一时刻只服务一个请求:static 靠 entry 锁,browser/stealth 靠属主线程
|
|
1121
|
+
# 天然串行。两种实现也都对「多线程同时用同一份会话」零容忍 —— Playwright 的同步
|
|
1122
|
+
# API 靠 greenlet 一次只服务一个线程,curl_cffi 的 Session 文档原话是「一个时刻一个
|
|
1123
|
+
# 会话」。表现是看不懂的崩溃,甚至是上下文串台 —— 所以在结构上就不给这个可能。
|
|
821
1124
|
try:
|
|
822
1125
|
if entry["type"] == "static":
|
|
823
|
-
|
|
1126
|
+
with entry["lock"]:
|
|
1127
|
+
response = session.get(url, **_static_params(args, url))
|
|
824
1128
|
else:
|
|
825
|
-
# 浏览器会话的代理在开场时就定死了(见 _make_session),这里不再逐 URL
|
|
826
|
-
# 覆盖的做法是新建 context,cookie 与登录态会随之清空。
|
|
1129
|
+
# 浏览器会话的代理在开场时就定死了(见 _make_session),这里不再逐 URL
|
|
1130
|
+
# 覆盖 —— 覆盖的做法是新建 context,cookie 与登录态会随之清空。
|
|
827
1131
|
params = _browser_params(args, url)
|
|
828
1132
|
params.pop("proxy", None)
|
|
829
1133
|
params.pop("extra_flags", None)
|
|
@@ -831,11 +1135,14 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
831
1135
|
if entry["type"] == "stealth":
|
|
832
1136
|
params["solve_cloudflare"] = bool(args.get("solveCloudflare", False))
|
|
833
1137
|
params["hide_canvas"] = bool(args.get("hideCanvas", False))
|
|
834
|
-
params["block_webrtc"] = bool(args.get("blockWebrtc", False)) or bool(
|
|
835
|
-
entry["proxied"]
|
|
836
|
-
)
|
|
1138
|
+
params["block_webrtc"] = bool(args.get("blockWebrtc", False)) or bool(entry["proxied"])
|
|
837
1139
|
params["allow_webgl"] = bool(args.get("allowWebgl", True))
|
|
838
|
-
|
|
1140
|
+
# 投递到属主线程执行:greenlet 绑定在那里(见 _SessionWorker)。排队期间调用
|
|
1141
|
+
# 线程原地等 —— 并发的 fetch 因此天然串行,entry 锁对浏览器会话是多余的。
|
|
1142
|
+
worker: _SessionWorker | None = entry["worker"]
|
|
1143
|
+
if worker is None: # pragma: no cover —— browser/stealth 条目必有属主线程
|
|
1144
|
+
raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
|
|
1145
|
+
response = worker.run(lambda: session.fetch(url, **params))
|
|
839
1146
|
except AdapterError:
|
|
840
1147
|
raise
|
|
841
1148
|
except Exception as error: # noqa: BLE001
|
|
@@ -859,30 +1166,57 @@ def session_list(_args: dict[str, Any]) -> dict[str, Any]:
|
|
|
859
1166
|
:param _args: 协议参数,本方法不用
|
|
860
1167
|
:returns: 会话列表
|
|
861
1168
|
"""
|
|
862
|
-
|
|
863
|
-
|
|
1169
|
+
# 字典遍历期间被别的线程插入/删除会抛 RuntimeError,而那正是 bridge 多 worker 下的
|
|
1170
|
+
# 常态。进锁里把清单复制出来,遍历就与并发改写无关。
|
|
1171
|
+
with _SESSION_LOCK:
|
|
1172
|
+
rows = [
|
|
864
1173
|
{
|
|
865
1174
|
"sessionId": session_id,
|
|
866
1175
|
"sessionType": entry["type"],
|
|
867
|
-
|
|
1176
|
+
# 构造中的条目还没有创建时间;报空串而不是 KeyError。
|
|
1177
|
+
"createdAt": entry.get("created_at", ""),
|
|
868
1178
|
}
|
|
869
1179
|
for session_id, entry in _SESSIONS.items()
|
|
870
1180
|
]
|
|
871
|
-
}
|
|
1181
|
+
return {"sessions": rows}
|
|
1182
|
+
|
|
872
1183
|
|
|
1184
|
+
def _release_entry(entry: dict[str, Any]) -> None:
|
|
1185
|
+
"""把一个已构造好的会话条目关掉。
|
|
873
1186
|
|
|
874
|
-
|
|
1187
|
+
:param entry: 登记条目
|
|
1188
|
+
"""
|
|
1189
|
+
# suppress 而不是 try/except/pass:关不掉也不能让桥接层挂掉,而那正是 suppress 的
|
|
1190
|
+
# 既有语义 —— 少一层缩进,意图也一样清楚。
|
|
1191
|
+
with contextlib.suppress(Exception):
|
|
1192
|
+
entry["closer"].close() if entry["type"] != "static" else entry["closer"].__exit__(None, None, None)
|
|
1193
|
+
|
|
1194
|
+
|
|
1195
|
+
def _close_entry(session_id: Any) -> None:
|
|
875
1196
|
"""关掉一个会话并从注册表移除。
|
|
876
1197
|
|
|
877
|
-
:param session_id: 会话 id
|
|
1198
|
+
:param session_id: 会话 id;JSON 载荷里来的,也可能是登记表的键
|
|
878
1199
|
"""
|
|
879
|
-
|
|
1200
|
+
with _SESSION_LOCK:
|
|
1201
|
+
entry = _SESSIONS.pop(session_id, None)
|
|
880
1202
|
if entry is None:
|
|
881
1203
|
return
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
1204
|
+
if entry.get("pending") is True:
|
|
1205
|
+
# 还没构造完:构造方自己会在成功时覆盖这一条,或在失败时把它摘掉。这里不能碰
|
|
1206
|
+
# closer —— 它还不存在。
|
|
1207
|
+
return
|
|
1208
|
+
worker: _SessionWorker | None = entry.get("worker")
|
|
1209
|
+
if worker is not None:
|
|
1210
|
+
# 浏览器会话的 close 是一次 Playwright 远端调用,必须在属主线程上做;投递进去
|
|
1211
|
+
# 还天然排在在途 fetch 之后 —— 「抓取进行中收到 close」会等抓取落地再关,而
|
|
1212
|
+
# 不是把一次正在跑的抓取从底下抽走。
|
|
1213
|
+
worker.run(lambda: _release_entry(entry))
|
|
1214
|
+
worker.stop()
|
|
1215
|
+
return
|
|
1216
|
+
# static 没有属主线程,用 entry 锁:否则「抓取进行中收到 close」会把一次正在跑的
|
|
1217
|
+
# 抓取从底下抽走,而 close 那一侧看到的是一个已经拆掉的会话。
|
|
1218
|
+
with entry["lock"]:
|
|
1219
|
+
_release_entry(entry)
|
|
886
1220
|
|
|
887
1221
|
|
|
888
1222
|
def session_close(args: dict[str, Any]) -> dict[str, Any]:
|
|
@@ -892,6 +1226,8 @@ def session_close(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
892
1226
|
:returns: 关闭结果
|
|
893
1227
|
"""
|
|
894
1228
|
session_id = args.get("sessionId")
|
|
1229
|
+
# _get_session 已确认它是非空字符串;这里直接用它,而 _close_entry 的入参标 Any 是因为
|
|
1230
|
+
# 两个调用来源不同 —— 本条路径来自 JSON 载荷,close_all_sessions 来自登记表的键。
|
|
895
1231
|
_get_session(session_id)
|
|
896
1232
|
_close_entry(session_id)
|
|
897
1233
|
return {"sessionId": session_id, "closed": True}
|