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

use async_trait::async_trait;

use super::response::ResponseItem;
use super::types::EngineHealth;
use super::{error::SearchError, response::Response, types::SearchEngineType};

/// 搜索请求
#[derive(Debug, Clone)]
pub struct SearchRequest {
    pub query: String,
    pub engine: Option<SearchEngineType>,
    pub limit: u32,
    pub offset: u32,
    pub lang: Option<String>,
    pub country: Option<String>,
}

impl SearchRequest {
    pub fn new(query: &str) -> Self {
        Self {
            query: query.to_string(),
            engine: None,
            limit: 10,
            offset: 0,
            lang: None,
            country: None,
        }
    }

    pub fn with_engine(mut self, engine: SearchEngineType) -> Self {
        self.engine = Some(engine);
        self
    }

    pub fn with_limit(mut self, limit: u32) -> Self {
        self.limit = limit;
        self
    }

    pub fn with_offset(mut self, offset: u32) -> Self {
        self.offset = offset;
        self
    }

    pub fn with_lang(mut self, lang: &str) -> Self {
        self.lang = Some(lang.to_string());
        self
    }

    pub fn with_country(mut self, country: &str) -> Self {
        self.country = Some(country.to_string());
        self
    }
}

impl Default for SearchRequest {
    fn default() -> Self {
        Self::new("")
    }
}

/// 搜索引擎 trait
#[async_trait]
pub trait SearchEngine: Send + Sync {
    fn name(&self) -> &'static str;
    fn engine_type(&self) -> SearchEngineType;
    fn health(&self) -> EngineHealth;
    async fn search(&self, request: &SearchRequest) -> Result<Response<ResponseItem>, SearchError>;

    /// Search with a specific engine (if engine is None, search all engines)
    /// Default implementation: searches without specific engine
    async fn search_with_engine(
        &self,
        query: &str,
        limit: u32,
        _lang: Option<&str>,
        _country: Option<&str>,
        engine: Option<&str>,
    ) -> Result<Vec<ResponseItem>, SearchError> {
        let mut request = SearchRequest::new(query).with_limit(limit);
        if let Some(engine_name) = engine {
            if let Some(engine_type) = SearchEngineType::from_name(engine_name) {
                request = request.with_engine(engine_type);
            }
        }
        let response = self.search(&request).await?;
        Ok(response.items)
    }
}

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

    // SearchRequest::new tests

    #[test]
    fn test_search_request_new_sets_query() {
        let req = SearchRequest::new("rust web scraping");
        assert_eq!(req.query, "rust web scraping");
    }

    #[test]
    fn test_search_request_new_defaults() {
        let req = SearchRequest::new("test");
        assert_eq!(req.limit, 10);
        assert_eq!(req.offset, 0);
        assert!(req.engine.is_none());
        assert!(req.lang.is_none());
        assert!(req.country.is_none());
    }

    #[test]
    fn test_search_request_new_empty_query() {
        let req = SearchRequest::new("");
        assert_eq!(req.query, "");
    }

    // SearchRequest::default tests

    #[test]
    fn test_search_request_default_empty_query() {
        let req = SearchRequest::default();
        assert_eq!(req.query, "");
    }

    #[test]
    fn test_search_request_default_limit_10() {
        let req = SearchRequest::default();
        assert_eq!(req.limit, 10);
    }

    #[test]
    fn test_search_request_default_offset_0() {
        let req = SearchRequest::default();
        assert_eq!(req.offset, 0);
    }

    // SearchRequest builder tests

    #[test]
    fn test_search_request_with_engine() {
        let req = SearchRequest::new("test").with_engine(SearchEngineType::Bing);
        assert_eq!(req.engine, Some(SearchEngineType::Bing));
    }

    #[test]
    fn test_search_request_with_engine_bing() {
        let req = SearchRequest::new("test").with_engine(SearchEngineType::Bing);
        assert_eq!(req.engine, Some(SearchEngineType::Bing));
    }

    #[test]
    fn test_search_request_with_limit() {
        let req = SearchRequest::new("test").with_limit(50);
        assert_eq!(req.limit, 50);
    }

    #[test]
    fn test_search_request_with_limit_zero() {
        let req = SearchRequest::new("test").with_limit(0);
        assert_eq!(req.limit, 0);
    }

    #[test]
    fn test_search_request_with_offset() {
        let req = SearchRequest::new("test").with_offset(20);
        assert_eq!(req.offset, 20);
    }

    #[test]
    fn test_search_request_with_offset_zero() {
        let req = SearchRequest::new("test").with_offset(0);
        assert_eq!(req.offset, 0);
    }

    #[test]
    fn test_search_request_with_lang() {
        let req = SearchRequest::new("test").with_lang("en");
        assert_eq!(req.lang, Some("en".to_string()));
    }

    #[test]
    fn test_search_request_with_lang_zh() {
        let req = SearchRequest::new("test").with_lang("zh-CN");
        assert_eq!(req.lang, Some("zh-CN".to_string()));
    }

    #[test]
    fn test_search_request_with_country() {
        let req = SearchRequest::new("test").with_country("US");
        assert_eq!(req.country, Some("US".to_string()));
    }

    #[test]
    fn test_search_request_with_country_cn() {
        let req = SearchRequest::new("test").with_country("CN");
        assert_eq!(req.country, Some("CN".to_string()));
    }

    // SearchRequest chained builder tests

    #[test]
    fn test_search_request_chained_builders() {
        let req = SearchRequest::new("rust")
            .with_engine(SearchEngineType::Baidu)
            .with_limit(20)
            .with_offset(5)
            .with_lang("zh")
            .with_country("CN");

        assert_eq!(req.query, "rust");
        assert_eq!(req.engine, Some(SearchEngineType::Baidu));
        assert_eq!(req.limit, 20);
        assert_eq!(req.offset, 5);
        assert_eq!(req.lang, Some("zh".to_string()));
        assert_eq!(req.country, Some("CN".to_string()));
    }

    #[test]
    fn test_search_request_clone() {
        let req = SearchRequest::new("test").with_limit(5);
        let cloned = req.clone();
        assert_eq!(cloned.query, req.query);
        assert_eq!(cloned.limit, req.limit);
    }

    #[test]
    fn test_search_request_debug() {
        let req = SearchRequest::new("test");
        let dbg = format!("{:?}", req);
        assert!(dbg.contains("SearchRequest"));
        assert!(dbg.contains("test"));
    }

    // Mock SearchEngine implementation tests

    struct MockSearchEngine;

    #[async_trait]
    impl SearchEngine for MockSearchEngine {
        fn name(&self) -> &'static str {
            "MockEngine"
        }

        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..request.limit as usize)
                .map(|i| ResponseItem {
                    title: format!("Result {}", i + 1),
                    url: format!("https://example.com/{}", i + 1),
                    description: format!("Description for result {}", i + 1),
                    engine: SearchEngineType::Bing,
                })
                .collect();
            Ok(Response {
                items,
                total_results: Some(request.limit as u64),
                engine: SearchEngineType::Bing,
            })
        }
    }

    #[test]
    fn test_mock_engine_name() {
        let engine = MockSearchEngine;
        assert_eq!(engine.name(), "MockEngine");
    }

    #[test]
    fn test_mock_engine_type() {
        let engine = MockSearchEngine;
        assert_eq!(engine.engine_type(), SearchEngineType::Bing);
    }

    #[test]
    fn test_mock_engine_health() {
        let engine = MockSearchEngine;
        assert_eq!(engine.health(), EngineHealth::Healthy);
    }

    #[tokio::test]
    async fn test_mock_engine_search_returns_results() {
        let engine = MockSearchEngine;
        let req = SearchRequest::new("test query").with_limit(5);
        let response = engine.search(&req).await.unwrap();
        assert_eq!(response.items.len(), 5);
        assert_eq!(response.engine, SearchEngineType::Bing);
        assert_eq!(response.total_results, Some(5));
    }

    #[tokio::test]
    async fn test_mock_engine_search_default_limit() {
        let engine = MockSearchEngine;
        let req = SearchRequest::new("test");
        let response = engine.search(&req).await.unwrap();
        assert_eq!(response.items.len(), 10);
    }

    #[tokio::test]
    async fn test_search_with_engine_no_engine_specified() {
        let engine = MockSearchEngine;
        let items = engine
            .search_with_engine("test", 3, None, None, None)
            .await
            .unwrap();
        assert_eq!(items.len(), 3);
    }

    #[tokio::test]
    async fn test_search_with_engine_named_engine() {
        let engine = MockSearchEngine;
        let items = engine
            .search_with_engine("test", 2, None, None, Some("Bing"))
            .await
            .unwrap();
        assert_eq!(items.len(), 2);
    }

    #[tokio::test]
    async fn test_search_with_engine_invalid_name_still_searches() {
        let engine = MockSearchEngine;
        // Invalid engine name should not cause an error - it just won't set the engine
        let items = engine
            .search_with_engine("test", 4, None, None, Some("invalid_engine"))
            .await
            .unwrap();
        assert_eq!(items.len(), 4);
    }

    #[tokio::test]
    async fn test_search_with_engine_with_lang_and_country() {
        let engine = MockSearchEngine;
        let items = engine
            .search_with_engine("test", 5, Some("en"), Some("US"), Some("bing"))
            .await
            .unwrap();
        assert_eq!(items.len(), 5);
    }

    #[tokio::test]
    async fn test_search_with_engine_zero_limit() {
        let engine = MockSearchEngine;
        let items = engine
            .search_with_engine("test", 0, None, None, None)
            .await
            .unwrap();
        assert!(items.is_empty());
    }

    // FailingSearchEngine for error propagation tests

    struct FailingSearchEngine;

    #[async_trait]
    impl SearchEngine for FailingSearchEngine {
        fn name(&self) -> &'static str {
            "FailingEngine"
        }

        fn engine_type(&self) -> SearchEngineType {
            SearchEngineType::Bing
        }

        fn health(&self) -> EngineHealth {
            EngineHealth::Unhealthy
        }

        async fn search(
            &self,
            _request: &SearchRequest,
        ) -> Result<Response<ResponseItem>, SearchError> {
            Err(SearchError::EngineFailed("mock failure".to_string()))
        }
    }

    #[tokio::test]
    async fn test_search_with_engine_propagates_search_error() {
        let engine = FailingSearchEngine;
        let result = engine.search_with_engine("test", 3, None, None, None).await;
        assert!(result.is_err(), "should propagate search error");
        match result.unwrap_err() {
            SearchError::EngineFailed(msg) => assert!(msg.contains("mock failure")),
            other => panic!("expected SearchError::EngineFailed, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_search_with_engine_error_with_named_engine() {
        let engine = FailingSearchEngine;
        let result = engine
            .search_with_engine("test", 3, None, None, Some("Bing"))
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_search_with_engine_error_with_lang_country() {
        let engine = FailingSearchEngine;
        let result = engine
            .search_with_engine("test", 3, Some("en"), Some("US"), Some("bing"))
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_failing_engine_name_and_type() {
        let engine = FailingSearchEngine;
        assert_eq!(engine.name(), "FailingEngine");
        assert_eq!(engine.engine_type(), SearchEngineType::Bing);
        assert_eq!(engine.health(), EngineHealth::Unhealthy);
    }
}