@jayyuen66/dsh-scrapling 0.0.0-stage → 0.0.1-rc.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/py/bridge.py ADDED
@@ -0,0 +1,327 @@
1
+ """py/bridge.py —— 常驻 Python 进程的入口:JSON-lines 请求/响应服务。
2
+
3
+ 为什么是常驻进程而不是每次拉起:Scrapling 最有价值的三块能力(浏览器会话、adaptive
4
+ 选择器的 SQLite 指纹库、Spider 的断点)全都跨请求有状态。每次新进程会把 cookie、
5
+ 指纹库和浏览器实例全部丢掉,等于只用了 Scrapling 的静态部分。
6
+
7
+ 协议(Host -> Python,每行一个 JSON 对象)::
8
+
9
+ {"id": "7", "method": "fetch", "params": {...}}
10
+
11
+ 响应(Python -> Host,同样一行一个)::
12
+
13
+ {"id": "7", "ok": true, "result": {...}}
14
+ {"id": "7", "ok": false, "error": {"code": "BAD_ARGS", "message": "..."}}
15
+
16
+ 启动时先主动发一条**没有 id** 的事件帧,Host 侧据此做能力协商::
17
+
18
+ {"event": "ready", "protocol": 1, "capabilities": {...}}
19
+
20
+ 四条硬约束,写错了会静默坏掉:
21
+
22
+ 1. **stdout 只能是协议帧。** 任何 ``print`` 或第三方库的进度输出都会把 JSON-lines
23
+ 流打坏,所以本文件与 adapters 的一切日志都走 stderr。
24
+ 2. **一行一帧且不能交错。** 并发请求各自回帧时要串行化,否则两个响应会被拼在同一行。
25
+ 3. **读 stdin 要按字节自行切行。** 直接用 ``sys.stdin.readline()`` 在管道上会因预读
26
+ 把两行一起吞掉,导致第二帧永远读不到。
27
+ 4. **worker 数与并发上限一致。** 浏览器抓取很吃内存(每个 Chromium 实例数百 MB),
28
+ 无上限会让几个并行的工具调用把机器拖垮。
29
+
30
+ 用法(``-u`` 关缓冲、``-I`` 隔离,避免用户 site-packages 里的同名模块把 scrapling 顶掉)::
31
+
32
+ python -u -I bridge.py
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import json
38
+ import sys
39
+ import threading
40
+ import time
41
+ import traceback
42
+ from typing import Any, Callable
43
+
44
+ # 让 py/ 目录里的 guard 能被 adapters 用 `from guard import install` 找到。
45
+ _HERE = __file__.rsplit("/", 1)[0] or "."
46
+ if _HERE not in sys.path:
47
+ sys.path.insert(0, _HERE)
48
+
49
+ PROTOCOL_VERSION = 1
50
+
51
+ # 并发上限:与工作线程数一致,多了也只是排队。
52
+ MAX_INFLIGHT = 4
53
+
54
+ # 单帧字节上限。readline() 拿到的是整行,超大的行在 json.loads 之前就该判掉 —— 解析本身
55
+ # 就要把这行再展开一份。宿主侧对每个工具的输出另有封顶,这条防的是「入参本身很大」。
56
+ MAX_FRAME_BYTES = 8 * 1024 * 1024
57
+
58
+ # 待处理队列的深度上限。队列只在 worker 全部占满时增长,而 worker 数是 MAX_INFLIGHT,
59
+ # 所以正常情况下的深度约等于 MAX_INFLIGHT;超过它说明调用方在以远超并发的速率灌帧,
60
+ # 继续收就是纯粹的内存增长。判否让调用方自己退避。
61
+ MAX_QUEUE_DEPTH = MAX_INFLIGHT * 4
62
+
63
+ _WRITE_LOCK = threading.Lock()
64
+ _SLOTS = threading.Semaphore(MAX_INFLIGHT)
65
+ _QUEUE: list[dict[str, Any]] = []
66
+ _QUEUE_LOCK = threading.Lock()
67
+ _WORKERS_LOCK = threading.Lock()
68
+ _WORKERS: list[threading.Thread] = []
69
+
70
+
71
+ def log(message: str) -> None:
72
+ """写日志到 stderr。stdout 留给协议帧。"""
73
+ print(f"[bridge] {message}", file=sys.stderr, flush=True)
74
+
75
+
76
+ def emit(frame: dict[str, Any]) -> None:
77
+ """写一帧到 stdout 并立刻冲刷。
78
+
79
+ 冲刷是必须的:Host 侧按行阻塞读取,不冲的话响应会卡在缓冲区里直到进程退出。
80
+ """
81
+ line = json.dumps(frame, ensure_ascii=False, separators=(",", ":"))
82
+ with _WRITE_LOCK:
83
+ sys.stdout.write(line + "\n")
84
+ sys.stdout.flush()
85
+
86
+
87
+ def ok(request_id: Any, result: Any) -> dict[str, Any]:
88
+ """构造成功响应帧。
89
+
90
+ :param request_id - 原样回传请求的 id
91
+ :param result - 业务结果
92
+ :returns: 响应帧
93
+ """
94
+ return {"id": request_id, "ok": True, "result": result}
95
+
96
+
97
+ def fail(request_id: Any, code: str, message: str) -> dict[str, Any]:
98
+ """构造失败响应帧。
99
+
100
+ :param request_id - 原样回传请求的 id
101
+ :param code - 机器可读错误码
102
+ :param message - 人读信息
103
+ :returns: 响应帧
104
+ """
105
+ return {"id": request_id, "ok": False, "error": {"code": code, "message": message}}
106
+
107
+
108
+ def handle(frame: dict[str, Any]) -> dict[str, Any]:
109
+ """分发一个请求帧。
110
+
111
+ :param frame - 已解析的请求帧
112
+ :returns: 响应帧
113
+ """
114
+ import adapters
115
+
116
+ request_id = frame.get("id")
117
+ method = frame.get("method")
118
+ params = frame.get("params")
119
+ if params is None:
120
+ params = {}
121
+ if not isinstance(params, dict):
122
+ return fail(request_id, "BAD_ARGS", "params must be an object")
123
+ if not isinstance(method, str):
124
+ return fail(request_id, "BAD_ARGS", "method must be a string")
125
+
126
+ handler: Callable[[dict[str, Any]], Any] | None = adapters.METHODS.get(method)
127
+ if handler is None:
128
+ return fail(request_id, "UNKNOWN_METHOD", f"unknown method: {method}")
129
+
130
+ with _SLOTS:
131
+ try:
132
+ return ok(request_id, handler(params))
133
+ except adapters.AdapterError as error:
134
+ return fail(request_id, error.code, str(error))
135
+ except ModuleNotFoundError as error:
136
+ # 缺的是可选依赖,不是抓取失败。落到下面的 FETCH_FAILED 会把它说成「请求出错」,
137
+ # 而模型与用户对这两种情况的正确反应完全不同:前者该退避重试,后者该去装包。
138
+ # 报错必须指向后者,所以单列一个码,并把本插件的硬性安装命令直接写进去——
139
+ # Scrapling 自己只说「装 markdownify」,而本插件要的是整个 extra。
140
+ missing = error.name or "某个可选依赖"
141
+ log(f"{method} aborted: missing dependency {missing}")
142
+ return fail(
143
+ request_id,
144
+ "DEPENDENCY_MISSING",
145
+ f"缺少可选依赖 {missing},这次调用无法执行。本插件的默认 extractionType 是 "
146
+ f'markdown,需要 scrapling 的 rag extra:pip install "scrapling[rag]>=0.4.15,<0.5"',
147
+ )
148
+ except Exception as error: # noqa: BLE001 —— 任何异常都要变成一帧错误,不能让线程死掉
149
+ log(f"{method} failed: {type(error).__name__}: {error}")
150
+ log(traceback.format_exc())
151
+ return fail(request_id, "FETCH_FAILED", f"{type(error).__name__}: {error}")
152
+
153
+
154
+ def _drain() -> dict[str, Any] | None:
155
+ """取一帧待处理请求;队列空给 None。"""
156
+ with _QUEUE_LOCK:
157
+ return _QUEUE.pop(0) if _QUEUE else None
158
+
159
+
160
+ def _worker() -> None:
161
+ """工作线程:取帧、处理、回帧。空闲时退出,由 ``_ensure_worker`` 按需再拉起。
162
+
163
+ 空闲退出而不是常驻,是为了让「跑过的 worker」不被记成活线程 —— 否则线程计数会
164
+ 只增不减,最后再多的请求也没有 worker 处理。
165
+ """
166
+ try:
167
+ while True:
168
+ frame = _drain()
169
+ if frame is None:
170
+ # 短暂等一下再退出:入队与起线程之间总有一个时间差,
171
+ # 立刻退出等于把这个窗口留给运气。
172
+ time.sleep(0.05)
173
+ frame = _drain()
174
+ if frame is None:
175
+ return
176
+ try:
177
+ emit(handle(frame))
178
+ except Exception as error: # noqa: BLE001 —— 连序列化失败都不能让线程死掉
179
+ log(f"emit failed: {type(error).__name__}: {error}")
180
+ finally:
181
+ with _WORKERS_LOCK:
182
+ current = threading.current_thread()
183
+ if current in _WORKERS:
184
+ _WORKERS.remove(current)
185
+
186
+
187
+ def _ensure_worker(count: int) -> None:
188
+ """保证活着的工作线程数达到 count。
189
+
190
+ 刻意**不用** ``threading.active_count()``:那是全局线程数,会把 Playwright、
191
+ patchright 留下的后台线程一起算进来,于是本包自己的 worker 永远算不满,一个请求
192
+ 都不会被处理。这里只数本包自己拉起来的线程。
193
+
194
+ :param count: 期望的存活线程数,上限 MAX_INFLIGHT
195
+ """
196
+ wanted = max(1, min(count, MAX_INFLIGHT))
197
+ while True:
198
+ with _WORKERS_LOCK:
199
+ _WORKERS[:] = [item for item in _WORKERS if item.is_alive()]
200
+ if len(_WORKERS) >= wanted:
201
+ return
202
+ worker = threading.Thread(target=_worker, daemon=True, name="bridge-worker")
203
+ _WORKERS.append(worker)
204
+ worker.start()
205
+
206
+
207
+ def _shutdown_sessions() -> None:
208
+ """退出前关掉全部会话。
209
+
210
+ 浏览器会话是独立进程:sidecar 自己退了、Chromium 还活着,就成了没人管的孤儿。
211
+ """
212
+ import adapters
213
+
214
+ try:
215
+ adapters.close_all_sessions()
216
+ except Exception as error: # noqa: BLE001 —— 关不掉也不能拖住关机
217
+ log(f"failed to close sessions: {type(error).__name__}: {error}")
218
+
219
+
220
+ def _drain_before_exit(timeout: float = 5.0) -> None:
221
+ """关机前给在途请求一个把话说完的机会。
222
+
223
+ 收到 shutdown 就直接 return 的话,队列里已排队的请求会被静默丢掉 —— Host 侧看到的
224
+ 是「没等到响应」而不是「被关机打断」。所以这里有界地等一下:等空了就走,等不到就
225
+ 记一行日志再走,不无限期拖住关机。
226
+
227
+ :param timeout - 最长等待秒数
228
+ """
229
+ deadline = time.monotonic() + timeout
230
+ while time.monotonic() < deadline:
231
+ with _QUEUE_LOCK:
232
+ pending = bool(_QUEUE)
233
+ with _WORKERS_LOCK:
234
+ busy = any(item.is_alive() for item in _WORKERS)
235
+ if not pending and not busy:
236
+ return
237
+ time.sleep(0.02)
238
+ log("shutdown: giving up on in-flight requests")
239
+
240
+
241
+ def read_loop() -> int:
242
+ """按字节读 stdin 并切成一帧一帧,直到 EOF 或收到 shutdown。
243
+
244
+ :returns: 进程退出码
245
+ """
246
+ import adapters
247
+ from guard import configure_from_env
248
+
249
+ configure_from_env()
250
+
251
+ try:
252
+ emit(
253
+ {
254
+ "event": "ready",
255
+ "protocol": PROTOCOL_VERSION,
256
+ "capabilities": adapters.capabilities(),
257
+ }
258
+ )
259
+ except Exception as error: # noqa: BLE001
260
+ log(f"failed to report readiness: {type(error).__name__}: {error}")
261
+
262
+ # 必须用 readline(),不能用 read(65536)。
263
+ # BufferedReader.read(n) 的语义是「读满 n 字节或遇到 EOF」:宿主只要保持管道开着
264
+ # (而常驻进程本来就该一直开着),它就会一直等下去,第一个请求永远进不来。
265
+ # 实测踩过:批量发完立刻 close stdin 的探针能过,逐帧交互的客户端会挂死。
266
+ # readline() 逐行返回、读到换行就走,既不会被预读吞掉下一帧,也不会空等。
267
+ for raw in iter(sys.stdin.buffer.readline, b""):
268
+ if not raw.strip():
269
+ continue
270
+ if len(raw) > MAX_FRAME_BYTES:
271
+ emit(
272
+ fail(
273
+ None,
274
+ "BAD_FRAME",
275
+ f"frame of {len(raw)} bytes exceeds the {MAX_FRAME_BYTES} byte limit",
276
+ )
277
+ )
278
+ continue
279
+ try:
280
+ frame = json.loads(raw.decode("utf-8"))
281
+ except (UnicodeDecodeError, json.JSONDecodeError) as error:
282
+ emit(fail(None, "BAD_FRAME", f"unparsable frame: {error}"))
283
+ continue
284
+ if not isinstance(frame, dict):
285
+ emit(fail(None, "BAD_FRAME", "frame must be an object"))
286
+ continue
287
+ if frame.get("method") == "shutdown":
288
+ emit(ok(frame.get("id"), {"stopping": True}))
289
+ _drain_before_exit()
290
+ return 0
291
+ # 顺序要紧:先入队再起 worker。反过来的话,新起的线程可能立刻醒来、
292
+ # 看到空队列就退出,这一帧就永远没人处理 —— 且只在时序凑巧时才会复现。
293
+ with _QUEUE_LOCK:
294
+ depth = len(_QUEUE)
295
+ if depth >= MAX_QUEUE_DEPTH:
296
+ emit(
297
+ fail(
298
+ frame.get("id"),
299
+ "BUSY",
300
+ f"{depth} requests already queued (limit {MAX_QUEUE_DEPTH})",
301
+ )
302
+ )
303
+ continue
304
+ _QUEUE.append(frame)
305
+ depth += 1
306
+ _ensure_worker(min(depth, MAX_INFLIGHT))
307
+ log("stdin closed")
308
+ _drain_before_exit()
309
+ _shutdown_sessions()
310
+ return 0
311
+
312
+
313
+ def main() -> int:
314
+ """进程入口。
315
+
316
+ :returns: 退出码
317
+ """
318
+ log(f"protocol {PROTOCOL_VERSION} ready; python {sys.version.split()[0]}")
319
+ try:
320
+ return read_loop()
321
+ except KeyboardInterrupt: # pragma: no cover —— 只有手动 Ctrl+C 才会走到
322
+ log("interrupted")
323
+ return 130
324
+
325
+
326
+ if __name__ == "__main__":
327
+ sys.exit(main())
package/py/crawl.py ADDED
@@ -0,0 +1,284 @@
1
+ """py/crawl.py —— 爬虫:用 Scrapling 自带的 Spider 框架在后台跑一个站点。
2
+
3
+ 为什么用 Spider 而不是自己写循环:Scrapling 已经实现了并发、限速(AutoThrottle)、
4
+ robots.txt 遵守、断点续爬、链接提取与去重 —— 这些我们不想重写一遍。
5
+
6
+ 为什么放到后台:一次爬取是分钟级的,而一次请求-响应撑不了那么久。所以这里**起一个
7
+ daemon 线程**跑 spider,主线程立刻返回 crawl id;进度通过「没有 id 的事件帧」推给宿主,
8
+ 宿主把它接到后台作业的输出环上,模型就能边跑边看,而不是干等一个超时。
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import threading
14
+ import uuid
15
+ from typing import Any
16
+ from urllib.parse import urlparse
17
+
18
+ from guard import proxies_for, url_allowed
19
+
20
+ # 正在跑的爬虫:crawl id -> {"thread": Thread, "crawl_id": str, "state": dict}
21
+ _CRAWLS: dict[str, dict[str, Any]] = {}
22
+
23
+ # 同时能跑几个爬虫。爬虫是重量级后台任务且**立刻返回**,因此 bridge 的并发槽位对它无效
24
+ # —— 不设上限的话连续几次 crawl.run 就会叠起多个 Spider 线程与 FetcherSession。
25
+ MAX_CONCURRENT_CRAWLS = 2
26
+
27
+ # 登记表最多留几个已结束的爬虫条目。crawl.status 是唯一能读走结果的入口,所以条目不能一
28
+ # 结束就删;但全留着就是内存泄漏,所以留一个上限,按最旧的淘汰。
29
+ MAX_REMEMBERED_CRAWLS = 16
30
+
31
+
32
+ def _clip_markdown(text: str, budget: int) -> str:
33
+ """把单页正文封顶到 budget 字符。
34
+
35
+ ``max_pages`` 限的是**页数**,页内正文长度是另一根轴。一页几 MB 的 HTML 会一路留在
36
+ state 里,而 crawl.status 每次轮询都把它整份序列化回去。
37
+
38
+ :param text: 原始正文
39
+ :param budget: 字符上限
40
+ :returns: 封顶后的正文;被截断时带上省略说明
41
+ """
42
+ if budget > 0 and len(text) > budget:
43
+ return text[:budget] + f"\n\n[truncated at {budget} chars]"
44
+ return text
45
+
46
+
47
+ def _emit_event(event: str, **fields: Any) -> None:
48
+ """往 stdout 推一条没有 id 的事件帧。
49
+
50
+ stdout 是与宿主的协议通道;事件帧与响应帧走同一条流,靠有没有 ``event`` 字段区分。
51
+ 桥接层晚于本模块导入,所以这里在函数体内 import,避免循环依赖。
52
+
53
+ :param event: 事件名
54
+ :param fields: 事件字段
55
+ """
56
+ import bridge
57
+
58
+ bridge.emit({"event": event, **fields})
59
+
60
+
61
+ def _allowed_domains(url: str) -> set[str]:
62
+ """从起始 URL 推出允许的域名集合,避免爬虫爬去站外。
63
+
64
+ :param url: 起始 URL
65
+ :returns: 域名集合;解析不出主机名时给空集
66
+ """
67
+ # 用 netloc(host:port)而不是 hostname:本地/自建站点几乎都带非默认端口,
68
+ # 只给 hostname 会让「同主机不同端口」的链接被判成站外而丢掉 —— 于是只爬到第一页就停。
69
+ # 主机名与 host:port 都放进去:Scrapling 的域过滤可能按 hostname 比,也可能按
70
+ # netloc 比。少放一个的表现是「只爬到第一页就停」,不报错,很难一眼看出原因。
71
+ parsed = urlparse(url)
72
+ domains = {value for value in (parsed.hostname, parsed.netloc) if value}
73
+ return domains
74
+
75
+
76
+ def _make_spider(url: str, limit: int, crawl_id: str, state: dict[str, Any]) -> Any:
77
+ """动态造一个 spider 类。
78
+
79
+ Spider 的 ``start_urls`` / ``allowed_domains`` / ``max_pages`` / ``output_dir``
80
+ 都是**类属性**而不是 ``__init__`` 参数 —— ``Spider.__init__`` 只收 crawldir 与
81
+ interval,当构造参数传会直接 TypeError。所以只能在类体上写。
82
+
83
+ :param url: 起始 URL
84
+ :param limit: 最多爬多少页
85
+ :param crawl_id: 爬虫 id,用于日志
86
+ :param state: 结果槽;爬完写进它
87
+ :returns: spider 实例
88
+ """
89
+ from scrapling.spiders import SiteToMarkdownSpider
90
+
91
+ class Collector(SiteToMarkdownSpider): # type: ignore[misc, valid-type]
92
+ """把页面攒进 state 并向上报进度,不落盘。"""
93
+
94
+ name = f"scrapling-{crawl_id}"
95
+ start_urls = [url]
96
+ allowed_domains = _allowed_domains(url)
97
+ max_pages = limit
98
+ output_dir = None
99
+
100
+ def configure_sessions(self, manager: Any) -> None:
101
+ """把爬虫的会话换成「只跟安全重定向、走配置里那份代理」的那一份。
102
+
103
+ Spider 默认加的是裸 ``FetcherSession()``,重定向按 curl_cffi 的默认走 —— 跳向私网
104
+ 不会被拦。Host 闸门只判起点 URL,重定向目标是它看不到的,所以这里必须自己兜住:
105
+ ``follow_redirects="safe"`` 让 curl_cffi 拒绝跳向私网的跳转。
106
+
107
+ 代理按起点 URL 定档(``allowed_domains`` 已经把爬虫锁在起点所在的域里,所以
108
+ 整场爬只有一个出口该选)。``proxies`` 为 None 表示用户没配任何代理相关设置,
109
+ 那就不传这个词,让 curl_cffi 照旧读环境 —— 与本包不介入时一致。
110
+
111
+ :param manager: SessionManager
112
+ """
113
+ from scrapling.fetchers import FetcherSession
114
+
115
+ session_kwargs: dict[str, Any] = {"follow_redirects": "safe"}
116
+ proxies = proxies_for(url)
117
+ if proxies is not None:
118
+ session_kwargs["proxies"] = proxies
119
+ manager.add("default", FetcherSession(**session_kwargs))
120
+
121
+ async def on_scraped_item(self, item: dict[str, Any]) -> dict[str, Any] | None:
122
+ """收一页并报进度。
123
+
124
+ 返回 None 表示「不要把这条当成要写出的结果」—— 我们已经把结果收进
125
+ state 了,再让 spider 落一次盘是白费 IO。
126
+
127
+ **必须是 async**:基类是 async 方法,引擎会 await 它。写成同步方法的话
128
+ `await None` 抛 TypeError,会把 parse() 这个生成器**在 yield 出后续链接请求
129
+ 之前**打断 —— 表现是「只爬到第一页就停」,而且不报任何错。
130
+
131
+ :param item: spider 交来的页面
132
+ :returns: 恒为 None
133
+ """
134
+ pages: list[dict[str, Any]] = state["pages"]
135
+ if len(pages) >= limit:
136
+ return None
137
+ page_url = str(item.get("url", ""))
138
+ # 收页前的最后一道:即使 safe 重定向放行了,这一页的最终 URL 仍可能落在私网上。
139
+ # 判否就不收 —— 内容已经在对端取过了,但至少不把它写进 state 流回模型上下文。
140
+ allowed, reason = url_allowed(page_url)
141
+ if not allowed:
142
+ _emit_event(
143
+ "crawlSkipped",
144
+ crawlId=crawl_id,
145
+ url=page_url,
146
+ text=f"skipped {page_url}: {reason}",
147
+ )
148
+ return None
149
+ pages.append(
150
+ {
151
+ "url": page_url,
152
+ "title": str(item.get("title", "")),
153
+ "markdown": _clip_markdown(
154
+ str(item.get("markdown", "")), state["max_content_chars"]
155
+ ),
156
+ }
157
+ )
158
+ _emit_event(
159
+ "progress",
160
+ crawlId=crawl_id,
161
+ done=len(pages),
162
+ limit=limit,
163
+ text=f"{len(pages)}/{limit} {page_url}",
164
+ )
165
+ return None
166
+
167
+ return Collector()
168
+
169
+
170
+ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
171
+ """起一个后台爬虫,立刻返回 crawl id。
172
+
173
+ :param args: 协议参数
174
+ :returns: {crawlId}
175
+ :raises adapters.AdapterError: 参数非法、起点 URL 不安全或并发已满
176
+ """
177
+ from adapters import (
178
+ DEFAULT_MAX_CONTENT_CHARS,
179
+ AdapterError,
180
+ _positive_int,
181
+ _url,
182
+ )
183
+
184
+ url = _url(args)
185
+ max_pages = _positive_int(args.get("maxPages"), "maxPages", 20)
186
+ max_content_chars = _positive_int(
187
+ args.get("maxContentChars"), "maxContentChars", DEFAULT_MAX_CONTENT_CHARS
188
+ )
189
+ crawl_id = uuid.uuid4().hex[:12]
190
+
191
+ # Host 闸门判的是这条 URL,但协议层不该假设调用方一定判过:这道复核与浏览器路径上
192
+ # 的 guard.url_allowed 是同一个实现,因此两侧同解。
193
+ allowed, reason = url_allowed(url)
194
+ if not allowed:
195
+ raise AdapterError("URL_BLOCKED", f"{url}: {reason}")
196
+
197
+ _evict_finished_crawls()
198
+ running = [entry for entry in _CRAWLS.values() if entry["thread"].is_alive()]
199
+ if len(running) >= MAX_CONCURRENT_CRAWLS:
200
+ raise AdapterError(
201
+ "CRAWL_BUSY",
202
+ f"already {len(running)} crawls running; the limit is {MAX_CONCURRENT_CRAWLS}",
203
+ )
204
+
205
+ state: dict[str, Any] = {"error": None, "pages": [], "max_content_chars": max_content_chars}
206
+ try:
207
+ spider = _make_spider(url, max_pages, crawl_id, state)
208
+ except Exception as error: # noqa: BLE001
209
+ raise AdapterError("CRAWL_SETUP_FAILED", f"{type(error).__name__}: {error}") from error
210
+
211
+ def worker() -> None:
212
+ """后台线程体:跑爬虫并把异常收进 state,不让它悄悄消失。"""
213
+ try:
214
+ spider.start()
215
+ except Exception as error: # noqa: BLE001
216
+ state["error"] = f"{type(error).__name__}: {error}"
217
+ _emit_event("crawlError", crawlId=crawl_id, text=str(error))
218
+
219
+ thread = threading.Thread(target=worker, daemon=True, name=f"crawl-{crawl_id}")
220
+ _CRAWLS[crawl_id] = {"thread": thread, "crawl_id": crawl_id, "state": state}
221
+ thread.start()
222
+ _emit_event("crawlStarted", crawlId=crawl_id, text=f"crawling {url} (max {max_pages} pages)")
223
+ return {"crawlId": crawl_id}
224
+
225
+
226
+ def _evict_finished_crawls() -> None:
227
+ """把已结束且超出留存量上限的爬虫条目从登记表里淘汰。
228
+
229
+ 爬虫跑在 daemon 线程里,没法优雅中断;但**跑完的**条目只是一份没人再读的历史,
230
+ 留久了就是纯内存占用。按插入顺序从最旧的开始丢。
231
+ """
232
+ finished = [key for key, entry in _CRAWLS.items() if not entry["thread"].is_alive()]
233
+ overflow = len(_CRAWLS) - MAX_REMEMBERED_CRAWLS
234
+ for key in finished[: max(0, overflow)]:
235
+ del _CRAWLS[key]
236
+
237
+
238
+ def _get_crawl(crawl_id: Any) -> dict[str, Any]:
239
+ """按 id 取爬虫登记条目。
240
+
241
+ :param crawl_id: 爬虫 id
242
+ :returns: 登记条目
243
+ :raises adapters.AdapterError: id 缺失或不存在
244
+ """
245
+ from adapters import AdapterError
246
+
247
+ if not isinstance(crawl_id, str) or not crawl_id:
248
+ raise AdapterError("BAD_ARGS", "crawlId is required")
249
+ entry = _CRAWLS.get(crawl_id)
250
+ if entry is None:
251
+ raise AdapterError("NO_SUCH_CRAWL", f"no such crawl: {crawl_id}")
252
+ return entry
253
+
254
+
255
+ def crawl_status(args: dict[str, Any]) -> dict[str, Any]:
256
+ """查一个爬虫的状态与已收结果。
257
+
258
+ :param args: 协议参数
259
+ :returns: {crawlId, running, pages, error}
260
+ """
261
+ entry = _get_crawl(args.get("crawlId"))
262
+ thread: threading.Thread = entry["thread"]
263
+ state: dict[str, Any] = entry["state"]
264
+ return {
265
+ "crawlId": entry["crawl_id"],
266
+ "running": thread.is_alive(),
267
+ "pages": state["pages"],
268
+ "error": state["error"],
269
+ }
270
+
271
+
272
+ def close_all_crawls() -> None:
273
+ """清掉爬虫登记表。
274
+
275
+ 爬虫跑在 daemon 线程里:sidecar 退出时它们跟着退出,所以这里只清登记,
276
+ 不需要(也没法)去优雅中断一个正在跑的 spider。
277
+ """
278
+ _CRAWLS.clear()
279
+
280
+
281
+ METHODS = {
282
+ "crawl.run": crawl_run,
283
+ "crawl.status": crawl_status,
284
+ }