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

use crate::utils::text_processing::processor::{
    CrawlProcessingError, CrawlTextProcessor, ProcessedCrawlContent,
};
use log::{debug, error, info, warn};

use crate::i18n::{tr_log, tr_log_args};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::sync::RwLock;

pub struct CrawlTextIntegration {
    processor: Arc<RwLock<CrawlTextProcessor>>,
    enabled: Arc<AtomicBool>,
}

impl CrawlTextIntegration {
    pub fn new(enabled: bool) -> Self {
        Self {
            processor: Arc::new(RwLock::new(CrawlTextProcessor::new())),
            enabled: Arc::new(AtomicBool::new(enabled)),
        }
    }

    /// Returns whether text processing is currently enabled.
    pub fn is_enabled(&self) -> bool {
        self.enabled.load(Ordering::SeqCst)
    }

    pub async fn enable(&self) {
        let _processor = self.processor.write().await;
        self.enabled.store(true, Ordering::SeqCst);
        info!("{}", tr_log("text-integration-enabled"));
    }

    pub async fn disable(&self) {
        let _processor = self.processor.write().await;
        self.enabled.store(false, Ordering::SeqCst);
        info!("{}", tr_log("text-integration-disabled"));
    }

    pub async fn process_scrape_response(
        &self,
        content: &[u8],
        url: &str,
        content_type: Option<&str>,
        status_code: u16,
    ) -> Result<ProcessedScrapeResponse, CrawlProcessingError> {
        // 禁用时不分配 2 份 String,直接返回原样响应。
        if !self.is_enabled() {
            debug!("{}", tr_log("text-integration-disabled-direct"));
            return Ok(passthrough_response(
                content,
                url,
                content_type,
                status_code,
                None,
            ));
        }

        let processor = self.processor.read().await;

        match processor.process_crawled_content(content, url, content_type) {
            Ok(processed_content) => Ok(success_response(processed_content, url, status_code)),
            Err(e) => {
                error!(
                    "{}",
                    tr_log_args(
                        "text-integration-failed",
                        &[("url", url.to_string()), ("error", e.to_string()),],
                    )
                );
                Ok(passthrough_response(
                    content,
                    url,
                    content_type,
                    status_code,
                    Some(e.to_string()),
                ))
            }
        }
    }

    pub async fn process_batch_scrape_responses(
        &self,
        responses: Vec<ScrapeResponseInput>,
    ) -> Vec<Result<ProcessedScrapeResponse, CrawlProcessingError>> {
        if !self.is_enabled() {
            debug!("{}", tr_log("text-integration-disabled-batch"));
            return responses
                .into_iter()
                .map(|response| Ok(passthrough_batch_response(response)))
                .collect();
        }

        let processor = self.processor.read().await;

        let batch_input: Vec<(&[u8], &str, Option<&str>)> = responses
            .iter()
            .map(|response| {
                (
                    response.content.as_slice(),
                    response.url.as_str(),
                    response.content_type.as_deref(),
                )
            })
            .collect();

        let batch_results = processor.process_batch(batch_input);

        batch_results
            .into_iter()
            .zip(responses)
            .map(|(result, response)| match result {
                Ok(processed_content) => Ok(batch_success_response(processed_content, response)),
                Err(e) => Ok(batch_failure_response(response, e)),
            })
            .collect()
    }
}

/// 未启用/处理失败时的原样回传响应。
///
/// 仅在最终需要 String 时做一次 utf8_lossy(lazy),避免提前分配两份 String。
fn passthrough_response(
    content: &[u8],
    url: &str,
    content_type: Option<&str>,
    status_code: u16,
    processing_error: Option<String>,
) -> ProcessedScrapeResponse {
    let original = String::from_utf8_lossy(content).into_owned();
    ProcessedScrapeResponse {
        original_content: original.clone(),
        processed_content: original,
        content_type: content_type.map(|s| s.to_string()),
        status_code,
        url: url.to_string(),
        encoding_detected: None,
        language_detected: None,
        is_html: false,
        processing_success: false,
        processing_error,
    }
}

/// 构建处理成功响应并记录成功日志。
fn success_response(
    processed_content: ProcessedCrawlContent,
    url: &str,
    status_code: u16,
) -> ProcessedScrapeResponse {
    let result = ProcessedScrapeResponse {
        original_content: processed_content.processed_content.original_content.clone(),
        processed_content: processed_content.processed_content.extracted_text.clone(),
        content_type: processed_content.processed_content.content_type.clone(),
        status_code,
        url: url.to_string(),
        encoding_detected: processed_content
            .processed_content
            .declared_encoding
            .clone(),
        language_detected: processed_content
            .processed_content
            .detected_language
            .clone(),
        is_html: processed_content.processed_content.is_html,
        processing_success: true,
        processing_error: None,
    };
    info!(
        "{}",
        tr_log_args(
            "text-integration-succeeded",
            &[
                ("url", url.to_string()),
                ("length", result.processed_content.len().to_string(),),
                (
                    "language",
                    result
                        .language_detected
                        .clone()
                        .unwrap_or_else(|| "none".to_string())
                        .to_string(),
                ),
            ],
        )
    );
    result
}

/// 批量路径:未启用时的原样回传响应。
fn passthrough_batch_response(response: ScrapeResponseInput) -> ProcessedScrapeResponse {
    let original = String::from_utf8_lossy(&response.content).into_owned();
    ProcessedScrapeResponse {
        original_content: original.clone(),
        processed_content: original,
        content_type: response.content_type,
        status_code: response.status_code,
        url: response.url,
        encoding_detected: None,
        language_detected: None,
        is_html: false,
        processing_success: false,
        processing_error: None,
    }
}

/// 批量路径:构建处理成功响应。
fn batch_success_response(
    processed_content: ProcessedCrawlContent,
    response: ScrapeResponseInput,
) -> ProcessedScrapeResponse {
    ProcessedScrapeResponse {
        original_content: processed_content.processed_content.original_content.clone(),
        processed_content: processed_content.processed_content.extracted_text.clone(),
        content_type: processed_content.processed_content.content_type.clone(),
        status_code: response.status_code,
        url: response.url,
        encoding_detected: processed_content
            .processed_content
            .declared_encoding
            .clone(),
        language_detected: processed_content
            .processed_content
            .detected_language
            .clone(),
        is_html: processed_content.processed_content.is_html,
        processing_success: true,
        processing_error: None,
    }
}

/// 批量路径:记录单项失败日志并构建兜底响应。
fn batch_failure_response(
    response: ScrapeResponseInput,
    e: CrawlProcessingError,
) -> ProcessedScrapeResponse {
    warn!(
        "{}",
        tr_log_args(
            "text-integration-item-failed",
            &[
                ("url", response.url.as_str().to_string()),
                ("error", e.to_string()),
            ],
        )
    );
    let original = String::from_utf8_lossy(&response.content).into_owned();
    ProcessedScrapeResponse {
        original_content: original.clone(),
        processed_content: original,
        content_type: response.content_type,
        status_code: response.status_code,
        url: response.url,
        encoding_detected: None,
        language_detected: None,
        is_html: false,
        processing_success: false,
        processing_error: Some(e.to_string()),
    }
}

#[derive(Debug, Clone)]
pub struct ScrapeResponseInput {
    pub content: Vec<u8>,
    pub url: String,
    pub content_type: Option<String>,
    pub status_code: u16,
}

#[derive(Debug, Clone)]
pub struct ProcessedScrapeResponse {
    pub original_content: String,
    pub processed_content: String,
    pub content_type: Option<String>,
    pub status_code: u16,
    pub url: String,
    pub encoding_detected: Option<String>,
    pub language_detected: Option<String>,
    pub is_html: bool,
    pub processing_success: bool,
    pub processing_error: Option<String>,
}

pub use crate::utils::text_processing::processor::CrawlProcessorConfig as CrawlTextProcessorConfig;

#[derive(Debug, Clone)]
pub struct CrawlTextIntegrationStatus {
    pub enabled: bool,
    pub config: CrawlTextProcessorConfig,
    pub uptime: std::time::Duration,
    pub processed_count: u64,
    pub error_count: u64,
}

#[derive(Debug, Clone, PartialEq)]
pub enum ContentQuality {
    Excellent,
    Good,
    Fair,
    Poor(String),
}

pub fn create_crawl_text_integration(enabled: bool) -> CrawlTextIntegration {
    CrawlTextIntegration::new(enabled)
}

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

    #[tokio::test]
    async fn test_integration_disabled() {
        let integration = CrawlTextIntegration::new(false);
        let content = "Hello, 世界!".as_bytes();
        let result = integration
            .process_scrape_response(content, "http://example.com", None, 200)
            .await
            .unwrap();
        assert!(!result.processing_success);
        assert_eq!(result.original_content, "Hello, 世界!");
        assert_eq!(result.processed_content, "Hello, 世界!");
    }

    #[tokio::test]
    async fn test_integration_enabled() {
        let integration = CrawlTextIntegration::new(true);
        let html_content = "<html><body><h1>测试页面</h1><p>这是一个测试页面,包含中文和English内容。</p></body></html>".as_bytes();
        let result = integration
            .process_scrape_response(html_content, "http://example.com", Some("text/html"), 200)
            .await
            .unwrap();
        assert!(result.processing_success);
        assert!(result.processed_content.contains("测试页面"));
        assert!(result.processed_content.contains("中文和English内容"));
        assert!(result.is_html);
    }

    #[tokio::test]
    async fn test_batch_disabled() {
        let integration = CrawlTextIntegration::new(false);
        let responses = vec![
            ScrapeResponseInput {
                content: b"Hello".to_vec(),
                url: "http://example.com/1".to_string(),
                content_type: Some("text/plain".to_string()),
                status_code: 200,
            },
            ScrapeResponseInput {
                content: b"World".to_vec(),
                url: "http://example.com/2".to_string(),
                content_type: None,
                status_code: 200,
            },
        ];
        let results = integration.process_batch_scrape_responses(responses).await;
        assert_eq!(results.len(), 2);
        for result in &results {
            assert!(result.is_ok());
            assert!(!result.as_ref().unwrap().processing_success);
        }
    }

    #[tokio::test]
    async fn test_batch_enabled() {
        let integration = CrawlTextIntegration::new(true);
        let html = b"<html><body><p>Test content</p></body></html>";
        let responses = vec![ScrapeResponseInput {
            content: html.to_vec(),
            url: "http://example.com".to_string(),
            content_type: Some("text/html".to_string()),
            status_code: 200,
        }];
        let results = integration.process_batch_scrape_responses(responses).await;
        assert_eq!(results.len(), 1);
        let result = results[0].as_ref().unwrap();
        assert!(result.processing_success);
        assert!(result.processed_content.contains("Test content"));
    }

    #[tokio::test]
    async fn test_enable_actually_enables_processing() {
        // After enable must actually set enabled=true.
        // Bug was: enable only logged and did not mutate the enabled flag.
        let integration = CrawlTextIntegration::new(false);
        assert!(!integration.is_enabled());

        integration.enable().await;
        assert!(integration.is_enabled());

        // Processing should now actually happen (success=true for valid HTML)
        let html = b"<html><body><p>Test content</p></body></html>";
        let result = integration
            .process_scrape_response(html, "http://example.com", Some("text/html"), 200)
            .await
            .unwrap();
        assert!(result.processing_success);
        assert!(result.processed_content.contains("Test content"));
    }

    #[tokio::test]
    async fn test_disable_actually_disables_processing() {
        // After disable must actually set enabled=false.
        // Bug was: disable only logged and did not mutate the enabled flag.
        let integration = CrawlTextIntegration::new(true);
        assert!(integration.is_enabled());

        integration.disable().await;
        assert!(!integration.is_enabled());

        // Processing should now skip (success=false)
        let html = b"<html><body><p>Test</p></body></html>";
        let result = integration
            .process_scrape_response(html, "http://example.com", Some("text/html"), 200)
            .await
            .unwrap();
        assert!(!result.processing_success);
    }

    #[tokio::test]
    async fn test_is_enabled_reflects_current_state() {
        let integration = CrawlTextIntegration::new(false);
        assert!(!integration.is_enabled());

        integration.enable().await;
        assert!(integration.is_enabled());

        integration.disable().await;
        assert!(!integration.is_enabled());
    }

    #[test]
    fn test_create_crawl_text_integration_disabled() {
        let integration = create_crawl_text_integration(false);
        let _ = integration;
    }

    #[test]
    fn test_create_crawl_text_integration_enabled() {
        let integration = create_crawl_text_integration(true);
        let _ = integration;
    }

    #[test]
    fn test_content_quality_variants() {
        let excellent = ContentQuality::Excellent;
        let good = ContentQuality::Good;
        let fair = ContentQuality::Fair;
        let poor = ContentQuality::Poor("reason".to_string());

        assert_eq!(excellent, ContentQuality::Excellent);
        assert_eq!(good, ContentQuality::Good);
        assert_eq!(fair, ContentQuality::Fair);
        assert_eq!(poor, ContentQuality::Poor("reason".to_string()));
    }

    #[test]
    fn test_scrape_response_input_construction() {
        let input = ScrapeResponseInput {
            content: vec![1, 2, 3],
            url: "http://test.com".to_string(),
            content_type: Some("text/html".to_string()),
            status_code: 404,
        };
        assert_eq!(input.content, vec![1, 2, 3]);
        assert_eq!(input.url, "http://test.com");
        assert_eq!(input.content_type, Some("text/html".to_string()));
        assert_eq!(input.status_code, 404);
    }

    #[test]
    fn test_processed_scrape_response_construction() {
        let response = ProcessedScrapeResponse {
            original_content: "original".to_string(),
            processed_content: "processed".to_string(),
            content_type: Some("text/html".to_string()),
            status_code: 200,
            url: "http://test.com".to_string(),
            encoding_detected: Some("utf-8".to_string()),
            language_detected: Some("en".to_string()),
            is_html: true,
            processing_success: true,
            processing_error: None,
        };
        assert_eq!(response.original_content, "original");
        assert_eq!(response.processed_content, "processed");
        assert!(response.is_html);
        assert!(response.processing_success);
    }

    #[test]
    fn test_crawl_text_integration_status_construction() {
        let status = CrawlTextIntegrationStatus {
            enabled: true,
            config: CrawlTextProcessorConfig::default(),
            uptime: std::time::Duration::from_secs(60),
            processed_count: 100,
            error_count: 5,
        };
        assert!(status.enabled);
        assert_eq!(status.uptime, std::time::Duration::from_secs(60));
        assert_eq!(status.processed_count, 100);
        assert_eq!(status.error_count, 5);
    }

    #[tokio::test]
    async fn test_process_scrape_response_with_invalid_utf8() {
        let integration = CrawlTextIntegration::new(true);
        let invalid_bytes = &[0xFF, 0xFE, 0xFD];
        let result = integration
            .process_scrape_response(invalid_bytes, "http://example.com", None, 500)
            .await
            .unwrap();
        assert_eq!(result.status_code, 500);
    }

    // 错误路径:ContentTooLarge 触发 process_crawled_content 返回 Err
    // 覆盖 process_scrape_response 的 Err 分支(行 87-99)

    #[tokio::test]
    async fn test_process_scrape_response_content_too_large_returns_ok_with_error() {
        let integration = CrawlTextIntegration::new(true);
        // CrawlTextProcessor::new 默认 max_content_size = 10 * 1024 * 1024
        let oversized: Vec<u8> = vec![0u8; 10 * 1024 * 1024 + 1];
        let result = integration
            .process_scrape_response(&oversized, "http://example.com", Some("text/html"), 200)
            .await
            .unwrap();
        // 错误被捕获,返回 Ok 但 processing_success=false
        assert!(!result.processing_success);
        assert!(result.processing_error.is_some());
        assert_eq!(result.status_code, 200);
        assert_eq!(result.url, "http://example.com");
        assert_eq!(result.content_type, Some("text/html".to_string()));
        assert!(!result.is_html);
        assert!(result.encoding_detected.is_none());
        assert!(result.language_detected.is_none());
        // 原始内容应保留(from_utf8_lossy 转换 0x00 字节)
        assert_eq!(result.original_content.len(), oversized.len());
        assert_eq!(result.processed_content.len(), oversized.len());
    }

    // 错误路径:批量处理中单个项目 ContentTooLarge
    // 覆盖 process_batch_scrape_responses 的 Err 分支(行 167-179)

    #[tokio::test]
    async fn test_batch_process_single_item_content_too_large() {
        let integration = CrawlTextIntegration::new(true);
        let oversized: Vec<u8> = vec![0u8; 10 * 1024 * 1024 + 1];
        let responses = vec![ScrapeResponseInput {
            content: oversized.clone(),
            url: "http://example.com/big".to_string(),
            content_type: Some("text/html".to_string()),
            status_code: 200,
        }];
        let results = integration.process_batch_scrape_responses(responses).await;
        assert_eq!(results.len(), 1);
        let result = results[0].as_ref().expect("should be Ok");
        assert!(!result.processing_success);
        assert!(result.processing_error.is_some());
        assert_eq!(result.url, "http://example.com/big");
        assert_eq!(result.status_code, 200);
    }

    // 混合批量:一个正常 + 一个过大,验证错误隔离

    #[tokio::test]
    async fn test_batch_mixed_success_and_error() {
        let integration = CrawlTextIntegration::new(true);
        let normal_html = b"<html><body><p>Normal content</p></body></html>".to_vec();
        let oversized: Vec<u8> = vec![0u8; 10 * 1024 * 1024 + 1];
        let responses = vec![
            ScrapeResponseInput {
                content: normal_html,
                url: "http://example.com/ok".to_string(),
                content_type: Some("text/html".to_string()),
                status_code: 200,
            },
            ScrapeResponseInput {
                content: oversized,
                url: "http://example.com/big".to_string(),
                content_type: Some("text/html".to_string()),
                status_code: 200,
            },
        ];
        let results = integration.process_batch_scrape_responses(responses).await;
        assert_eq!(results.len(), 2);
        // 第一个应成功
        let first = results[0].as_ref().unwrap();
        assert!(first.processing_success);
        assert!(first.processed_content.contains("Normal content"));
        // 第二个应失败但返回 Ok
        let second = results[1].as_ref().unwrap();
        assert!(!second.processing_success);
        assert!(second.processing_error.is_some());
    }
}