@jayyuen66/dsh-scrapling 0.1.0 → 0.1.2
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 +113 -0
- package/LICENSE +1 -1
- package/README.md +252 -547
- package/README.zh-CN.md +246 -395
- package/client.js +3 -1384
- package/host.js +28 -22
- package/package.json +41 -40
- package/py/adapters.py +77 -26
- package/py/bridge.py +29 -2
- package/py/crawl.py +71 -7
- package/py/guard.py +44 -18
package/py/adapters.py
CHANGED
|
@@ -23,6 +23,7 @@ import concurrent.futures
|
|
|
23
23
|
import contextlib
|
|
24
24
|
import queue
|
|
25
25
|
import re
|
|
26
|
+
import sys
|
|
26
27
|
import threading
|
|
27
28
|
import uuid
|
|
28
29
|
from datetime import datetime, timezone
|
|
@@ -68,9 +69,10 @@ class AdapterError(RuntimeError):
|
|
|
68
69
|
def _require(engine: object) -> None:
|
|
69
70
|
"""引擎不可用时给出可执行的提示,而不是抛一个裸 AttributeError。"""
|
|
70
71
|
if engine is None:
|
|
72
|
+
# 带上解释器路径:装在哪份 Python 里是这条错误的全部信息量,而用户手上通常不止一份。
|
|
71
73
|
raise AdapterError(
|
|
72
74
|
"SCRAPLING_MISSING",
|
|
73
|
-
'Scrapling is not importable in
|
|
75
|
+
f'Scrapling is not importable in {sys.executable}. Install it with: pip install "scrapling[rag]"',
|
|
74
76
|
)
|
|
75
77
|
|
|
76
78
|
|
|
@@ -224,7 +226,7 @@ def redact_url_secrets(raw: str) -> str:
|
|
|
224
226
|
|
|
225
227
|
|
|
226
228
|
def _network_summary(
|
|
227
|
-
network: Any, #
|
|
229
|
+
network: Any, # 上游的 NetworkRecorder
|
|
228
230
|
*,
|
|
229
231
|
pattern: str | None,
|
|
230
232
|
limit: int,
|
|
@@ -392,7 +394,7 @@ def drop_data_uris(text: str, *, html: bool = False) -> str:
|
|
|
392
394
|
return "\n".join(out)
|
|
393
395
|
|
|
394
396
|
|
|
395
|
-
def _scoped_pages(page: Any, css_selector: str | None) -> list[Any]: #
|
|
397
|
+
def _scoped_pages(page: Any, css_selector: str | None) -> list[Any]: # 同上
|
|
396
398
|
"""按 ``css_selector`` 把清洗过的树收窄成若干棵子树;没给选择器就是整棵。
|
|
397
399
|
|
|
398
400
|
口径与 Scrapling 自家 ``Convertor._extract_content`` 一致:命中 0 个元素就是空表,
|
|
@@ -545,10 +547,6 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
545
547
|
# 发、对端收到空体,而回包上没有一行能看出这件事。
|
|
546
548
|
params["json"] = _jsonable(body)
|
|
547
549
|
|
|
548
|
-
# Host 侧闸门判过之后到 curl_cffi 真解析、真建连之间隔着一个进程边界(TOCTOU),
|
|
549
|
-
# 所以这里在发车之前用同一份 guard 复判一次 —— 浏览器路径由 page.route 逐请求兜住,
|
|
550
|
-
# 静态路径没有那一层,不在这里补就是「两道防线」只说了一半。判在写方法之后:那一条是
|
|
551
|
-
# 部署表态(非 GET 一律拒),与目标地址无关,不该被一条 URL_BLOCKED 盖掉。
|
|
552
550
|
# Host 侧闸门判过之后到 curl_cffi 真解析、真建连之间隔着一个进程边界(TOCTOU),
|
|
553
551
|
# 所以这里在发车之前用同一份 guard 复判一次 —— 浏览器路径由 page.route 逐请求兜住,
|
|
554
552
|
# 静态路径没有那一层,不在这里补就是「两道防线」只说了一半。判在写方法之后:那一条是
|
|
@@ -665,7 +663,7 @@ _DEPLOYMENT_KNOBS: tuple[tuple[str, str, type], ...] = (
|
|
|
665
663
|
)
|
|
666
664
|
|
|
667
665
|
|
|
668
|
-
def _knob_value(kind: type, value: Any) -> Any: #
|
|
666
|
+
def _knob_value(kind: type, value: Any) -> Any: # 收的是部署载荷里的任意 JSON 值
|
|
669
667
|
"""按声明的类型收下一枚部署旋钮值;类型不符给 None。
|
|
670
668
|
|
|
671
669
|
类型必须真的对得上:这一层承载的是部署表态,把字符串塞进一个整数旋钮(或反过来)时
|
|
@@ -849,6 +847,14 @@ def _capture_once(
|
|
|
849
847
|
from scrapling.fetchers import StealthySession
|
|
850
848
|
|
|
851
849
|
session_params = _session_browser_params(args)
|
|
850
|
+
# 与 _make_session 对齐:浏览器会话的代理只能在构造期给,而 _session_browser_params
|
|
851
|
+
# 按 SESSION_ONLY_KEYS 把它连同 block_webrtc 一起过滤掉了。不在这里补,配了代理的
|
|
852
|
+
# 机器上这条路径的 Chromium 会直连 —— 泄露真实出口 IP,三条浏览器路径行为不一致。
|
|
853
|
+
proxy = guard.split_proxy(guard.default_proxy())
|
|
854
|
+
if proxy is not None:
|
|
855
|
+
session_params["proxy"] = proxy
|
|
856
|
+
# 走代理时强制为真,与 _make_session 同一条理由:WebRTC 泄露的是访客真实出口 IP。
|
|
857
|
+
session_params["block_webrtc"] = bool(args.get("blockWebrtc")) or proxy is not None
|
|
852
858
|
session_params["record_requests"] = True
|
|
853
859
|
fetch_params = _browser_params(args, url, level="fetch")
|
|
854
860
|
# 会话的代理在构造期就定死了,逐次 fetch 再给一次只会被上游丢掉。
|
|
@@ -1163,6 +1169,11 @@ MAX_SESSIONS = 8
|
|
|
1163
1169
|
# 其中最多几个可以是吃内存的浏览器会话。static 只是连接池,便宜得多。
|
|
1164
1170
|
MAX_BROWSER_SESSIONS = 3
|
|
1165
1171
|
|
|
1172
|
+
# 等属主线程回结果的预算。这是**兜底**,不是抓取超时:单次调用的超时由它自己的
|
|
1173
|
+
# timeoutSeconds 管(浏览器导航可能合法地跑上几分钟),这里只负责把「线程已经不在了」
|
|
1174
|
+
# 从「调用很慢」里分出来。取 10 分钟是为了让最长的合法抓取仍先于它触发。
|
|
1175
|
+
_WORKER_RESULT_TIMEOUT_SECONDS = 600.0
|
|
1176
|
+
|
|
1166
1177
|
|
|
1167
1178
|
class _SessionWorker:
|
|
1168
1179
|
"""一个会话的**专属执行线程**:这份会话上的全部远端调用都在它上面排队执行。
|
|
@@ -1179,6 +1190,10 @@ class _SessionWorker:
|
|
|
1179
1190
|
def __init__(self) -> None:
|
|
1180
1191
|
self._jobs: "queue.SimpleQueue[tuple[Callable[[], Any], concurrent.futures.Future[Any]] | None]"
|
|
1181
1192
|
self._jobs = queue.SimpleQueue()
|
|
1193
|
+
# stop() 之后 _loop 已经取走哨兵并返回:此后投进来的任务永远排在一个没人消费的
|
|
1194
|
+
# 队列里,而 run() 的 done.result() 没有超时 —— 调用方会永久阻塞。用这个标记把
|
|
1195
|
+
# 「已停止」变成立刻可见的错误,而不是一次等不到回音的等待。
|
|
1196
|
+
self._closed = threading.Event()
|
|
1182
1197
|
self._thread = threading.Thread(target=self._loop, daemon=True, name="session-worker")
|
|
1183
1198
|
self._thread.start()
|
|
1184
1199
|
|
|
@@ -1197,19 +1212,30 @@ class _SessionWorker:
|
|
|
1197
1212
|
except BaseException as error: # noqa: BLE001 —— 任务异常必须回到调用方线程
|
|
1198
1213
|
done.set_exception(error)
|
|
1199
1214
|
|
|
1200
|
-
def run(self, fn: Callable[[], Any]) -> Any: #
|
|
1215
|
+
def run(self, fn: Callable[[], Any]) -> Any: # 会话调用的返回形态由引擎定
|
|
1201
1216
|
"""把 fn 投递到属主线程执行,并阻塞调用线程直到它结束。
|
|
1202
1217
|
|
|
1203
1218
|
:param fn: 要在属主线程上执行的调用
|
|
1204
1219
|
:returns: fn 的返回值
|
|
1220
|
+
:raises AdapterError: 这条线程已经停止,投进去也没有人会执行
|
|
1205
1221
|
:raises BaseException: fn 抛什么这里就抛什么
|
|
1206
1222
|
"""
|
|
1223
|
+
# 与 stop() 之间没有锁:检查通过之后 stop() 仍可能抢先取走哨兵。那个窗口里
|
|
1224
|
+
# put 进队列的任务确实没人消费,所以下面的 result 必须带超时兜底。
|
|
1225
|
+
if self._closed.is_set():
|
|
1226
|
+
raise AdapterError("NO_SUCH_SESSION", "session has already been closed")
|
|
1207
1227
|
done: concurrent.futures.Future[Any] = concurrent.futures.Future()
|
|
1208
1228
|
self._jobs.put((fn, done))
|
|
1209
|
-
|
|
1229
|
+
try:
|
|
1230
|
+
return done.result(timeout=_WORKER_RESULT_TIMEOUT_SECONDS)
|
|
1231
|
+
except concurrent.futures.TimeoutError:
|
|
1232
|
+
# fn 里真实的长调用(浏览器导航、大页面抓取)不该走到这里:那个预算由它自己的
|
|
1233
|
+
# 超时管。到这里说明这条线程已经不在了,继续等只会把调用方一起挂死。
|
|
1234
|
+
raise AdapterError("SESSION_CLOSED", "session worker did not answer; the session is gone") from None
|
|
1210
1235
|
|
|
1211
1236
|
def stop(self) -> None:
|
|
1212
1237
|
"""发哨兵收线程。队列里的任务会先跑完,所以 close 之后 stop 是安全的。"""
|
|
1238
|
+
self._closed.set()
|
|
1213
1239
|
self._jobs.put(None)
|
|
1214
1240
|
self._thread.join(timeout=5.0)
|
|
1215
1241
|
|
|
@@ -1353,17 +1379,33 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1353
1379
|
raise AdapterError("SESSION_OPEN_FAILED", f"{type(error).__name__}: {error}") from error
|
|
1354
1380
|
|
|
1355
1381
|
with _SESSION_LOCK:
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
"
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1382
|
+
abandoned = placeholder.get("closed_while_pending") is True
|
|
1383
|
+
if abandoned:
|
|
1384
|
+
created_at = ""
|
|
1385
|
+
else:
|
|
1386
|
+
_SESSIONS[session_id] = {
|
|
1387
|
+
"session": usable, # 真正发请求的对象
|
|
1388
|
+
"closer": closer, # 关它用的对象(static 是 wrapper,浏览器是自身)
|
|
1389
|
+
"type": kind,
|
|
1390
|
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
|
1391
|
+
# 同一把锁:占位时建的那把,盖回来而不是新建 —— 新建会让构造期与使用期各锁各的。
|
|
1392
|
+
"lock": entry_lock,
|
|
1393
|
+
# browser/stealth 的专属执行线程;static 为 None(见 _SessionWorker 的说明)。
|
|
1394
|
+
"worker": worker,
|
|
1395
|
+
}
|
|
1396
|
+
created_at = _SESSIONS[session_id]["created_at"]
|
|
1397
|
+
if abandoned:
|
|
1398
|
+
# 构造期间已经被要求关闭(sidecar 关机走的就是 close_all_sessions):这一份刚建好的
|
|
1399
|
+
# 会话绝不能登记 —— 登记了就没有任何人会再去关它,浏览器进程会活过 sidecar 自己。
|
|
1400
|
+
abandoned_entry = {"closer": closer, "type": kind, "lock": entry_lock}
|
|
1401
|
+
if worker is not None:
|
|
1402
|
+
# 浏览器会话的 close 必须在属主线程上跑:Playwright 的同步 API 与创建它的线程
|
|
1403
|
+
# 绑定,跨线程调用抛 greenlet 错误,而 _release_entry 会 suppress 掉它 ——
|
|
1404
|
+
# 随后 stop() 又把属主线程收掉,这个 Chromium 就再没有任何线程能关。
|
|
1405
|
+
worker.run(lambda: _release_entry(abandoned_entry))
|
|
1406
|
+
worker.stop()
|
|
1407
|
+
else:
|
|
1408
|
+
_release_entry(abandoned_entry)
|
|
1367
1409
|
return {
|
|
1368
1410
|
"sessionId": session_id,
|
|
1369
1411
|
"sessionType": kind,
|
|
@@ -1452,7 +1494,7 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1452
1494
|
response = worker.run(lambda: session.fetch(url, **params))
|
|
1453
1495
|
except AdapterError:
|
|
1454
1496
|
raise
|
|
1455
|
-
except Exception as error:
|
|
1497
|
+
except Exception as error:
|
|
1456
1498
|
raise AdapterError("FETCH_FAILED", f"{type(error).__name__}: {error}") from error
|
|
1457
1499
|
|
|
1458
1500
|
payload = to_payload(
|
|
@@ -1506,11 +1548,17 @@ def _close_entry(session_id: Any) -> None:
|
|
|
1506
1548
|
"""
|
|
1507
1549
|
with _SESSION_LOCK:
|
|
1508
1550
|
entry = _SESSIONS.pop(session_id, None)
|
|
1551
|
+
if entry is not None and entry.get("pending") is True:
|
|
1552
|
+
# 墓碑必须与 pop 在同一个临界区:session_open 是在 _SESSION_LOCK 里读它的。
|
|
1553
|
+
# 写在锁外会留下这个时序 —— 这里已 pop 并释放锁,构造方接着在锁内读到 False
|
|
1554
|
+
# 并把建好的会话登记回 _SESSIONS,之后才轮到写 True,那条会话就没人关了。
|
|
1555
|
+
entry["closed_while_pending"] = True
|
|
1509
1556
|
if entry is None:
|
|
1510
1557
|
return
|
|
1511
1558
|
if entry.get("pending") is True:
|
|
1512
1559
|
# 还没构造完:构造方自己会在成功时覆盖这一条,或在失败时把它摘掉。这里不能碰
|
|
1513
|
-
# closer ——
|
|
1560
|
+
# closer —— 它还不存在。但墓碑已经留下:构造方一会儿会把建好的会话登记回来,
|
|
1561
|
+
# 那一步要看见这次关闭,否则刚建好的浏览器没有任何人会再去关它。
|
|
1514
1562
|
return
|
|
1515
1563
|
worker: _SessionWorker | None = entry.get("worker")
|
|
1516
1564
|
if worker is not None:
|
|
@@ -1600,9 +1648,12 @@ def _state_path(args: dict[str, Any]) -> str:
|
|
|
1600
1648
|
name = args.get("name")
|
|
1601
1649
|
if not isinstance(name, str) or not name:
|
|
1602
1650
|
raise AdapterError("BAD_ARGS", "name is required")
|
|
1603
|
-
|
|
1651
|
+
# NUL 让 `Path(name).name` 仍然等于 name,却能进到后面的文件调用里:那一层会以一条
|
|
1652
|
+
# 语焉不详的错误收场,而不是在这里点名说清。
|
|
1653
|
+
if name != Path(name).name or name.startswith(".") or "\x00" in name:
|
|
1604
1654
|
raise AdapterError("BAD_ARGS", f"name must be a plain file name, got {name!r}")
|
|
1605
|
-
|
|
1655
|
+
stem = name[:-5] if name.lower().endswith(".json") else name
|
|
1656
|
+
return str(Path(directory) / f"{stem}.json")
|
|
1606
1657
|
|
|
1607
1658
|
|
|
1608
1659
|
def _session_state(args: dict[str, Any], *, saving: bool) -> dict[str, Any]:
|
|
@@ -1630,7 +1681,7 @@ def _session_state(args: dict[str, Any], *, saving: bool) -> dict[str, Any]:
|
|
|
1630
1681
|
worker.run(lambda: session.save_state(target))
|
|
1631
1682
|
else:
|
|
1632
1683
|
worker.run(lambda: session.load_state(target))
|
|
1633
|
-
except Exception as error: #
|
|
1684
|
+
except Exception as error: # 上游的文件/JSON 错误一律翻成可路由的码
|
|
1634
1685
|
raise AdapterError("STATE_FAILED", f"{type(error).__name__}: {error}") from error
|
|
1635
1686
|
return {"sessionId": session_id, "path": target, "saved": saving}
|
|
1636
1687
|
|
package/py/bridge.py
CHANGED
|
@@ -35,12 +35,26 @@
|
|
|
35
35
|
from __future__ import annotations
|
|
36
36
|
|
|
37
37
|
import json
|
|
38
|
+
import os
|
|
38
39
|
import sys
|
|
39
40
|
import threading
|
|
40
41
|
import time
|
|
41
42
|
import traceback
|
|
42
43
|
from typing import Any, Callable
|
|
43
44
|
|
|
45
|
+
# 协议帧与日志一律 UTF-8:宿主按 UTF-8 解码本进程的 stdout/stderr,而两者都是管道。
|
|
46
|
+
# 管道在 Windows 上默认走本地 ANSI 代码页;`LC_ALL=C` 配上 `PYTHONUTF8=0` 这类环境
|
|
47
|
+
# 也会让它们退成 ascii —— 那时 emit 里的非 ASCII 正文会抛 UnicodeEncodeError,而
|
|
48
|
+
# worker 把它当请求异常吞掉,调用方拿不到任何响应,只能等到超时。
|
|
49
|
+
# backslashreplace 兜住另一个方向:json.loads 能把 "\ud800" 解成孤立代理项,严格编码
|
|
50
|
+
# 会让整帧写不出去,替换成转义文本至少留下可读的痕迹。
|
|
51
|
+
# 用 getattr 取 reconfigure:被重定向成 io.StringIO 的流没有这个方法(测试与嵌宿主都可能
|
|
52
|
+
# 这么做),缺了它不该让整个 sidecar 起不来。
|
|
53
|
+
for _stream in (sys.stdout, sys.stderr):
|
|
54
|
+
_reconfigure = getattr(_stream, "reconfigure", None)
|
|
55
|
+
if callable(_reconfigure):
|
|
56
|
+
_reconfigure(encoding="utf-8", errors="backslashreplace")
|
|
57
|
+
|
|
44
58
|
MIN_PYTHON = (3, 14)
|
|
45
59
|
|
|
46
60
|
|
|
@@ -66,7 +80,10 @@ if _gate_message is not None:
|
|
|
66
80
|
|
|
67
81
|
|
|
68
82
|
# 让 py/ 目录里的 guard 能被 adapters 用 `from guard import install` 找到。
|
|
69
|
-
|
|
83
|
+
# 必须走 os.path:宿主传进来的 bridgePath 是 path.join(import.meta.dirname, "py", "bridge.py")
|
|
84
|
+
# 的产物,Windows 上是反斜杠分隔,按 "/" 切会得到整个文件路径,于是 adapters/guard 全都
|
|
85
|
+
# import 不到、ready 握手永远等不到。`-I` 又关掉了脚本目录自动进 sys.path,所以这一步不能省。
|
|
86
|
+
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
70
87
|
if _HERE not in sys.path:
|
|
71
88
|
sys.path.insert(0, _HERE)
|
|
72
89
|
|
|
@@ -196,7 +213,17 @@ def _worker() -> None:
|
|
|
196
213
|
time.sleep(0.05)
|
|
197
214
|
frame = _drain()
|
|
198
215
|
if frame is None:
|
|
199
|
-
|
|
216
|
+
# 「判定该退出」必须与入队互斥:读者是在 _QUEUE_LOCK 里 append 之后才去数
|
|
217
|
+
# worker 的,而这里在同一个锁里复查队列 —— 否则会出现「_ensure_worker 看到
|
|
218
|
+
# 我还活着所以不补人,我随后就退了」,那一帧被永久搁置在队列里。
|
|
219
|
+
with _QUEUE_LOCK:
|
|
220
|
+
if _QUEUE:
|
|
221
|
+
continue
|
|
222
|
+
with _WORKERS_LOCK:
|
|
223
|
+
current = threading.current_thread()
|
|
224
|
+
if current in _WORKERS:
|
|
225
|
+
_WORKERS.remove(current)
|
|
226
|
+
return
|
|
200
227
|
try:
|
|
201
228
|
emit(handle(frame))
|
|
202
229
|
except Exception as error: # noqa: BLE001 —— 连序列化失败都不能让线程死掉
|
package/py/crawl.py
CHANGED
|
@@ -10,6 +10,7 @@ daemon 线程**跑 spider,主线程立刻返回 crawl id;进度通过「没
|
|
|
10
10
|
|
|
11
11
|
from __future__ import annotations
|
|
12
12
|
|
|
13
|
+
import json
|
|
13
14
|
import threading
|
|
14
15
|
import time
|
|
15
16
|
import uuid
|
|
@@ -35,6 +36,10 @@ MAX_CONCURRENT_CRAWLS = 2
|
|
|
35
36
|
# 结束就删;但全留着就是内存泄漏,所以留一个上限,按最旧的淘汰。
|
|
36
37
|
MAX_REMEMBERED_CRAWLS = 16
|
|
37
38
|
|
|
39
|
+
# 一次 crawl.status 回包的字节上界。Host 侧按 8 MiB 切帧,而一个快站点能在一个轮询间隔里
|
|
40
|
+
# 落下几十页;留一半余量,越过切帧线的那一帧会把整个 sidecar 拆掉。回不完的由 `more` 交接。
|
|
41
|
+
MAX_STATUS_BYTES = 4 * 1024 * 1024
|
|
42
|
+
|
|
38
43
|
# 一次爬虫的整体截止(毫秒)。页数上限管不了「一页等一分钟」:1000 页的慢站点能跑几个
|
|
39
44
|
# 小时,而爬虫跑在没人看的后台线程里,没有任何外部计时器会来叫停它。部署侧可按次调小。
|
|
40
45
|
DEFAULT_MAX_RUNTIME_MS = 1_800_000
|
|
@@ -379,12 +384,18 @@ def _is_running(entry: dict[str, Any]) -> bool:
|
|
|
379
384
|
"""这个登记条目算不算「正在跑」。
|
|
380
385
|
|
|
381
386
|
``thread`` 为 ``None`` 表示 spider 还在构造中:它已经占了并发名额,所以算在跑。
|
|
387
|
+
``thread.ident`` 为 ``None`` 是另一段窗口——线程对象已登记但还没 ``start()``。只按
|
|
388
|
+
``is_alive()`` 判会在这段窗口里把条目当成已结束:并发的 :func:`crawl_run` 少算一个名额
|
|
389
|
+
(突破并发上限)、:func:`_evict_finished_crawls` 把它当历史淘汰(之后那次 ``start()``
|
|
390
|
+
就跑在没有登记项的蜘蛛上,叫不停)、:func:`crawl_stop` 判成不在跑。
|
|
382
391
|
|
|
383
392
|
:param entry: 登记条目
|
|
384
393
|
:returns: 是否占用名额
|
|
385
394
|
"""
|
|
386
395
|
thread = entry.get("thread")
|
|
387
|
-
|
|
396
|
+
if thread is None:
|
|
397
|
+
return True
|
|
398
|
+
return thread.ident is None or thread.is_alive()
|
|
388
399
|
|
|
389
400
|
|
|
390
401
|
def _evict_finished_crawls() -> None:
|
|
@@ -422,12 +433,13 @@ def crawl_status(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
422
433
|
"""查一个爬虫的状态与已收结果。
|
|
423
434
|
|
|
424
435
|
``since`` 是本轮之前已经读走多少页(按下标,不是 URL)。带上它只回新增的那一段:
|
|
425
|
-
整份 pages 每轮重发,流量是 O(n²)
|
|
426
|
-
|
|
427
|
-
|
|
436
|
+
整份 pages 每轮重发,流量是 O(n²)。但增量本身也可能很大 —— 一个快站点能在一个轮询
|
|
437
|
+
间隔里落下几十页,每页又按 ``max_content_chars`` 封顶 —— 而 Host 侧是按 8 MiB 切帧的:
|
|
438
|
+
超了就是一帧坏帧,整个 sidecar 连同正在跑的会话一起被拆掉。所以回包再按**字节**分片:
|
|
439
|
+
回不完就置 ``more``,调用方拿新的 ``since`` 立刻接着取,一页都不丢。
|
|
428
440
|
|
|
429
441
|
:param args: 协议参数
|
|
430
|
-
:returns: {crawlId, running, pages, total, error, expired}
|
|
442
|
+
:returns: {crawlId, running, pages, total, error, expired, more}
|
|
431
443
|
"""
|
|
432
444
|
from adapters import AdapterError
|
|
433
445
|
|
|
@@ -437,10 +449,10 @@ def crawl_status(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
437
449
|
entry = _get_crawl(args.get("crawlId"))
|
|
438
450
|
state: dict[str, Any] = entry["state"]
|
|
439
451
|
# pages 是 spider 线程边跑边 append 的活列表,而回包要经 json.dumps 序列化。
|
|
440
|
-
#
|
|
452
|
+
# 进锁里取一段:一边序列化一边追加,结果要么漏一页要么撞上 RuntimeError。
|
|
441
453
|
with _CRAWL_LOCK:
|
|
442
454
|
total = len(state["pages"])
|
|
443
|
-
pages =
|
|
455
|
+
pages, more = _take_pages(state["pages"], since)
|
|
444
456
|
running = _is_running(entry)
|
|
445
457
|
return {
|
|
446
458
|
"crawlId": entry["crawl_id"],
|
|
@@ -448,12 +460,64 @@ def crawl_status(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
448
460
|
"running": running,
|
|
449
461
|
"pages": pages,
|
|
450
462
|
"total": total,
|
|
463
|
+
"more": more,
|
|
451
464
|
"error": state["error"],
|
|
452
465
|
# 截止到点而停的爬虫带这个标记:模型能看出「为什么比 maxPages 少」。
|
|
453
466
|
"expired": state.get("expired") is True,
|
|
454
467
|
}
|
|
455
468
|
|
|
456
469
|
|
|
470
|
+
def _shrink_page(page: dict[str, Any], budget: int) -> dict[str, Any]:
|
|
471
|
+
"""把单页压到 ``budget`` 字节以内。
|
|
472
|
+
|
|
473
|
+
``maxContentChars`` 没有上界(部署侧的 ``fetchMaxOutputChars`` 只声明了 ``min(1)``),
|
|
474
|
+
所以「一页就超过回包预算」是可达的:这时 :func:`_take_pages` 若照原样把它交出去,那一帧
|
|
475
|
+
会顶过 Host 的 8 MiB 切帧线,整个 sidecar 连同正在跑的会话一起被判成坏帧拆掉。宁可回
|
|
476
|
+
一页被截断的正文,也不要拆进程。
|
|
477
|
+
|
|
478
|
+
截断量按**序列化之后**的剩余空间算:先量出除 markdown 以外的固定开销,再把 markdown
|
|
479
|
+
砍到剩下的额度。CJK 一个字在 UTF-8 里三字节,所以按字符砍之后还要复查一次字节数,
|
|
480
|
+
复查不过就继续砍,直到装得下或已砍空。
|
|
481
|
+
|
|
482
|
+
:param page: 原始页
|
|
483
|
+
:param budget: 这一页的字节预算
|
|
484
|
+
:returns: 压过的新页(不就地改原对象,state 里留全量)
|
|
485
|
+
"""
|
|
486
|
+
overhead = len(json.dumps({**page, "markdown": ""}, ensure_ascii=False).encode("utf-8"))
|
|
487
|
+
room = max(0, budget - overhead)
|
|
488
|
+
markdown = str(page.get("markdown", ""))
|
|
489
|
+
clipped = markdown[:room] + "\n\n[truncated to fit the status frame budget]"
|
|
490
|
+
while len(clipped.encode("utf-8")) > room and clipped:
|
|
491
|
+
clipped = clipped[: max(0, len(clipped) - max(1, len(clipped) // 4))]
|
|
492
|
+
return {**page, "markdown": clipped, "truncated": True}
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def _take_pages(all_pages: list[dict[str, Any]], since: int) -> tuple[list[dict[str, Any]], bool]:
|
|
496
|
+
"""从 ``since`` 起取一段页,按 :data:`MAX_STATUS_BYTES` 封顶。
|
|
497
|
+
|
|
498
|
+
至少回一页:单页就超预算时也回它,否则调用方永远取不到下一页,轮询变成死循环。但这一
|
|
499
|
+
页必须**压到预算之内**再回 —— 原样交出去的那一帧会顶过 Host 的 8 MiB 切帧线。
|
|
500
|
+
|
|
501
|
+
:param all_pages: 活页表
|
|
502
|
+
:param since: 已经读走多少页
|
|
503
|
+
:returns: (这一段的页, 后面还有没有)
|
|
504
|
+
"""
|
|
505
|
+
if since >= len(all_pages):
|
|
506
|
+
return [], False
|
|
507
|
+
taken: list[dict[str, Any]] = []
|
|
508
|
+
spent = 0
|
|
509
|
+
for index in range(since, len(all_pages)):
|
|
510
|
+
size = len(json.dumps(all_pages[index], ensure_ascii=False).encode("utf-8"))
|
|
511
|
+
if size > MAX_STATUS_BYTES:
|
|
512
|
+
# 单页就超预算:压到预算内回它,并置 more 让调用方知道后面还有(或还有别的页)。
|
|
513
|
+
return [_shrink_page(all_pages[index], MAX_STATUS_BYTES)], index + 1 < len(all_pages)
|
|
514
|
+
if taken and spent + size > MAX_STATUS_BYTES:
|
|
515
|
+
return taken, True
|
|
516
|
+
taken.append(all_pages[index])
|
|
517
|
+
spent += size
|
|
518
|
+
return taken, False
|
|
519
|
+
|
|
520
|
+
|
|
457
521
|
def crawl_stop(args: dict[str, Any]) -> dict[str, Any]:
|
|
458
522
|
"""叫停一个爬虫。
|
|
459
523
|
|
package/py/guard.py
CHANGED
|
@@ -27,9 +27,6 @@ from urllib.parse import unquote, urlparse
|
|
|
27
27
|
# 放行的额外主机名。默认空 —— 只有字面量公网 IP 与解析到公网的域名能过。
|
|
28
28
|
ALLOWED_HOSTS: frozenset[str] = frozenset()
|
|
29
29
|
|
|
30
|
-
# 额外放行的端口;空表示不限端口(与 dsh 内置 fetch provider 同取舍)。
|
|
31
|
-
ALLOWED_PORTS: frozenset[int] = frozenset()
|
|
32
|
-
|
|
33
30
|
# 允许额外放行主机名的环境变量。默认不设 ⇒ 放行集合为空 ⇒ 守卫最严。
|
|
34
31
|
#
|
|
35
32
|
# 这是一个**安全相关**开关:把它指到内网地址等于主动放弃对那些目标的 SSRF 防护。
|
|
@@ -121,21 +118,18 @@ EXTRA_NAT64_PREFIXES: tuple[str, ...] = ()
|
|
|
121
118
|
_NAT64_EMBEDDED_OFFSET: dict[int, int] = {96: 12, 64: 9, 56: 7, 48: 6, 40: 5, 32: 4}
|
|
122
119
|
|
|
123
120
|
|
|
124
|
-
def configure(allowed_hosts=None,
|
|
121
|
+
def configure(allowed_hosts=None, nat64_prefixes=None, allow_write_methods=None) -> None:
|
|
125
122
|
"""按部署配置收紧或放宽放行集合。
|
|
126
123
|
|
|
127
124
|
只应由宿主侧在启动时调用一次,参数来自用户显式设置,而不是模型入参。
|
|
128
125
|
|
|
129
126
|
:param allowed_hosts: 额外放行的主机名;None 表示沿用当前值
|
|
130
|
-
:param allowed_ports: 额外放行的端口;None 表示沿用当前值
|
|
131
127
|
:param nat64_prefixes: 额外的 NAT64 前缀(CIDR);None 表示沿用当前值
|
|
132
128
|
:param allow_write_methods: 是否开放写方法;None 表示沿用当前值
|
|
133
129
|
"""
|
|
134
|
-
global ALLOWED_HOSTS,
|
|
130
|
+
global ALLOWED_HOSTS, EXTRA_NAT64_PREFIXES, ALLOW_WRITE_METHODS # noqa: PLW0603 —— 模块级策略常量,需整体替换
|
|
135
131
|
if allowed_hosts is not None:
|
|
136
132
|
ALLOWED_HOSTS = allowed_hosts
|
|
137
|
-
if allowed_ports is not None:
|
|
138
|
-
ALLOWED_PORTS = allowed_ports
|
|
139
133
|
if nat64_prefixes is not None:
|
|
140
134
|
EXTRA_NAT64_PREFIXES = nat64_prefixes
|
|
141
135
|
if allow_write_methods is not None:
|
|
@@ -161,7 +155,7 @@ def configure_from_env() -> None:
|
|
|
161
155
|
configure(nat64_prefixes=prefixes)
|
|
162
156
|
|
|
163
157
|
global SYNTHETIC_NETWORKS, PROXY_URL, PROXY_BYPASS, ALLOW_WRITE_METHODS, _BYPASS_ENTRIES # noqa: PLW0603 —— 启动时定一次
|
|
164
|
-
global _ENV_PROXIES, _ENV_BYPASS, _SYSTEM_PROXIES, _PAC_NOTICE #
|
|
158
|
+
global _ENV_PROXIES, _ENV_BYPASS, _SYSTEM_PROXIES, _PAC_NOTICE # 同上
|
|
165
159
|
networks: list[ipaddress.IPv4Network] = []
|
|
166
160
|
for item in os.environ.get(SYNTHETIC_RANGES_ENV, "").split(","):
|
|
167
161
|
text = item.strip()
|
|
@@ -288,7 +282,9 @@ def parse_windows_proxy(entries: dict[str, str]) -> dict[str, str]:
|
|
|
288
282
|
:param entries: 键是 ``ProxyEnable`` / ``ProxyServer`` / ``AutoConfigURL`` 的小写形式
|
|
289
283
|
:returns: 代理表
|
|
290
284
|
"""
|
|
291
|
-
|
|
285
|
+
# `reg query` 对 REG_DWORD 输出的就是十六进制(`0x1`),只有部分工具会写成十进制
|
|
286
|
+
# `1`。只认后者的话这条探测在 Windows 上永远返回空表,整条系统代理路径静默失效。
|
|
287
|
+
if entries.get("proxyenable", "").strip().lower() not in ("1", "0x1"):
|
|
292
288
|
return {}
|
|
293
289
|
raw = entries.get("proxyserver", "").strip()
|
|
294
290
|
if not raw:
|
|
@@ -476,7 +472,15 @@ def split_proxy(raw: str) -> dict[str, str] | None:
|
|
|
476
472
|
:param raw: 代理地址
|
|
477
473
|
:returns: 代理字典;地址不可用时为 None
|
|
478
474
|
"""
|
|
479
|
-
|
|
475
|
+
try:
|
|
476
|
+
parsed = urlparse(raw)
|
|
477
|
+
# 提前取一次端口:越界(`:99999`)或非数字(`:abc`)的端口在这时才抛
|
|
478
|
+
# ValueError,而下面还有几处要读 `parsed.port`。畸形方括号(`http://[::1`)
|
|
479
|
+
# 在 urlparse 里就抛。两处一并按「地址不可用」处理 —— 本函数的契约是返回
|
|
480
|
+
# None 而不是抛,调用方(configure_from_env / proxy_settings)据此如实报未配置。
|
|
481
|
+
port = parsed.port
|
|
482
|
+
except ValueError:
|
|
483
|
+
return None
|
|
480
484
|
scheme = (parsed.scheme or "").lower()
|
|
481
485
|
if scheme not in _BROWSER_PROXY_SCHEMES or not parsed.hostname:
|
|
482
486
|
return None
|
|
@@ -484,8 +488,8 @@ def split_proxy(raw: str) -> dict[str, str] | None:
|
|
|
484
488
|
# server 里得再装回去 —— 否则 `[::1]` 会被解析成端口。
|
|
485
489
|
host = parsed.hostname if ":" not in parsed.hostname else f"[{parsed.hostname}]"
|
|
486
490
|
server = f"{scheme}://{host}"
|
|
487
|
-
if
|
|
488
|
-
server = f"{server}:{
|
|
491
|
+
if port:
|
|
492
|
+
server = f"{server}:{port}"
|
|
489
493
|
return {
|
|
490
494
|
"server": server,
|
|
491
495
|
# 凭据要 percent-decode:urlparse 不解,而 Playwright 是把这对值原样塞进
|
|
@@ -543,13 +547,36 @@ def _nat64_tables() -> tuple[tuple[ipaddress.IPv6Network, int, int], ...]:
|
|
|
543
547
|
return tuple(tables)
|
|
544
548
|
|
|
545
549
|
|
|
550
|
+
def _nat64_inner_bytes(packed: bytes, offset: int) -> bytes:
|
|
551
|
+
"""按 RFC 6052 §2.2 的布局从 16 字节里取出内嵌 IPv4。
|
|
552
|
+
|
|
553
|
+
``/40``、``/48``、``/56`` 这几档的 IPv4 被第 9 个字节(下标 8 的 u 字节)从中间切断:
|
|
554
|
+
前半段在 u 之前,后半段在 u 之后,并不连续。按起点连续切 4 字节会把 u 字节当成 IPv4
|
|
555
|
+
的一位读进来、同时漏掉最后一位 —— ``/48`` 下内嵌 192.0.2.33 的地址会被读成
|
|
556
|
+
192.0.0.2,于是私网地址能被读成公网地址。
|
|
557
|
+
|
|
558
|
+
``/32`` 与 ``/64`` 的 4 字节恰好落在 u 的同一侧,按连续切本来就对;``/96`` 在最后
|
|
559
|
+
4 字节,与 u 无关。统一写法:取 5 字节窗口再剔除 u 字节,六档共用一条路径。
|
|
560
|
+
|
|
561
|
+
:param packed: IPv6 的 16 字节
|
|
562
|
+
:param offset: 内嵌 IPv4 的起始下标
|
|
563
|
+
:returns: 内嵌 IPv4 的 4 字节
|
|
564
|
+
"""
|
|
565
|
+
window = packed[offset : offset + 5]
|
|
566
|
+
return bytes(byte for index, byte in enumerate(window) if offset + index != 8)[:4]
|
|
567
|
+
|
|
568
|
+
|
|
546
569
|
def _embedded_ipv4(address: ipaddress.IPv6Address) -> ipaddress.IPv4Address | None:
|
|
547
|
-
"""若地址落在某个 NAT64 前缀里,抽出内嵌的 IPv4。
|
|
570
|
+
"""若地址落在某个 NAT64 前缀里,抽出内嵌的 IPv4。
|
|
571
|
+
|
|
572
|
+
:param address: IPv6 地址
|
|
573
|
+
:returns: 内嵌的 IPv4 地址;不落在任何前缀里时返回 ``None``
|
|
574
|
+
"""
|
|
548
575
|
packed = address.packed
|
|
549
576
|
for network, _prefixlen, offset in _nat64_tables():
|
|
550
577
|
if address not in network:
|
|
551
578
|
continue
|
|
552
|
-
return ipaddress.IPv4Address(packed
|
|
579
|
+
return ipaddress.IPv4Address(_nat64_inner_bytes(packed, offset))
|
|
553
580
|
return None
|
|
554
581
|
|
|
555
582
|
|
|
@@ -799,11 +826,10 @@ def url_allowed(url: str) -> tuple[bool, str]:
|
|
|
799
826
|
if not host:
|
|
800
827
|
return False, "URL has no host"
|
|
801
828
|
try:
|
|
802
|
-
|
|
829
|
+
_ = parsed.port
|
|
803
830
|
except ValueError:
|
|
831
|
+
# 端口超界(如 :99999)时 urlparse 只在取 .port 那一刻才抛,hostname 本身是好的。
|
|
804
832
|
return False, "URL has an invalid port"
|
|
805
|
-
if ALLOWED_PORTS and port is not None and port not in ALLOWED_PORTS:
|
|
806
|
-
return False, f"port {port} is not in the allow list"
|
|
807
833
|
if not is_public_address(host, proxied=bool(proxy_for(url))):
|
|
808
834
|
return False, f"host does not resolve to a public address: {host}"
|
|
809
835
|
return True, ""
|