@jayyuen66/dsh-scrapling 0.1.1 → 0.1.3

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 CHANGED
@@ -35,12 +35,28 @@
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
+ # newline="\n":协议帧以 LF 分帧,而 Windows 的文本模式会把 "\n" 翻成 "\r\n";宿主侧虽然
54
+ # 容忍行尾的 \r,但那是容忍,不该由协议来依赖。
55
+ for _stream in (sys.stdout, sys.stderr):
56
+ _reconfigure = getattr(_stream, "reconfigure", None)
57
+ if callable(_reconfigure):
58
+ _reconfigure(encoding="utf-8", errors="backslashreplace", newline="\n")
59
+
44
60
  MIN_PYTHON = (3, 14)
45
61
 
46
62
 
@@ -66,7 +82,10 @@ if _gate_message is not None:
66
82
 
67
83
 
68
84
  # 让 py/ 目录里的 guard 能被 adapters 用 `from guard import install` 找到。
69
- _HERE = __file__.rsplit("/", 1)[0] or "."
85
+ # 必须走 os.path:宿主传进来的 bridgePath 是 path.join(import.meta.dirname, "py", "bridge.py")
86
+ # 的产物,Windows 上是反斜杠分隔,按 "/" 切会得到整个文件路径,于是 adapters/guard 全都
87
+ # import 不到、ready 握手永远等不到。`-I` 又关掉了脚本目录自动进 sys.path,所以这一步不能省。
88
+ _HERE = os.path.dirname(os.path.abspath(__file__))
70
89
  if _HERE not in sys.path:
71
90
  sys.path.insert(0, _HERE)
72
91
 
@@ -118,15 +137,19 @@ def ok(request_id: Any, result: Any) -> dict[str, Any]:
118
137
  return {"id": request_id, "ok": True, "result": result}
119
138
 
120
139
 
121
- def fail(request_id: Any, code: str, message: str) -> dict[str, Any]:
140
+ def fail(request_id: Any, code: str, message: str, details: dict[str, Any] | None = None) -> dict[str, Any]:
122
141
  """构造失败响应帧。
123
142
 
124
143
  :param request_id - 原样回传请求的 id
125
144
  :param code - 机器可读错误码
126
145
  :param message - 人读信息
146
+ :param details - 可选的机器可读细节(例如动作失败的下标)
127
147
  :returns: 响应帧
128
148
  """
129
- return {"id": request_id, "ok": False, "error": {"code": code, "message": message}}
149
+ error: dict[str, Any] = {"code": code, "message": message}
150
+ if details:
151
+ error["details"] = details
152
+ return {"id": request_id, "ok": False, "error": error}
130
153
 
131
154
 
132
155
  def handle(frame: dict[str, Any]) -> dict[str, Any]:
@@ -155,7 +178,7 @@ def handle(frame: dict[str, Any]) -> dict[str, Any]:
155
178
  try:
156
179
  return ok(request_id, handler(params))
157
180
  except adapters.AdapterError as error:
158
- return fail(request_id, error.code, str(error))
181
+ return fail(request_id, error.code, str(error), error.details)
159
182
  except ModuleNotFoundError as error:
160
183
  # 缺的是可选依赖,不是抓取失败。落到下面的 FETCH_FAILED 会把它说成「请求出错」,
161
184
  # 而模型与用户对这两种情况的正确反应完全不同:前者该退避重试,后者该去装包。
@@ -238,6 +261,21 @@ def _ensure_worker(count: int) -> None:
238
261
  worker.start()
239
262
 
240
263
 
264
+ def _shutdown_crawls() -> None:
265
+ """退出前叫停全部爬虫,并给它们的线程一点收尾时间。
266
+
267
+ 蜘蛛跑在自己的线程里:进程退出它们才退,中间还能往 stdout 推事件帧 —— 那时宿主已经
268
+ 不读这一路了,帧落进管道就是没人认领的字节。所以爬虫要在会话之前关:蜘蛛自己也要用
269
+ 浏览器,先把会话抽走只会让它在下一次请求里抛。
270
+ """
271
+ try:
272
+ import crawl
273
+
274
+ crawl.close_all_crawls()
275
+ except Exception as error: # noqa: BLE001 —— 关不掉也不能拖住关机
276
+ log(f"failed to stop crawls: {type(error).__name__}: {error}")
277
+
278
+
241
279
  def _shutdown_sessions() -> None:
242
280
  """退出前关掉全部会话。
243
281
 
@@ -323,6 +361,7 @@ def read_loop() -> int:
323
361
  _drain_before_exit()
324
362
  # 与 EOF 路径同一套收尾:浏览器会话是独立进程,不显式关掉就会活过 sidecar
325
363
  # 本身。宿主的优雅关闭走的就是这一帧(见 lib/sidecar.ts 的 dispose)。
364
+ _shutdown_crawls()
326
365
  _shutdown_sessions()
327
366
  return 0
328
367
  # 顺序要紧:先入队再起 worker。反过来的话,新起的线程可能立刻醒来、
@@ -347,6 +386,7 @@ def read_loop() -> int:
347
386
  _ensure_worker(min(depth, MAX_INFLIGHT))
348
387
  log("stdin closed")
349
388
  _drain_before_exit()
389
+ _shutdown_crawls()
350
390
  _shutdown_sessions()
351
391
  return 0
352
392