crawlrs 0.2.0

crawlrs - Enterprise-grade web scraping and crawling platform built with Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! 引擎层 DTO 类型定义
//!
//! 包含 `EngineClient` 的请求/响应 DTO、配置类型和内部引擎接口类型。
//! 从 `engine_client.rs` 拆分而来(ARC-002),降低单文件复杂度。

use crate::common::CacheMode;
use log::warn;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Duration;

// HttpMethod 已提升至 `common::http_method`(消除
// 原 `infrastructure::oxcache::cache_mode`(现已提升至 `common::cache_mode`)对 `engines` 层的反向依赖)。
// 此处 `pub use` 重新导出,保持与 `ScrapeRequest` / `ScrapeOptions` 等
// 引擎类型的协同导入路径(符合代码库既有 `pub use crate::...` 惯例)。
pub use crate::common::HttpMethod;

/// Unified request structure for scraping operations.
///
/// This is the canonical request type for all scraping operations through EngineClient.
/// Callers should use this structure instead of interacting with engines directly.
#[derive(Debug, Clone)]
pub struct ScrapeRequest {
    /// The target URL to scrape
    pub url: String,
    /// Optional configuration for the scrape operation
    pub options: ScrapeOptions,
}

impl ScrapeRequest {
    /// Create a new scrape request with required URL and default options.
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            options: ScrapeOptions::default(),
        }
    }

    /// Create a request with a URL and custom options builder.
    pub fn with_options(mut self, options: ScrapeOptions) -> Self {
        self.options = options;
        self
    }

    /// Configure the request to require JavaScript rendering.
    pub fn needs_js(mut self) -> Self {
        self.options.needs_js = true;
        self
    }

    /// Configure the request to require a screenshot.
    pub fn needs_screenshot(mut self) -> Self {
        self.options.needs_screenshot = true;
        self
    }

    /// Configure the request to use a mobile user agent.
    pub fn mobile(mut self) -> Self {
        self.options.mobile = true;
        self
    }

    /// Set a custom timeout for the request.
    pub fn timeout(mut self, duration: Duration) -> Self {
        self.options.timeout = duration;
        self
    }

    /// Configure the request to use MLLM autonomous navigation .
    pub fn needs_mllm(mut self) -> Self {
        self.options.needs_mllm = true;
        self
    }
}

/// session_id 最大长度(字节)— 防止 DoS
///
/// 限制 ProxyPool::sticky 的 DashMap key 长度,防止恶意超长 session_id
/// 导致内存耗尽。128 字节对绝大多数会话标识场景足够。
pub const MAX_SESSION_ID_LEN: usize = 128;

/// 校验 session_id 是否合法
///
/// # 校验规则
///
/// - 长度 <= [`MAX_SESSION_ID_LEN`] 字节
/// - 字符集为可打印 ASCII(0x20-0x7E),排除控制字符
///
/// # 防护
///
/// - 超长字符串 → 防止 DashMap key 内存耗尽(DoS)
/// - 控制字符/换行符 → 防止日志注入(CWE-117)
///
/// # 返回
///
/// - `true`:合法
/// - `false`:非法
#[must_use]
pub fn validate_session_id(session_id: &str) -> bool {
    if session_id.len() > MAX_SESSION_ID_LEN {
        return false;
    }
    session_id.bytes().all(|b| (0x20..=0x7E).contains(&b))
}

/// 页面加载后等待策略
///
/// 三种模式:
/// - [`WaitFor::NetworkIdle`]:等待网络空闲(无新请求持续 500ms)
/// - `WaitFor::Selector(String)`:等待指定 CSS selector 出现在 DOM 中
/// - `WaitFor::DomStable(Duration)`:等待 DOM 稳定(无变化持续指定时长)
///
/// # 设计动机
///
/// 原有 `sync_wait_ms` 是固定 sleep,无论页面是否就绪都阻塞相同时间。
/// `WaitFor` 提供条件式等待:满足条件立即返回,超时返回错误,避免无谓阻塞。
/// 在 Playwright 引擎中替代 `sync_wait_ms` 的固定 sleep 逻辑。
///
/// # 实现
///
/// 枚举本身不依赖 `chromiumoxide`,可被非浏览器引擎代码持有。
/// `wait` 方法的实现在 `engines/wait.rs`(`engine-playwright` feature 门控),
/// 依赖 `chromiumoxide::Page`。
///
/// # 安全性
///
/// `Selector` 模式对 selector 字符串做 JS 字符串转义,防注入(CWE-94)。
/// `DomStable` 的 `stable_duration` 上限 60s,防恶意调用方设置过长导致 DoS。
#[derive(Debug, Clone, PartialEq, Default, Serialize)]
pub enum WaitFor {
    /// 等待网络空闲(无新请求持续 500ms)
    ///
    /// chromiumoxide 的 `goto` 已等待 load 事件,此处额外等待确保异步请求完成。
    /// 引擎实现语义有差:Playwright 观察网络事件;moli 为 readyState=complete +
    /// 固定静默窗的近似(见 engines/client/moli.rs),SPA 的 load 后 XHR 突发场景
    /// 下弱于本契约——需要精确语义时用 Selector/DomStable 显式指定。
    #[default]
    NetworkIdle,
    /// 等待指定 CSS selector 出现在 DOM 中
    ///
    /// selector 字符串会在 JS 中转义,防注入。
    Selector(String),
    /// 等待 DOM 稳定(无变化持续指定时长)
    ///
    /// 通过轮询 `document.body.innerHTML.length` 比较,若连续 `stable_duration`
    /// 内长度不变则视为稳定。`stable_duration` 上限 60s。
    DomStable(Duration),
    /// 等待某响应 URL 匹配 regex(吸收 moli `--wait-response-url` 语义)
    ///
    /// `pattern` 为 [regex crate](https://docs.rs/regex) 语法,在桥接层
    /// (`ScrapeRequest::to_internal`)前置编译校验,非法 regex 请求被拒不入队。
    /// 引擎支持面:Playwright 监听 CDP 响应事件;moli 的 CDP Network 事件面
    /// 实测不可达(见 scripts/poc/moli/network-probe-output.txt),对其返回
    /// `EngineError::Unsupported`——不静默吞变体。
    ResponseUrl(String),
    /// 等待某响应体包含指定文本(吸收 moli `--wait-response-body` 语义)
    ///
    /// 按子串包含匹配响应体;单响应体匹配检查上限 10 MiB(对齐默认
    /// `max_response_body_bytes`),超出跳过不做全量缓冲。
    ResponseBody(String),
}

/// Optional configuration for scrape operations.
///
/// `Serialize` 供请求身份指纹(`workers::request_identity`)对完整请求身份做确定性指纹:
/// 新增字段会自动进入指纹,避免同 URL 不同选项的请求被错误合并。
/// 例外:`cache_mode` 本身是缓存/合并控制开关,指纹计算时归一为 `None`;
/// 合并键另行叠加由它派生的 `cache_read_allowed` 布尔投影(见
/// `workers::request_identity::coalesce_fingerprint`)。
#[derive(Debug, Clone, Serialize)]
pub struct ScrapeOptions {
    /// HTTP method for the request
    pub method: HttpMethod,
    /// Whether JavaScript rendering is required (default: false)
    pub needs_js: bool,
    /// Whether screenshot capture is required (default: false)
    pub needs_screenshot: bool,
    /// Whether to use mobile user agent (default: false)
    pub mobile: bool,
    /// Request timeout duration (default: 30 seconds)
    pub timeout: Duration,
    /// Optional request body
    pub body: Option<String>,
    /// Sync wait duration in milliseconds after page load (default: 0)
    pub sync_wait_ms: u32,
    /// Page actions to perform (clicks, scrolls, etc.)
    pub actions: Vec<PageAction>,
    /// Screenshot configuration
    pub screenshot_config: Option<ScreenshotConfig>,
    /// Proxy URL (optional)
    pub proxy: Option<String>,
    /// Skip TLS verification (default: false)
    pub skip_tls_verification: bool,
    /// Custom HTTP headers (default: empty)
    pub headers: HashMap<String, String>,
    /// Enable TLS fingerprinting for anti-fingerprinting (default: false)
    pub needs_tls_fingerprint: bool,
    /// Force use of Fire Engine (CDP) for this request (default: false)
    pub use_fire_engine: bool,
    /// Block ad / tracker domains via CDP Fetch request interception (default: false)
    ///
    /// 当为 true 且使用浏览器引擎时,启用广告/追踪域名黑名单拦截,
    /// 命中 [`crate::engines::intercept::AD_DOMAIN_BLACKLIST`] 的请求将被 `Fetch.failRequest` 中止。
    pub block_ads: bool,
    /// Block media resources (image/media/font) via CDP Fetch interception (default: false)
    ///
    /// 当为 true 且使用浏览器引擎时,启用媒体资源类型拦截,
    /// CDP `ResourceType::{Image, Media, Font}` 的请求将被 `Fetch.failRequest` 中止。
    pub block_media: bool,
    /// 粘性会话 ID(用于 ProxyStrategy::Sticky 时调用 ProxyProvider::sticky)
    ///
    /// 调用方在需要粘性会话(同一会话固定走同一代理)时设置。
    /// `None` 时按 `ProxyStrategy::RoundRobin` 走 `ProxyProvider::next`。
    pub session_id: Option<String>,
    /// 缓存模式
    ///
    /// 控制本次抓取的缓存读写行为。`None`(默认)等价于 `Some(CacheMode::Enabled)`,
    /// 由 `scrape_worker` 在读写 `CacheService` 前经 `CacheContext` 门控。
    ///
    /// 5 种模式详见 [`crate::common::CacheMode`]。
    pub cache_mode: Option<CacheMode>,
    /// 页面加载后等待策略
    ///
    /// 仅浏览器引擎(Playwright)生效。`None`(默认)时 Playwright 使用
    /// [`WaitFor::NetworkIdle`](与原 `sync_wait_ms` 默认 1 秒等待语义一致)。
    ///
    /// 设置后**替代** Playwright 中基于 `sync_wait_ms` 的固定 sleep 逻辑:
    /// 满足条件立即返回,超时返回 `EngineError::BrowserError`。
    ///
    /// `sync_wait_ms` 字段保留供非浏览器引擎(如 FlareSolverr)使用。
    pub wait_for: Option<WaitFor>,
    /// MLLM 自主导航模式由 `engine-mllm` feature 门控
    ///
    /// 为 true 时路由优先选择 MllmEngine,通过视觉大模型分析截图自主导航。
    pub needs_mllm: bool,
}

impl Default for ScrapeOptions {
    fn default() -> Self {
        Self {
            method: HttpMethod::Get,
            needs_js: false,
            needs_screenshot: false,
            mobile: false,
            timeout: Duration::from_secs(30),
            body: None,
            sync_wait_ms: 0,
            actions: Vec::new(),
            screenshot_config: None,
            proxy: None,
            skip_tls_verification: false,
            headers: HashMap::new(),
            needs_tls_fingerprint: false,
            use_fire_engine: false,
            block_ads: false,
            block_media: false,
            session_id: None,
            cache_mode: None,
            wait_for: None,
            needs_mllm: false,
        }
    }
}

impl ScrapeOptions {
    /// Create options builder.
    pub fn builder() -> ScrapeOptionsBuilder {
        ScrapeOptionsBuilder::default()
    }
}

/// Builder for ScrapeOptions.
#[derive(Debug, Clone, Default)]
pub struct ScrapeOptionsBuilder(ScrapeOptions);

impl ScrapeOptionsBuilder {
    pub fn method(mut self, method: HttpMethod) -> Self {
        self.0.method = method;
        self
    }

    pub fn needs_js(mut self, enabled: bool) -> Self {
        self.0.needs_js = enabled;
        self
    }

    pub fn needs_screenshot(mut self, enabled: bool) -> Self {
        self.0.needs_screenshot = enabled;
        self
    }

    pub fn mobile(mut self, enabled: bool) -> Self {
        self.0.mobile = enabled;
        self
    }

    pub fn timeout(mut self, duration: Duration) -> Self {
        self.0.timeout = duration;
        self
    }

    pub fn body(mut self, body: impl Into<String>) -> Self {
        self.0.body = Some(body.into());
        self
    }

    pub fn sync_wait_ms(mut self, ms: u32) -> Self {
        self.0.sync_wait_ms = ms;
        self
    }

    pub fn proxy(mut self, proxy: impl Into<String>) -> Self {
        self.0.proxy = Some(proxy.into());
        self
    }

    /// Configure whether to skip TLS certificate verification.
    ///
    /// # Security Warning
    ///
    /// Skipping TLS verification is **FORBIDDEN** in production environments.
    /// This option is only available in development/test environments for testing purposes.
    ///
    /// In production, attempting to skip TLS verification will:
    /// - Log a security warning
    /// - Ignore the skip request (TLS verification remains enabled)
    ///
    /// # Arguments
    ///
    /// * `skip` - Whether to skip TLS verification (ignored in production)
    ///
    /// # Returns
    ///
    /// Returns the builder with TLS verification settings applied.
    pub fn skip_tls_verification(mut self, skip: bool) -> Self {
        if skip {
            // Check environment - use both APP_ENVIRONMENT and CRAWLRS_ENV for compatibility
            let env = std::env::var("APP_ENVIRONMENT")
                .or_else(|_| std::env::var("CRAWLRS_ENV"))
                .unwrap_or_else(|_| "development".to_string());

            let is_production =
                env.eq_ignore_ascii_case("production") || env.eq_ignore_ascii_case("prod");

            if is_production {
                // SECURITY: Reject TLS verification skip in production
                warn!(
                    target: "security",
                    "SECURITY ALERT: Attempt to skip TLS verification in production environment '{}' - DENIED. \
                     TLS verification will remain enabled to prevent man-in-the-middle attacks.",
                    env
                );
                // Return without modifying the setting - TLS verification stays enabled
                return self;
            }

            // Allow skip in non-production environments with warning
            warn!(
                target: "security",
                "TLS certificate verification disabled in '{}' environment. \
                 This should ONLY be used for testing purposes. \
                 NEVER disable TLS verification in production as it enables man-in-the-middle attacks.",
                env
            );
        }
        self.0.skip_tls_verification = skip;
        self
    }

    pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
        self.0.headers = headers;
        self
    }

    pub fn needs_tls_fingerprint(mut self, enabled: bool) -> Self {
        self.0.needs_tls_fingerprint = enabled;
        self
    }

    pub fn use_fire_engine(mut self, enabled: bool) -> Self {
        self.0.use_fire_engine = enabled;
        self
    }

    pub fn screenshot_config(mut self, config: ScreenshotConfig) -> Self {
        self.0.screenshot_config = Some(config);
        self
    }

    /// Enable/disable ad & tracker domain blocking via CDP Fetch interception .
    pub fn block_ads(mut self, enabled: bool) -> Self {
        self.0.block_ads = enabled;
        self
    }

    /// Enable/disable media resource (image/media/font) blocking via CDP Fetch interception .
    pub fn block_media(mut self, enabled: bool) -> Self {
        self.0.block_media = enabled;
        self
    }

    /// 设置粘性会话 ID(用于 ProxyStrategy::Sticky)
    ///
    /// 调用方在需要粘性会话(同一会话固定走同一代理)时设置。
    /// `None` 时按 `ProxyStrategy::RoundRobin` 走 `ProxyProvider::next`。
    ///
    /// # 安全校验
    ///
    /// - 长度上限:[`MAX_SESSION_ID_LEN`] 字节(128)
    /// - 字符集:可打印 ASCII(0x20-0x7E),排除控制字符
    ///
    /// 非法输入(超长或含控制字符)会被拒绝并记录 warn 日志,`session_id` 保持 `None`。
    /// 防止 DoS(超长字符串填充 sticky binding map)和日志注入(CWE-117)。
    pub fn session_id(mut self, session_id: impl Into<String>) -> Self {
        let sid = session_id.into();
        if validate_session_id(&sid) {
            self.0.session_id = Some(sid);
        } else {
            warn!(
                "session_id rejected (length={}, max={}, must be printable ASCII); \
                 falling back to None (RoundRobin)",
                sid.len(),
                MAX_SESSION_ID_LEN
            );
        }
        self
    }

    pub fn build(self) -> ScrapeOptions {
        self.0
    }

    /// 启用 MLLM 自主导航模式
    ///
    /// 为 true 时路由优先选择 MllmEngine,通过视觉大模型分析截图自主导航。
    pub fn needs_mllm(mut self, enabled: bool) -> Self {
        self.0.needs_mllm = enabled;
        self
    }

    /// 设置缓存模式
    ///
    /// `None`(默认)等价于 `Some(CacheMode::Enabled)`。
    /// 详见 [`crate::common::CacheMode`]。
    pub fn cache_mode(mut self, mode: impl Into<Option<CacheMode>>) -> Self {
        self.0.cache_mode = mode.into();
        self
    }

    /// 设置页面加载后等待策略
    ///
    /// 仅浏览器引擎(Playwright)生效。`None` 时使用 [`WaitFor::NetworkIdle`]。
    /// 详见 [`WaitFor`]。
    #[must_use]
    pub fn wait_for(mut self, wait: impl Into<Option<WaitFor>>) -> Self {
        self.0.wait_for = wait.into();
        self
    }
}

/// Page action to perform during scraping.
#[derive(Debug, Clone, Serialize)]
pub enum PageAction {
    /// Wait for specified milliseconds
    Wait { milliseconds: u64 },
    /// Click element by CSS selector
    Click { selector: String },
    /// Scroll in direction
    Scroll { direction: ScrollDirection },
    /// Input text into element
    Input { selector: String, text: String },
}

/// Scroll direction for PageAction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
pub enum ScrollDirection {
    #[default]
    Down,
    Up,
    Bottom,
    Top,
}

/// Screenshot configuration.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ScreenshotConfig {
    /// Capture full page (default: true)
    pub full_page: bool,
    /// CSS selector for element-specific screenshot
    pub selector: Option<String>,
    /// Image quality 1-100 (for JPEG, default: 80)
    pub quality: Option<u8>,
    /// Image format (default: "jpeg")
    pub format: Option<String>,
}

impl Default for ScreenshotConfig {
    fn default() -> Self {
        Self {
            full_page: true,
            selector: None,
            quality: Some(80),
            format: Some("jpeg".to_string()),
        }
    }
}

/// Playwright 捕获的 XHR/Fetch 后台响应(公共输出形态)
///
/// 仅当 Playwright 引擎启用 `capture_xhr` 时非空;随 `ScrapeResponse`
/// 序列化输出(空 Vec 不出现在 JSON)。
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CapturedResponse {
    /// 触发响应的请求 URL
    pub url: String,
    /// 响应 HTTP 状态码
    pub status: u16,
    /// 响应 MIME 类型(CDP `Response.mimeType`,如 `application/json`)
    pub mime_type: String,
    /// 响应体(base64 已解码;二进制按 UTF-8 lossy 转换)
    pub body: String,
}

/// Unified response structure for scraping operations.
///
/// This is the canonical response type returned by EngineClient.
///
/// 实现 `Serialize`/`Deserialize` 以支持 `scrape_worker`
/// 缓存门控——抓取成功后序列化为 JSON 字符串写入 `CacheService`,
/// 读缓存命中时反序列化还原为 `ScrapeResponse` 直返,跳过实际抓取。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScrapeResponse {
    /// HTTP status code
    pub status_code: u16,
    /// Response content (HTML or extracted text)
    pub content: String,
    /// Base64-encoded screenshot (if requested)
    pub screenshot: Option<String>,
    /// Response content type
    pub content_type: String,
    /// Response headers
    pub headers: HashMap<String, String>,
    /// Time taken to complete request in milliseconds
    pub response_time_ms: u64,
    /// Final URL after any redirects
    pub final_url: Option<String>,
    /// Markdown 转换结果
    ///
    /// 仅当请求 `formats` 含 `"markdown"` 且 `markdown` 特性启用时由
    /// `scrape_worker` 填充;其余情况为 `None`,对老调用方透明。
    pub markdown: Option<String>,
    /// XHR/Fetch 后台响应捕获结果
    ///
    /// 仅 Playwright 引擎在 `capture_xhr` 启用时非空;其余引擎为空。
    /// `default` + `skip_serializing_if` 保证空捕获不出现在 JSON,
    /// 且旧缓存条目(无此字段)可正常反序列化。
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub captured_responses: Vec<CapturedResponse>,
    /// JS 降级标记(内存水位调度)
    ///
    /// 内存水位 Critical 且无可用 JS 引擎时按 `fallback_to_static` 回退静态抓取置
    /// `Some(true)`;其余情况 `None`——JSON 不出现该字段,旧缓存条目可正常反序列化。
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub js_degraded: Option<bool>,
}

impl ScrapeResponse {
    /// Create a new response.
    pub fn new(
        status_code: u16,
        content: impl Into<String>,
        content_type: impl Into<String>,
    ) -> Self {
        Self {
            status_code,
            content: content.into(),
            screenshot: None,
            content_type: content_type.into(),
            headers: HashMap::new(),
            response_time_ms: 0,
            final_url: None,
            markdown: None,
            captured_responses: Vec::new(),
            js_degraded: None,
        }
    }

    /// Check if the request was successful (2xx status code).
    pub fn is_success(&self) -> bool {
        (200..300).contains(&self.status_code)
    }
}

// === Internal Request/Response Types for Router ===
// These are used internally by EngineRouter and engines

/// Internal request type for engine operations
#[derive(Debug, Clone)]
pub struct InternalScrapeRequest {
    pub url: String,
    pub method: HttpMethod,
    pub headers: HashMap<String, String>,
    pub timeout: Duration,
    pub needs_js: bool,
    pub needs_screenshot: bool,
    pub screenshot_config: Option<InternalScreenshotConfig>,
    pub mobile: bool,
    pub proxy: Option<String>,
    pub skip_tls_verification: bool,
    pub needs_tls_fingerprint: bool,
    pub use_fire_engine: bool,
    pub actions: Vec<InternalPageAction>,
    pub body: Option<String>,
    pub sync_wait_ms: u32,
    /// 广告/追踪域名拦截开关(仅浏览器引擎生效)
    pub block_ads: bool,
    /// 媒体资源类型拦截开关(仅浏览器引擎生效)
    pub block_media: bool,
    /// 粘性会话 ID(用于 ProxyStrategy::Sticky 时调用 ProxyProvider::sticky)
    ///
    /// 通过 `ScrapeRequest::to_internal` 从 `ScrapeOptions.session_id` 桥接而来。
    pub session_id: Option<String>,
    /// 页面加载后等待策略
    ///
    /// 通过 `ScrapeRequest::to_internal` 从 `ScrapeOptions.wait_for` 桥接而来。
    /// 仅浏览器引擎(Playwright)消费;`None` 时 Playwright 使用 [`WaitFor::NetworkIdle`]。
    pub wait_for: Option<WaitFor>,
    /// MLLM 自主导航模式
    pub needs_mllm: bool,
}

/// Internal screenshot configuration
#[derive(Debug, Clone)]
pub struct InternalScreenshotConfig {
    pub full_page: bool,
    pub selector: Option<String>,
    pub quality: Option<u8>,
    pub format: Option<String>,
}

/// Internal page action for engine operations
#[derive(Debug, Clone)]
pub enum InternalPageAction {
    Wait { milliseconds: u64 },
    Click { selector: String },
    Scroll { direction: String },
    Input { selector: String, text: String },
    Screenshot { full_page: bool },
}

/// Internal response type for engine operations
#[derive(Debug, Clone, Default)]
pub struct InternalScrapeResponse {
    pub status_code: u16,
    pub content: String,
    pub screenshot: Option<String>,
    pub content_type: String,
    pub headers: HashMap<String, String>,
    pub response_time_ms: u64,
    /// 引擎实际得到的最终 URL(重定向 / 浏览器页面导航后)。
    /// `None` 表示引擎未提供,`to_public` 回退为原始请求 URL。
    pub final_url: Option<String>,
    /// XHR/Fetch 后台响应捕获结果
    ///
    /// 仅 PlaywrightEngine 在 `capture_xhr` 启用时填充;其余引擎为空
    /// (`Default` 派生使构造点可零改动透传空值)。
    pub captured_responses: Vec<InternalCapturedResponse>,
    /// JS 降级标记(内存水位调度)
    ///
    /// 内存水位 Critical 且无可用 JS 引擎时按 `fallback_to_static` 回退静态抓取置 `true`;
    /// 其余路径恒 `false`(`Default` 派生使构造点可零改动透传)。
    pub js_degraded: bool,
}

/// Internal captured XHR/Fetch response
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct InternalCapturedResponse {
    pub url: String,
    pub status: u16,
    pub mime_type: String,
    pub body: String,
}

/// Convert from public ScrapeRequest to internal format
impl ScrapeRequest {
    /// 桥接为引擎内部请求;`ResponseUrl` 变体的 regex 在此前置编译校验
    /// (非法 regex 返回错误,请求不进入引擎——输入校验前置,不在引擎内编译)。
    #[inline]
    pub(crate) fn to_internal(
        &self,
    ) -> Result<InternalScrapeRequest, crate::engines::engine_client::EngineError> {
        if let Some(crate::engines::engine_client::WaitFor::ResponseUrl(pattern)) =
            &self.options.wait_for
        {
            if let Err(e) = regex::Regex::new(pattern) {
                return Err(crate::engines::engine_client::EngineError::InvalidUrl(
                    format!("wait_for_response_url regex invalid: {}", e),
                ));
            }
        }
        let options = &self.options;

        let internal = InternalScrapeRequest {
            url: self.url.clone(),
            method: options.method,
            headers: options.headers.clone(),
            timeout: options.timeout,
            needs_js: options.needs_js,
            needs_screenshot: options.needs_screenshot,
            screenshot_config: options
                .screenshot_config
                .as_ref()
                .map(convert_screenshot_config),
            mobile: options.mobile,
            proxy: options.proxy.clone(),
            skip_tls_verification: options.skip_tls_verification,
            needs_tls_fingerprint: options.needs_tls_fingerprint,
            use_fire_engine: options.use_fire_engine,
            actions: convert_page_actions(&options.actions),
            body: options.body.clone(),
            sync_wait_ms: options.sync_wait_ms,
            block_ads: options.block_ads,
            block_media: options.block_media,
            session_id: resolve_session_id(&options.session_id),
            wait_for: options.wait_for.clone(),
            needs_mllm: options.needs_mllm,
        };
        Ok(internal)
    }
}

/// 公开页动作 → 引擎内部页动作(逐字段克隆,无行为改动)。
fn convert_page_actions(actions: &[PageAction]) -> Vec<InternalPageAction> {
    actions
        .iter()
        .map(|action| match action {
            PageAction::Wait { milliseconds } => InternalPageAction::Wait {
                milliseconds: *milliseconds,
            },
            PageAction::Click { selector } => InternalPageAction::Click {
                selector: selector.clone(),
            },
            PageAction::Scroll { direction } => {
                let direction_str = match direction {
                    ScrollDirection::Down => "down",
                    ScrollDirection::Up => "up",
                    ScrollDirection::Bottom => "bottom",
                    ScrollDirection::Top => "top",
                };
                InternalPageAction::Scroll {
                    direction: direction_str.to_string(),
                }
            }
            PageAction::Input { selector, text } => InternalPageAction::Input {
                selector: selector.clone(),
                text: text.clone(),
            },
        })
        .collect()
}

/// 公开截图配置 → 引擎内部截图配置。
fn convert_screenshot_config(config: &ScreenshotConfig) -> InternalScreenshotConfig {
    InternalScreenshotConfig {
        full_page: config.full_page,
        selector: config.selector.clone(),
        quality: config.quality,
        format: config.format.clone(),
    }
}

/// 校验并归一化 session_id(非法值降级为 `None`,保留告警)。
///
/// `to_internal` 二次校验 session_id
/// 防用户绕过 builder 直接构造 ScrapeOptions 注入非法 session_id
///(超长字符串 DoS / 控制字符日志注入 CWE-117)。
fn resolve_session_id(session_id: &Option<String>) -> Option<String> {
    match session_id {
        Some(sid) if validate_session_id(sid) => Some(sid.clone()),
        Some(sid) => {
            warn!(
                "session_id rejected in to_internal (length={}, max={}, \
                 must be printable ASCII); falling back to None (RoundRobin)",
                sid.len(),
                MAX_SESSION_ID_LEN
            );
            None
        }
        None => None,
    }
}

/// Convert from internal ScrapeResponse to public format
impl InternalScrapeResponse {
    #[inline]
    pub fn to_public(&self, _original_url: &str) -> ScrapeResponse {
        ScrapeResponse {
            status_code: self.status_code,
            content: self.content.clone(),
            screenshot: self.screenshot.clone(),
            content_type: self.content_type.clone(),
            headers: self.headers.clone(),
            response_time_ms: self.response_time_ms,
            // 只转发引擎实际报告的最终 URL;不得用请求 URL 伪造——上游把
            // final_url 当作“实际落点”用于安全判定(如团队域名黑名单复核),
            // 伪造会让检查静默放行。None 由消费方按 fail-closed 处理。
            final_url: self.final_url.clone(),
            markdown: None,
            captured_responses: self
                .captured_responses
                .iter()
                .map(|c| CapturedResponse {
                    url: c.url.clone(),
                    status: c.status,
                    mime_type: c.mime_type.clone(),
                    body: c.body.clone(),
                })
                .collect(),
            js_degraded: if self.js_degraded { Some(true) } else { None },
        }
    }
}