@jayyuen66/dsh-scrapling 0.1.5 → 0.1.7
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/CHANGELOG.md +81 -7
- package/LICENSE +1 -1
- package/README.md +20 -19
- package/README.zh-CN.md +18 -17
- package/THIRD_PARTY_NOTICES.md +32 -11
- package/bin/dsh-scrapling.mjs +68 -71
- package/client.js +9 -9
- package/cordis.patch.yml +7 -3
- package/docs/DETAIL.md +6 -6
- package/docs/DETAIL.zh.md +6 -6
- package/host.js +19 -33
- package/package.json +53 -47
- package/py/adapters.py +30 -8
- package/py/bridge.py +137 -30
- package/py/crawl.py +69 -27
- package/py/extraction.py +70 -24
- package/py/guard.py +55 -24
- package/py/media.py +30 -9
- package/py/redact.py +20 -2
- package/py/redis_storage.py +92 -31
- package/py/search.py +9 -2
- package/py/session_page.py +57 -24
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jayyuen66/dsh-scrapling",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.7",
|
|
4
4
|
"description": "Scrapling 网页抓取插件(dsh):静态/浏览器抓取 + CSS/XPath 结构化抽取 + 选择器自愈 + capture_xhr 与会话网络历史 + 登录态存取 + Spider 爬虫,由常驻 Python 进程驱动。",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh",
|
|
@@ -15,7 +15,10 @@
|
|
|
15
15
|
"url": "https://github.com/JayYuen666/dsh-scrapling/issues"
|
|
16
16
|
},
|
|
17
17
|
"license": "MIT",
|
|
18
|
-
"author":
|
|
18
|
+
"author": {
|
|
19
|
+
"name": "JayYuen",
|
|
20
|
+
"url": "https://github.com/JayYuen666"
|
|
21
|
+
},
|
|
19
22
|
"repository": {
|
|
20
23
|
"type": "git",
|
|
21
24
|
"url": "git+https://github.com/JayYuen666/dsh-scrapling.git"
|
|
@@ -67,52 +70,54 @@
|
|
|
67
70
|
},
|
|
68
71
|
"dependencies": {
|
|
69
72
|
"@modelcontextprotocol/sdk": "1.32.2",
|
|
73
|
+
"fs-native-extensions": "1.5.3",
|
|
70
74
|
"ipaddr.js": "2.5.0",
|
|
71
75
|
"zod": "4.6.7"
|
|
72
76
|
},
|
|
73
77
|
"devDependencies": {
|
|
74
|
-
"@deepseek-ai/cordis": "4.0.6-alpha.
|
|
75
|
-
"@deepseek-ai/cordis-plugin-include": "1.0.11-alpha.
|
|
76
|
-
"@deepseek-ai/cordis-plugin-loader": "1.0.7-alpha.
|
|
77
|
-
"@deepseek-ai/dsh-api-remotes": "0.2.2-alpha.
|
|
78
|
-
"@deepseek-ai/dsh-client-locale": "0.2.2-alpha.
|
|
79
|
-
"@deepseek-ai/dsh-client-store": "0.2.2-alpha.
|
|
80
|
-
"@deepseek-ai/dsh-client-ui-chat": "0.2.2-alpha.
|
|
81
|
-
"@deepseek-ai/dsh-client-ui-conversation": "0.2.2-alpha.
|
|
82
|
-
"@deepseek-ai/dsh-client-ui-layout": "0.2.2-alpha.
|
|
83
|
-
"@deepseek-ai/dsh-client-ui-plugin-manager": "0.2.2-alpha.
|
|
84
|
-
"@deepseek-ai/dsh-client-ui-renderer": "0.2.2-alpha.
|
|
85
|
-
"@deepseek-ai/dsh-client-ui-settings": "0.2.2-alpha.
|
|
86
|
-
"@deepseek-ai/dsh-client-ui-slots": "0.2.2-alpha.
|
|
87
|
-
"@deepseek-ai/dsh-client-ui-tool": "0.2.2-alpha.
|
|
88
|
-
"@deepseek-ai/dsh-host-webserver": "0.2.2-alpha.
|
|
89
|
-
"@deepseek-ai/dsh-http-proxy": "0.2.2-alpha.
|
|
90
|
-
"@deepseek-ai/dsh-jobs": "0.2.2-alpha.
|
|
91
|
-
"@deepseek-ai/dsh-jobs-local": "0.2.2-alpha.
|
|
92
|
-
"@deepseek-ai/dsh-output-retention": "0.2.2-alpha.
|
|
93
|
-
"@deepseek-ai/dsh-package-manifest": "0.2.2-alpha.
|
|
94
|
-
"@deepseek-ai/dsh-ptc-runtime": "0.2.2-alpha.
|
|
95
|
-
"@deepseek-ai/dsh-sandbox": "0.2.2-alpha.
|
|
96
|
-
"@deepseek-ai/dsh-scope": "0.2.2-alpha.
|
|
97
|
-
"@deepseek-ai/dsh-session": "0.2.2-alpha.
|
|
98
|
-
"@deepseek-ai/dsh-settings": "0.2.2-alpha.
|
|
99
|
-
"@deepseek-ai/dsh-shell": "0.2.2-alpha.
|
|
100
|
-
"@deepseek-ai/dsh-subprocess": "0.2.2-alpha.
|
|
101
|
-
"@deepseek-ai/dsh-system-prompt": "0.2.2-alpha.
|
|
102
|
-
"@deepseek-ai/dsh-tool-executor-native": "0.2.2-alpha.
|
|
103
|
-
"@deepseek-ai/dsh-tools": "0.2.2-alpha.
|
|
104
|
-
"@deepseek-ai/dsh-typert-protocol": "0.2.2-alpha.
|
|
105
|
-
"@deepseek-ai/dsh-user-approval": "0.2.2-alpha.
|
|
106
|
-
"@deepseek-ai/dsh-web": "0.2.2-alpha.
|
|
107
|
-
"@deepseek-ai/schemastery": "3.18.6-alpha.
|
|
78
|
+
"@deepseek-ai/cordis": "4.0.6-alpha.2",
|
|
79
|
+
"@deepseek-ai/cordis-plugin-include": "1.0.11-alpha.2",
|
|
80
|
+
"@deepseek-ai/cordis-plugin-loader": "1.0.7-alpha.2",
|
|
81
|
+
"@deepseek-ai/dsh-api-remotes": "0.2.2-alpha.3",
|
|
82
|
+
"@deepseek-ai/dsh-client-locale": "0.2.2-alpha.3",
|
|
83
|
+
"@deepseek-ai/dsh-client-store": "0.2.2-alpha.3",
|
|
84
|
+
"@deepseek-ai/dsh-client-ui-chat": "0.2.2-alpha.3",
|
|
85
|
+
"@deepseek-ai/dsh-client-ui-conversation": "0.2.2-alpha.3",
|
|
86
|
+
"@deepseek-ai/dsh-client-ui-layout": "0.2.2-alpha.3",
|
|
87
|
+
"@deepseek-ai/dsh-client-ui-plugin-manager": "0.2.2-alpha.3",
|
|
88
|
+
"@deepseek-ai/dsh-client-ui-renderer": "0.2.2-alpha.3",
|
|
89
|
+
"@deepseek-ai/dsh-client-ui-settings": "0.2.2-alpha.3",
|
|
90
|
+
"@deepseek-ai/dsh-client-ui-slots": "0.2.2-alpha.3",
|
|
91
|
+
"@deepseek-ai/dsh-client-ui-tool": "0.2.2-alpha.3",
|
|
92
|
+
"@deepseek-ai/dsh-host-webserver": "0.2.2-alpha.3",
|
|
93
|
+
"@deepseek-ai/dsh-http-proxy": "0.2.2-alpha.3",
|
|
94
|
+
"@deepseek-ai/dsh-jobs": "0.2.2-alpha.3",
|
|
95
|
+
"@deepseek-ai/dsh-jobs-local": "0.2.2-alpha.3",
|
|
96
|
+
"@deepseek-ai/dsh-output-retention": "0.2.2-alpha.3",
|
|
97
|
+
"@deepseek-ai/dsh-package-manifest": "0.2.2-alpha.3",
|
|
98
|
+
"@deepseek-ai/dsh-ptc-runtime": "0.2.2-alpha.3",
|
|
99
|
+
"@deepseek-ai/dsh-sandbox": "0.2.2-alpha.3",
|
|
100
|
+
"@deepseek-ai/dsh-scope": "0.2.2-alpha.3",
|
|
101
|
+
"@deepseek-ai/dsh-session": "0.2.2-alpha.3",
|
|
102
|
+
"@deepseek-ai/dsh-settings": "0.2.2-alpha.3",
|
|
103
|
+
"@deepseek-ai/dsh-shell": "0.2.2-alpha.3",
|
|
104
|
+
"@deepseek-ai/dsh-subprocess": "0.2.2-alpha.3",
|
|
105
|
+
"@deepseek-ai/dsh-system-prompt": "0.2.2-alpha.3",
|
|
106
|
+
"@deepseek-ai/dsh-tool-executor-native": "0.2.2-alpha.3",
|
|
107
|
+
"@deepseek-ai/dsh-tools": "0.2.2-alpha.3",
|
|
108
|
+
"@deepseek-ai/dsh-typert-protocol": "0.2.2-alpha.3",
|
|
109
|
+
"@deepseek-ai/dsh-user-approval": "0.2.2-alpha.3",
|
|
110
|
+
"@deepseek-ai/dsh-web": "0.2.2-alpha.3",
|
|
111
|
+
"@deepseek-ai/schemastery": "3.18.6-alpha.2",
|
|
108
112
|
"@e18e/eslint-plugin": "0.8.1",
|
|
109
|
-
"@jayyuen66/dsh-plugin-shared": "0.2.
|
|
113
|
+
"@jayyuen66/dsh-plugin-shared": "0.2.3",
|
|
110
114
|
"@types/node": "26.6.6",
|
|
111
115
|
"@types/react": "19.3.0",
|
|
112
116
|
"@vitest/coverage-v8": "5.0.5",
|
|
113
117
|
"eslint-plugin-regexp": "3.3.2",
|
|
114
118
|
"eslint-plugin-sonarjs": "4.2.2",
|
|
115
119
|
"eslint-plugin-zod": "5.2.2",
|
|
120
|
+
"fast-check": "4.10.2",
|
|
116
121
|
"oxfmt": "0.75.0",
|
|
117
122
|
"oxlint": "1.90.0",
|
|
118
123
|
"oxlint-tsgolint": "7.0.2005",
|
|
@@ -123,12 +128,12 @@
|
|
|
123
128
|
"vitest": "5.0.5"
|
|
124
129
|
},
|
|
125
130
|
"peerDependencies": {
|
|
126
|
-
"@deepseek-ai/dsh": "^0.2.1-rc.
|
|
127
|
-
"@deepseek-ai/dsh-output-retention": "^0.2.1-rc.
|
|
128
|
-
"@deepseek-ai/dsh-tools": "^0.2.1-rc.
|
|
129
|
-
"@deepseek-ai/dsh-typert-protocol": "^0.2.1-rc.
|
|
130
|
-
"@deepseek-ai/dsh-web": "^0.2.1-rc.
|
|
131
|
-
"@deepseek-ai/schemastery": "3.18.6-alpha.1"
|
|
131
|
+
"@deepseek-ai/dsh": "^0.2.1-rc.5 || ^0.2.2-alpha.3",
|
|
132
|
+
"@deepseek-ai/dsh-output-retention": "^0.2.1-rc.5 || ^0.2.2-alpha.3",
|
|
133
|
+
"@deepseek-ai/dsh-tools": "^0.2.1-rc.5 || ^0.2.2-alpha.3",
|
|
134
|
+
"@deepseek-ai/dsh-typert-protocol": "^0.2.1-rc.5 || ^0.2.2-alpha.3",
|
|
135
|
+
"@deepseek-ai/dsh-web": "^0.2.1-rc.5 || ^0.2.2-alpha.3",
|
|
136
|
+
"@deepseek-ai/schemastery": "^3.18.6-alpha.1"
|
|
132
137
|
},
|
|
133
138
|
"peerDependenciesMeta": {
|
|
134
139
|
"@deepseek-ai/dsh": {
|
|
@@ -140,8 +145,8 @@
|
|
|
140
145
|
},
|
|
141
146
|
"icon": "icon.svg",
|
|
142
147
|
"engines": {
|
|
143
|
-
"dsh": "^0.2.1-rc.3",
|
|
144
|
-
"node": ">=22.
|
|
148
|
+
"dsh": "^0.2.1-rc.5 || ^0.2.2-alpha.3",
|
|
149
|
+
"node": ">=22.18.0"
|
|
145
150
|
},
|
|
146
151
|
"dsh": {
|
|
147
152
|
"manifestVersion": 1,
|
|
@@ -160,11 +165,12 @@
|
|
|
160
165
|
"lint": "oxlint .",
|
|
161
166
|
"test": "vitest run --coverage",
|
|
162
167
|
"test:watch": "vitest",
|
|
163
|
-
"check": "npm run --loglevel=warn typecheck && npm run --loglevel=warn lint && npm run --loglevel=warn build:client && npm run --loglevel=warn build && npm run --loglevel=warn test && npm run --loglevel=warn fmt:check && npm run --loglevel=warn check:py",
|
|
168
|
+
"check": "npm run --loglevel=warn typecheck && npm run --loglevel=warn lint && npm run --loglevel=warn build:client && npm run --loglevel=warn build && npm run --loglevel=warn test && npm run --loglevel=warn gate:eol && npm run --loglevel=warn fmt:check && npm run --loglevel=warn check:py",
|
|
164
169
|
"fmt:check": "oxfmt --check .",
|
|
165
170
|
"py": "node py-launcher.mjs",
|
|
166
171
|
"py:which": "node py-launcher.mjs --which",
|
|
167
172
|
"face:py": "node face-py.mjs",
|
|
173
|
+
"gate:eol": "node eol-gate.mjs",
|
|
168
174
|
"lint:py": "npm run --loglevel=warn py -- -m ruff check py/",
|
|
169
175
|
"fmt:py": "npm run --loglevel=warn py -- -m ruff format --check py/",
|
|
170
176
|
"typecheck:py": "npm run --loglevel=warn py -- -m mypy py/",
|
|
@@ -173,7 +179,7 @@
|
|
|
173
179
|
"cov:py": "node py-launcher.mjs -m coverage erase && node py-launcher.mjs --env=DSH_PY_COVERAGE=1 -m coverage run --parallel-mode py/tests/test_bridge.py && node py-launcher.mjs -m coverage combine && node py-launcher.mjs -m coverage report -m && node py-launcher.mjs -m coverage erase",
|
|
174
180
|
"coverage:floor": "node py-launcher.mjs -m coverage erase && node py-launcher.mjs --env=DSH_PY_COVERAGE=1 -m coverage run --parallel-mode py/tests/test_bridge.py && node py-launcher.mjs -m coverage combine && node py-launcher.mjs -m coverage report --omit=\"py/tests/*\" --fail-under=74 && node -e \"require('node:fs').mkdirSync('coverage',{recursive:true})\" && node py-launcher.mjs -m coverage json --omit=\"py/tests/*\" -o coverage/python-coverage.json && node coverage-floor.mjs && node py-launcher.mjs -m coverage erase",
|
|
175
181
|
"deps:py": "node deps-check.mjs",
|
|
176
|
-
"check:py": "npm run --loglevel=warn py:which && npm run --loglevel=warn face:py && npm run --loglevel=warn deps:py && npm run --loglevel=warn lint:py && npm run --loglevel=warn fmt:py && npm run --loglevel=warn typecheck:py && npm run --loglevel=warn
|
|
182
|
+
"check:py": "npm run --loglevel=warn py:which && npm run --loglevel=warn face:py && npm run --loglevel=warn deps:py && npm run --loglevel=warn lint:py && npm run --loglevel=warn fmt:py && npm run --loglevel=warn typecheck:py && npm run --loglevel=warn bandit:py && npm run --loglevel=warn coverage:floor",
|
|
177
183
|
"build:cli": "node build-cli.ts"
|
|
178
184
|
}
|
|
179
185
|
}
|
package/py/adapters.py
CHANGED
|
@@ -203,7 +203,7 @@ def _network_summary(
|
|
|
203
203
|
"id": int(meta.get("network_id") or 0),
|
|
204
204
|
"url": redact_url_secrets(str(item.url)),
|
|
205
205
|
"status": item.status,
|
|
206
|
-
"bytes": len(body),
|
|
206
|
+
"bytes": len(body) if body else 0,
|
|
207
207
|
# 上游把方法记在 Response.method 上;从 meta / request_headers 读会退化成 GET,
|
|
208
208
|
# POST 的 XHR 在摘要里一律显示成 GET(V5 已复现)。
|
|
209
209
|
"method": str(getattr(item, "method", "GET")),
|
|
@@ -263,6 +263,9 @@ def _sanitized_page(response: Any, *, main_content_only: bool) -> Any:
|
|
|
263
263
|
return Convertor._sanitize_for_ai(Convertor._strip_noise_tags(page))
|
|
264
264
|
|
|
265
265
|
|
|
266
|
+
_ACTIVE_CONTENT_WARNED = threading.Event()
|
|
267
|
+
|
|
268
|
+
|
|
266
269
|
def _strip_active_content(page: Any) -> None:
|
|
267
270
|
"""剥掉元素上的可执行残留,让清洗后的 HTML 真的只剩内容。
|
|
268
271
|
|
|
@@ -270,9 +273,19 @@ def _strip_active_content(page: Any) -> None:
|
|
|
270
273
|
清洗后 ``onclick`` 照样在,``<meta http-equiv=refresh>`` 与 ``srcdoc`` 也照样在 ——
|
|
271
274
|
那些是事件处理器与跳转指令,直接把内网地址带进模型上下文。html 那条路径还回传
|
|
272
275
|
完整标签,所以得在这里补一刀;text 路径取的是文本,不受属性影响。
|
|
276
|
+
|
|
277
|
+
拿不到可迭的 ``_root`` 时不能静默放行:那意味着上游的树形态变了,本函数从「补一刀」
|
|
278
|
+
退化成「什么都不做」。每个进程只报一次,避免逐条抽取刷屏。
|
|
273
279
|
"""
|
|
274
280
|
root = getattr(page, "_root", None)
|
|
275
281
|
if root is None or not hasattr(root, "iter"):
|
|
282
|
+
if not _ACTIVE_CONTENT_WARNED.is_set():
|
|
283
|
+
_ACTIVE_CONTENT_WARNED.set()
|
|
284
|
+
print(
|
|
285
|
+
"[adapters] page._root has no iter(); active-content attributes were not stripped",
|
|
286
|
+
file=sys.stderr,
|
|
287
|
+
flush=True,
|
|
288
|
+
)
|
|
276
289
|
return
|
|
277
290
|
for element in list(root.iter()):
|
|
278
291
|
tag = str(getattr(element, "tag", "") or "").lower()
|
|
@@ -299,7 +312,7 @@ def _strip_active_content(page: Any) -> None:
|
|
|
299
312
|
# (百分号编码形式则多出 %),两者都不含右括号,所以这个非贪婪匹配不会提前截断。
|
|
300
313
|
_MD_DATA_IMAGE = re.compile(r"!\[([^\]]*)\]\(\s*data:[^)]*\)", re.IGNORECASE)
|
|
301
314
|
# HTML 路径:<img src="data:..."> 与 <source srcset="data:...">。
|
|
302
|
-
_HTML_DATA_ATTR = re.compile(r"""(data:[^"'\s>]+)""", re.IGNORECASE)
|
|
315
|
+
_HTML_DATA_ATTR = re.compile(r"""(data:image/[^"'\s>]+)""", re.IGNORECASE)
|
|
303
316
|
# 代码围栏的分隔行。围栏**内部**的 data URI 必须原样保留 —— 那可能是教程里教的示例代码,
|
|
304
317
|
# 剥掉它等于把文档本身改了。
|
|
305
318
|
_FENCE = re.compile(r"\A\s*(?:```|~~~)")
|
|
@@ -1738,7 +1751,8 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1738
1751
|
:returns: 归一后的载荷
|
|
1739
1752
|
:raises AdapterError: 会话不存在 / 类型不支持 / 抓取失败 / 把 static 专属的键给了浏览器会话
|
|
1740
1753
|
"""
|
|
1741
|
-
|
|
1754
|
+
session_id = args.get("sessionId")
|
|
1755
|
+
entry = _get_session(session_id)
|
|
1742
1756
|
session = entry["session"]
|
|
1743
1757
|
extraction_type, css_selector, main_content_only, limit = _extraction(args)
|
|
1744
1758
|
url = _url(args)
|
|
@@ -1753,19 +1767,24 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1753
1767
|
try:
|
|
1754
1768
|
if entry["type"] == "static":
|
|
1755
1769
|
with entry["lock"]:
|
|
1770
|
+
# 取到条目之后、拿到锁之前,close 可能已经把它摘下并关掉了。未置位时
|
|
1771
|
+
# 会持锁使用一份已关闭的会话,异常最终被归成 FETCH_FAILED——语义错位。
|
|
1772
|
+
if entry.get("closed") is True:
|
|
1773
|
+
raise AdapterError("NO_SUCH_SESSION", f"no such session: {session_id}")
|
|
1756
1774
|
# 与一次性 fetch 同一条复判:static 会话的请求不经过浏览器的 page.route,
|
|
1757
1775
|
# 少了这一道,「Host 判完 → curl_cffi 自己再解析」之间就是敞开的。
|
|
1758
1776
|
allowed, reason = guard.url_allowed(url)
|
|
1759
1777
|
if not allowed:
|
|
1760
1778
|
raise AdapterError("URL_BLOCKED", f"{url}: {reason}")
|
|
1761
|
-
# form/json
|
|
1762
|
-
#
|
|
1763
|
-
|
|
1764
|
-
|
|
1779
|
+
# 方法与一次性 fetch 同源:显式 method 优先,没给时由 form/json/body
|
|
1780
|
+
# 推 POST,显式 GET 带体会报错。只看 form/json 的两行写法会让
|
|
1781
|
+
# session.fetch 的 method=PUT/DELETE 与裸 body 静默落地(请求照发、
|
|
1782
|
+
# 语义错了),而调用方从回包上看不出这件事。
|
|
1783
|
+
static_method = _static_method(args)
|
|
1765
1784
|
if static_method != "GET" and not guard.ALLOW_WRITE_METHODS:
|
|
1766
1785
|
raise AdapterError(
|
|
1767
1786
|
"WRITE_DISABLED",
|
|
1768
|
-
"
|
|
1787
|
+
f"{static_method} changes state on the remote side; the deployment must set "
|
|
1769
1788
|
f"allowWriteMethods (env {guard.ALLOW_WRITE_METHODS_ENV}) to allow it",
|
|
1770
1789
|
)
|
|
1771
1790
|
static_params = _static_params(args, url)
|
|
@@ -2042,6 +2061,9 @@ def _close_entry(session_id: Any) -> None:
|
|
|
2042
2061
|
# 写在锁外会留下这个时序 —— 这里已 pop 并释放锁,构造方接着在锁内读到 False
|
|
2043
2062
|
# 并把建好的会话登记回 _SESSIONS,之后才轮到写 True,那条会话就没人关了。
|
|
2044
2063
|
entry["closed_while_pending"] = True
|
|
2064
|
+
elif entry is not None:
|
|
2065
|
+
# 已构造好的条目:置位与摘除同一临界区,之后抢到 entry 锁的 fetch 会看到它。
|
|
2066
|
+
entry["closed"] = True
|
|
2045
2067
|
if entry is None:
|
|
2046
2068
|
return
|
|
2047
2069
|
if entry.get("pending") is True:
|
package/py/bridge.py
CHANGED
|
@@ -22,8 +22,9 @@
|
|
|
22
22
|
1. **stdout 只能是协议帧。** 任何 ``print`` 或第三方库的进度输出都会把 JSON-lines
|
|
23
23
|
流打坏,所以本文件与 adapters 的一切日志都走 stderr。
|
|
24
24
|
2. **一行一帧且不能交错。** 并发请求各自回帧时要串行化,否则两个响应会被拼在同一行。
|
|
25
|
-
3. **读 stdin 要按字节自行切行。**
|
|
26
|
-
|
|
25
|
+
3. **读 stdin 要按字节自行切行。** 逐帧读取既不能等 ``read(n)`` 读满(管道上会一直
|
|
26
|
+
空等),也不能让 ``readline()`` 把整行先吃进内存(超长残帧会先占住无界缓冲);
|
|
27
|
+
因此按块取字节、在自建的缓冲区里切行并增量判长。
|
|
27
28
|
4. **worker 数与并发上限一致。** 浏览器抓取很吃内存(每个 Chromium 实例数百 MB),
|
|
28
29
|
无上限会让几个并行的工具调用把机器拖垮。
|
|
29
30
|
|
|
@@ -40,7 +41,8 @@ import sys
|
|
|
40
41
|
import threading
|
|
41
42
|
import time
|
|
42
43
|
import traceback
|
|
43
|
-
from
|
|
44
|
+
from io import BufferedReader
|
|
45
|
+
from typing import Any, Callable, cast
|
|
44
46
|
|
|
45
47
|
# 协议帧与日志一律 UTF-8:宿主按 UTF-8 解码本进程的 stdout/stderr,而两者都是管道。
|
|
46
48
|
# 管道在 Windows 上默认走本地 ANSI 代码页;`LC_ALL=C` 配上 `PYTHONUTF8=0` 这类环境
|
|
@@ -94,14 +96,19 @@ PROTOCOL_VERSION = 1
|
|
|
94
96
|
# 并发上限:与工作线程数一致,多了也只是排队。
|
|
95
97
|
MAX_INFLIGHT = 4
|
|
96
98
|
|
|
97
|
-
#
|
|
98
|
-
#
|
|
99
|
+
# 单帧字节上限。切出整行后先判长度再解析:解析本身就要把这行再展开一份。
|
|
100
|
+
# 读侧按块累积,一旦缓冲超过上限就弃帧报 BAD_FRAME,不会为一个不带换行的写入
|
|
101
|
+
# 继续累积。宿主侧对每个工具的输出另有封顶,这条防的是「入参本身很大」。
|
|
99
102
|
MAX_FRAME_BYTES = 8 * 1024 * 1024
|
|
100
103
|
|
|
101
104
|
# 待处理队列的深度上限。队列只在 worker 全部占满时增长,而 worker 数是 MAX_INFLIGHT,
|
|
102
105
|
# 所以正常情况下的深度约等于 MAX_INFLIGHT;超过它说明调用方在以远超并发的速率灌帧,
|
|
103
106
|
# 继续收就是纯粹的内存增长。判否让调用方自己退避。
|
|
104
107
|
MAX_QUEUE_DEPTH = MAX_INFLIGHT * 4
|
|
108
|
+
# 关机时每一路 close(爬虫、会话)的最长等待秒数。取 10 秒:浏览器会话的退出要给
|
|
109
|
+
# Chromium 进程留收尾时间,而 sidecar 自己已经不再服务任何请求,等更久只是把
|
|
110
|
+
# 「有界关机」变回无界。
|
|
111
|
+
SHUTDOWN_CLOSE_TIMEOUT = 10.0
|
|
105
112
|
|
|
106
113
|
_WRITE_LOCK = threading.Lock()
|
|
107
114
|
_SLOTS = threading.Semaphore(MAX_INFLIGHT)
|
|
@@ -152,6 +159,25 @@ def fail(request_id: Any, code: str, message: str, details: dict[str, Any] | Non
|
|
|
152
159
|
return {"id": request_id, "ok": False, "error": error}
|
|
153
160
|
|
|
154
161
|
|
|
162
|
+
# scrapling 的可选 extra(fetchers / rag)会按需导入这些包;只有它们缺失才算
|
|
163
|
+
# 「环境没装对」。其它 ModuleNotFoundError 是本插件自己的导入缺陷,不能包装成
|
|
164
|
+
# 安装提示——用户照提示装完仍然会失败。
|
|
165
|
+
OPTIONAL_DEPENDENCIES = frozenset(
|
|
166
|
+
{
|
|
167
|
+
"markdownify",
|
|
168
|
+
"playwright",
|
|
169
|
+
"patchright",
|
|
170
|
+
"curl_cffi",
|
|
171
|
+
"browserforge",
|
|
172
|
+
"msgspec",
|
|
173
|
+
"protego",
|
|
174
|
+
"anyio",
|
|
175
|
+
"click",
|
|
176
|
+
"apify_fingerprint_datapoints",
|
|
177
|
+
}
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
|
|
155
181
|
def handle(frame: dict[str, Any]) -> dict[str, Any]:
|
|
156
182
|
"""分发一个请求帧。
|
|
157
183
|
|
|
@@ -184,7 +210,16 @@ def handle(frame: dict[str, Any]) -> dict[str, Any]:
|
|
|
184
210
|
# 而模型与用户对这两种情况的正确反应完全不同:前者该退避重试,后者该去装包。
|
|
185
211
|
# 报错必须指向后者,所以单列一个码,并把本插件的硬性安装命令直接写进去——
|
|
186
212
|
# Scrapling 自己只说「装 markdownify」,而本插件要的是整个 extra。
|
|
187
|
-
missing = error.name or "
|
|
213
|
+
missing = error.name or "某个模块"
|
|
214
|
+
if missing not in OPTIONAL_DEPENDENCIES:
|
|
215
|
+
# 插件自身代码里的导入错误同样会抛 ModuleNotFoundError;把它说成
|
|
216
|
+
# 「去装 rag extra」会让用户装完仍然报同一个错。
|
|
217
|
+
log(f"{method} aborted: internal import failed: {missing}")
|
|
218
|
+
return fail(
|
|
219
|
+
request_id,
|
|
220
|
+
"FETCH_FAILED",
|
|
221
|
+
f"内部依赖导入失败:{missing}(这是插件自身的缺陷,不是环境缺包)",
|
|
222
|
+
)
|
|
188
223
|
log(f"{method} aborted: missing dependency {missing}")
|
|
189
224
|
return fail(
|
|
190
225
|
request_id,
|
|
@@ -233,7 +268,15 @@ def _worker() -> None:
|
|
|
233
268
|
try:
|
|
234
269
|
emit(handle(frame))
|
|
235
270
|
except Exception as error: # noqa: BLE001 —— 连序列化失败都不能让线程死掉
|
|
236
|
-
|
|
271
|
+
request_id = frame.get("id")
|
|
272
|
+
log(f"emit failed for request {request_id}: {type(error).__name__}: {error}")
|
|
273
|
+
try:
|
|
274
|
+
emit(fail(request_id, "INTERNAL", f"failed to emit response: {type(error).__name__}: {error}"))
|
|
275
|
+
except Exception as fallback_error: # noqa: BLE001 —— 兜底帧也写不出去,只能留日志
|
|
276
|
+
log(
|
|
277
|
+
f"fallback frame for request {request_id} also failed: "
|
|
278
|
+
f"{type(fallback_error).__name__}: {fallback_error}"
|
|
279
|
+
)
|
|
237
280
|
finally:
|
|
238
281
|
with _WORKERS_LOCK:
|
|
239
282
|
current = threading.current_thread()
|
|
@@ -261,6 +304,21 @@ def _ensure_worker(count: int) -> None:
|
|
|
261
304
|
worker.start()
|
|
262
305
|
|
|
263
306
|
|
|
307
|
+
def _run_bounded(label: str, action: Callable[[], None], timeout: float) -> None:
|
|
308
|
+
"""在后台线程里跑一次关闭并等它有界完成。
|
|
309
|
+
|
|
310
|
+
`close_all_crawls()` / `close_all_sessions()` 自己没有超时:它们要等 handler 释放
|
|
311
|
+
持有的锁,而那时 drain 已经放弃等待,关机就会从「有界」变成等一个不确定的对端。
|
|
312
|
+
超时后不重跑也不硬等——进程马上要退,这些资源由 OS 收;留一行日志是为了让宿主侧
|
|
313
|
+
读得出「这一轮是超时收的场」而不是「关干净了」。
|
|
314
|
+
"""
|
|
315
|
+
worker = threading.Thread(target=action, daemon=True, name=f"bridge-{label}")
|
|
316
|
+
worker.start()
|
|
317
|
+
worker.join(timeout)
|
|
318
|
+
if worker.is_alive():
|
|
319
|
+
log(f"shutdown: {label} still running after {timeout}s; leaving it to process exit")
|
|
320
|
+
|
|
321
|
+
|
|
264
322
|
def _shutdown_crawls() -> None:
|
|
265
323
|
"""退出前叫停全部爬虫,并给它们的线程一点收尾时间。
|
|
266
324
|
|
|
@@ -268,12 +326,16 @@ def _shutdown_crawls() -> None:
|
|
|
268
326
|
不读这一路了,帧落进管道就是没人认领的字节。所以爬虫要在会话之前关:蜘蛛自己也要用
|
|
269
327
|
浏览器,先把会话抽走只会让它在下一次请求里抛。
|
|
270
328
|
"""
|
|
271
|
-
try:
|
|
272
|
-
import crawl
|
|
273
329
|
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
330
|
+
def close() -> None:
|
|
331
|
+
try:
|
|
332
|
+
import crawl
|
|
333
|
+
|
|
334
|
+
crawl.close_all_crawls()
|
|
335
|
+
except Exception as error: # noqa: BLE001 —— 关不掉也不能拖住关机
|
|
336
|
+
log(f"failed to stop crawls: {type(error).__name__}: {error}")
|
|
337
|
+
|
|
338
|
+
_run_bounded("close-crawls", close, SHUTDOWN_CLOSE_TIMEOUT)
|
|
277
339
|
|
|
278
340
|
|
|
279
341
|
def _shutdown_sessions() -> None:
|
|
@@ -281,12 +343,16 @@ def _shutdown_sessions() -> None:
|
|
|
281
343
|
|
|
282
344
|
浏览器会话是独立进程:sidecar 自己退了、Chromium 还活着,就成了没人管的孤儿。
|
|
283
345
|
"""
|
|
284
|
-
import adapters
|
|
285
346
|
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
347
|
+
def close() -> None:
|
|
348
|
+
try:
|
|
349
|
+
import adapters
|
|
350
|
+
|
|
351
|
+
adapters.close_all_sessions()
|
|
352
|
+
except Exception as error: # noqa: BLE001 —— 关不掉也不能拖住关机
|
|
353
|
+
log(f"failed to close sessions: {type(error).__name__}: {error}")
|
|
354
|
+
|
|
355
|
+
_run_bounded("close-sessions", close, SHUTDOWN_CLOSE_TIMEOUT)
|
|
290
356
|
|
|
291
357
|
|
|
292
358
|
def _drain_before_exit(timeout: float = 5.0) -> None:
|
|
@@ -294,20 +360,30 @@ def _drain_before_exit(timeout: float = 5.0) -> None:
|
|
|
294
360
|
|
|
295
361
|
收到 shutdown 就直接 return 的话,队列里已排队的请求会被静默丢掉 —— Host 侧看到的
|
|
296
362
|
是「没等到响应」而不是「被关机打断」。所以这里有界地等一下:等空了就走,等不到就
|
|
297
|
-
|
|
363
|
+
把还排着的帧逐条点名再走,不无限期拖住关机。
|
|
364
|
+
|
|
365
|
+
点名只覆盖队列里的帧:已经出队、正在 handler 里跑的请求没有一处集中的登记面,要命名
|
|
366
|
+
它们就得在 worker 的热路径上加簿记,这比一条关机日志不值。那一路的后果由
|
|
367
|
+
`_shutdown_crawls` / `_shutdown_sessions` 的有界关闭兜住(宿主侧等的是帧,不是关闭)。
|
|
298
368
|
|
|
299
369
|
:param timeout - 最长等待秒数
|
|
300
370
|
"""
|
|
301
371
|
deadline = time.monotonic() + timeout
|
|
302
|
-
while
|
|
372
|
+
while True:
|
|
303
373
|
with _QUEUE_LOCK:
|
|
304
|
-
pending =
|
|
374
|
+
pending = list(_QUEUE)
|
|
305
375
|
with _WORKERS_LOCK:
|
|
306
376
|
busy = any(item.is_alive() for item in _WORKERS)
|
|
307
377
|
if not pending and not busy:
|
|
308
378
|
return
|
|
379
|
+
if time.monotonic() >= deadline:
|
|
380
|
+
ids = [str(item.get("id", "(无 id)")) for item in pending]
|
|
381
|
+
log(
|
|
382
|
+
f"shutdown: giving up after {timeout}s — {len(ids)} 帧仍在队列里未应答 "
|
|
383
|
+
f"ids={','.join(ids) if ids else '(空)'}"
|
|
384
|
+
)
|
|
385
|
+
return
|
|
309
386
|
time.sleep(0.02)
|
|
310
|
-
log("shutdown: giving up on in-flight requests")
|
|
311
387
|
|
|
312
388
|
|
|
313
389
|
def read_loop() -> int:
|
|
@@ -331,14 +407,23 @@ def read_loop() -> int:
|
|
|
331
407
|
except Exception as error: # noqa: BLE001
|
|
332
408
|
log(f"failed to report readiness: {type(error).__name__}: {error}")
|
|
333
409
|
|
|
334
|
-
#
|
|
410
|
+
# 必须按块读(read1),既不能用 read(65536),也不能用 readline()。
|
|
335
411
|
# BufferedReader.read(n) 的语义是「读满 n 字节或遇到 EOF」:宿主只要保持管道开着
|
|
336
412
|
# (而常驻进程本来就该一直开着),它就会一直等下去,第一个请求永远进不来。
|
|
337
413
|
# 实测踩过:批量发完立刻 close stdin 的探针能过,逐帧交互的客户端会挂死。
|
|
338
|
-
# readline()
|
|
339
|
-
|
|
414
|
+
# readline() 则把整行读进内存**才**交回来:宿主侧 FrameSplitter 在
|
|
415
|
+
# MAX_FRAME_BYTES 处增量截断,这里若等整行,一个不带换行的超长写入仍会把无界字节
|
|
416
|
+
# 吃进内存(两侧同解的对称性缺口)。read1 有多少给多少,配合自建的 pending
|
|
417
|
+
# 增量判长,超限即弃帧报 BAD_FRAME 并清到下一行。
|
|
418
|
+
# typeshed 把 sys.stdin.buffer 标成 BinaryIO,那份协议里没有 read1;运行时它是
|
|
419
|
+
# _io.BufferedReader(管道与重定向文件都实测到这一型),cast 补这处过粗的标注。
|
|
420
|
+
stream = cast(BufferedReader, sys.stdin.buffer)
|
|
421
|
+
pending = bytearray()
|
|
422
|
+
|
|
423
|
+
def handle_raw(raw: bytes) -> bool:
|
|
424
|
+
"""处理一个完整帧(含行尾换行)。交回 False = 收到 shutdown,读循环退出。"""
|
|
340
425
|
if not raw.strip():
|
|
341
|
-
|
|
426
|
+
return True
|
|
342
427
|
if len(raw) > MAX_FRAME_BYTES:
|
|
343
428
|
emit(
|
|
344
429
|
fail(
|
|
@@ -347,15 +432,15 @@ def read_loop() -> int:
|
|
|
347
432
|
f"frame of {len(raw)} bytes exceeds the {MAX_FRAME_BYTES} byte limit",
|
|
348
433
|
)
|
|
349
434
|
)
|
|
350
|
-
|
|
435
|
+
return True
|
|
351
436
|
try:
|
|
352
437
|
frame = json.loads(raw.decode("utf-8"))
|
|
353
438
|
except (UnicodeDecodeError, json.JSONDecodeError) as error:
|
|
354
439
|
emit(fail(None, "BAD_FRAME", f"unparsable frame: {error}"))
|
|
355
|
-
|
|
440
|
+
return True
|
|
356
441
|
if not isinstance(frame, dict):
|
|
357
442
|
emit(fail(None, "BAD_FRAME", "frame must be an object"))
|
|
358
|
-
|
|
443
|
+
return True
|
|
359
444
|
if frame.get("method") == "shutdown":
|
|
360
445
|
emit(ok(frame.get("id"), {"stopping": True}))
|
|
361
446
|
_drain_before_exit()
|
|
@@ -363,7 +448,7 @@ def read_loop() -> int:
|
|
|
363
448
|
# 本身。宿主的优雅关闭走的就是这一帧(见 lib/sidecar.ts 的 dispose)。
|
|
364
449
|
_shutdown_crawls()
|
|
365
450
|
_shutdown_sessions()
|
|
366
|
-
return
|
|
451
|
+
return False
|
|
367
452
|
# 顺序要紧:先入队再起 worker。反过来的话,新起的线程可能立刻醒来、
|
|
368
453
|
# 看到空队列就退出,这一帧就永远没人处理 —— 且只在时序凑巧时才会复现。
|
|
369
454
|
busy_reply: dict[str, Any] | None = None
|
|
@@ -382,8 +467,30 @@ def read_loop() -> int:
|
|
|
382
467
|
# emit 在锁外:stdout 一旦阻塞(宿主读得慢),持锁写流会把全部 worker 的
|
|
383
468
|
# _drain 一起冻住 —— 回帧可以慢,队列不能停。
|
|
384
469
|
emit(busy_reply)
|
|
385
|
-
|
|
470
|
+
return True
|
|
386
471
|
_ensure_worker(min(depth, MAX_INFLIGHT))
|
|
472
|
+
return True
|
|
473
|
+
|
|
474
|
+
for chunk in iter(lambda: stream.read1(65536), b""):
|
|
475
|
+
pending.extend(chunk)
|
|
476
|
+
while b"\n" in pending:
|
|
477
|
+
index = pending.index(b"\n")
|
|
478
|
+
raw = bytes(pending[: index + 1])
|
|
479
|
+
del pending[: index + 1]
|
|
480
|
+
if not handle_raw(raw):
|
|
481
|
+
log("stdin closed")
|
|
482
|
+
return 0
|
|
483
|
+
if len(pending) > MAX_FRAME_BYTES:
|
|
484
|
+
# 无换行的超长残帧:与宿主侧 FrameSplitter 同解——弃缓冲、报 BAD_FRAME、
|
|
485
|
+
# 进程不死,后续带换行的合法帧照常处理。
|
|
486
|
+
del pending[:]
|
|
487
|
+
emit(
|
|
488
|
+
fail(
|
|
489
|
+
None,
|
|
490
|
+
"BAD_FRAME",
|
|
491
|
+
f"a frame went over the {MAX_FRAME_BYTES} byte limit without a newline",
|
|
492
|
+
)
|
|
493
|
+
)
|
|
387
494
|
log("stdin closed")
|
|
388
495
|
_drain_before_exit()
|
|
389
496
|
_shutdown_crawls()
|