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
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

use crate::engines::client::reqwest::ReqwestEngine;
use crate::engines::engine_client::{EngineClient, ScrapeOptions, ScrapeRequest};
use crate::engines::router::{EngineRouter, EngineRouterTrait};
use crate::search::engine_trait::{SearchEngine, SearchRequest};
use anyhow::Result;
use std::sync::Arc;

#[derive(Debug, Default, Clone)]
pub struct TestResult {
    pub total: usize,
    pub accessible: usize,
    pub inaccessible: usize,
}

pub async fn run_engine_test_with_output<E: SearchEngine>(
    name: &str,
    engine: E,
    query: Option<&str>,
    timeout_secs: u64,
    limit: Option<u32>,
) -> Result<TestResult> {
    use tokio::time::timeout;

    let start_time = std::time::Instant::now();
    let query_str = query.unwrap_or("test query");

    let request = SearchRequest::new(query_str).with_limit(limit.unwrap_or(10));

    let result = timeout(
        std::time::Duration::from_secs(timeout_secs),
        engine.search(&request),
    )
    .await;

    let elapsed = start_time.elapsed();

    let engine_client = build_test_engine_client();

    match result {
        Ok(Ok(response)) => {
            let total = response.items.len();
            let mut accessible = 0;
            let mut inaccessible = 0;

            for entry in response.items {
                let url = &entry.url;
                let is_accessible = match engine_client.as_ref() {
                    Some(client) => check_url_accessible(client, url).await,
                    None => false,
                };
                if is_accessible {
                    accessible += 1;
                } else {
                    inaccessible += 1;
                }
            }

            log::info!(
                "[{}] Search completed in {:.2}s",
                name,
                elapsed.as_secs_f64()
            );
            log::info!("[{}] Total results: {}", name, total);

            Ok(TestResult {
                total,
                accessible,
                inaccessible,
            })
        }
        Ok(Err(e)) => {
            log::error!("[{}] Search failed: {:?}", name, e);
            Err(e.into())
        }
        Err(_) => {
            log::error!("[{}] Search timed out after {}s", name, timeout_secs);
            Err(anyhow::anyhow!("Search timed out"))
        }
    }
}

fn build_test_engine_client() -> Option<Arc<EngineClient>> {
    let http_client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(5))
        .build()
        .ok()?;
    let reqwest_engine = ReqwestEngine::new(Arc::new(http_client));
    let router: Arc<dyn EngineRouterTrait> =
        Arc::new(EngineRouter::new(vec![Arc::new(reqwest_engine)]));
    Some(Arc::new(EngineClient::with_router(router)))
}

async fn check_url_accessible(engine_client: &EngineClient, url: &str) -> bool {
    let options = ScrapeOptions::builder()
        .timeout(std::time::Duration::from_secs(5))
        .build();
    let request = ScrapeRequest::new(url).with_options(options);
    engine_client
        .scrape(&request)
        .await
        .map(|response| response.is_success())
        .unwrap_or(false)
}

#[cfg(test)]
mod tests {
    use super::*;

    // TestResult::default tests

    #[test]
    fn test_test_result_default_total_is_zero() {
        let r = TestResult::default();
        assert_eq!(r.total, 0, "default total should be 0");
    }

    #[test]
    fn test_test_result_default_accessible_is_zero() {
        let r = TestResult::default();
        assert_eq!(r.accessible, 0, "default accessible should be 0");
    }

    #[test]
    fn test_test_result_default_inaccessible_is_zero() {
        let r = TestResult::default();
        assert_eq!(r.inaccessible, 0, "default inaccessible should be 0");
    }

    #[test]
    fn test_test_result_default_all_fields_zero() {
        let r = TestResult::default();
        assert_eq!((r.total, r.accessible, r.inaccessible), (0, 0, 0));
    }

    // TestResult construction tests

    #[test]
    fn test_test_result_construction_all_accessible() {
        let r = TestResult {
            total: 10,
            accessible: 10,
            inaccessible: 0,
        };
        assert_eq!(r.total, 10);
        assert_eq!(r.accessible, 10);
        assert_eq!(r.inaccessible, 0);
    }

    #[test]
    fn test_test_result_construction_mixed() {
        let r = TestResult {
            total: 10,
            accessible: 7,
            inaccessible: 3,
        };
        assert_eq!(r.total, 10);
        assert_eq!(r.accessible, 7);
        assert_eq!(r.inaccessible, 3);
    }

    #[test]
    fn test_test_result_construction_all_inaccessible() {
        let r = TestResult {
            total: 5,
            accessible: 0,
            inaccessible: 5,
        };
        assert_eq!(r.accessible, 0);
        assert_eq!(r.inaccessible, 5);
    }

    // TestResult Clone tests

    #[test]
    fn test_test_result_clone_preserves_fields() {
        let original = TestResult {
            total: 8,
            accessible: 5,
            inaccessible: 3,
        };
        let cloned = original.clone();
        assert_eq!(cloned.total, original.total);
        assert_eq!(cloned.accessible, original.accessible);
        assert_eq!(cloned.inaccessible, original.inaccessible);
    }

    // TestResult Debug tests

    #[test]
    fn test_test_result_debug_contains_struct_name() {
        let r = TestResult::default();
        let dbg = format!("{:?}", r);
        assert!(
            dbg.contains("TestResult"),
            "Debug should contain struct name"
        );
    }

    #[test]
    fn test_test_result_debug_contains_field_values() {
        let r = TestResult {
            total: 42,
            accessible: 40,
            inaccessible: 2,
        };
        let dbg = format!("{:?}", r);
        assert!(dbg.contains("42"), "Debug should contain total value");
    }

    // TestResult field-by-field comparison tests

    #[test]
    fn test_test_result_same_values_match_field_by_field() {
        let a = TestResult {
            total: 3,
            accessible: 2,
            inaccessible: 1,
        };
        let b = TestResult {
            total: 3,
            accessible: 2,
            inaccessible: 1,
        };
        // TestResult does not derive PartialEq, so compare field by field.
        assert_eq!(a.total, b.total);
        assert_eq!(a.accessible, b.accessible);
        assert_eq!(a.inaccessible, b.inaccessible);
    }

    #[test]
    fn test_test_result_different_total_differs_field_by_field() {
        let a = TestResult {
            total: 3,
            accessible: 2,
            inaccessible: 1,
        };
        let b = TestResult {
            total: 4,
            accessible: 2,
            inaccessible: 1,
        };
        assert_ne!(a.total, b.total, "different total should differ");
    }

    // TestResult edge cases

    #[test]
    fn test_test_result_zero_total() {
        let r = TestResult {
            total: 0,
            accessible: 0,
            inaccessible: 0,
        };
        assert_eq!(r.total + r.accessible + r.inaccessible, 0);
    }

    #[test]
    fn test_test_result_large_values() {
        let r = TestResult {
            total: usize::MAX,
            accessible: usize::MAX / 2,
            inaccessible: usize::MAX / 2,
        };
        assert_eq!(r.total, usize::MAX);
    }

    #[test]
    fn test_test_result_default_is_zero_struct() {
        let default = TestResult::default();
        let explicit = TestResult {
            total: 0,
            accessible: 0,
            inaccessible: 0,
        };
        assert_eq!(default.total, explicit.total);
        assert_eq!(default.accessible, explicit.accessible);
        assert_eq!(default.inaccessible, explicit.inaccessible);
    }

    #[test]
    fn test_test_result_debug_contains_all_field_names() {
        let r = TestResult {
            total: 1,
            accessible: 2,
            inaccessible: 3,
        };
        let dbg = format!("{:?}", r);
        assert!(dbg.contains("total"), "Debug should contain 'total' field");
        assert!(
            dbg.contains("accessible"),
            "Debug should contain 'accessible' field"
        );
        assert!(
            dbg.contains("inaccessible"),
            "Debug should contain 'inaccessible' field"
        );
    }

    #[test]
    fn test_test_result_clone_independent_after_clone() {
        let original = TestResult {
            total: 5,
            accessible: 3,
            inaccessible: 2,
        };
        let cloned = original.clone();
        // cloned should have same values
        assert_eq!(cloned.total, 5);
        assert_eq!(cloned.accessible, 3);
        assert_eq!(cloned.inaccessible, 2);
    }

    #[test]
    fn test_test_result_debug_format_consistency() {
        let r = TestResult::default();
        let dbg = format!("{:?}", r);
        let dbg_alt = format!("{:#?}", r);
        // Both should contain the struct name
        assert!(dbg.contains("TestResult"));
        assert!(dbg_alt.contains("TestResult"));
    }

    // build_test_engine_client tests

    #[test]
    fn test_build_test_engine_client_returns_some() {
        let client = build_test_engine_client();
        assert!(
            client.is_some(),
            "build_test_engine_client should return Some"
        );
    }

    #[test]
    fn test_build_test_engine_client_creates_valid_client() {
        let client = build_test_engine_client();
        assert!(client.is_some());
        let client = client.unwrap();
        // The client should be a valid Arc<EngineClient>
        let _ref: &EngineClient = &client;
    }

    #[test]
    fn test_build_test_engine_client_has_one_engine() {
        // build_test_engine_client registers exactly one ReqwestEngine.
        let client = build_test_engine_client().expect("client should be Some");
        assert_eq!(
            client.engine_count(),
            1,
            "exactly one engine (reqwest) should be registered"
        );
    }

    #[test]
    fn test_build_test_engine_client_registered_engines_contains_reqwest() {
        let client = build_test_engine_client().expect("client should be Some");
        let names = client.registered_engines();
        assert!(
            names.iter().any(|n| n == "reqwest"),
            "registered engines should contain 'reqwest', got {:?}",
            names
        );
    }

    #[test]
    fn test_build_test_engine_client_registered_engines_count_matches_engine_count() {
        let client = build_test_engine_client().expect("client should be Some");
        let names = client.registered_engines();
        assert_eq!(
            names.len(),
            client.engine_count(),
            "registered_engines().len() should equal engine_count()"
        );
    }

    #[test]
    fn test_build_test_engine_client_deterministic_returns_some() {
        // Repeated calls must always succeed (the builder is deterministic and
        // does not depend on external state).
        for i in 0..5 {
            assert!(
                build_test_engine_client().is_some(),
                "call #{} should return Some",
                i
            );
        }
    }

    #[test]
    fn test_build_test_engine_client_creates_independent_instances() {
        // Each call constructs a fresh EngineClient; the returned Arcs must not
        // share the same allocation.
        let a = build_test_engine_client().expect("first call should be Some");
        let b = build_test_engine_client().expect("second call should be Some");
        assert!(
            !Arc::ptr_eq(&a, &b),
            "each call should produce an independent EngineClient instance"
        );
    }

    // run_engine_test_with_output tests (mock SearchEngine)

    use crate::search::{EngineHealth, Response, ResponseItem, SearchEngineType, SearchError};
    use async_trait::async_trait;
    use std::time::Duration;

    /// Mock engine that returns an empty result set.
    struct MockEngineEmpty;

    #[async_trait]
    impl SearchEngine for MockEngineEmpty {
        fn name(&self) -> &'static str {
            "MockEmpty"
        }
        fn engine_type(&self) -> SearchEngineType {
            SearchEngineType::Bing
        }
        fn health(&self) -> EngineHealth {
            EngineHealth::Healthy
        }
        async fn search(
            &self,
            _request: &SearchRequest,
        ) -> Result<Response<ResponseItem>, SearchError> {
            Ok(Response {
                items: vec![],
                total_results: Some(0),
                engine: SearchEngineType::Bing,
            })
        }
    }

    /// Mock engine that returns items with internal URLs (blocked by SSRF).
    struct MockEngineWithItems {
        item_count: usize,
    }

    #[async_trait]
    impl SearchEngine for MockEngineWithItems {
        fn name(&self) -> &'static str {
            "MockWithItems"
        }
        fn engine_type(&self) -> SearchEngineType {
            SearchEngineType::Bing
        }
        fn health(&self) -> EngineHealth {
            EngineHealth::Healthy
        }
        async fn search(
            &self,
            _request: &SearchRequest,
        ) -> Result<Response<ResponseItem>, SearchError> {
            let items = (0..self.item_count)
                .map(|i| ResponseItem {
                    title: format!("Result {}", i + 1),
                    // Use localhost URLs so SSRF validation blocks them
                    // without making real HTTP requests.
                    url: format!("http://127.0.0.1:1/page-{}", i + 1),
                    description: format!("Description {}", i + 1),
                    engine: SearchEngineType::Bing,
                })
                .collect();
            Ok(Response {
                items,
                total_results: Some(self.item_count as u64),
                engine: SearchEngineType::Bing,
            })
        }
    }

    /// Mock engine that always returns a search error.
    struct MockEngineError;

    #[async_trait]
    impl SearchEngine for MockEngineError {
        fn name(&self) -> &'static str {
            "MockError"
        }
        fn engine_type(&self) -> SearchEngineType {
            SearchEngineType::Bing
        }
        fn health(&self) -> EngineHealth {
            EngineHealth::Healthy
        }
        async fn search(
            &self,
            _request: &SearchRequest,
        ) -> Result<Response<ResponseItem>, SearchError> {
            Err(SearchError::EngineFailed("mock engine failure".to_string()))
        }
    }

    /// Mock engine that sleeps longer than the test timeout.
    struct MockEngineTimeout;

    #[async_trait]
    impl SearchEngine for MockEngineTimeout {
        fn name(&self) -> &'static str {
            "MockTimeout"
        }
        fn engine_type(&self) -> SearchEngineType {
            SearchEngineType::Bing
        }
        fn health(&self) -> EngineHealth {
            EngineHealth::Healthy
        }
        async fn search(
            &self,
            _request: &SearchRequest,
        ) -> Result<Response<ResponseItem>, SearchError> {
            // Sleep longer than the test timeout to trigger a timeout.
            tokio::time::sleep(Duration::from_secs(10)).await;
            Ok(Response {
                items: vec![],
                total_results: Some(0),
                engine: SearchEngineType::Bing,
            })
        }
    }

    #[tokio::test]
    async fn test_run_engine_test_success_empty_results() {
        let result = run_engine_test_with_output(
            "MockEmpty",
            MockEngineEmpty,
            Some("test query"),
            5,
            Some(10),
        )
        .await;

        assert!(result.is_ok(), "empty result search should succeed");
        let tr = result.unwrap();
        assert_eq!(tr.total, 0, "empty result should have 0 total");
        assert_eq!(tr.accessible, 0);
        assert_eq!(tr.inaccessible, 0);
    }

    #[tokio::test]
    async fn test_run_engine_test_success_with_items_all_inaccessible() {
        let result = run_engine_test_with_output(
            "MockWithItems",
            MockEngineWithItems { item_count: 3 },
            Some("test query"),
            5,
            Some(10),
        )
        .await;

        assert!(result.is_ok(), "search with items should succeed");
        let tr = result.unwrap();
        assert_eq!(tr.total, 3, "should have 3 total results");
        assert_eq!(
            tr.accessible, 0,
            "all localhost URLs should be inaccessible"
        );
        assert_eq!(tr.inaccessible, 3, "all 3 items should be inaccessible");
    }

    #[tokio::test]
    async fn test_run_engine_test_search_error() {
        let result = run_engine_test_with_output(
            "MockError",
            MockEngineError,
            Some("test query"),
            5,
            Some(10),
        )
        .await;

        assert!(result.is_err(), "search error should propagate as Err");
        let err_msg = format!("{}", result.unwrap_err());
        assert!(
            err_msg.contains("mock engine failure"),
            "error message should contain the engine error, got: {}",
            err_msg
        );
    }

    #[tokio::test]
    async fn test_run_engine_test_timeout() {
        let result = run_engine_test_with_output(
            "MockTimeout",
            MockEngineTimeout,
            Some("test query"),
            1,
            Some(10),
        )
        .await;

        assert!(result.is_err(), "timeout should produce an error");
        let err_msg = format!("{}", result.unwrap_err());
        assert!(
            err_msg.contains("timed out"),
            "error message should mention timeout, got: {}",
            err_msg
        );
    }

    #[tokio::test]
    async fn test_run_engine_test_uses_default_query_when_none() {
        // When query is None, the function should use "test query" as default.
        let result = run_engine_test_with_output("MockEmpty", MockEngineEmpty, None, 5, None).await;

        assert!(
            result.is_ok(),
            "should succeed with default query and limit"
        );
        let tr = result.unwrap();
        assert_eq!(tr.total, 0);
    }

    // check_url_accessible tests

    #[tokio::test]
    async fn test_check_url_accessible_returns_false_for_internal_url() {
        // Internal URLs (127.0.0.1) are blocked by SSRF validation in
        // EngineClient::scrape, so check_url_accessible should return false.
        let client = build_test_engine_client().expect("client should be Some");
        let result = check_url_accessible(&client, "http://127.0.0.1:1/nonexistent").await;
        assert!(
            !result,
            "internal URL should not be accessible (SSRF blocked)"
        );
    }

    #[tokio::test]
    async fn test_check_url_accessible_returns_false_for_localhost() {
        let client = build_test_engine_client().expect("client should be Some");
        let result = check_url_accessible(&client, "http://localhost:1/page").await;
        assert!(
            !result,
            "localhost URL should not be accessible (SSRF blocked)"
        );
    }

    #[tokio::test]
    async fn test_check_url_accessible_returns_false_for_private_ip() {
        let client = build_test_engine_client().expect("client should be Some");
        let result = check_url_accessible(&client, "http://10.0.0.1:8080/internal").await;
        assert!(
            !result,
            "private IP URL should not be accessible (SSRF blocked)"
        );
    }

    // log::info! 参数求值覆盖测试

    use log::{LevelFilter, Log, Metadata, Record};
    use std::sync::Once;

    static SEARCH_LOGGER_INIT: Once = Once::new();

    struct CapturingInfoLogger;

    impl Log for CapturingInfoLogger {
        fn enabled(&self, metadata: &Metadata) -> bool {
            metadata.level() <= log::Level::Info
        }
        fn log(&self, _record: &Record) {}
        fn flush(&self) {}
    }

    fn ensure_info_logger() {
        SEARCH_LOGGER_INIT.call_once(|| {
            static CAPTURING_LOGGER: CapturingInfoLogger = CapturingInfoLogger;
            let _ = log::set_logger(&CAPTURING_LOGGER);
            log::set_max_level(LevelFilter::Info);
        });
    }

    #[tokio::test]
    async fn test_run_engine_test_logs_info_with_logger_initialized() {
        // 初始化 logger 设置 max_level = Info,让 log::info! 参数被求值,
        // 覆盖行 64-65 的 log::info! 调用。
        ensure_info_logger();
        let result = run_engine_test_with_output(
            "MockEmptyLogged",
            MockEngineEmpty,
            Some("test query"),
            5,
            Some(10),
        )
        .await;

        assert!(result.is_ok(), "search should succeed with logger init");
        let tr = result.unwrap();
        assert_eq!(tr.total, 0);
    }

    #[tokio::test]
    async fn test_run_engine_test_logs_info_with_items_and_logger() {
        // 初始化 logger,确保 log::info! 参数在有结果时也被求值。
        ensure_info_logger();
        let result = run_engine_test_with_output(
            "MockWithItemsLogged",
            MockEngineWithItems { item_count: 2 },
            Some("test query"),
            5,
            Some(10),
        )
        .await;

        assert!(result.is_ok(), "search with items should succeed");
        let tr = result.unwrap();
        assert_eq!(tr.total, 2);
    }
}