@jayyuen66/dsh-scrapling 0.0.1-rc.2 → 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 +71 -18
- package/README.zh-CN.md +29 -11
- package/client.js +461 -98
- package/host.js +21 -20
- 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 +157 -52
package/py/bridge.py
CHANGED
|
@@ -287,22 +287,29 @@ def read_loop() -> int:
|
|
|
287
287
|
if frame.get("method") == "shutdown":
|
|
288
288
|
emit(ok(frame.get("id"), {"stopping": True}))
|
|
289
289
|
_drain_before_exit()
|
|
290
|
+
# 与 EOF 路径同一套收尾:浏览器会话是独立进程,不显式关掉就会活过 sidecar
|
|
291
|
+
# 本身。宿主的优雅关闭走的就是这一帧(见 lib/sidecar.ts 的 dispose)。
|
|
292
|
+
_shutdown_sessions()
|
|
290
293
|
return 0
|
|
291
294
|
# 顺序要紧:先入队再起 worker。反过来的话,新起的线程可能立刻醒来、
|
|
292
295
|
# 看到空队列就退出,这一帧就永远没人处理 —— 且只在时序凑巧时才会复现。
|
|
296
|
+
busy_reply: dict[str, Any] | None = None
|
|
293
297
|
with _QUEUE_LOCK:
|
|
294
298
|
depth = len(_QUEUE)
|
|
295
299
|
if depth >= MAX_QUEUE_DEPTH:
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
f"{depth} requests already queued (limit {MAX_QUEUE_DEPTH})",
|
|
301
|
-
)
|
|
300
|
+
busy_reply = fail(
|
|
301
|
+
frame.get("id"),
|
|
302
|
+
"BUSY",
|
|
303
|
+
f"{depth} requests already queued (limit {MAX_QUEUE_DEPTH})",
|
|
302
304
|
)
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
305
|
+
else:
|
|
306
|
+
_QUEUE.append(frame)
|
|
307
|
+
depth += 1
|
|
308
|
+
if busy_reply is not None:
|
|
309
|
+
# emit 在锁外:stdout 一旦阻塞(宿主读得慢),持锁写流会把全部 worker 的
|
|
310
|
+
# _drain 一起冻住 —— 回帧可以慢,队列不能停。
|
|
311
|
+
emit(busy_reply)
|
|
312
|
+
continue
|
|
306
313
|
_ensure_worker(min(depth, MAX_INFLIGHT))
|
|
307
314
|
log("stdin closed")
|
|
308
315
|
_drain_before_exit()
|
package/py/crawl.py
CHANGED
|
@@ -11,7 +11,9 @@ daemon 线程**跑 spider,主线程立刻返回 crawl id;进度通过「没
|
|
|
11
11
|
from __future__ import annotations
|
|
12
12
|
|
|
13
13
|
import threading
|
|
14
|
+
import time
|
|
14
15
|
import uuid
|
|
16
|
+
from contextlib import suppress
|
|
15
17
|
from typing import Any
|
|
16
18
|
from urllib.parse import urlparse
|
|
17
19
|
|
|
@@ -20,6 +22,11 @@ from guard import proxies_for, url_allowed
|
|
|
20
22
|
# 正在跑的爬虫:crawl id -> {"thread": Thread, "crawl_id": str, "state": dict}
|
|
21
23
|
_CRAWLS: dict[str, dict[str, Any]] = {}
|
|
22
24
|
|
|
25
|
+
# bridge 有多个 worker 线程,crawl_run 会并发进来。判名额与登记必须原子,否则两个调用
|
|
26
|
+
# 各自数到「还没满」再各自起一条 Spider,MAX_CONCURRENT_CRAWLS 就名存实亡。判定与登记
|
|
27
|
+
# 之间隔着造 Spider(要建会话、可能要走网络),这个窗口足够宽。
|
|
28
|
+
_CRAWL_LOCK = threading.Lock()
|
|
29
|
+
|
|
23
30
|
# 同时能跑几个爬虫。爬虫是重量级后台任务且**立刻返回**,因此 bridge 的并发槽位对它无效
|
|
24
31
|
# —— 不设上限的话连续几次 crawl.run 就会叠起多个 Spider 线程与 FetcherSession。
|
|
25
32
|
MAX_CONCURRENT_CRAWLS = 2
|
|
@@ -28,6 +35,10 @@ MAX_CONCURRENT_CRAWLS = 2
|
|
|
28
35
|
# 结束就删;但全留着就是内存泄漏,所以留一个上限,按最旧的淘汰。
|
|
29
36
|
MAX_REMEMBERED_CRAWLS = 16
|
|
30
37
|
|
|
38
|
+
# 一次爬虫的整体截止(毫秒)。页数上限管不了「一页等一分钟」:1000 页的慢站点能跑几个
|
|
39
|
+
# 小时,而爬虫跑在没人看的后台线程里,没有任何外部计时器会来叫停它。部署侧可按次调小。
|
|
40
|
+
DEFAULT_MAX_RUNTIME_MS = 1_800_000
|
|
41
|
+
|
|
31
42
|
|
|
32
43
|
def _clip_markdown(text: str, budget: int) -> str:
|
|
33
44
|
"""把单页正文封顶到 budget 字符。
|
|
@@ -69,11 +80,34 @@ def _allowed_domains(url: str) -> set[str]:
|
|
|
69
80
|
# 主机名与 host:port 都放进去:Scrapling 的域过滤可能按 hostname 比,也可能按
|
|
70
81
|
# netloc 比。少放一个的表现是「只爬到第一页就停」,不报错,很难一眼看出原因。
|
|
71
82
|
parsed = urlparse(url)
|
|
72
|
-
|
|
73
|
-
|
|
83
|
+
return {value for value in (parsed.hostname, parsed.netloc) if value}
|
|
84
|
+
|
|
74
85
|
|
|
86
|
+
def _within_allowed_domains(url: str, allowed: set[str]) -> bool:
|
|
87
|
+
"""这个地址还在起始域里吗。
|
|
75
88
|
|
|
76
|
-
|
|
89
|
+
口径与 Scrapling 引擎的 ``_is_domain_allowed`` 逐字一致(netloc 相等,或落在某个
|
|
90
|
+
允许域的子域下)—— 链接发现那一侧本来就这么滤。但**它只管链接发现**:重定向是
|
|
91
|
+
curl_cffi 自己跟的,``follow_redirects="safe"`` 只拒绝跳向私网,站外公网跳转照跟。
|
|
92
|
+
所以最终落在哪个主机上,必须在收页之前自己复判一次。
|
|
93
|
+
|
|
94
|
+
:param url: 待判定的地址
|
|
95
|
+
:param allowed: 允许的域集合
|
|
96
|
+
:returns: 是否仍在起始域内
|
|
97
|
+
"""
|
|
98
|
+
domain = urlparse(url).netloc.lower()
|
|
99
|
+
if not domain:
|
|
100
|
+
return False
|
|
101
|
+
return any(domain == entry or domain.endswith(f".{entry}") for entry in allowed)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _make_spider(
|
|
105
|
+
url: str,
|
|
106
|
+
limit: int,
|
|
107
|
+
crawl_id: str,
|
|
108
|
+
state: dict[str, Any],
|
|
109
|
+
domains: set[str],
|
|
110
|
+
) -> Any:
|
|
77
111
|
"""动态造一个 spider 类。
|
|
78
112
|
|
|
79
113
|
Spider 的 ``start_urls`` / ``allowed_domains`` / ``max_pages`` / ``output_dir``
|
|
@@ -84,6 +118,7 @@ def _make_spider(url: str, limit: int, crawl_id: str, state: dict[str, Any]) ->
|
|
|
84
118
|
:param limit: 最多爬多少页
|
|
85
119
|
:param crawl_id: 爬虫 id,用于日志
|
|
86
120
|
:param state: 结果槽;爬完写进它
|
|
121
|
+
:param domains: 起始域集合,链接发现与收页复核共用同一份
|
|
87
122
|
:returns: spider 实例
|
|
88
123
|
"""
|
|
89
124
|
from scrapling.spiders import SiteToMarkdownSpider
|
|
@@ -93,7 +128,7 @@ def _make_spider(url: str, limit: int, crawl_id: str, state: dict[str, Any]) ->
|
|
|
93
128
|
|
|
94
129
|
name = f"scrapling-{crawl_id}"
|
|
95
130
|
start_urls = [url]
|
|
96
|
-
allowed_domains =
|
|
131
|
+
allowed_domains = domains
|
|
97
132
|
max_pages = limit
|
|
98
133
|
output_dir = None
|
|
99
134
|
|
|
@@ -135,9 +170,14 @@ def _make_spider(url: str, limit: int, crawl_id: str, state: dict[str, Any]) ->
|
|
|
135
170
|
if len(pages) >= limit:
|
|
136
171
|
return None
|
|
137
172
|
page_url = str(item.get("url", ""))
|
|
138
|
-
#
|
|
139
|
-
#
|
|
173
|
+
# 收页前的最后两道:
|
|
174
|
+
# 一是即使 safe 重定向放行了,这一页的最终 URL 仍可能落在私网上;
|
|
175
|
+
# 二是它可能被重定向去了**站外另一台公网主机** —— allowed_domains 只参与链接
|
|
176
|
+
# 发现,拦不住 curl_cffi 自己跟的那一跳。判否就不收:内容已经在对端取过了,
|
|
177
|
+
# 但至少不把它写进 state 流回模型上下文。
|
|
140
178
|
allowed, reason = url_allowed(page_url)
|
|
179
|
+
if allowed and not _within_allowed_domains(page_url, domains):
|
|
180
|
+
allowed, reason = False, "left the start domain (redirect)"
|
|
141
181
|
if not allowed:
|
|
142
182
|
_emit_event(
|
|
143
183
|
"crawlSkipped",
|
|
@@ -146,6 +186,19 @@ def _make_spider(url: str, limit: int, crawl_id: str, state: dict[str, Any]) ->
|
|
|
146
186
|
text=f"skipped {page_url}: {reason}",
|
|
147
187
|
)
|
|
148
188
|
return None
|
|
189
|
+
# 整体截止:页数上限管不了慢站点,而爬虫跑在没人看的后台线程里。到了点就按
|
|
190
|
+
# 引擎自己的停机通道退场 —— pause() 让引擎在在途请求收尾后停,不是撕进程。
|
|
191
|
+
if time.monotonic() >= state["deadline"]:
|
|
192
|
+
state["expired"] = True
|
|
193
|
+
_emit_event(
|
|
194
|
+
"crawlSkipped",
|
|
195
|
+
crawlId=crawl_id,
|
|
196
|
+
url=page_url,
|
|
197
|
+
text=f"crawl stopped: runtime budget of {state['budget_ms']}ms reached",
|
|
198
|
+
)
|
|
199
|
+
with suppress(RuntimeError):
|
|
200
|
+
self.pause()
|
|
201
|
+
return None
|
|
149
202
|
markdown = str(item.get("markdown", ""))
|
|
150
203
|
# 与其余抓取路径同一口径:内嵌 base64 图片是纯 token 噪音,先剥再封顶 ——
|
|
151
204
|
# 顺序反了等于白剥,那几十 KB 早就把 max_content_chars 的额度吃掉了。
|
|
@@ -192,11 +245,19 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
192
245
|
|
|
193
246
|
url = _url(args)
|
|
194
247
|
max_pages = _positive_int(args.get("maxPages"), "maxPages", 20)
|
|
195
|
-
max_content_chars = _positive_int(
|
|
196
|
-
|
|
197
|
-
)
|
|
248
|
+
max_content_chars = _positive_int(args.get("maxContentChars"), "maxContentChars", DEFAULT_MAX_CONTENT_CHARS)
|
|
249
|
+
budget_ms = _positive_int(args.get("maxDurationMs"), "maxDurationMs", DEFAULT_MAX_RUNTIME_MS)
|
|
198
250
|
strip_inline_images = _strip_inline_images(args)
|
|
199
251
|
crawl_id = uuid.uuid4().hex[:12]
|
|
252
|
+
state: dict[str, Any] = {
|
|
253
|
+
"error": None,
|
|
254
|
+
"pages": [],
|
|
255
|
+
"max_content_chars": max_content_chars,
|
|
256
|
+
"strip_inline_images": strip_inline_images,
|
|
257
|
+
"budget_ms": budget_ms,
|
|
258
|
+
"deadline": time.monotonic() + budget_ms / 1000,
|
|
259
|
+
}
|
|
260
|
+
domains = _allowed_domains(url)
|
|
200
261
|
|
|
201
262
|
# Host 闸门判的是这条 URL,但协议层不该假设调用方一定判过:这道复核与浏览器路径上
|
|
202
263
|
# 的 guard.url_allowed 是同一个实现,因此两侧同解。
|
|
@@ -204,27 +265,39 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
204
265
|
if not allowed:
|
|
205
266
|
raise AdapterError("URL_BLOCKED", f"{url}: {reason}")
|
|
206
267
|
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
268
|
+
with _CRAWL_LOCK:
|
|
269
|
+
_evict_finished_crawls()
|
|
270
|
+
running = [entry for entry in _CRAWLS.values() if _is_running(entry)]
|
|
271
|
+
if len(running) >= MAX_CONCURRENT_CRAWLS:
|
|
272
|
+
raise AdapterError(
|
|
273
|
+
"CRAWL_BUSY",
|
|
274
|
+
f"already {len(running)} crawls running; the limit is {MAX_CONCURRENT_CRAWLS}",
|
|
275
|
+
)
|
|
276
|
+
# 先占位再回去造 Spider。占位条目的 thread 是 None,_is_running 把它算作在跑 ——
|
|
277
|
+
# 名额要在造 spider 的那几百毫秒里一直占着,否则并发调用会各自数到「还没满」。
|
|
278
|
+
# stop_requested 也在占位时就位:那期间到来的叫停不能丢。
|
|
279
|
+
_CRAWLS[crawl_id] = {
|
|
280
|
+
"thread": None,
|
|
281
|
+
"crawl_id": crawl_id,
|
|
282
|
+
"state": state,
|
|
283
|
+
"stop_requested": False,
|
|
284
|
+
}
|
|
214
285
|
|
|
215
|
-
state: dict[str, Any] = {
|
|
216
|
-
"error": None,
|
|
217
|
-
"pages": [],
|
|
218
|
-
"max_content_chars": max_content_chars,
|
|
219
|
-
"strip_inline_images": strip_inline_images,
|
|
220
|
-
}
|
|
221
286
|
try:
|
|
222
|
-
spider = _make_spider(url, max_pages, crawl_id, state)
|
|
223
|
-
except
|
|
287
|
+
spider = _make_spider(url, max_pages, crawl_id, state, domains)
|
|
288
|
+
except BaseException as error:
|
|
289
|
+
with _CRAWL_LOCK:
|
|
290
|
+
_CRAWLS.pop(crawl_id, None)
|
|
291
|
+
if isinstance(error, AdapterError):
|
|
292
|
+
raise
|
|
224
293
|
raise AdapterError("CRAWL_SETUP_FAILED", f"{type(error).__name__}: {error}") from error
|
|
225
294
|
|
|
226
295
|
def worker() -> None:
|
|
227
296
|
"""后台线程体:跑爬虫并把异常收进 state,不让它悄悄消失。"""
|
|
297
|
+
with _CRAWL_LOCK:
|
|
298
|
+
if _CRAWLS.get(crawl_id, {}).get("stop_requested") is True:
|
|
299
|
+
# 线程还没跑就被叫停了(crawl_stop 在 spider 登记之前到):一页都不抓。
|
|
300
|
+
return
|
|
228
301
|
try:
|
|
229
302
|
spider.start()
|
|
230
303
|
except Exception as error: # noqa: BLE001
|
|
@@ -232,19 +305,36 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
232
305
|
_emit_event("crawlError", crawlId=crawl_id, text=str(error))
|
|
233
306
|
|
|
234
307
|
thread = threading.Thread(target=worker, daemon=True, name=f"crawl-{crawl_id}")
|
|
235
|
-
|
|
308
|
+
with _CRAWL_LOCK:
|
|
309
|
+
# spider 也要登记:叫停时拿得到它,才调得动引擎的停机通道。
|
|
310
|
+
_CRAWLS[crawl_id]["spider"] = spider
|
|
311
|
+
_CRAWLS[crawl_id]["thread"] = thread
|
|
236
312
|
thread.start()
|
|
237
313
|
_emit_event("crawlStarted", crawlId=crawl_id, text=f"crawling {url} (max {max_pages} pages)")
|
|
238
314
|
return {"crawlId": crawl_id}
|
|
239
315
|
|
|
240
316
|
|
|
317
|
+
def _is_running(entry: dict[str, Any]) -> bool:
|
|
318
|
+
"""这个登记条目算不算「正在跑」。
|
|
319
|
+
|
|
320
|
+
``thread`` 为 ``None`` 表示 spider 还在构造中:它已经占了并发名额,所以算在跑。
|
|
321
|
+
|
|
322
|
+
:param entry: 登记条目
|
|
323
|
+
:returns: 是否占用名额
|
|
324
|
+
"""
|
|
325
|
+
thread = entry.get("thread")
|
|
326
|
+
return thread is None or thread.is_alive()
|
|
327
|
+
|
|
328
|
+
|
|
241
329
|
def _evict_finished_crawls() -> None:
|
|
242
330
|
"""把已结束且超出留存量上限的爬虫条目从登记表里淘汰。
|
|
243
331
|
|
|
244
332
|
爬虫跑在 daemon 线程里,没法优雅中断;但**跑完的**条目只是一份没人再读的历史,
|
|
245
|
-
|
|
333
|
+
留久了就是纯内存占用。按插入顺序从最旧的开始丢。构造中的条目不算已结束。
|
|
334
|
+
|
|
335
|
+
:func:`_evict_finished_crawls` 只在 :func:`crawl_run` 持锁时被调用。
|
|
246
336
|
"""
|
|
247
|
-
finished = [key for key, entry in _CRAWLS.items() if not entry
|
|
337
|
+
finished = [key for key, entry in _CRAWLS.items() if not _is_running(entry)]
|
|
248
338
|
overflow = len(_CRAWLS) - MAX_REMEMBERED_CRAWLS
|
|
249
339
|
for key in finished[: max(0, overflow)]:
|
|
250
340
|
del _CRAWLS[key]
|
|
@@ -271,19 +361,59 @@ def crawl_status(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
271
361
|
"""查一个爬虫的状态与已收结果。
|
|
272
362
|
|
|
273
363
|
:param args: 协议参数
|
|
274
|
-
:returns: {crawlId, running, pages, error}
|
|
364
|
+
:returns: {crawlId, running, pages, error, expired}
|
|
275
365
|
"""
|
|
276
366
|
entry = _get_crawl(args.get("crawlId"))
|
|
277
|
-
thread: threading.Thread = entry["thread"]
|
|
278
367
|
state: dict[str, Any] = entry["state"]
|
|
368
|
+
# pages 是 spider 线程边跑边 append 的活列表,而回包要经 json.dumps 序列化。
|
|
369
|
+
# 进锁里复制一份:一边序列化一边追加,结果要么漏一页要么撞上 RuntimeError。
|
|
370
|
+
with _CRAWL_LOCK:
|
|
371
|
+
pages = list(state["pages"])
|
|
372
|
+
running = _is_running(entry)
|
|
279
373
|
return {
|
|
280
374
|
"crawlId": entry["crawl_id"],
|
|
281
|
-
|
|
282
|
-
"
|
|
375
|
+
# thread 为 None 表示 spider 还在构造中:没跑起来,但也没结束。
|
|
376
|
+
"running": running,
|
|
377
|
+
"pages": pages,
|
|
283
378
|
"error": state["error"],
|
|
379
|
+
# 截止到点而停的爬虫带这个标记:模型能看出「为什么比 maxPages 少」。
|
|
380
|
+
"expired": state.get("expired") is True,
|
|
284
381
|
}
|
|
285
382
|
|
|
286
383
|
|
|
384
|
+
def crawl_stop(args: dict[str, Any]) -> dict[str, Any]:
|
|
385
|
+
"""叫停一个爬虫。
|
|
386
|
+
|
|
387
|
+
为什么必须有这条:宿主的作业取消只活在 Node 侧,Python 里的 Spider 跑在自己的
|
|
388
|
+
线程上,看不见它。少了这一条,「作业显示已杀」之后爬虫还在后台跑,Python 进程也
|
|
389
|
+
一直被一个没人管的蜘蛛占着。三条路各管一段:已经在跑的由 ``Spider.pause()`` 立刻
|
|
390
|
+
收尾(引擎留给外部叫停的通道,等在途请求收尾后自己退出);还没开始跑的把截止提前到
|
|
391
|
+
现在,并在抓到第一页之前退出。
|
|
392
|
+
|
|
393
|
+
已经跑完的爬虫叫不停(引擎已拆),那不是错误:调用的意图是「别跑了」,已经停了。
|
|
394
|
+
|
|
395
|
+
:param args: 协议参数
|
|
396
|
+
:returns: {crawlId, stopping}
|
|
397
|
+
:raises adapters.AdapterError: id 缺失或不存在
|
|
398
|
+
"""
|
|
399
|
+
entry = _get_crawl(args.get("crawlId"))
|
|
400
|
+
state: dict[str, Any] = entry["state"]
|
|
401
|
+
# 截止提前到「现在」:构造中的蜘蛛、刚起线程还没抓到页的蜘蛛,都在收到第一页时停。
|
|
402
|
+
state["deadline"] = time.monotonic()
|
|
403
|
+
with _CRAWL_LOCK:
|
|
404
|
+
spider = entry.get("spider")
|
|
405
|
+
running = _is_running(entry)
|
|
406
|
+
if spider is None:
|
|
407
|
+
# 线程还没起:置个标志,worker 起手看见它就直接退出,一页都不抓。
|
|
408
|
+
entry["stop_requested"] = True
|
|
409
|
+
stopping = False
|
|
410
|
+
if spider is not None and running:
|
|
411
|
+
with suppress(RuntimeError):
|
|
412
|
+
spider.pause()
|
|
413
|
+
stopping = True
|
|
414
|
+
return {"crawlId": entry["crawl_id"], "stopping": stopping}
|
|
415
|
+
|
|
416
|
+
|
|
287
417
|
def close_all_crawls() -> None:
|
|
288
418
|
"""清掉爬虫登记表。
|
|
289
419
|
|
|
@@ -296,4 +426,5 @@ def close_all_crawls() -> None:
|
|
|
296
426
|
METHODS = {
|
|
297
427
|
"crawl.run": crawl_run,
|
|
298
428
|
"crawl.status": crawl_status,
|
|
429
|
+
"crawl.stop": crawl_stop,
|
|
299
430
|
}
|