@jayyuen66/dsh-scrapling 0.1.13 → 0.1.15
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 +52 -1
- package/README.md +20 -11
- package/README.zh-CN.md +20 -11
- package/THIRD_PARTY_NOTICES.md +1 -0
- package/bin/dsh-scrapling.mjs +74 -68
- package/client.js +5 -119
- package/cordis.patch.yml +4 -0
- package/docs/DETAIL.md +10 -4
- package/docs/DETAIL.zh.md +10 -4
- package/host.js +31 -26
- package/package.json +54 -56
- package/py/bridge.py +41 -0
- package/py/extraction.py +68 -8
- package/py/media.py +2 -2
- package/py/redact.py +43 -8
- package/py/redis_storage.py +127 -22
- package/py/search.py +39 -27
- package/py/session_page.py +106 -23
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jayyuen66/dsh-scrapling",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.15",
|
|
4
4
|
"description": "Scrapling 网页抓取插件(dsh):静态/浏览器抓取 + CSS/XPath 结构化抽取 + 选择器自愈 + capture_xhr 与会话网络历史 + 登录态存取 + Spider 爬虫,由常驻 Python 进程驱动。",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh",
|
|
@@ -69,8 +69,9 @@
|
|
|
69
69
|
"registry": "https://registry.npmjs.org"
|
|
70
70
|
},
|
|
71
71
|
"dependencies": {
|
|
72
|
+
"@jayyuen66/dsh-plugin-shared": "^0.2.12",
|
|
72
73
|
"@modelcontextprotocol/sdk": "1.32.2",
|
|
73
|
-
"fs-native-extensions": "1.5.
|
|
74
|
+
"fs-native-extensions": "1.5.4",
|
|
74
75
|
"ipaddr.js": "2.5.0",
|
|
75
76
|
"zod": "4.6.7"
|
|
76
77
|
},
|
|
@@ -78,79 +79,73 @@
|
|
|
78
79
|
"@deepseek-ai/cordis": "4.1.0",
|
|
79
80
|
"@deepseek-ai/cordis-plugin-include": "1.1.0",
|
|
80
81
|
"@deepseek-ai/cordis-plugin-loader": "1.1.0",
|
|
81
|
-
"@deepseek-ai/dsh-api-remotes": "0.2.2-rc.
|
|
82
|
-
"@deepseek-ai/dsh-client-locale": "0.2.2-rc.
|
|
83
|
-
"@deepseek-ai/dsh-client-store": "0.2.2-rc.
|
|
84
|
-
"@deepseek-ai/dsh-client-ui-chat": "0.2.2-rc.
|
|
85
|
-
"@deepseek-ai/dsh-client-ui-conversation": "0.2.2-rc.
|
|
86
|
-
"@deepseek-ai/dsh-client-ui-layout": "0.2.2-rc.
|
|
87
|
-
"@deepseek-ai/dsh-client-ui-plugin-manager": "0.2.2-rc.
|
|
88
|
-
"@deepseek-ai/dsh-client-ui-renderer": "0.2.2-rc.
|
|
89
|
-
"@deepseek-ai/dsh-client-ui-settings": "0.2.2-rc.
|
|
90
|
-
"@deepseek-ai/dsh-client-ui-slots": "0.2.2-rc.
|
|
91
|
-
"@deepseek-ai/dsh-client-ui-tool": "0.2.2-rc.
|
|
92
|
-
"@deepseek-ai/dsh-error": "0.2.2-rc.
|
|
93
|
-
"@deepseek-ai/dsh-host-webserver": "0.2.2-rc.
|
|
94
|
-
"@deepseek-ai/dsh-http-proxy": "0.2.2-rc.
|
|
95
|
-
"@deepseek-ai/dsh-jobs": "0.2.2-rc.
|
|
96
|
-
"@deepseek-ai/dsh-jobs-local": "0.2.2-rc.
|
|
97
|
-
"@deepseek-ai/dsh-output-retention": "0.2.2-rc.
|
|
98
|
-
"@deepseek-ai/dsh-package-manifest": "0.2.2-rc.
|
|
99
|
-
"@deepseek-ai/dsh-sandbox": "0.2.2-rc.
|
|
100
|
-
"@deepseek-ai/dsh-scope": "0.2.2-rc.
|
|
101
|
-
"@deepseek-ai/dsh-session": "0.2.2-rc.
|
|
102
|
-
"@deepseek-ai/dsh-settings": "0.2.2-rc.
|
|
103
|
-
"@deepseek-ai/dsh-shell": "0.2.2-rc.
|
|
104
|
-
"@deepseek-ai/dsh-skill": "0.2.2-rc.
|
|
105
|
-
"@deepseek-ai/dsh-subprocess": "0.2.2-rc.
|
|
106
|
-
"@deepseek-ai/dsh-system-prompt": "0.2.2-rc.
|
|
107
|
-
"@deepseek-ai/dsh-tool-executor-native": "0.2.2-rc.
|
|
108
|
-
"@deepseek-ai/dsh-tools": "0.2.2-rc.
|
|
109
|
-
"@deepseek-ai/dsh-typert-protocol": "0.2.2-rc.
|
|
110
|
-
"@deepseek-ai/dsh-user-approval": "0.2.2-rc.
|
|
111
|
-
"@deepseek-ai/dsh-web": "0.2.2-rc.
|
|
82
|
+
"@deepseek-ai/dsh-api-remotes": "0.2.2-rc.5",
|
|
83
|
+
"@deepseek-ai/dsh-client-locale": "0.2.2-rc.5",
|
|
84
|
+
"@deepseek-ai/dsh-client-store": "0.2.2-rc.5",
|
|
85
|
+
"@deepseek-ai/dsh-client-ui-chat": "0.2.2-rc.5",
|
|
86
|
+
"@deepseek-ai/dsh-client-ui-conversation": "0.2.2-rc.5",
|
|
87
|
+
"@deepseek-ai/dsh-client-ui-layout": "0.2.2-rc.5",
|
|
88
|
+
"@deepseek-ai/dsh-client-ui-plugin-manager": "0.2.2-rc.5",
|
|
89
|
+
"@deepseek-ai/dsh-client-ui-renderer": "0.2.2-rc.5",
|
|
90
|
+
"@deepseek-ai/dsh-client-ui-settings": "0.2.2-rc.5",
|
|
91
|
+
"@deepseek-ai/dsh-client-ui-slots": "0.2.2-rc.5",
|
|
92
|
+
"@deepseek-ai/dsh-client-ui-tool": "0.2.2-rc.5",
|
|
93
|
+
"@deepseek-ai/dsh-error": "0.2.2-rc.5",
|
|
94
|
+
"@deepseek-ai/dsh-host-webserver": "0.2.2-rc.5",
|
|
95
|
+
"@deepseek-ai/dsh-http-proxy": "0.2.2-rc.5",
|
|
96
|
+
"@deepseek-ai/dsh-jobs": "0.2.2-rc.5",
|
|
97
|
+
"@deepseek-ai/dsh-jobs-local": "0.2.2-rc.5",
|
|
98
|
+
"@deepseek-ai/dsh-output-retention": "0.2.2-rc.5",
|
|
99
|
+
"@deepseek-ai/dsh-package-manifest": "0.2.2-rc.5",
|
|
100
|
+
"@deepseek-ai/dsh-sandbox": "0.2.2-rc.5",
|
|
101
|
+
"@deepseek-ai/dsh-scope": "0.2.2-rc.5",
|
|
102
|
+
"@deepseek-ai/dsh-session": "0.2.2-rc.5",
|
|
103
|
+
"@deepseek-ai/dsh-settings": "0.2.2-rc.5",
|
|
104
|
+
"@deepseek-ai/dsh-shell": "0.2.2-rc.5",
|
|
105
|
+
"@deepseek-ai/dsh-skill": "0.2.2-rc.5",
|
|
106
|
+
"@deepseek-ai/dsh-subprocess": "0.2.2-rc.5",
|
|
107
|
+
"@deepseek-ai/dsh-system-prompt": "0.2.2-rc.5",
|
|
108
|
+
"@deepseek-ai/dsh-tool-executor-native": "0.2.2-rc.5",
|
|
109
|
+
"@deepseek-ai/dsh-tools": "0.2.2-rc.5",
|
|
110
|
+
"@deepseek-ai/dsh-typert-protocol": "0.2.2-rc.5",
|
|
111
|
+
"@deepseek-ai/dsh-user-approval": "0.2.2-rc.5",
|
|
112
|
+
"@deepseek-ai/dsh-web": "0.2.2-rc.5",
|
|
112
113
|
"@deepseek-ai/schemastery": "3.19.0",
|
|
113
114
|
"@e18e/eslint-plugin": "0.8.1",
|
|
114
|
-
"@jayyuen66/dsh-plugin-shared": "^0.2.8",
|
|
115
115
|
"@types/node": "26.6.6",
|
|
116
116
|
"@types/react": "19.3.0",
|
|
117
|
-
"@vitest/coverage-v8": "5.1.
|
|
117
|
+
"@vitest/coverage-v8": "5.1.1",
|
|
118
118
|
"eslint-plugin-regexp": "3.3.3",
|
|
119
119
|
"eslint-plugin-sonarjs": "4.2.2",
|
|
120
|
-
"eslint-plugin-zod": "5.
|
|
121
|
-
"fast-check": "4.10.
|
|
122
|
-
"oxfmt": "0.
|
|
123
|
-
"oxlint": "1.
|
|
124
|
-
"oxlint-tsgolint": "7.0.
|
|
120
|
+
"eslint-plugin-zod": "5.3.0",
|
|
121
|
+
"fast-check": "4.10.3",
|
|
122
|
+
"oxfmt": "0.79.0",
|
|
123
|
+
"oxlint": "1.94.0",
|
|
124
|
+
"oxlint-tsgolint": "7.0.2007",
|
|
125
125
|
"react": "^19.3.0",
|
|
126
|
-
"
|
|
126
|
+
"react-dom": "^19.3.0",
|
|
127
|
+
"rolldown": "1.3.3",
|
|
127
128
|
"typescript": "7.0.2",
|
|
128
129
|
"vite": "8.3.8",
|
|
129
|
-
"vitest": "5.1.
|
|
130
|
+
"vitest": "5.1.1"
|
|
130
131
|
},
|
|
131
132
|
"peerDependencies": {
|
|
132
|
-
"@deepseek-ai/dsh": "^0.2.2-rc.
|
|
133
|
-
"@deepseek-ai/dsh-error": "^0.2.2-rc.
|
|
134
|
-
"@deepseek-ai/dsh-output-retention": "^0.2.2-rc.
|
|
135
|
-
"@deepseek-ai/dsh-tools": "^0.2.2-rc.
|
|
136
|
-
"@deepseek-ai/dsh-typert-protocol": "^0.2.2-rc.
|
|
137
|
-
"@deepseek-ai/dsh-web": "^0.2.2-rc.
|
|
133
|
+
"@deepseek-ai/dsh": "^0.2.2-rc.5",
|
|
134
|
+
"@deepseek-ai/dsh-error": "^0.2.2-rc.5",
|
|
135
|
+
"@deepseek-ai/dsh-output-retention": "^0.2.2-rc.5",
|
|
136
|
+
"@deepseek-ai/dsh-tools": "^0.2.2-rc.5",
|
|
137
|
+
"@deepseek-ai/dsh-typert-protocol": "^0.2.2-rc.5",
|
|
138
|
+
"@deepseek-ai/dsh-web": "^0.2.2-rc.5",
|
|
138
139
|
"@deepseek-ai/schemastery": "^3.19.0"
|
|
139
140
|
},
|
|
140
141
|
"peerDependenciesMeta": {
|
|
141
142
|
"@deepseek-ai/dsh": {
|
|
142
143
|
"optional": true
|
|
143
|
-
},
|
|
144
|
-
"@deepseek-ai/dsh-error": {
|
|
145
|
-
"optional": true
|
|
146
|
-
},
|
|
147
|
-
"@deepseek-ai/dsh-tools": {
|
|
148
|
-
"optional": true
|
|
149
144
|
}
|
|
150
145
|
},
|
|
151
146
|
"icon": "icon.svg",
|
|
152
147
|
"engines": {
|
|
153
|
-
"dsh": "^0.2.2-rc.
|
|
148
|
+
"dsh": "^0.2.2-rc.5",
|
|
154
149
|
"node": ">=24.9.0"
|
|
155
150
|
},
|
|
156
151
|
"dsh": {
|
|
@@ -160,7 +155,10 @@
|
|
|
160
155
|
},
|
|
161
156
|
"client": {
|
|
162
157
|
"platform": "web",
|
|
163
|
-
"immediately": true
|
|
158
|
+
"immediately": true,
|
|
159
|
+
"external": [
|
|
160
|
+
"@jayyuen66/dsh-plugin-shared/client"
|
|
161
|
+
]
|
|
164
162
|
}
|
|
165
163
|
},
|
|
166
164
|
"scripts": {
|
package/py/bridge.py
CHANGED
|
@@ -91,6 +91,47 @@ _HERE = os.path.dirname(os.path.abspath(__file__))
|
|
|
91
91
|
if _HERE not in sys.path:
|
|
92
92
|
sys.path.insert(0, _HERE)
|
|
93
93
|
|
|
94
|
+
|
|
95
|
+
def configure_ca_bundle() -> str | None:
|
|
96
|
+
"""环境里没有指定 CA 包时,用 certifi 的那份兜底,返回实际用上的路径。
|
|
97
|
+
|
|
98
|
+
为什么需要这一步:托管 CPython(``runtime/python/<版本>/``)编译时没有自己的
|
|
99
|
+
OpenSSL 配置,``ssl.get_default_verify_paths()`` 在 macOS 上会落到系统库
|
|
100
|
+
``/private/etc/ssl/cert.pem``。那份库缺若干公开根 —— 实测 example.com 走
|
|
101
|
+
SSL.com 链,系统库里验不过(``openssl s_client`` 报 ``verify error:num=20``,
|
|
102
|
+
同一张证书链用 certifi 的 bundle 验则 ``Verify return code: 0``)。症状在插件这一层
|
|
103
|
+
是 ``scrapling_fetch`` 一律 ``FETCH_FAILED ... unable to get local issuer certificate``,
|
|
104
|
+
而 curl_cffi 与 urllib 的报错都只说「找不到签发者」,看不出是信任源选错了。
|
|
105
|
+
|
|
106
|
+
两枚变量都要设,因为它们喂的是两条不同的链:``SSL_CERT_FILE`` 给 Python 的 ``ssl``
|
|
107
|
+
(urllib、httpx、playwright 一侧),``CURL_CA_BUNDLE`` 给 libcurl(curl_cffi 的
|
|
108
|
+
impersonate 路径)。
|
|
109
|
+
|
|
110
|
+
只在两枚变量都没被设过时才动手(**空值按没设处理**):用户显式指定的 CA 包
|
|
111
|
+
(企业 MITM 代理、自签根)必须压过这里的兜底,否则那些环境反而全坏。
|
|
112
|
+
|
|
113
|
+
:returns: 兜底用上的 bundle 路径;certifi 不可用、或两枚变量都已有非空取值时返回 None
|
|
114
|
+
"""
|
|
115
|
+
if os.environ.get("SSL_CERT_FILE") or os.environ.get("CURL_CA_BUNDLE"):
|
|
116
|
+
return None
|
|
117
|
+
try:
|
|
118
|
+
import certifi
|
|
119
|
+
except ImportError:
|
|
120
|
+
# certifi 是 runtime-requirements 里钉版的传递依赖,真装不上时不该把 sidecar
|
|
121
|
+
# 拖死:退回系统库只是少几个根,能连的主机照连。
|
|
122
|
+
return None
|
|
123
|
+
bundle = certifi.where()
|
|
124
|
+
if not bundle:
|
|
125
|
+
return None
|
|
126
|
+
# 早退那一支已经确认两枚都为空,所以这里直接赋值(而不是 setdefault):
|
|
127
|
+
# 直接赋值与「空值算没设」同口径,空值环境也会真的被兜底路径填上。
|
|
128
|
+
os.environ["SSL_CERT_FILE"] = bundle
|
|
129
|
+
os.environ["CURL_CA_BUNDLE"] = bundle
|
|
130
|
+
return bundle
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
CA_BUNDLE = configure_ca_bundle()
|
|
134
|
+
|
|
94
135
|
PROTOCOL_VERSION = 1
|
|
95
136
|
|
|
96
137
|
# 并发上限:与工作线程数一致,多了也只是排队。
|
package/py/extraction.py
CHANGED
|
@@ -41,17 +41,33 @@ def _json_value_within(value: Any, room: int) -> tuple[Any, int, bool]:
|
|
|
41
41
|
"""把值收进 room 的 JSON 预算;返回 (值, 实际长度, 是否被裁)。
|
|
42
42
|
|
|
43
43
|
字符串按序列化长度收缩;其它形态(列表、对象)没有便宜的收缩方式,超预算时
|
|
44
|
-
降级为 null —— 留着整段会让调用方拿到的载荷远超
|
|
44
|
+
降级为 null —— 留着整段会让调用方拿到的载荷远超 max_content_chars。
|
|
45
|
+
|
|
46
|
+
返回的 ``size`` 是**实际会占的长度**,即使它大于 ``room``:降级成 ``null`` 也要花
|
|
47
|
+
4 个字符,把这个长度报成 0 会让调用方以为预算还富余。
|
|
45
48
|
"""
|
|
46
49
|
size = _json_len(value)
|
|
47
50
|
if size <= room:
|
|
48
51
|
return value, size, False
|
|
49
|
-
if isinstance(value, str)
|
|
50
|
-
|
|
52
|
+
if isinstance(value, str):
|
|
53
|
+
# 预算连一对引号都放不下时 `_fit_text` 自己会回空串:文本字段被裁之后仍是字符串,
|
|
54
|
+
# 不降级成 null —— 模型读到的 null 是「这个字段没有值」,而这里的实情是
|
|
55
|
+
# 「值被预算咬掉了」,两者用同一个记号就分不开了。
|
|
56
|
+
fitted = _fit_text(value, max(0, room))
|
|
51
57
|
return fitted, _json_len(fitted), True
|
|
52
58
|
return None, _json_len(None), True
|
|
53
59
|
|
|
54
60
|
|
|
61
|
+
def _row_overhead(names: list[str]) -> int:
|
|
62
|
+
"""一行里与取值无关的那部分 JSON 长度:键名、引号、冒号、大括号与逗号。
|
|
63
|
+
|
|
64
|
+
预算若只累加各字段**值**的长度,每行的键名与标点都不计入 —— 字段名越长、字段越多、
|
|
65
|
+
行数越多,真实返回体超出 max_content_chars 越多,而 ``_json_len`` 的注释写着
|
|
66
|
+
「与模型看到的形状一致」。这里把骨架单独算一次,由调用方逐行计入。
|
|
67
|
+
"""
|
|
68
|
+
return _json_len(dict.fromkeys(names, None)) - len(names) * _json_len(None)
|
|
69
|
+
|
|
70
|
+
|
|
55
71
|
def _resolve_url(page: Any, value: str) -> str:
|
|
56
72
|
"""把相对地址拼成绝对地址;空值或拼不出来时保留原值。"""
|
|
57
73
|
if not value:
|
|
@@ -188,7 +204,12 @@ def field_value(
|
|
|
188
204
|
page: Any,
|
|
189
205
|
resolve_urls: bool = False,
|
|
190
206
|
) -> Any:
|
|
191
|
-
"""取一个字段的值;缺失给 None,all=true 时给列表。
|
|
207
|
+
"""取一个字段的值;缺失给 None,all=true 时给列表。
|
|
208
|
+
|
|
209
|
+
``all=true`` 时列表里**不含 None**:attribute 模式下属性缺席的节点会被跳过,所以返回
|
|
210
|
+
列表的下标与命中节点不是一一对应的。这一位是有意的过滤(缺值的条目留在列表里只会让
|
|
211
|
+
模型误以为「这一条字段是 null」),要按下标对齐就改用单值模式逐条取。
|
|
212
|
+
"""
|
|
192
213
|
selector, mode, attribute, many = _field_spec(spec)
|
|
193
214
|
found = _select_field_nodes(node, selector)
|
|
194
215
|
if many:
|
|
@@ -232,11 +253,20 @@ def collect_fields(
|
|
|
232
253
|
if not isinstance(fields, dict) or not fields:
|
|
233
254
|
raise ValueError("fields must be a non-empty object")
|
|
234
255
|
rows: list[dict[str, Any]] = []
|
|
235
|
-
|
|
256
|
+
# 每行的键名与标点也占字符:只累加值会让真实返回体超出预算,而调用方拿到的
|
|
257
|
+
# 正是整份 rows 的序列化体积(含外层方括号与行间逗号)。
|
|
258
|
+
names = [str(name) for name in fields]
|
|
259
|
+
per_row = _row_overhead(names)
|
|
260
|
+
# 外层 `[` `]` 两个字符。
|
|
261
|
+
spent = _json_len([])
|
|
236
262
|
truncated = False
|
|
237
263
|
node_iter = iter(nodes)
|
|
238
264
|
for node in node_iter:
|
|
239
265
|
row: dict[str, Any] = {}
|
|
266
|
+
# 行与行之间还有一个逗号;第一行前面没有。
|
|
267
|
+
if rows:
|
|
268
|
+
spent += 1
|
|
269
|
+
spent += per_row
|
|
240
270
|
for name, spec in fields.items():
|
|
241
271
|
value = field_value(node, spec, page=page, resolve_urls=resolve_urls)
|
|
242
272
|
room = max(0, max_content_chars - spent)
|
|
@@ -253,6 +283,33 @@ def collect_fields(
|
|
|
253
283
|
return rows, truncated
|
|
254
284
|
|
|
255
285
|
|
|
286
|
+
def _similarity_threshold(value: Any) -> float:
|
|
287
|
+
"""校验 ``similarityThreshold``:0..1 的实数,显式 null 也按缺省 0.2 处理。
|
|
288
|
+
|
|
289
|
+
直接 ``float(args.get(...))`` 会在模型显式传 ``null`` 时抛 ``TypeError``(键在、值是 None),
|
|
290
|
+
而 ``adapters._wrap_extraction`` 只把 ``ValueError`` 归成 ``BAD_ARGS`` —— ``TypeError``
|
|
291
|
+
会一路穿到 bridge 的兜底分支变成 ``FETCH_FAILED``,错误码与成因对不上。
|
|
292
|
+
"""
|
|
293
|
+
if value is None:
|
|
294
|
+
return 0.2
|
|
295
|
+
if not isinstance(value, (int, float)) or isinstance(value, bool) or not 0 <= value <= 1:
|
|
296
|
+
raise ValueError("similarityThreshold must be a number between 0 and 1")
|
|
297
|
+
return float(value)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _ignore_attributes(value: Any) -> tuple[str, ...]:
|
|
301
|
+
"""校验 ``ignoreAttributes``:字符串数组;未给时用默认的 href/src。
|
|
302
|
+
|
|
303
|
+
不校验的后果是静默错误:字符串 ``"href"`` 会被 ``list(...)`` 拆成 ``['h','r','e','f']``,
|
|
304
|
+
dict 会被拆成键名列表 —— 两种都变成一组不存在的属性名,``find_similar`` 不会报错。
|
|
305
|
+
"""
|
|
306
|
+
if value is None:
|
|
307
|
+
return ("href", "src")
|
|
308
|
+
if not isinstance(value, (list, tuple)) or not all(isinstance(item, str) for item in value):
|
|
309
|
+
raise ValueError("ignoreAttributes must be an array of strings")
|
|
310
|
+
return tuple(value)
|
|
311
|
+
|
|
312
|
+
|
|
256
313
|
def locate(args: dict[str, Any]) -> dict[str, Any]:
|
|
257
314
|
"""定位元素并返回生成选择器;不发网络请求,不写 adaptive 指纹。"""
|
|
258
315
|
from scrapling.parser import Selector
|
|
@@ -287,8 +344,8 @@ def locate(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
287
344
|
partial=bool(args.get("partial", False)),
|
|
288
345
|
case_sensitive=bool(args.get("caseSensitive", False)),
|
|
289
346
|
clean_match=bool(args.get("cleanMatch", True)),
|
|
290
|
-
similarity_threshold=
|
|
291
|
-
ignore_attributes=args.get("ignoreAttributes")
|
|
347
|
+
similarity_threshold=_similarity_threshold(args.get("similarityThreshold")),
|
|
348
|
+
ignore_attributes=_ignore_attributes(args.get("ignoreAttributes")),
|
|
292
349
|
match_text=bool(args.get("matchText", False)),
|
|
293
350
|
)
|
|
294
351
|
matches: list[dict[str, Any]] = []
|
|
@@ -422,7 +479,10 @@ def links(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
422
479
|
reason = _next_reason(text, href)
|
|
423
480
|
if not reason:
|
|
424
481
|
continue
|
|
425
|
-
|
|
482
|
+
# href 来自被抓页面(不可信输入):`http://[` 这类值会让 urljoin 抛 ValueError,
|
|
483
|
+
# 而这条路径上的异常会被 _wrap_extraction 归成 BAD_ARGS —— 参数其实没问题,
|
|
484
|
+
# 是页面内容坏了。复用 _resolve_url 的兜底(拼不出来就保留原值)。
|
|
485
|
+
url = _resolve_url(page, href)
|
|
426
486
|
if url in seen:
|
|
427
487
|
continue
|
|
428
488
|
seen.add(url)
|
package/py/media.py
CHANGED
|
@@ -448,7 +448,7 @@ def screenshot(
|
|
|
448
448
|
timeout_ms: int,
|
|
449
449
|
) -> dict[str, Any]:
|
|
450
450
|
"""对会话当前页或页内单个元素截图,返回 base64 与固有尺寸。"""
|
|
451
|
-
from session_page import _finish_page, _ready_page
|
|
451
|
+
from session_page import _closed_page_error, _finish_page, _ready_page
|
|
452
452
|
|
|
453
453
|
if image_type not in ("png", "jpeg"):
|
|
454
454
|
raise _error("BAD_ARGS", "imageType must be png or jpeg")
|
|
@@ -463,7 +463,7 @@ def screenshot(
|
|
|
463
463
|
page = page_info.page
|
|
464
464
|
try:
|
|
465
465
|
if page.is_closed():
|
|
466
|
-
raise
|
|
466
|
+
raise _closed_page_error()
|
|
467
467
|
if selector is not None:
|
|
468
468
|
locator = page.locator(selector)
|
|
469
469
|
matches = locator.count()
|
package/py/redact.py
CHANGED
|
@@ -7,12 +7,21 @@ guard 的日志与 adapters 的网络摘要在「给日志、给模型看」之
|
|
|
7
7
|
from __future__ import annotations
|
|
8
8
|
|
|
9
9
|
import re
|
|
10
|
-
from urllib.parse import
|
|
10
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
11
11
|
|
|
12
12
|
# 畸形 URL(urlsplit 抛 ValueError)上仍要按参数名兜底:解析失败不能等于「整串放行」。
|
|
13
13
|
_QUERY_SECRET_FALLBACK = re.compile(
|
|
14
14
|
r"(?i)([?&;](?:token|key|secret|password|pwd|sig|signature|auth|session)[^=&#]*=)[^&#]*"
|
|
15
15
|
)
|
|
16
|
+
# 兜底路径同样要摘 authority 里的 `user:pass@`:`http://user:pass@[::1/x?token=abc` 这种
|
|
17
|
+
# 括号不闭合的形态会让 urlsplit 抛 ValueError,而它的口令就藏在 authority 段 —— 只处理查询串
|
|
18
|
+
# 等于把口令原样放行。锚在 `//` 上(mailto:/tel: 这类没有 `//`,不会误伤)。
|
|
19
|
+
_AUTHORITY_USERINFO_FALLBACK = re.compile(r"(?<=//)[^\s/?#@]*@")
|
|
20
|
+
# 查询串的两种合法分隔符:`&` 与 `;`(HTML 4 / RFC 1738)。切片时保留分隔符本身,
|
|
21
|
+
# 于是 `split` 的奇数位就是分隔符。
|
|
22
|
+
_QUERY_SEPARATOR = re.compile(r"([&;])")
|
|
23
|
+
# 一段 `name=value`。名字允许空(`?=x` 是畸形但存在),值允许空(`?token=`)。
|
|
24
|
+
_QUERY_PAIR = re.compile(r"(?P<name>[^=]*)=(?P<value>.*)", re.DOTALL)
|
|
16
25
|
# 这些 scheme 的 ``@`` 属于地址本身(mailto/tel 之类),不是 user:pass@host 的 authority。
|
|
17
26
|
_NON_AUTHORITY_SCHEMES = frozenset({"mailto", "tel", "data", "javascript", "urn", "about", "blob"})
|
|
18
27
|
|
|
@@ -54,6 +63,21 @@ _SECRET_QUERY_KEYS = frozenset(
|
|
|
54
63
|
"token",
|
|
55
64
|
}
|
|
56
65
|
)
|
|
66
|
+
# 参数名判据的归一形态:去掉 `-` 与 `_` 再比对。浏览器端 JS 拼接口时最常写 `accessToken`
|
|
67
|
+
# / `clientSecret` / `idToken`(驼峰),而集合里记的是下划线形式 —— 只做 `strip().lower()`
|
|
68
|
+
# 时 `accessToken`.lower() 是 `accesstoken`,命中不了 `access_token`,凭据于是原样进摘要。
|
|
69
|
+
# 归一方向只有一个:两边都去掉 `-`/`_` 再比,集合与输入用同一套规则。
|
|
70
|
+
_SECRET_QUERY_KEYS_FLAT = frozenset(key.replace("-", "").replace("_", "") for key in _SECRET_QUERY_KEYS)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _is_secret_query_key(name: str) -> bool:
|
|
74
|
+
"""判一个查询参数名是否装凭据;`_`/`-`/大小写都不敏感。
|
|
75
|
+
|
|
76
|
+
:param name: 参数名(可能带空白与混合大小写)
|
|
77
|
+
:returns: 命中凭据名单时为真
|
|
78
|
+
"""
|
|
79
|
+
flat = name.strip().lower().replace("-", "").replace("_", "")
|
|
80
|
+
return flat in _SECRET_QUERY_KEYS_FLAT
|
|
57
81
|
|
|
58
82
|
|
|
59
83
|
def _redacted_query(text: str) -> str:
|
|
@@ -67,17 +91,27 @@ def _redacted_query(text: str) -> str:
|
|
|
67
91
|
"""
|
|
68
92
|
if not text:
|
|
69
93
|
return text
|
|
70
|
-
pairs: list[tuple[str, str]] = []
|
|
71
94
|
changed = False
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
95
|
+
pieces: list[str] = []
|
|
96
|
+
# **不能只按 `&` 切**:`;` 在 HTML 4 与 RFC 1738 里也是合法的参数分隔符,真实站点至今仍在用
|
|
97
|
+
# `?a=1;token=…`,而 Python 3.10 起 `parse_qsl` 不再把 `;` 当分隔符 —— 整串于是被读成一个
|
|
98
|
+
# 名字 `a`、值 `1;token=abc`,参数名判据命中不了,凭据原样进日志。这里自己按 `&` 与 `;` 切、
|
|
99
|
+
# 逐段判名,分隔符原样保留(重排或替换分隔符会让日志里的 URL 与真实请求对不上)。
|
|
100
|
+
for position, token in enumerate(_QUERY_SEPARATOR.split(text)):
|
|
101
|
+
if position % 2 == 1 or not token:
|
|
102
|
+
pieces.append(token)
|
|
103
|
+
continue
|
|
104
|
+
match = _QUERY_PAIR.fullmatch(token)
|
|
105
|
+
name = match.group("name") if match is not None else token
|
|
106
|
+
value = match.group("value") if match is not None else None
|
|
107
|
+
if value is not None and _is_secret_query_key(name):
|
|
108
|
+
pieces.append(f"{name}=<redacted>")
|
|
75
109
|
changed = True
|
|
76
110
|
else:
|
|
77
|
-
|
|
111
|
+
pieces.append(token)
|
|
78
112
|
if not changed:
|
|
79
113
|
return text
|
|
80
|
-
return
|
|
114
|
+
return "".join(pieces)
|
|
81
115
|
|
|
82
116
|
|
|
83
117
|
def _redacted_fragment(fragment: str) -> str:
|
|
@@ -112,7 +146,8 @@ def redact_url_secrets(raw: str) -> str:
|
|
|
112
146
|
try:
|
|
113
147
|
parsed = urlsplit(raw)
|
|
114
148
|
except ValueError:
|
|
115
|
-
|
|
149
|
+
without_userinfo = _AUTHORITY_USERINFO_FALLBACK.sub("", raw)
|
|
150
|
+
return _QUERY_SECRET_FALLBACK.sub(r"\1<redacted>", without_userinfo)
|
|
116
151
|
# 没有 scheme 的 ``user:pass@host:8080`` 会被 urlsplit 读成 scheme='user'、
|
|
117
152
|
# path='pass@host:8080':netloc 为空,下面按 netloc 摘 userinfo 的那一步什么都不做,
|
|
118
153
|
# 整条代理口令于是原样漏进日志(PROXY_URL 不可用那条日志正是这么来的)。这种形态的
|
package/py/redis_storage.py
CHANGED
|
@@ -26,10 +26,25 @@ DEFAULT_TIMEOUT_SECONDS = 2.0
|
|
|
26
26
|
# 而 adapters 的 ``storage_args`` 里带着**整页 URL**,所以每抓一个新页面就会新建一个存储实例。
|
|
27
27
|
# 连接池若跟着实例走,就是每页新开一池、上一个池被挤出缓存时没人关(连接要等 GC 才释放)。
|
|
28
28
|
# 按连接串复用之后,实例的多少不再放大连接数。
|
|
29
|
-
|
|
29
|
+
#
|
|
30
|
+
# 复用带**引用计数**是承重的:一份客户端会被同一连接串上的多个实例同时持有(每页一个),
|
|
31
|
+
# 谁先 close 都不该把兄弟实例仍在用的连接池关掉 —— 那样 B 的 save/retrieve 会撞上已关闭的
|
|
32
|
+
# 客户端(redis-py 抛 ConnectionError/RedisError),而 B 手里没有任何线索,只能由 adapters
|
|
33
|
+
# 兜底降级成「指纹存不上」。所以计数归零才真关。
|
|
34
|
+
_CLIENT_CACHE: dict[tuple[str, float], _CachedClient] = {}
|
|
30
35
|
_CLIENT_LOCK = Lock()
|
|
31
36
|
|
|
32
37
|
|
|
38
|
+
class _CachedClient:
|
|
39
|
+
"""复用表里的一格:客户端本体 + 当前有几个存储实例拿着它。"""
|
|
40
|
+
|
|
41
|
+
__slots__ = ("client", "users")
|
|
42
|
+
|
|
43
|
+
def __init__(self, client: Any) -> None:
|
|
44
|
+
self.client = client
|
|
45
|
+
self.users = 0
|
|
46
|
+
|
|
47
|
+
|
|
33
48
|
class RedisUnavailable(RuntimeError):
|
|
34
49
|
"""Redis 不可用或客户端缺失;调用方把它翻成带码的失败。"""
|
|
35
50
|
|
|
@@ -62,13 +77,24 @@ def redacted_redis_url(raw: str) -> str:
|
|
|
62
77
|
|
|
63
78
|
|
|
64
79
|
def _default_client(redis_url: str, *, timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS) -> Any:
|
|
80
|
+
"""回一份按 (连接串, 超时) 复用的客户端(只管取,不计数)。"""
|
|
81
|
+
return _client_entry(redis_url, timeout_seconds=timeout_seconds)[0]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _client_entry(redis_url: str, *, timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS) -> tuple[Any, bool]:
|
|
85
|
+
"""取复用表里的客户端,并说明它是不是**这次新建**的。
|
|
86
|
+
|
|
87
|
+
第二个返回值是给构造用的:只有新建的客户端才需要 ping。复用命中意味着它早就连通过
|
|
88
|
+
(上一次构造 ping 过),而 Redis 不可达时那次 ping 会吃满 ``socket_connect_timeout``,
|
|
89
|
+
每页重 ping 就是每页白等一次超时。
|
|
90
|
+
"""
|
|
65
91
|
# 同一 (连接串, 超时) 只建一个客户端:存储实例是每个 URL 一个(见 _CLIENT_CACHE 的说明),
|
|
66
92
|
# 连接池跟着实例走就会每页新开一池。复用之后连接数由连接串的个数决定,不由页面个数决定。
|
|
67
93
|
key = (redis_url, timeout_seconds)
|
|
68
94
|
with _CLIENT_LOCK:
|
|
69
95
|
cached = _CLIENT_CACHE.get(key)
|
|
70
96
|
if cached is not None:
|
|
71
|
-
return cached
|
|
97
|
+
return cached.client, False
|
|
72
98
|
try:
|
|
73
99
|
from redis import Redis
|
|
74
100
|
except ModuleNotFoundError as error:
|
|
@@ -84,15 +110,53 @@ def _default_client(redis_url: str, *, timeout_seconds: float = DEFAULT_TIMEOUT_
|
|
|
84
110
|
socket_timeout=timeout_seconds,
|
|
85
111
|
socket_connect_timeout=timeout_seconds,
|
|
86
112
|
)
|
|
87
|
-
_CLIENT_CACHE[key] = client
|
|
88
|
-
return client
|
|
113
|
+
_CLIENT_CACHE[key] = _CachedClient(client)
|
|
114
|
+
return client, True
|
|
115
|
+
|
|
89
116
|
|
|
117
|
+
def _retain_client(key: tuple[str, float], client: Any) -> bool:
|
|
118
|
+
"""给这一份客户端加一个使用者;返回「它是否由复用表托管」。
|
|
90
119
|
|
|
91
|
-
|
|
92
|
-
|
|
120
|
+
自定义 ``client_factory`` 造的客户端不在表里,返回 False —— 那种客户端没人共享,
|
|
121
|
+
关掉它不会连坐,由持有者自己负责。
|
|
122
|
+
"""
|
|
93
123
|
with _CLIENT_LOCK:
|
|
94
|
-
|
|
95
|
-
|
|
124
|
+
entry = _CLIENT_CACHE.get(key)
|
|
125
|
+
if entry is None or entry.client is not client:
|
|
126
|
+
return False
|
|
127
|
+
entry.users += 1
|
|
128
|
+
return True
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _release_client(key: tuple[str, float], client: Any) -> bool:
|
|
132
|
+
"""放掉一个使用者;返回「现在可以关掉这份客户端了」。
|
|
133
|
+
|
|
134
|
+
不在表里(自定义工厂)时回 True:那份没有兄弟,由调用方关。
|
|
135
|
+
表里有兄弟使用者时回 False,并把客户端留在表里让它们继续用。
|
|
136
|
+
"""
|
|
137
|
+
with _CLIENT_LOCK:
|
|
138
|
+
entry = _CLIENT_CACHE.get(key)
|
|
139
|
+
if entry is None or entry.client is not client:
|
|
140
|
+
return True
|
|
141
|
+
if entry.users > 1:
|
|
142
|
+
entry.users -= 1
|
|
143
|
+
return False
|
|
144
|
+
_CLIENT_CACHE.pop(key, None)
|
|
145
|
+
return True
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _discard_client(key: tuple[str, float], client: Any) -> bool:
|
|
149
|
+
"""连不上时把这份客户端从复用表里摘掉;返回「现在可以关掉它了」。
|
|
150
|
+
|
|
151
|
+
兄弟实例还在用(``users > 0``)就只留着不动:它连不上是这次探测的结论,而那些实例
|
|
152
|
+
此刻还在用这份客户端,摘掉表项会让它们 close 时找不到计数、进而把仍被使用的连接池关掉。
|
|
153
|
+
"""
|
|
154
|
+
with _CLIENT_LOCK:
|
|
155
|
+
entry = _CLIENT_CACHE.get(key)
|
|
156
|
+
if entry is None or entry.client is not client or entry.users > 0:
|
|
157
|
+
return False
|
|
158
|
+
_CLIENT_CACHE.pop(key, None)
|
|
159
|
+
return True
|
|
96
160
|
|
|
97
161
|
|
|
98
162
|
@lru_cache(1, typed=True)
|
|
@@ -118,9 +182,17 @@ class RedisStorageSystem(StorageSystemMixin):
|
|
|
118
182
|
self.prefix = prefix
|
|
119
183
|
self.timeout_seconds = timeout_seconds
|
|
120
184
|
self._client_key = (redis_url, timeout_seconds)
|
|
185
|
+
self._closed = False
|
|
121
186
|
# 构造阶段与连接阶段分开报:工厂抛的是「谁也没连上」,ping 抛的才是「连不上」。
|
|
122
187
|
try:
|
|
123
|
-
|
|
188
|
+
if client_factory is _default_client:
|
|
189
|
+
# 复用表命中时不 ping:那份客户端上一次构造已经 ping 通过,而 Redis 不可达时
|
|
190
|
+
# ping 会吃满 socket_connect_timeout,每页重 ping 就是每页白等一次超时。
|
|
191
|
+
self._client, fresh = _client_entry(redis_url, timeout_seconds=timeout_seconds)
|
|
192
|
+
else:
|
|
193
|
+
# 自定义工厂造的客户端不在复用表里,没有「上次通过」这回事,照旧每次 ping。
|
|
194
|
+
self._client = client_factory(redis_url, timeout_seconds=timeout_seconds)
|
|
195
|
+
fresh = True
|
|
124
196
|
except RedisUnavailable:
|
|
125
197
|
raise
|
|
126
198
|
except TypeError:
|
|
@@ -131,14 +203,26 @@ class RedisStorageSystem(StorageSystemMixin):
|
|
|
131
203
|
raise RedisUnavailable(
|
|
132
204
|
f"redis client setup failed for {redacted_redis_url(redis_url)}: {type(error).__name__}: {error}"
|
|
133
205
|
) from error
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
#
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
206
|
+
if fresh:
|
|
207
|
+
try:
|
|
208
|
+
self._client.ping()
|
|
209
|
+
except Exception as error: # 连接失败的种类由客户端决定
|
|
210
|
+
# 连不上就把这份客户端从复用表里摘掉并关掉:留着它只会让下一次构造再撞同一堵墙。
|
|
211
|
+
# 此刻还没计数(计数在 ping 通过之后才加),所以表里那份没有兄弟在用。
|
|
212
|
+
self._dispose_failed()
|
|
213
|
+
raise RedisUnavailable(
|
|
214
|
+
f"redis is not reachable at {redacted_redis_url(redis_url)}: {type(error).__name__}: {error}"
|
|
215
|
+
) from error
|
|
216
|
+
# 计数放在 ping 通过之后:连不上的客户端不该先占住一个使用者名额,否则那份永远摘不掉。
|
|
217
|
+
_retain_client(self._client_key, self._client)
|
|
218
|
+
|
|
219
|
+
def _dispose_failed(self) -> None:
|
|
220
|
+
"""构造期连不上时的收尾:摘出复用表,没人共享就真关掉,别让连接池悬着。"""
|
|
221
|
+
if not _discard_client(self._client_key, self._client):
|
|
222
|
+
return
|
|
223
|
+
close = getattr(self._client, "close", None)
|
|
224
|
+
if callable(close):
|
|
225
|
+
close()
|
|
142
226
|
|
|
143
227
|
def _key(self, identifier: str) -> str:
|
|
144
228
|
bucket = self._get_base_url()
|
|
@@ -170,7 +254,21 @@ class RedisStorageSystem(StorageSystemMixin):
|
|
|
170
254
|
) from error
|
|
171
255
|
if raw is None:
|
|
172
256
|
return None
|
|
173
|
-
|
|
257
|
+
# 解码也归到「存储层故障一律翻成 RedisUnavailable」这条契约里:值被别的写入方覆盖成
|
|
258
|
+
# 非法 JSON 时,orjson 的 JSONDecodeError 原样抛给调用方,就成了本类唯一一处不走
|
|
259
|
+
# RedisUnavailable 的失败。同理,合法 JSON 不等于验证器指纹字典(键被写成标量时
|
|
260
|
+
# loads 照样成功),形状不对也要在这里拦下来,别把 int/str 当成指纹交给上游。
|
|
261
|
+
try:
|
|
262
|
+
decoded = loads(raw)
|
|
263
|
+
except Exception as error:
|
|
264
|
+
where = redacted_redis_url(self.redis_url)
|
|
265
|
+
raise RedisUnavailable(
|
|
266
|
+
f"redis value is not valid JSON at {where}: {type(error).__name__}: {error}"
|
|
267
|
+
) from error
|
|
268
|
+
if not isinstance(decoded, dict):
|
|
269
|
+
where = redacted_redis_url(self.redis_url)
|
|
270
|
+
raise RedisUnavailable(f"redis value is not a fingerprint object at {where}: got {type(decoded).__name__}")
|
|
271
|
+
return decoded
|
|
174
272
|
|
|
175
273
|
def close(self) -> None:
|
|
176
274
|
"""关掉客户端,并把自己从 lru_cache 里摘掉。
|
|
@@ -178,11 +276,18 @@ class RedisStorageSystem(StorageSystemMixin):
|
|
|
178
276
|
第二件事是承重的:类是用 lru_cache(1) 包的(上游按 __wrapped__ 校验),关掉客户端后
|
|
179
277
|
它仍会把同一个实例发给下一次相同参数的构造,于是那份存储永久坏死——每次 save/retrieve
|
|
180
278
|
都撞一个已关闭的客户端,adapters 每页降级,没有任何自愈路径。
|
|
279
|
+
|
|
280
|
+
**客户端只在最后一个使用者放掉时才真关**:同一连接串上的多个实例共用一份客户端
|
|
281
|
+
(每页一个),先 close 的那个不该把兄弟实例仍在用的连接池关掉 —— 那样对方的
|
|
282
|
+
save/retrieve 会撞上已关闭的客户端,而它手里没有任何线索。
|
|
181
283
|
"""
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
284
|
+
if self._closed:
|
|
285
|
+
return
|
|
286
|
+
self._closed = True
|
|
287
|
+
if _release_client(self._client_key, self._client):
|
|
288
|
+
close = getattr(self._client, "close", None)
|
|
289
|
+
if callable(close):
|
|
290
|
+
close()
|
|
186
291
|
# 注意取的是模块级的包装对象:实例的 type 是**原始类**,lru 包装上的 cache_clear
|
|
187
292
|
# 只挂在模块导出的那个可调用对象上。
|
|
188
293
|
drop_cache = getattr(RedisStorageSystem, "cache_clear", None)
|