@jayyuen66/dsh-scrapling 0.1.16 → 0.2.0

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/adapters.py CHANGED
@@ -22,6 +22,7 @@ from __future__ import annotations
22
22
  import codecs
23
23
  import concurrent.futures
24
24
  import contextlib
25
+ import contextvars
25
26
  import json
26
27
  import queue
27
28
  import re
@@ -31,11 +32,14 @@ import uuid
31
32
  from datetime import datetime, timezone
32
33
  from pathlib import Path
33
34
  from typing import Any, Callable, NamedTuple
35
+ from urllib.parse import urlparse
34
36
 
37
+ import document
35
38
  import extraction
36
39
  import guard
37
40
  import media
38
41
  import search
42
+ from cancellation import RequestCancelled, raise_if_cancelled
39
43
  from redact import redact_url_secrets
40
44
 
41
45
  # Scrapling 缺失时不要让整个 sidecar 起不来:桥接层会把它报成能力缺失,
@@ -52,10 +56,13 @@ DEFAULT_EXTRACTION = "markdown"
52
56
  DEFAULT_TIMEOUT_SECONDS = 120.0
53
57
  DEFAULT_TIMEOUT_MS = 30_000
54
58
  DEFAULT_MAX_CONTENT_CHARS = 200_000
55
- # 一次读网络历史最多回多少条、单条正文最多回多少字符。上游为每条响应体存下的是 1 MiB
56
- # 量级,而这份摘要是给模型看的 —— 两个预算都由本包定,不由上游存了多少决定。
59
+ # 一次读网络历史的条目数、单条正文与总正文三条上限。上游为每条响应体存下的是 1 MiB
60
+ # 量级,而这份摘要是给模型看的 —— 三条预算都由本包定,不由上游存了多少决定。
57
61
  DEFAULT_NETWORK_ENTRIES = 50
58
- DEFAULT_NETWORK_BODY_CHARS = 20_000
62
+ NETWORK_MAX_ENTRIES = 200
63
+ NETWORK_MAX_BODY_CHARS = 20_000
64
+ NETWORK_MAX_TOTAL_BODY_CHARS = 120_000
65
+ DEFAULT_NETWORK_BODY_CHARS = NETWORK_MAX_BODY_CHARS
59
66
  EXTRACTION_TYPES = ("markdown", "html", "text", "json")
60
67
  # adaptive 指纹库的文件名。**相对路径**:bridge 由宿主以部署侧的 dataDir 为工作目录拉起
61
68
  # (见 host.ts 的 sidecar env),相对路径正好把库落进 dataDir —— Scrapling 自己的默认值
@@ -160,25 +167,30 @@ def _safe_headers(headers: Any) -> dict[str, str]:
160
167
  return {str(key): str(value) for key, value in headers.items() if str(key).lower() not in _SENSITIVE_HEADERS}
161
168
 
162
169
 
163
- def _network_summary(
170
+ def _network_summary_with_count(
164
171
  network: Any, # 上游的 NetworkRecorder
165
172
  *,
166
173
  query: _NetworkQuery,
167
- ) -> list[dict[str, Any]]:
168
- """把会话网络历史压成给模型看的条目。
174
+ ) -> tuple[list[dict[str, Any]], int]:
175
+ """把会话网络历史压成给模型看的条目,并独立报告过滤后的记录数。
169
176
 
170
177
  只取 XHR/fetch 与 HTTP 错误(``include_static=False``):这条路径的用途是「页面数据来自
171
178
  接口而不是 DOM 时,找到那个接口」,静态资源只会把列表淹掉。
172
179
 
173
- 正文只在显式要求时回传,并按 ``max_body_chars`` 逐条截断 —— 上游为每条响应体设了
174
- 1 MiB、会话总量 20 MiB 的硬上限,那几十倍于模型预算的量级不该由「上游记了什么」决定
175
- 「模型看见什么」。没存下正文时上游会在 ``meta['body_note']`` 里写原因,一并带出去,
176
- 这样「这条接口没正文」与「这个接口本来就空」不是同一件事。
180
+ ``count`` 在 ``networkLimit`` 与逐条投影之前计算:上游 ``NetworkRecorder.search`` 的
181
+ ``limit=None`` 返回全部过滤结果,因此单条投影失败也不会把总数一起减掉。
182
+
183
+ 正文只在显式要求时回传,并按 ``max_body_chars`` 逐条截断;所有条目的正文字符总数另受
184
+ ``NETWORK_MAX_TOTAL_BODY_CHARS`` 约束。上游为每条响应体设了 1 MiB、会话总量 20 MiB 的
185
+ 硬上限,那几十倍于模型预算的量级不该由「上游记了什么」决定「模型看见什么」。没存下正文时
186
+ 上游会在 ``meta['body_note']`` 里写原因,一并带出去,这样「这条接口没正文」与「这个接口
187
+ 本来就空」不是同一件事。
177
188
 
178
189
  URL 里的凭据型查询参数在这一层就脱敏:这份摘要是给模型看的,而模型用不上一个
179
190
  access token 却会把整条 URL 原样复述出去。
180
191
  """
181
192
  summary: list[dict[str, Any]] = []
193
+ total_body_chars = 0
182
194
  try:
183
195
  if query.request_id is not None:
184
196
  record = network.get(query.request_id)
@@ -190,12 +202,13 @@ def _network_summary(
190
202
  resource_type=query.resource_type,
191
203
  status=query.status,
192
204
  after_id=query.after_id,
193
- limit=query.limit,
205
+ limit=None,
194
206
  include_static=query.include_static,
195
207
  )
196
208
  except Exception: # noqa: BLE001 —— 记录器未启用或上游改了口径:当成「没有历史」
197
- return summary
198
- for item in records:
209
+ return summary, 0
210
+ count = len(records)
211
+ for item in records[: query.limit]:
199
212
  try:
200
213
  meta = item.meta if isinstance(item.meta, dict) else {}
201
214
  body = item.body
@@ -205,7 +218,7 @@ def _network_summary(
205
218
  "status": item.status,
206
219
  "bytes": len(body) if body else 0,
207
220
  # 上游把方法记在 Response.method 上;从 meta / request_headers 读会退化成 GET,
208
- # POST 的 XHR 在摘要里一律显示成 GET(V5 已复现)。
221
+ # POST 的 XHR 在摘要里一律显示成 GET。
209
222
  "method": str(getattr(item, "method", "GET")),
210
223
  "resourceType": str(meta.get("resource_type") or ""),
211
224
  }
@@ -217,15 +230,30 @@ def _network_summary(
217
230
  entry["bodyNote"] = note
218
231
  elif query.include_body:
219
232
  text = body.decode("utf-8", "replace") if isinstance(body, bytes) else str(body)
220
- clipped, truncated = clip(text, query.body_chars)
221
- entry["body"] = clipped
222
- if truncated:
233
+ remaining = NETWORK_MAX_TOTAL_BODY_CHARS - total_body_chars
234
+ if remaining == 0:
235
+ entry["body"] = ""
223
236
  entry["bodyTruncated"] = True
237
+ else:
238
+ clipped, truncated = clip(text, min(query.body_chars, remaining))
239
+ entry["body"] = clipped
240
+ total_body_chars += len(clipped)
241
+ if truncated:
242
+ entry["bodyTruncated"] = True
224
243
  summary.append(entry)
225
244
  # 单条摘要失败不该拖垮整次读取;继续处理下一条。
226
245
  except Exception: # noqa: BLE001, S112 # nosec B112
227
246
  continue
228
- return summary
247
+ return summary, count
248
+
249
+
250
+ def _network_summary(
251
+ network: Any, # 上游的 NetworkRecorder
252
+ *,
253
+ query: _NetworkQuery,
254
+ ) -> list[dict[str, Any]]:
255
+ """只返回投影后的条目;一次性 capture 不需要过滤后的总数。"""
256
+ return _network_summary_with_count(network, query=query)[0]
229
257
 
230
258
 
231
259
  def _extraction(args: dict[str, Any]) -> tuple[str, str | None, bool, int]:
@@ -416,8 +444,9 @@ def to_payload(
416
444
 
417
445
  ``json`` 是数据而不是正文:直接解析并序列化,不过 markdown 反注入清洗;但序列化后的
418
446
  文本照旧剥 data URI(内联图片对模型不可读,还会白吃 ``maxContentChars`` 的额度)并受
419
- 同一个 ``maxContentChars`` 封顶——与 html/text/markdown 三条路径同一套收口(spec:363)。
447
+ 同一个 ``maxContentChars`` 封顶——与 html/text/markdown 三条路径同一套封顶流程。
420
448
  """
449
+ raise_if_cancelled()
421
450
  if extraction_type == "json":
422
451
  try:
423
452
  parsed = response.json()
@@ -425,7 +454,7 @@ def to_payload(
425
454
  raw = getattr(response, "html_content", "") or getattr(response, "text", "")
426
455
  raise AdapterError("NOT_JSON", f"response is not JSON: {str(raw)[:200]}") from error
427
456
  text = json.dumps(parsed, ensure_ascii=False)
428
- # spec:363 —— JSON 文本与正文走同一条剥图/清洗再封顶的路径:序列化之后的 data URI
457
+ # JSON 文本与正文走同一条剥图/清洗再封顶的路径:序列化之后的 data URI
429
458
  # 同样会白吃 maxContentChars 的额度,而且内联图片是模型读不懂的字节。
430
459
  if strip_inline_images:
431
460
  text = drop_data_uris(text)
@@ -464,6 +493,7 @@ def to_payload(
464
493
  }
465
494
  if include_metadata:
466
495
  payload["metadata"] = _response_metadata(response, redirects)
496
+ raise_if_cancelled()
467
497
  return payload
468
498
 
469
499
 
@@ -665,12 +695,13 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
665
695
  params["impersonate"] = impersonate
666
696
 
667
697
  # Host 侧闸门判过之后到 curl_cffi 真解析、真建连之间隔着一个进程边界(TOCTOU),
668
- # 所以这里在发车之前用同一份 guard 复判一次 —— 浏览器路径由 page.route 逐请求兜住,
698
+ # 所以这里在发车之前用同一份 guard 复判一次 —— 浏览器路径由 page.route 逐请求拦截,
669
699
  # 静态路径没有那一层,不在这里补就是「两道防线」只说了一半。判在写方法之后:那一条是
670
700
  # 部署表态(非 GET 一律拒),与目标地址无关,不该被一条 URL_BLOCKED 盖掉。
671
701
  allowed, reason = guard.url_allowed(url)
672
702
  if not allowed:
673
703
  raise AdapterError("URL_BLOCKED", f"{url}: {reason}")
704
+ raise_if_cancelled()
674
705
  try:
675
706
  response = getattr(Fetcher, method.lower())(url, **params)
676
707
  except Exception as error:
@@ -787,11 +818,8 @@ SESSION_ONLY_KEYS = frozenset(
787
818
  # 与模型入参走同一条通道而它承载的是**部署表态**:类型错了静默生效比报错更糟(例如
788
819
  # maxRecordedRequests 收到字符串,上游会拿它当容量直接炸会话构造)。
789
820
  #
790
- # 这里没有 CDP 端点那一枚:Scrapling 0.5.1 把 `cdp_url` 收归 RemoteSession,递给
791
- # StealthSession 会 `TypeError`(`engines/_browsers/_validators.py` 的
792
- # 「cdp_url and new_context require RemoteSession」那条),而本包没有远端会话模式。
793
- # 递过去在 0.5 上能用、在 0.5.1 上炸会话构造,等于让同一条文档范围 `>=0.5,<0.6` 里
794
- # 的两个版本行为分叉,所以这个旋钮整体撤掉。
821
+ # CDP 端点不在这张表里:它只属于 RemoteSession 的构造参数,递给 StealthySession
822
+ # 会被上游明确拒绝。remote 分支在 _make_session 里单独读取并校验部署值。
795
823
  _DEPLOYMENT_KNOBS: tuple[tuple[str, str, type], ...] = (
796
824
  ("browserExecutablePath", "executable_path", str),
797
825
  ("browserInitScript", "init_script", str),
@@ -954,6 +982,7 @@ def render(args: dict[str, Any]) -> dict[str, Any]:
954
982
 
955
983
  params = _browser_params(args, url)
956
984
  params["page_setup"] = page_setup
985
+ raise_if_cancelled()
957
986
  response = StealthyFetcher.fetch(url, **params)
958
987
  return to_payload(
959
988
  response,
@@ -985,6 +1014,9 @@ class _NetworkQuery(NamedTuple):
985
1014
  def _network_read(args: dict[str, Any]) -> _NetworkQuery:
986
1015
  """抽出「读网络历史」的过滤与投影参数并校验。
987
1016
 
1017
+ 条目数与单条正文只压上限,不把 0、负数或非整数静默改成合法值;总正文在
1018
+ ``_network_summary`` 逐条累计。
1019
+
988
1020
  :param args: 协议参数
989
1021
  :returns: 归一后的查询参数
990
1022
  """
@@ -1005,9 +1037,15 @@ def _network_read(args: dict[str, Any]) -> _NetworkQuery:
1005
1037
  raise AdapterError("BAD_ARGS", "requestId must be a positive integer or null")
1006
1038
  return _NetworkQuery(
1007
1039
  pattern=_url_pattern(args),
1008
- limit=_positive_int(args.get("networkLimit"), "networkLimit", DEFAULT_NETWORK_ENTRIES),
1040
+ limit=min(
1041
+ _positive_int(args.get("networkLimit"), "networkLimit", DEFAULT_NETWORK_ENTRIES),
1042
+ NETWORK_MAX_ENTRIES,
1043
+ ),
1009
1044
  include_body=bool(args.get("includeBody", False)),
1010
- body_chars=_positive_int(args.get("maxBodyChars"), "maxBodyChars", DEFAULT_NETWORK_BODY_CHARS),
1045
+ body_chars=min(
1046
+ _positive_int(args.get("maxBodyChars"), "maxBodyChars", DEFAULT_NETWORK_BODY_CHARS),
1047
+ NETWORK_MAX_BODY_CHARS,
1048
+ ),
1011
1049
  method=method.upper() if isinstance(method, str) else None,
1012
1050
  status=status,
1013
1051
  resource_type=resource_type,
@@ -1036,6 +1074,7 @@ def _capture_once(
1036
1074
  """
1037
1075
  from scrapling.fetchers import StealthySession
1038
1076
 
1077
+ raise_if_cancelled()
1039
1078
  session_params = _session_browser_params(args)
1040
1079
  # 与 _make_session 对齐:浏览器会话的代理只能在构造期给,而 _session_browser_params
1041
1080
  # 按 SESSION_ONLY_KEYS 把它连同 block_webrtc 一起过滤掉了。不在这里补,配了代理的
@@ -1053,8 +1092,11 @@ def _capture_once(
1053
1092
  session = StealthySession(**session_params)
1054
1093
  try:
1055
1094
  session.start()
1095
+ raise_if_cancelled()
1056
1096
  response = session.fetch(url, **fetch_params)
1097
+ raise_if_cancelled()
1057
1098
  records = _network_summary(session.network, query=query)
1099
+ raise_if_cancelled()
1058
1100
  finally:
1059
1101
  # 这条会话不进注册表,所以没有别人会替它收尸 —— 成败都要在这里关掉。
1060
1102
  with contextlib.suppress(Exception):
@@ -1123,8 +1165,9 @@ def _adaptive_kwargs(args: dict[str, Any], url: str) -> dict[str, Any]:
1123
1165
  """按部署表态给出 adaptive 指纹库的 storage 与 storage_args。
1124
1166
 
1125
1167
  ``deployment.adaptiveStorage`` 只认 ``sqlite``(默认)与 ``redis``;Redis 那一支把连接
1126
- 串与按注册域分桶的 ``url`` 一起交给 ``RedisStorageSystem``,客户端不可达时翻成带码的
1127
- ``ADAPTIVE_STORAGE_UNAVAILABLE``,而不是让整次抽取以原始异常收场。
1168
+ 串与按注册域分桶的 ``url`` 一起交给 ``RedisStorageSystem``。存储层连不上时不让抽取
1169
+ 失败:调用方降级为不带 adaptive 的普通抽取,notice 带 ``ADAPTIVE_STORAGE_FAILED``
1170
+ 与原因。
1128
1171
  """
1129
1172
  deployment = args.get("deployment")
1130
1173
  settings = deployment if isinstance(deployment, dict) else {}
@@ -1148,6 +1191,8 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
1148
1191
  """对已有 HTML 做选择,返回命中文本、属性或多字段行。"""
1149
1192
  from scrapling.parser import Selector
1150
1193
 
1194
+ raise_if_cancelled()
1195
+
1151
1196
  html = args.get("html")
1152
1197
  if not isinstance(html, str):
1153
1198
  raise AdapterError("BAD_ARGS", "html must be a string")
@@ -1235,7 +1280,7 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
1235
1280
  # 替换而不是补齐,漏了 url 全部指纹都会落进 default 桶。url 为空时也显式传空串,
1236
1281
  # 存储层把它归入 default 桶(StorageSystemMixin 对空值有兜底)。
1237
1282
  #
1238
- # spec §7.2 / §12.2:存储故障**不使抽取失败** —— 降级为不带 adaptive 的普通
1283
+ # 存储故障**不使抽取失败** —— 降级为不带 adaptive 的普通
1239
1284
  # Selector 再抽一次,正文照常返回,notice 带 ADAPTIVE_STORAGE_FAILED 与原因。
1240
1285
  # sqlite 与 redis 两侧同解:指纹库坏了不该让模型连正文都拿不到。
1241
1286
  try:
@@ -1251,6 +1296,7 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
1251
1296
  page = Selector(html, url=url or "")
1252
1297
  nodes, notice = query_nodes(page, use_adaptive=False)
1253
1298
 
1299
+ raise_if_cancelled()
1254
1300
  limit = _positive_int(args.get("limit"), "limit", 200)
1255
1301
  budget = _positive_int(args.get("maxContentChars"), "maxContentChars", DEFAULT_MAX_CONTENT_CHARS)
1256
1302
  include_attributes = bool(args.get("includeAttributes", False))
@@ -1261,6 +1307,7 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
1261
1307
  if fields is not None:
1262
1308
  if not isinstance(fields, dict):
1263
1309
  raise AdapterError("BAD_ARGS", "fields must be an object or null")
1310
+ raise_if_cancelled()
1264
1311
  try:
1265
1312
  rows, fields_truncated = extraction.collect_fields(
1266
1313
  list(nodes)[:limit],
@@ -1271,6 +1318,7 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
1271
1318
  )
1272
1319
  except ValueError as error:
1273
1320
  raise AdapterError("BAD_ARGS", str(error)) from error
1321
+ raise_if_cancelled()
1274
1322
  return {
1275
1323
  "count": len(nodes),
1276
1324
  "truncated": fields_truncated or len(nodes) > limit,
@@ -1282,6 +1330,7 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
1282
1330
  spent = 0
1283
1331
  clipped = False
1284
1332
  for node in nodes:
1333
+ raise_if_cancelled()
1285
1334
  if len(matches) >= limit:
1286
1335
  break
1287
1336
  item = extraction.serialize_match(
@@ -1376,13 +1425,24 @@ def _websocket_guard_capability() -> bool:
1376
1425
  return guard.websocket_guard_supported(Page)
1377
1426
 
1378
1427
 
1428
+ def _remote_session_available() -> bool:
1429
+ """当前 Scrapling 是否导出 RemoteSession;不连接端点也能判断。"""
1430
+ try:
1431
+ from scrapling.fetchers import RemoteSession
1432
+ except ImportError:
1433
+ return False
1434
+ return callable(RemoteSession)
1435
+
1436
+
1379
1437
  def capabilities() -> dict[str, Any]:
1380
1438
  """报告本进程当前具备的能力,供 Host 侧决定注册哪些工具。"""
1381
1439
  report: dict[str, Any] = {
1382
1440
  "scrapling": SCRAPLING_AVAILABLE,
1383
1441
  "static": SCRAPLING_AVAILABLE,
1384
1442
  "extract": SCRAPLING_AVAILABLE,
1443
+ "documents": document.available(),
1385
1444
  "browser": False,
1445
+ "remote": False,
1386
1446
  # 写方法这一档**与 scrapling 在不在无关**:它是部署表态,而排障的人得能一眼看出
1387
1447
  # 「这台到底许不许写」,而不是等到发 POST 被拒才发现环境里少一个变量。
1388
1448
  "writeMethods": guard.ALLOW_WRITE_METHODS,
@@ -1393,6 +1453,7 @@ def capabilities() -> dict[str, Any]:
1393
1453
  # 0.5 只剩 patchright 那一套浏览器,所以这一项就是「浏览器抓取能不能用」的全部答案 ——
1394
1454
  # 0.4.15 时代那两个「普通浏览器 / 反检测浏览器」各自探测的规则已经没有第二个引擎可标。
1395
1455
  report["browser"] = _probe_browser("patchright.sync_api")
1456
+ report["remote"] = _remote_session_available()
1396
1457
  # 浏览器守卫覆盖面的那一半(WebSocket 握手)在这里报出:拦不住时 install 只会往 stderr
1397
1458
  # 记一行,而那要等第一个页面建起来才看得见 —— 排障的人得在装载阶段就知道。
1398
1459
  report["websocketGuard"] = _websocket_guard_capability()
@@ -1404,18 +1465,24 @@ def capabilities() -> dict[str, Any]:
1404
1465
 
1405
1466
  def _wrap_extraction(fn: Callable[[dict[str, Any]], dict[str, Any]], args: dict[str, Any]) -> dict[str, Any]:
1406
1467
  """把 extraction 的 ValueError 归成协议里的 BAD_ARGS。"""
1468
+ raise_if_cancelled()
1407
1469
  try:
1408
- return fn(args)
1470
+ result = fn(args)
1409
1471
  except ValueError as error:
1410
1472
  raise AdapterError("BAD_ARGS", str(error)) from error
1473
+ raise_if_cancelled()
1474
+ return result
1411
1475
 
1412
1476
 
1413
1477
  def _wrap_search(fn: Callable[[dict[str, Any]], dict[str, Any]], args: dict[str, Any]) -> dict[str, Any]:
1414
1478
  """把 SearchError 的码原样转成协议错误。"""
1479
+ raise_if_cancelled()
1415
1480
  try:
1416
- return fn(args)
1481
+ result = fn(args)
1417
1482
  except search.SearchError as error:
1418
1483
  raise AdapterError(error.code, str(error)) from error
1484
+ raise_if_cancelled()
1485
+ return result
1419
1486
 
1420
1487
 
1421
1488
  def search_discover(args: dict[str, Any]) -> dict[str, Any]:
@@ -1432,6 +1499,7 @@ METHODS = {
1432
1499
  "select": select,
1433
1500
  "locate": lambda args: _wrap_extraction(extraction.locate, args),
1434
1501
  "links": lambda args: _wrap_extraction(extraction.links, args),
1502
+ "document.read": lambda args: document.read(args),
1435
1503
  "search.discover": search_discover,
1436
1504
  }
1437
1505
 
@@ -1443,24 +1511,26 @@ METHODS = {
1443
1511
  # 会话把这份状态留在 sidecar 进程里跨请求复用 —— 这是 Scrapling 相对
1444
1512
  # 「每次调用都重新来」最实用的一块。
1445
1513
  #
1446
- # 两种类型与 Scrapling 的一一对应:
1514
+ # 三种类型与 Scrapling 的一一对应:
1447
1515
  # static -> FetcherSession(curl_cffi)
1448
- # stealth -> StealthySession(patchright,0.5 起唯一的浏览器引擎)
1516
+ # stealth -> StealthySession(patchright,本机启动浏览器)
1517
+ # remote -> RemoteSession(patchright,连接部署指定的 CDP 浏览器)
1449
1518
  # ---------------------------------------------------------------------------
1450
1519
 
1451
1520
  _SESSION_CLASSES = {
1452
1521
  "static": "FetcherSession",
1453
1522
  "stealth": "StealthySession",
1523
+ "remote": "RemoteSession",
1454
1524
  }
1455
1525
 
1456
- # 吃内存的那几类(每个都是一个真实浏览器进程):名额与专属执行线程都按它判。
1457
- _BROWSER_KINDS = frozenset({"stealth"})
1526
+ # 浏览器类会话:名额与专属执行线程都按它判。remote 不启动本机进程,但仍占用 page pool。
1527
+ _BROWSER_KINDS = frozenset({"stealth", "remote"})
1458
1528
 
1459
1529
  # 会话注册表。sidecar 是常驻进程,这里就是它的内存;进程退出时全部随之消失。
1460
1530
  # 值里存 {"session": <对象>, "type": <str>, "created_at": <iso8601>, "lock": Lock,
1461
1531
  # "worker": _SessionWorker | None};正在构造中的条目只有
1462
1532
  # {"pending": True, "type": <str>, "lock": Lock},那样它就已经占了名额。
1463
- # lock 从占位那一刻就存在,所以构造期与使用期是同一把锁;worker 只在 browser/stealth
1533
+ # lock 从占位那一刻就存在,所以构造期与使用期是同一把锁;worker 只在 stealth/remote
1464
1534
  # 上出现(见下),static 为 None。
1465
1535
  _SESSIONS: dict[str, dict[str, Any]] = {}
1466
1536
 
@@ -1490,7 +1560,7 @@ class _SessionWorker:
1490
1560
  ``greenlet.error: cannot switch to a different thread``。而 bridge 的 worker 是
1491
1561
  「谁抢到帧谁处理」,还会空闲 50ms 就退出换新线程:会话在 A 线程里开、下一个请求
1492
1562
  几乎必然落在 B 线程。按会话加锁只能保证「不同时用」,保证不了「同一线程用」——
1493
- 所以每个 browser/stealth 会话配一条专用线程,open/fetch/close 全部投递到它,
1563
+ 所以每个 stealth/remote 会话配一条专用线程,open/fetch/close 全部投递到它,
1494
1564
  串行执行;调用线程原地等结果。static(curl_cffi)没有线程亲和,不走这套。
1495
1565
  """
1496
1566
 
@@ -1519,10 +1589,11 @@ class _SessionWorker:
1519
1589
  except BaseException as error: # noqa: BLE001 —— 任务异常必须回到调用方线程
1520
1590
  done.set_exception(error)
1521
1591
 
1522
- def run(self, fn: Callable[[], Any]) -> Any: # 会话调用的返回形态由引擎定
1592
+ def run(self, fn: Callable[[], Any], *, cancellable: bool = True) -> Any: # 会话调用的返回形态由引擎定
1523
1593
  """把 fn 投递到属主线程执行,并阻塞调用线程直到它结束。
1524
1594
 
1525
1595
  :param fn: 要在属主线程上执行的调用
1596
+ :param cancellable: 请求任务在真实操作前复查取消;关闭会话等清理任务传 False
1526
1597
  :returns: fn 的返回值
1527
1598
  :raises AdapterError: 这条线程已经停止,投进去也没有人会执行
1528
1599
  :raises BaseException: fn 抛什么这里就抛什么
@@ -1532,7 +1603,18 @@ class _SessionWorker:
1532
1603
  if self._closed.is_set():
1533
1604
  raise AdapterError("NO_SUCH_SESSION", "session has already been closed")
1534
1605
  done: concurrent.futures.Future[Any] = concurrent.futures.Future()
1535
- self._jobs.put((fn, done))
1606
+ # 新线程不会自动继承调用线程的 contextvar;每笔任务复制当前请求上下文,
1607
+ # 否则会话抓取/动作在属主线程上看不到 bridge 绑定的取消 token。
1608
+ context = contextvars.copy_context()
1609
+
1610
+ def invoke() -> Any:
1611
+ # 入队前取消只是第一道检查;任务可能在队列里等很久,必须出队后、真实操作前
1612
+ # 再查一次。清理任务显式豁免,否则取消中的 close 会把自己跳过并漏掉浏览器。
1613
+ if cancellable:
1614
+ raise_if_cancelled()
1615
+ return fn()
1616
+
1617
+ self._jobs.put((lambda: context.run(invoke), done))
1536
1618
  try:
1537
1619
  return done.result(timeout=_WORKER_RESULT_TIMEOUT_SECONDS)
1538
1620
  except concurrent.futures.TimeoutError:
@@ -1547,7 +1629,7 @@ class _SessionWorker:
1547
1629
  self._thread.join(timeout=5.0)
1548
1630
 
1549
1631
  def alive(self) -> bool:
1550
- """属主线程是否还在跑(T10 的 ``alive`` 判据:只读,不改动任何状态)。"""
1632
+ """属主线程是否还在跑(只读判据,不改动任何状态)。"""
1551
1633
  return not self._closed.is_set() and self._thread.is_alive()
1552
1634
 
1553
1635
 
@@ -1559,6 +1641,19 @@ def _new_session_id() -> str:
1559
1641
  return uuid.uuid4().hex[:12]
1560
1642
 
1561
1643
 
1644
+ def _remote_cdp_url(args: dict[str, Any]) -> str:
1645
+ """读取部署级 CDP 端点;缺失或协议不符时在连接前报参数错误。"""
1646
+ deployment = args.get("deployment")
1647
+ raw = deployment.get("browserCdpUrl") if isinstance(deployment, dict) else None
1648
+ if not isinstance(raw, str) or not raw.strip():
1649
+ raise AdapterError("BAD_ARGS", "remote sessions require deployment.browserCdpUrl")
1650
+ endpoint = raw.strip()
1651
+ parsed = urlparse(endpoint)
1652
+ if parsed.scheme not in {"ws", "wss", "http", "https"} or not parsed.netloc:
1653
+ raise AdapterError("BAD_ARGS", "browserCdpUrl must be a ws/wss/http/https URL with a host")
1654
+ return endpoint
1655
+
1656
+
1562
1657
  def _make_session(kind: str, args: dict[str, Any]) -> Any:
1563
1658
  """按类型造一个**已启动**的会话对象。
1564
1659
 
@@ -1567,7 +1662,7 @@ def _make_session(kind: str, args: dict[str, Any]) -> Any:
1567
1662
  cookie 与登录态 —— 那是会话存在的理由。绕过清单因此对浏览器会话不逐 URL 生效(对
1568
1663
  静态会话生效,那边是每次请求各自的参数,换代理不丢任何东西)。
1569
1664
 
1570
- :param kind: static / browser / stealth
1665
+ :param kind: static / stealth / remote
1571
1666
  :param args: 创建参数
1572
1667
  :returns: 已 start(或已进入上下文)的会话对象
1573
1668
  :raises AdapterError: 类型不认识,或构造/启动失败
@@ -1588,8 +1683,6 @@ def _make_session(kind: str, args: dict[str, Any]) -> Any:
1588
1683
  # wrapper 要留在登记条目里,close 时才能 __exit__。
1589
1684
  return logic, wrapper
1590
1685
 
1591
- from scrapling.fetchers import StealthySession
1592
-
1593
1686
  # 只有开场才生效的那些设置(block_ads / record_requests / headless / locale /
1594
1687
  # timezone_id / useragent / executable_path / timeout)必须在这里进会话:
1595
1688
  # fetch 层传过去会被 validate_fetch 静默丢掉(见 FETCH_LEVEL_KEYS)。
@@ -1613,7 +1706,21 @@ def _make_session(kind: str, args: dict[str, Any]) -> Any:
1613
1706
  # 是直连的:模型明确填了 blockWebrtc=false 也会被静默盖掉。
1614
1707
  # 这里整体重写,不继承那份结论。
1615
1708
  common["block_webrtc"] = bool(args.get("blockWebrtc")) or proxy is not None
1616
- session = StealthySession(**common)
1709
+ session: Any
1710
+ if kind == "remote":
1711
+ from scrapling.fetchers import RemoteSession
1712
+
1713
+ endpoint = _remote_cdp_url(args)
1714
+ # RemoteSession 只接受 context 级参数;real_chrome 会被上游明确拒绝,
1715
+ # executable_path 与 headless 则只对本机启动有意义。
1716
+ common.pop("real_chrome", None)
1717
+ common.pop("executable_path", None)
1718
+ common.pop("headless", None)
1719
+ session = RemoteSession(cdp_url=endpoint, new_context=True, **common)
1720
+ else:
1721
+ from scrapling.fetchers import StealthySession
1722
+
1723
+ session = StealthySession(**common)
1617
1724
  session.start()
1618
1725
  return session, session
1619
1726
 
@@ -1670,7 +1777,7 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
1670
1777
  _SESSIONS[session_id] = placeholder
1671
1778
  entry_lock = placeholder["lock"]
1672
1779
 
1673
- # browser/stealth 先起属主线程,构造(含 sync_playwright 的启动)整个发生在它上面
1780
+ # stealth/remote 先起属主线程,构造(含 sync_playwright 的启动)整个发生在它上面
1674
1781
  # —— greenlet 绑定从此指向这条线程,之后每次 fetch/close 都转交回来。static 没有
1675
1782
  # 线程亲和,留在调用线程即可。
1676
1783
  worker: _SessionWorker | None = None
@@ -1680,6 +1787,13 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
1680
1787
  else:
1681
1788
  worker = _SessionWorker()
1682
1789
  usable, closer = worker.run(lambda: _make_session(kind, args))
1790
+ except RequestCancelled:
1791
+ if worker is not None:
1792
+ worker.stop()
1793
+ with _SESSION_LOCK:
1794
+ if _SESSIONS.get(session_id) is placeholder:
1795
+ _SESSIONS.pop(session_id, None)
1796
+ raise
1683
1797
  except BaseException as error:
1684
1798
  if worker is not None:
1685
1799
  worker.stop()
@@ -1689,6 +1803,23 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
1689
1803
  raise
1690
1804
  raise AdapterError("SESSION_OPEN_FAILED", f"{type(error).__name__}: {error}") from error
1691
1805
 
1806
+ try:
1807
+ # 构造可能耗时数百毫秒;返回后先复查,取消时刚建好的浏览器必须先关掉,绝不能
1808
+ # 插进注册表等一个永远不会到来的请求。清理任务在属主线程执行且不受取消影响。
1809
+ raise_if_cancelled()
1810
+ except RequestCancelled:
1811
+ abandoned_entry = {"closer": closer, "type": kind, "lock": entry_lock}
1812
+ if worker is not None:
1813
+ with contextlib.suppress(Exception):
1814
+ worker.run(lambda: _release_entry(abandoned_entry), cancellable=False)
1815
+ worker.stop()
1816
+ else:
1817
+ _release_entry(abandoned_entry)
1818
+ with _SESSION_LOCK:
1819
+ if _SESSIONS.get(session_id) is placeholder:
1820
+ _SESSIONS.pop(session_id, None)
1821
+ raise
1822
+
1692
1823
  with _SESSION_LOCK:
1693
1824
  abandoned = placeholder.get("closed_while_pending") is True
1694
1825
  if abandoned:
@@ -1699,12 +1830,12 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
1699
1830
  "closer": closer, # 关它用的对象(static 是 wrapper,浏览器是自身)
1700
1831
  "type": kind,
1701
1832
  "created_at": datetime.now(timezone.utc).isoformat(),
1702
- # T10 的非敏感设置摘要:在开场时把生效值记下来,session.list 不必回头去
1833
+ # 非敏感设置摘要:在开场时把生效值记下来,session.list 不必回头去
1703
1834
  # 猜(凭据一类的东西永远不进这份摘要)。
1704
1835
  "settings": _session_settings(kind, args),
1705
1836
  # 同一把锁:占位时建的那把,盖回来而不是新建 —— 新建会让构造期与使用期各锁各的。
1706
1837
  "lock": entry_lock,
1707
- # browser/stealth 的专属执行线程;static 为 None(见 _SessionWorker 的说明)。
1838
+ # stealth/remote 的专属执行线程;static 为 None(见 _SessionWorker 的说明)。
1708
1839
  "worker": worker,
1709
1840
  }
1710
1841
  created_at = _SESSIONS[session_id]["created_at"]
@@ -1716,7 +1847,7 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
1716
1847
  # 浏览器会话的 close 必须在属主线程上跑:Playwright 的同步 API 与创建它的线程
1717
1848
  # 绑定,跨线程调用抛 greenlet 错误,而 _release_entry 会 suppress 掉它 ——
1718
1849
  # 随后 stop() 又把属主线程收掉,这个 Chromium 就再没有任何线程能关。
1719
- worker.run(lambda: _release_entry(abandoned_entry))
1850
+ worker.run(lambda: _release_entry(abandoned_entry), cancellable=False)
1720
1851
  worker.stop()
1721
1852
  else:
1722
1853
  _release_entry(abandoned_entry)
@@ -1768,6 +1899,7 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
1768
1899
  # 两种实现也都对「多线程同时用同一份会话」零容忍 —— Playwright 的同步 API 靠 greenlet
1769
1900
  # 一次只服务一个线程,curl_cffi 的 Session 文档原话是「一个时刻一个会话」。表现是看不懂
1770
1901
  # 的崩溃,甚至是上下文串台 —— 所以在结构上就不给这个可能。
1902
+ raise_if_cancelled()
1771
1903
  try:
1772
1904
  if entry["type"] == "static":
1773
1905
  with entry["lock"]:
@@ -1775,6 +1907,7 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
1775
1907
  # 会持锁使用一份已关闭的会话,异常最终被归成 FETCH_FAILED——语义错位。
1776
1908
  if entry.get("closed") is True:
1777
1909
  raise AdapterError("NO_SUCH_SESSION", f"no such session: {session_id}")
1910
+ raise_if_cancelled()
1778
1911
  # 与一次性 fetch 同一条复判:static 会话的请求不经过浏览器的 page.route,
1779
1912
  # 少了这一道,「Host 判完 → curl_cffi 自己再解析」之间就是敞开的。
1780
1913
  allowed, reason = guard.url_allowed(url)
@@ -1841,7 +1974,10 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
1841
1974
  worker: _SessionWorker | None = entry["worker"]
1842
1975
  if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
1843
1976
  raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
1977
+ raise_if_cancelled()
1844
1978
  response = worker.run(lambda: session.fetch(url, **params))
1979
+ except RequestCancelled:
1980
+ raise
1845
1981
  except AdapterError:
1846
1982
  raise
1847
1983
  except Exception as error:
@@ -1866,6 +2002,9 @@ def session_read(args: dict[str, Any]) -> dict[str, Any]:
1866
2002
  if entry["type"] == "static":
1867
2003
  raise AdapterError("BAD_ARGS", "only browser sessions keep a current page")
1868
2004
  extraction_type, css_selector, main_content_only, limit = _extraction(args)
2005
+ snapshot_type = args.get("snapshotType", "text")
2006
+ if not isinstance(snapshot_type, str) or snapshot_type not in {"text", "aria"}:
2007
+ raise AdapterError("BAD_ARGS", "snapshotType must be text or aria")
1869
2008
  worker: _SessionWorker | None = entry["worker"]
1870
2009
  if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
1871
2010
  raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
@@ -1880,6 +2019,7 @@ def session_read(args: dict[str, Any]) -> dict[str, Any]:
1880
2019
  max_content_chars=limit,
1881
2020
  include_metadata=bool(args.get("includeMetadata", False)),
1882
2021
  strip_inline_images=_strip_inline_images(args),
2022
+ snapshot_type=snapshot_type,
1883
2023
  )
1884
2024
  )
1885
2025
 
@@ -1919,6 +2059,11 @@ def download(args: dict[str, Any]) -> dict[str, Any]:
1919
2059
  return media.download(args)
1920
2060
 
1921
2061
 
2062
+ def document_read(args: dict[str, Any]) -> dict[str, Any]:
2063
+ """PDF 文本读取入口。"""
2064
+ return document.read(args)
2065
+
2066
+
1922
2067
  def screenshot(args: dict[str, Any]) -> dict[str, Any]:
1923
2068
  """截当前会话页;不会新建浏览器。"""
1924
2069
  entry = _get_session(args.get("sessionId"))
@@ -1948,7 +2093,7 @@ def screenshot(args: dict[str, Any]) -> dict[str, Any]:
1948
2093
 
1949
2094
 
1950
2095
  def _session_settings(kind: str, args: dict[str, Any]) -> dict[str, Any]:
1951
- """会话的非敏感设置摘要(T10)。
2096
+ """会话的非敏感设置摘要。
1952
2097
 
1953
2098
  只收「这次会话是怎么配的」的开关,绝不包含 cookies、代理凭据或任何 key —— 这份
1954
2099
  摘要会被模型读到。静态会话没有浏览器那一组开关,逐项给 null。
@@ -1991,7 +2136,7 @@ def _session_alive(entry: dict[str, Any]) -> bool:
1991
2136
  def _pool_stats(entry: dict[str, Any]) -> dict[str, int] | None:
1992
2137
  """浏览器会话的页池统计;没有这条能力或取不到时给 None(绝不抛)。
1993
2138
 
1994
- T10 的 ``poolStats`` 是可选字段:一只已经跑完开始收尾的会话也可能在取统计的一瞬
2139
+ ``poolStats`` 是可选字段:一只已经跑完开始收尾的会话也可能在取统计的一瞬
1995
2140
  出错,那不该把整个 session.list 变成一次失败。
1996
2141
 
1997
2142
  :param entry: 登记条目
@@ -2005,7 +2150,7 @@ def _pool_stats(entry: dict[str, Any]) -> dict[str, int] | None:
2005
2150
  return None
2006
2151
  try:
2007
2152
  stats = getter()
2008
- except Exception: # noqa: BLE001 —— T10:统计拿不到时省略,不许让 list 整体失败
2153
+ except Exception: # noqa: BLE001 —— 统计拿不到时省略,不许让 list 整体失败
2009
2154
  return None
2010
2155
  if not isinstance(stats, dict):
2011
2156
  return None
@@ -2080,7 +2225,7 @@ def _close_entry(session_id: Any) -> None:
2080
2225
  # 浏览器会话的 close 是一次 Playwright 远端调用,必须在属主线程上做;转交进去
2081
2226
  # 还天然排在在途 fetch 之后 —— 「抓取进行中收到 close」会等抓取落地再关,而
2082
2227
  # 不是把一次正在跑的抓取从底下抽走。
2083
- worker.run(lambda: _release_entry(entry))
2228
+ worker.run(lambda: _release_entry(entry), cancellable=False)
2084
2229
  worker.stop()
2085
2230
  return
2086
2231
  # static 没有属主线程,用 entry 锁:否则「抓取进行中收到 close」会把一次正在跑的
@@ -2130,8 +2275,8 @@ def session_network(args: dict[str, Any]) -> dict[str, Any]:
2130
2275
  worker: _SessionWorker | None = entry["worker"]
2131
2276
  if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
2132
2277
  raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
2133
- matches = worker.run(lambda: _network_summary(recorder, query=query))
2134
- return {"sessionId": session_id, "count": len(matches), "matches": matches}
2278
+ matches, count = worker.run(lambda: _network_summary_with_count(recorder, query=query))
2279
+ return {"sessionId": session_id, "count": count, "matches": matches}
2135
2280
 
2136
2281
 
2137
2282
  def _state_path(args: dict[str, Any]) -> str:
@@ -2192,12 +2337,14 @@ def _session_state(args: dict[str, Any], *, saving: bool) -> dict[str, Any]:
2192
2337
  try:
2193
2338
  if saving:
2194
2339
  worker.run(lambda: session.save_state(target))
2195
- # spec §11.6:登录态文件是凭据一类的东西(cookie / localStorage / IndexedDB),写到磁盘后
2340
+ # 登录态文件是凭据一类的东西(cookie / localStorage / IndexedDB),写到磁盘后
2196
2341
  # 收到 0600。Windows 上 chmod 只动只读位,失败也不该让存取整体失败。
2197
2342
  with contextlib.suppress(OSError):
2198
2343
  Path(target).chmod(0o600)
2199
2344
  else:
2200
2345
  worker.run(lambda: session.load_state(target))
2346
+ except RequestCancelled:
2347
+ raise
2201
2348
  except FileNotFoundError as error:
2202
2349
  if saving:
2203
2350
  # save 路径的 FileNotFoundError 只能是目录在 mkdir 之后又不可用(竞态、权限):