@jayyuen66/dsh-scrapling 0.1.2 → 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/media.py ADDED
@@ -0,0 +1,399 @@
1
+ """下载落盘与截图字节。两者都不经过正文清洗:字节就是字节。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import hashlib
7
+ import os
8
+ import struct
9
+ import uuid
10
+ from pathlib import Path
11
+ from typing import Any
12
+ from urllib.parse import urlparse
13
+
14
+ DEFAULT_DOWNLOAD_MAX_BYTES = 10 * 1024 * 1024
15
+
16
+
17
+ def _error(code: str, message: str) -> Exception:
18
+ from adapters import AdapterError
19
+
20
+ return AdapterError(code, message)
21
+
22
+
23
+ def _safe_name(raw: Any, url: str) -> str:
24
+ """把调用方给的文件名收成目录内的纯文件名;任何路径成分都拒绝。"""
25
+ name = raw if isinstance(raw, str) and raw else Path(urlparse(url).path).name
26
+ if not name:
27
+ name = "download.bin"
28
+ if "\x00" in name or "/" in name or "\\" in name:
29
+ raise _error("DOWNLOAD_PATH", "filename must not contain path separators or NUL")
30
+ if name in (".", "..") or os.path.isabs(name):
31
+ raise _error("DOWNLOAD_PATH", "filename must be a plain file name")
32
+ return name
33
+
34
+
35
+ def _claim_path(directory: Path, name: str) -> Path:
36
+ """占住一个当前不存在的目标名并创建空文件;占不住就按 -1、-2… 往后找。
37
+
38
+ 「探测」与「占位」必须是同一原子操作:O_EXCL 的创建语义保证了两个并发下载不可能
39
+ 各自都以为拿到了同一个名字——而先 ``exists()`` 再写的那两步之间,另一路可以整个
40
+ 走完,后落盘的 ``os.replace`` 就把先到的那份覆盖掉了。占位本身产生一个空文件,
41
+ 正常路径随后会被 ``os.replace`` 原子覆盖成正文。
42
+ """
43
+ candidate = directory / name
44
+ stem = candidate.stem
45
+ suffix = candidate.suffix
46
+ index = 0
47
+ while True:
48
+ try:
49
+ handle = os.open(candidate, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
50
+ except FileExistsError:
51
+ index += 1
52
+ candidate = directory / f"{stem}-{index}{suffix}"
53
+ continue
54
+ os.close(handle)
55
+ return candidate
56
+
57
+
58
+ def _release_claim(target: Path) -> None:
59
+ """撤掉一个尚未被正文覆盖的占位空文件;占位可能已被覆盖或已被撤,缺席不算错。"""
60
+ try:
61
+ if target.stat().st_size == 0:
62
+ target.unlink()
63
+ except OSError:
64
+ return
65
+
66
+
67
+ def _temp_path(directory: Path, name: str) -> Path:
68
+ """一次落盘的临时文件名:点前缀 + uuid,让「写到一半」的文件不会撞上任何正名。"""
69
+ return directory / f".{name}.{uuid.uuid4().hex}.part"
70
+
71
+
72
+ def _header_value(headers: Any, name: str) -> str:
73
+ """按大小写不敏感读一个响应头;读不到给空串。dict 与 curl_cffi 的 Headers 都适用。"""
74
+ try:
75
+ items = list(headers.items())
76
+ except Exception: # noqa: BLE001 —— 形状不对就当没有这个头
77
+ return ""
78
+ for key, value in items:
79
+ if str(key).lower() == name.lower():
80
+ return str(value)
81
+ return ""
82
+
83
+
84
+ def _commit_temp(directory: Path, name: str, temporary: Path) -> Path:
85
+ """把已写完的临时文件落成正式名:占位 + 原子替换,不覆盖任何已存在的文件。"""
86
+ target = _claim_path(directory, name)
87
+ try:
88
+ os.replace(temporary, target)
89
+ except OSError:
90
+ _release_claim(target)
91
+ raise
92
+ return target
93
+
94
+
95
+ def _download_dir(args: dict[str, Any]) -> Path:
96
+ deployment = args.get("deployment")
97
+ configured = deployment.get("downloadDir") if isinstance(deployment, dict) else None
98
+ if isinstance(configured, str) and configured:
99
+ return Path(configured)
100
+ return Path.home() / ".dsh-scrapling" / "downloads"
101
+
102
+
103
+ def _max_bytes(args: dict[str, Any]) -> int:
104
+ """下载字节上限。
105
+
106
+ 部署侧的 ``downloadMaxBytes`` 是**硬上限**:模型给的 ``maxBytes`` 只能在它下面
107
+ 往下收,不能把它顶掉。早先只在 ``maxBytes`` 缺席时才读部署项,于是模型随手写一个
108
+ 大数就绕过了运维定的那道闸。
109
+ """
110
+ deployment = args.get("deployment")
111
+ configured = deployment.get("downloadMaxBytes") if isinstance(deployment, dict) else None
112
+ if configured is not None and (not isinstance(configured, int) or isinstance(configured, bool) or configured <= 0):
113
+ # 部署项写坏不悄悄回落默认值:那会让人以为「上限是默认的那一档」,而实际配置没生效。
114
+ raise _error("BAD_ARGS", "deployment.downloadMaxBytes must be a positive integer")
115
+ ceiling = configured if isinstance(configured, int) else DEFAULT_DOWNLOAD_MAX_BYTES
116
+ raw = args.get("maxBytes")
117
+ if raw is None:
118
+ return ceiling
119
+ if not isinstance(raw, int) or isinstance(raw, bool) or raw <= 0:
120
+ raise _error("BAD_ARGS", "maxBytes must be a positive integer")
121
+ return min(raw, ceiling)
122
+
123
+
124
+ _DOWNLOAD_CHUNK_BYTES = 64 * 1024
125
+
126
+
127
+ def download(args: dict[str, Any]) -> dict[str, Any]:
128
+ """取一个 URL 的字节并写进下载目录;流式落盘,不覆盖、不越界。"""
129
+ import guard
130
+
131
+ if not guard.ALLOW_FILE_DOWNLOADS:
132
+ raise _error(
133
+ "DOWNLOAD_DISABLED",
134
+ f"file downloads are disabled; the deployment must set {guard.ALLOW_FILE_DOWNLOADS_ENV}",
135
+ )
136
+ from adapters import _string_map, _url
137
+
138
+ url = _url(args)
139
+ allowed, reason = guard.url_allowed(url)
140
+ if not allowed:
141
+ raise _error("URL_BLOCKED", f"{url}: {reason}")
142
+ name = _safe_name(args.get("filename"), url)
143
+ limit = _max_bytes(args)
144
+ directory = _download_dir(args)
145
+ directory.mkdir(parents=True, exist_ok=True)
146
+
147
+ headers = _string_map(args.get("headers"), "headers")
148
+ cookies = _string_map(args.get("cookies"), "cookies")
149
+ timeout = args.get("timeoutSeconds", 120.0)
150
+ if not isinstance(timeout, (int, float)) or isinstance(timeout, bool) or timeout <= 0:
151
+ raise _error("BAD_ARGS", "timeoutSeconds must be a positive number")
152
+ if args.get("useBrowser") is True:
153
+ if cookies is not None:
154
+ raise _error("BAD_ARGS", "cookies need a session; use useBrowser:false for a one-off download")
155
+ return _download_via_browser(url, name=name, directory=directory, limit=limit, timeout=timeout, headers=headers)
156
+ impersonate = args.get("impersonate")
157
+ return _download_via_stream(
158
+ url,
159
+ name=name,
160
+ directory=directory,
161
+ limit=limit,
162
+ timeout=timeout,
163
+ headers=headers,
164
+ cookies=cookies,
165
+ impersonate=impersonate if isinstance(impersonate, str) and impersonate else "chrome",
166
+ )
167
+
168
+
169
+ def _download_via_stream(
170
+ url: str,
171
+ *,
172
+ name: str,
173
+ directory: Path,
174
+ limit: int,
175
+ timeout: float,
176
+ headers: dict[str, str] | None,
177
+ cookies: dict[str, str] | None,
178
+ impersonate: str,
179
+ ) -> dict[str, Any]:
180
+ """流式下载:逐块落盘并计哈希,内存占用与块同阶,与响应体大小无关。
181
+
182
+ 走 curl_cffi 而不是 Scrapling 的 Fetcher:后者的响应整体缓冲,大小上限只能在
183
+ 「全部读进内存之后」判,一条快链路足以在超时窗口内把进程内存顶爆。下载不需要
184
+ Scrapling 的解析层;impersonate 的默认档沿用它的 ``chrome``,代理表与重定向
185
+ 安全档与静态抓取共用同一份 guard 判定。
186
+ """
187
+ import guard
188
+ from curl_cffi import requests as curl_requests
189
+
190
+ session_kwargs: dict[str, Any] = {"impersonate": impersonate}
191
+ proxies = guard.proxies_for(url)
192
+ if proxies is not None:
193
+ session_kwargs["proxies"] = proxies
194
+ request_kwargs: dict[str, Any] = {
195
+ "timeout": float(timeout),
196
+ # 直连 curl_cffi 就用它的参数名:Scrapling 的 follow_redirects 是它自己翻成
197
+ # allow_redirects 的那一层(engines/static.py),这里没有翻译层可借。
198
+ "allow_redirects": "safe",
199
+ "stream": True,
200
+ }
201
+ if headers is not None:
202
+ request_kwargs["headers"] = headers
203
+ if cookies is not None:
204
+ request_kwargs["cookies"] = cookies
205
+ try:
206
+ session = curl_requests.Session(**session_kwargs)
207
+ except Exception as error:
208
+ raise _error("DOWNLOAD_FAILED", f"download failed: {type(error).__name__}") from error
209
+ try:
210
+ try:
211
+ response = session.request("GET", url, **request_kwargs)
212
+ except Exception as error:
213
+ raise _error("DOWNLOAD_FAILED", f"download failed: {type(error).__name__}") from error
214
+ try:
215
+ status = int(getattr(response, "status_code", 0))
216
+ if not 200 <= status < 300:
217
+ raise _error("DOWNLOAD_FAILED", f"download answered HTTP {status}")
218
+ declared = _header_value(response.headers, "Content-Length")
219
+ # 头部预检在正文传输之前给出结论;谎报长度的服务端由流式循环里的复核兜住。
220
+ if declared.isdigit() and int(declared) > limit:
221
+ raise _error(
222
+ "DOWNLOAD_TOO_LARGE",
223
+ f"download is {int(declared)} bytes by Content-Length, over the {limit}-byte cap",
224
+ )
225
+ digest = hashlib.sha256()
226
+ total = 0
227
+ temporary = _temp_path(directory, name)
228
+ try:
229
+ with open(temporary, "wb") as sink:
230
+ for chunk in response.iter_content(chunk_size=_DOWNLOAD_CHUNK_BYTES):
231
+ sink.write(chunk)
232
+ digest.update(chunk)
233
+ total += len(chunk)
234
+ if total > limit:
235
+ raise _error(
236
+ "DOWNLOAD_TOO_LARGE",
237
+ f"download is over the {limit}-byte cap"
238
+ + (f" (Content-Length declared {int(declared)})" if declared.isdigit() else ""),
239
+ )
240
+ target = _commit_temp(directory, name, temporary)
241
+ except BaseException:
242
+ temporary.unlink(missing_ok=True)
243
+ raise
244
+ return {
245
+ "path": str(target),
246
+ "bytes": total,
247
+ "sha256": digest.hexdigest(),
248
+ "contentType": _header_value(response.headers, "Content-Type"),
249
+ "status": status,
250
+ }
251
+ finally:
252
+ response.close()
253
+ finally:
254
+ session.close()
255
+
256
+
257
+ def _commit_bytes(directory: Path, name: str, body: bytes) -> Path:
258
+ """把一段已在内存里的字节落成正式名(浏览器路径):临时文件 + 占位 + 原子替换。"""
259
+ temporary = _temp_path(directory, name)
260
+ try:
261
+ temporary.write_bytes(body)
262
+ return _commit_temp(directory, name, temporary)
263
+ except BaseException:
264
+ temporary.unlink(missing_ok=True)
265
+ raise
266
+
267
+
268
+ def _download_via_browser(
269
+ url: str,
270
+ *,
271
+ name: str,
272
+ directory: Path,
273
+ limit: int,
274
+ timeout: float,
275
+ headers: dict[str, str] | None,
276
+ ) -> dict[str, Any]:
277
+ """浏览器路径的下载:Scrapling 的响应整体缓冲,没有流式出口。
278
+
279
+ 内存上界因此由 requestTimeoutSeconds 与链路吞吐共同决定;这一档是给「要 JS 才拿
280
+ 得到文件」的少数场景用的,静态路径(默认)已经是流式。
281
+ """
282
+ import guard
283
+
284
+ # 与 :func:`adapters.render` 同一条判据:浏览器路径必须显式挂上网络守卫与部署代理。
285
+ # 少了 ``page_setup``,重定向与页面子资源都不经过 guard.install 的 ``**/*`` 路由,
286
+ # 一条被下载链接重定向到内网的响应会绕过 url_allowed;少了 ``proxy``,配了代理的
287
+ # 机器上这条路径直连(Chromium 不读 HTTP_PROXY)。
288
+ from adapters import page_setup
289
+ from scrapling.fetchers import StealthyFetcher
290
+
291
+ browser_params: dict[str, Any] = {
292
+ "timeout": int(timeout * 1000),
293
+ "page_setup": page_setup,
294
+ }
295
+ proxy = guard.browser_proxy(url)
296
+ if proxy is not None:
297
+ browser_params["proxy"] = proxy
298
+ if headers is not None:
299
+ browser_params["extra_headers"] = headers
300
+ try:
301
+ response = StealthyFetcher.fetch(url, **browser_params)
302
+ except Exception as error:
303
+ raise _error("DOWNLOAD_FAILED", f"download failed: {type(error).__name__}") from error
304
+ status = int(getattr(response, "status", 0))
305
+ if not 200 <= status < 300:
306
+ raise _error("DOWNLOAD_FAILED", f"download answered HTTP {status}")
307
+ body = response.body
308
+ if not isinstance(body, (bytes, bytearray)):
309
+ raise _error("DOWNLOAD_FAILED", "download response had no byte body")
310
+ if len(body) > limit:
311
+ raise _error("DOWNLOAD_TOO_LARGE", f"download is {len(body)} bytes, over the {limit}-byte cap")
312
+ target = _commit_bytes(directory, name, bytes(body))
313
+ return {
314
+ "path": str(target),
315
+ "bytes": len(body),
316
+ "sha256": hashlib.sha256(bytes(body)).hexdigest(),
317
+ "contentType": _header_value(getattr(response, "headers", {}), "Content-Type"),
318
+ "status": status,
319
+ }
320
+
321
+
322
+ def _image_size(data: bytes, image_type: str) -> tuple[int, int]:
323
+ """从 PNG/JPEG 字节里读固有尺寸;读不出时给 (0, 0)。"""
324
+ if image_type == "png" and data[:8] == b"\x89PNG\r\n\x1a\n" and len(data) >= 24:
325
+ width, height = struct.unpack(">II", data[16:24])
326
+ return int(width), int(height)
327
+ if image_type == "jpeg":
328
+ index = 2
329
+ while index + 9 < len(data):
330
+ if data[index] != 0xFF:
331
+ index += 1
332
+ continue
333
+ marker = data[index + 1]
334
+ if marker in (0xC0, 0xC1, 0xC2, 0xC3):
335
+ height, width = struct.unpack(">HH", data[index + 5 : index + 9])
336
+ return int(width), int(height)
337
+ if marker in (0xD8, 0xD9) or 0xD0 <= marker <= 0xD7:
338
+ index += 2
339
+ continue
340
+ length = struct.unpack(">H", data[index + 2 : index + 4])[0]
341
+ index += 2 + length
342
+ return 0, 0
343
+
344
+
345
+ def screenshot(
346
+ session: Any,
347
+ *,
348
+ image_type: str,
349
+ full_page: bool,
350
+ quality: Any,
351
+ selector: str | None,
352
+ timeout_ms: int,
353
+ ) -> dict[str, Any]:
354
+ """对会话当前页或页内单个元素截图,返回 base64 与固有尺寸。"""
355
+ from session_page import _finish_page, _ready_page
356
+
357
+ if image_type not in ("png", "jpeg"):
358
+ raise _error("BAD_ARGS", "imageType must be png or jpeg")
359
+ if quality is not None and (not isinstance(quality, int) or isinstance(quality, bool) or not 1 <= quality <= 100):
360
+ raise _error("BAD_ARGS", "quality must be an integer from 1 to 100")
361
+ if quality is not None and image_type != "jpeg":
362
+ raise _error("BAD_ARGS", "quality only applies to jpeg screenshots")
363
+ if full_page and selector is not None:
364
+ raise _error("BAD_ARGS", "fullPage and selector cannot be combined")
365
+
366
+ page_info = _ready_page(session)
367
+ page = page_info.page
368
+ try:
369
+ if page.is_closed():
370
+ raise _error("PAGE_BUSY", "the session's page has been closed")
371
+ if selector is not None:
372
+ locator = page.locator(selector)
373
+ matches = locator.count()
374
+ if matches != 1:
375
+ raise _error("BAD_ARGS", f"selector must match exactly one element, matched {matches}")
376
+ # timeout 与整页那支同源:参数面声明了 timeoutMs,两条路径都得真生效。
377
+ data = locator.screenshot(
378
+ type=image_type,
379
+ timeout=timeout_ms,
380
+ **({"quality": quality} if quality else {}),
381
+ )
382
+ else:
383
+ data = page.screenshot(
384
+ type=image_type,
385
+ full_page=full_page,
386
+ **({"quality": quality} if quality else {}),
387
+ timeout=timeout_ms,
388
+ )
389
+ encoded = bytes(data)
390
+ width, height = _image_size(encoded, image_type)
391
+ return {
392
+ "base64": base64.b64encode(encoded).decode("ascii"),
393
+ "mediaType": "image/png" if image_type == "png" else "image/jpeg",
394
+ "width": width,
395
+ "height": height,
396
+ "url": str(page.url),
397
+ }
398
+ finally:
399
+ _finish_page(session.page_pool, page_info)
package/py/redact.py ADDED
@@ -0,0 +1,118 @@
1
+ """py/redact.py —— 把 URL 里像凭据的部分换成占位符。
2
+
3
+ guard 的日志与 adapters 的网络摘要在「给日志、给模型看」之前都要过这里。单独成模块
4
+ 是因为 guard 不能 import adapters(adapters 顶层 import guard,反过来就是环)。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
10
+
11
+ # 查询串里这些名字的参数装的是凭据而不是筛选条件。XHR 摘要与守卫日志都是要离开本进程的
12
+ # 文本——摘要进会话上下文、进第三方 provider,日志进宿主日志面——而真实站点把 access
13
+ # token、会话 id、签名都放在查询串里。抓到一条就等于把凭据抄进载体,而读者既用不上它、
14
+ # 也拦不住它被复述出来。值的部分一律换成固定占位符:定位接口靠的是路径与参数名,不是那个
15
+ # token。
16
+ _SECRET_QUERY_KEYS = frozenset(
17
+ {
18
+ "access_token",
19
+ "api_key",
20
+ "apikey",
21
+ "auth",
22
+ "auth_token",
23
+ "authorization",
24
+ "code",
25
+ "credential",
26
+ "id_token",
27
+ "key",
28
+ "password",
29
+ "pwd",
30
+ "refresh_token",
31
+ "secret",
32
+ "session",
33
+ "sessionid",
34
+ "session_id",
35
+ "sig",
36
+ "signature",
37
+ "sign",
38
+ "token",
39
+ }
40
+ )
41
+
42
+
43
+ def _redacted_query(text: str) -> str:
44
+ """把一段查询串里像凭据的参数值换成占位符;没有命中时原样返回。
45
+
46
+ 与 :func:`redact_url_secrets` 同一套参数名判据,片段也复用它 —— OAuth2 隐式流程把
47
+ 令牌放在 ``#access_token=`` 里,那同样是「离开本进程就等于抄出去」的凭据。
48
+
49
+ :param text: 查询串(或片段的查询部分)
50
+ :returns: 脱敏后的文本
51
+ """
52
+ if not text:
53
+ return text
54
+ pairs: list[tuple[str, str]] = []
55
+ changed = False
56
+ for name, value in parse_qsl(text, keep_blank_values=True):
57
+ if name.strip().lower() in _SECRET_QUERY_KEYS:
58
+ pairs.append((name, "<redacted>"))
59
+ changed = True
60
+ else:
61
+ pairs.append((name, value))
62
+ if not changed:
63
+ return text
64
+ return urlencode(pairs)
65
+
66
+
67
+ def _redacted_fragment(fragment: str) -> str:
68
+ """把片段里像查询串的那一段脱敏;没有命中时原样返回。
69
+
70
+ 片段有两种藏令牌的写法:OAuth2 隐式流程把整个片段当查询串(``#access_token=…``),
71
+ 单页应用的路由则是先路径后查询(``#!/list?token=…``)。两种都要覆盖。
72
+
73
+ :param fragment: URL 的 fragment 段
74
+ :returns: 脱敏后的 fragment
75
+ """
76
+ head, separator, query = fragment.partition("?")
77
+ if separator:
78
+ return f"{head}?{_redacted_query(query)}"
79
+ return _redacted_query(fragment)
80
+
81
+
82
+ def redact_url_secrets(raw: str) -> str:
83
+ """把 URL 里像凭据的部分替换成占位符。
84
+
85
+ 三处各藏一类凭据:查询串与片段的查询部分按**参数名**判(真实站点把 access token、
86
+ 会话 id、签名放在那里),authority 里的 ``user:pass@`` 整段丢掉(代理与 Basic 认证
87
+ 的接口都爱这么写)。值的部分一律换成固定占位符:定位接口靠的是路径与参数名,不是
88
+ 那个 token。
89
+
90
+ 只按参数名判断、不看值 —— 值本身无法可靠判定(短 token 与普通 id 长得一样)。
91
+ 认不出来的参数原样保留:把 ``?page=2`` 也涂掉只会让摘要失去意义,而那不是凭据。
92
+
93
+ :param raw: 原始 URL
94
+ :returns: 已脱敏的 URL;解析不出或没有可脱敏的部分时原样返回
95
+ """
96
+ try:
97
+ parsed = urlsplit(raw)
98
+ except ValueError:
99
+ return raw
100
+ # 没有 scheme 的 ``user:pass@host:8080`` 会被 urlsplit 读成 scheme='user'、
101
+ # path='pass@host:8080':netloc 为空,下面按 netloc 摘 userinfo 的那一步什么都不做,
102
+ # 整条代理口令于是原样漏进日志(PROXY_URL 不可用那条日志正是这么来的)。这种形态的
103
+ # authority 落在 path 的第一段上,按同一套规则摘掉;误读成 scheme 的那段一起丢弃。
104
+ authority, slash, rest = parsed.path.partition("/")
105
+ standalone_authority = not parsed.netloc and "@" in authority
106
+ if standalone_authority:
107
+ path = authority.rpartition("@")[2] + slash + rest
108
+ netloc = ""
109
+ else:
110
+ path = parsed.path
111
+ # rpartition 取最后一段:IPv6 字面量与端口都留在主机那一侧,只把用户信息摘掉。
112
+ netloc = parsed.netloc.rpartition("@")[2]
113
+ query = _redacted_query(parsed.query)
114
+ fragment = _redacted_fragment(parsed.fragment)
115
+ if path == parsed.path and netloc == parsed.netloc and query == parsed.query and fragment == parsed.fragment:
116
+ return raw
117
+ scheme = "" if standalone_authority else parsed.scheme
118
+ return urlunsplit((scheme, netloc, path, query, fragment))
@@ -0,0 +1,129 @@
1
+ """py/redis_storage.py —— Scrapling adaptive 指纹的 Redis 存储。
2
+
3
+ 上游只发 SQLite 一种具体实现,但把扩展点留成了 ``StorageSystemMixin`` 子类;
4
+ 它的文档里 Redis 就是这一档的示例。这里按同一个契约实现:键按
5
+ ``<prefix>:<注册域>:<sha256(identifier)>`` 落,值是该元素指纹的 orjson 串。
6
+
7
+ 两个约束来自上游 ``Selector`` 的装配代码:类必须用 ``lru_cache`` 包一层
8
+ (它检查 ``__wrapped__``),且构造参数必须全从 ``storage_args`` 来。因此这里的
9
+ ``__init__`` 只收可序列化的值;测试要注入替身客户端时才用 ``client_factory``。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from functools import lru_cache
15
+ from threading import RLock
16
+ from typing import Any, Callable, Optional
17
+ from urllib.parse import urlsplit
18
+
19
+ from scrapling.core.storage import StorageSystemMixin
20
+
21
+ DEFAULT_REDIS_URL = "redis://127.0.0.1:6379/0"
22
+ KEY_PREFIX = "scrapling:adaptive"
23
+ DEFAULT_TIMEOUT_SECONDS = 2.0
24
+
25
+
26
+ class RedisUnavailable(RuntimeError):
27
+ """Redis 不可用或客户端缺失;调用方把它翻成带码的失败。"""
28
+
29
+
30
+ def redacted_redis_url(raw: str) -> str:
31
+ """去掉 userinfo 的展示形式:口令不进日志、不进错误消息。"""
32
+ try:
33
+ parts = urlsplit(raw)
34
+ except ValueError:
35
+ return "redis://<invalid>"
36
+ host = parts.hostname or "<invalid>"
37
+ port = f":{parts.port}" if parts.port is not None else ""
38
+ database = parts.path or ""
39
+ return f"{parts.scheme or 'redis'}://{host}{port}{database}"
40
+
41
+
42
+ def _default_client(redis_url: str, *, timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS) -> Any:
43
+ try:
44
+ from redis import Redis
45
+ except ModuleNotFoundError as error:
46
+ # 没装客户端是**部署**的问题,不是抓取失败:点名的错误让人知道该装 adaptive-redis 包。
47
+ raise RedisUnavailable(
48
+ "the redis client is missing; install the adaptive-redis pack (pip install redis)"
49
+ ) from error
50
+ # 超时要真的交给客户端:早先它只落在 self.timeout_seconds 上、全文件没有使用点,于是
51
+ # socket 超时一直是客户端自己的默认值(连接卡住时表现为整场抓取挂死)。
52
+ return Redis.from_url(
53
+ redis_url,
54
+ decode_responses=True,
55
+ socket_timeout=timeout_seconds,
56
+ socket_connect_timeout=timeout_seconds,
57
+ )
58
+
59
+
60
+ @lru_cache(1, typed=True)
61
+ class RedisStorageSystem(StorageSystemMixin):
62
+ """以 Redis 为后端的 adaptive 指纹库。
63
+
64
+ 与 ``SQLiteStorageSystem`` 同契约:``save(element, identifier)`` /
65
+ ``retrieve(identifier)``;``_get_base_url`` 由上游 mixin 提供(按注册域分桶)。
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ redis_url: str = DEFAULT_REDIS_URL,
71
+ url: Optional[str] = None,
72
+ *,
73
+ prefix: str = KEY_PREFIX,
74
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
75
+ client_factory: Callable[..., Any] = _default_client,
76
+ ) -> None:
77
+ # redis 客户端是可选件,导入放在 _default_client 里;本模块本身只依赖 scrapling。
78
+ super().__init__(url)
79
+ self.redis_url = redis_url
80
+ self.prefix = prefix
81
+ self.timeout_seconds = timeout_seconds
82
+ self._lock = RLock()
83
+ try:
84
+ self._client = client_factory(redis_url, timeout_seconds=timeout_seconds)
85
+ self._client.ping()
86
+ except RedisUnavailable:
87
+ raise
88
+ except Exception as error: # 连接失败的种类由客户端决定
89
+ raise RedisUnavailable(
90
+ f"redis is not reachable at {redacted_redis_url(redis_url)}: {type(error).__name__}"
91
+ ) from error
92
+
93
+ def _key(self, identifier: str) -> str:
94
+ bucket = self._get_base_url()
95
+ digest = self._get_hash(identifier)
96
+ return f"{self.prefix}:{bucket}:{digest}"
97
+
98
+ def save(self, element: Any, identifier: str) -> None:
99
+ from orjson import dumps
100
+ from scrapling.core.utils import _StorageTools
101
+
102
+ payload = dumps(_StorageTools.element_to_dict(element)).decode("utf-8")
103
+ try:
104
+ with self._lock:
105
+ self._client.set(self._key(identifier), payload)
106
+ except Exception as error:
107
+ raise RedisUnavailable(
108
+ f"redis write failed at {redacted_redis_url(self.redis_url)}: {type(error).__name__}"
109
+ ) from error
110
+
111
+ def retrieve(self, identifier: str) -> Optional[dict[str, Any]]:
112
+ from orjson import loads
113
+
114
+ try:
115
+ with self._lock:
116
+ raw = self._client.get(self._key(identifier))
117
+ except Exception as error:
118
+ raise RedisUnavailable(
119
+ f"redis read failed at {redacted_redis_url(self.redis_url)}: {type(error).__name__}"
120
+ ) from error
121
+ if raw is None:
122
+ return None
123
+ return loads(raw)
124
+
125
+ def close(self) -> None:
126
+ with self._lock:
127
+ close = getattr(self._client, "close", None)
128
+ if callable(close):
129
+ close()