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

//! Crawl domain model - pure domain entity without ORM annotations
//!
//! This module contains the pure domain model for Crawl,
//! following Domain-Driven Design principles.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;

/// Crawl domain model
///
/// Represents a website crawl task with multiple sub-tasks.
/// This is a pure domain model without any ORM annotations.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Crawl {
    /// Unique identifier
    pub id: crate::domain::id::Id,
    /// Team ID for multi-tenancy
    pub team_id: crate::domain::id::Id,
    /// Human-readable name
    pub name: String,
    /// Root URL for the crawl
    pub root_url: String,
    /// Current target URL
    pub url: String,
    /// Current status
    pub status: CrawlStatus,
    /// Crawl configuration as JSON
    config: serde_json::Value,
    /// Total number of sub-tasks
    total_tasks: i32,
    /// Number of completed sub-tasks
    completed_tasks: i32,
    /// Number of failed sub-tasks
    failed_tasks: i32,
    /// When the crawl was created
    pub created_at: DateTime<Utc>,
    /// When the crawl was last updated
    pub updated_at: DateTime<Utc>,
    /// When the crawl completed
    pub completed_at: Option<DateTime<Utc>>,
}

impl Crawl {
    /// Create a new crawl
    pub fn new(
        id: crate::domain::id::Id,
        team_id: crate::domain::id::Id,
        name: String,
        root_url: String,
        url: String,
        config: serde_json::Value,
    ) -> Self {
        let now = Utc::now();
        Self {
            id,
            team_id,
            name,
            root_url,
            url,
            status: CrawlStatus::Queued,
            config,
            total_tasks: 0,
            completed_tasks: 0,
            failed_tasks: 0,
            created_at: now,
            updated_at: now,
            completed_at: None,
        }
    }

    /// Create a crawl with all fields (for mappers)
    #[allow(clippy::too_many_arguments)]
    pub fn with_all_fields(
        id: crate::domain::id::Id,
        team_id: crate::domain::id::Id,
        name: String,
        root_url: String,
        url: String,
        status: CrawlStatus,
        config: serde_json::Value,
        total_tasks: i32,
        completed_tasks: i32,
        failed_tasks: i32,
        created_at: DateTime<Utc>,
        updated_at: DateTime<Utc>,
        completed_at: Option<DateTime<Utc>>,
    ) -> Self {
        Self {
            id,
            team_id,
            name,
            root_url,
            url,
            status,
            config,
            total_tasks,
            completed_tasks,
            failed_tasks,
            created_at,
            updated_at,
            completed_at,
        }
    }

    /// Get the crawl configuration
    pub fn config(&self) -> &serde_json::Value {
        &self.config
    }

    /// Get total tasks count
    pub fn total_tasks(&self) -> i32 {
        self.total_tasks
    }

    /// Get completed tasks count
    pub fn completed_tasks(&self) -> i32 {
        self.completed_tasks
    }

    /// Get failed tasks count
    pub fn failed_tasks(&self) -> i32 {
        self.failed_tasks
    }

    /// Calculate progress percentage
    pub fn progress_percentage(&self) -> f64 {
        if self.total_tasks == 0 {
            return 100.0;
        }
        (self.completed_tasks as f64 / self.total_tasks as f64) * 100.0
    }

    /// 服务端写入 crawl.config 的可变访问(入口注入团队策略等)。
    pub fn config_mut(&mut self) -> &mut serde_json::Value {
        &mut self.config
    }

    /// Check if the crawl is finished
    pub fn is_finished(&self) -> bool {
        matches!(
            self.status,
            CrawlStatus::Completed | CrawlStatus::Failed | CrawlStatus::Cancelled
        )
    }

    /// Start the crawl
    ///
    /// 状态守卫:仅 `Queued` → `Processing`,终态不可重启。
    pub fn start(&mut self) {
        if self.is_finished() {
            log::warn!(
                "Cannot start crawl {}: already in terminal state {:?}",
                self.id,
                self.status
            );
            return;
        }
        if self.status != CrawlStatus::Queued {
            log::warn!(
                "Cannot start crawl {}: current state is {:?}, expected Queued",
                self.id,
                self.status
            );
            return;
        }
        self.status = CrawlStatus::Processing;
        self.updated_at = Utc::now();
    }

    /// Complete the crawl
    ///
    /// 状态守卫:仅 `Processing` → `Completed`,防止覆盖其他终态。
    pub fn complete(&mut self) {
        if self.status != CrawlStatus::Processing {
            log::warn!(
                "Cannot complete crawl {}: current state is {:?}, expected Processing",
                self.id,
                self.status
            );
            return;
        }
        self.status = CrawlStatus::Completed;
        self.completed_at = Some(Utc::now());
        self.updated_at = Utc::now();
    }

    /// Fail the crawl
    ///
    /// 状态守卫:仅 `Processing` → `Failed`,防止覆盖已完成/已取消状态。
    pub fn fail(&mut self) {
        if self.is_finished() {
            log::warn!(
                "Cannot fail crawl {}: already in terminal state {:?}",
                self.id,
                self.status
            );
            return;
        }
        if self.status != CrawlStatus::Processing {
            log::warn!(
                "Cannot fail crawl {}: current state is {:?}, expected Processing",
                self.id,
                self.status
            );
            return;
        }
        self.status = CrawlStatus::Failed;
        self.completed_at = Some(Utc::now());
        self.updated_at = Utc::now();
    }

    /// Cancel the crawl
    ///
    /// 状态守卫:终态不可取消(已完成/已失败/已取消)。
    pub fn cancel(&mut self) {
        if self.is_finished() {
            log::warn!(
                "Cannot cancel crawl {}: already in terminal state {:?}",
                self.id,
                self.status
            );
            return;
        }
        self.status = CrawlStatus::Cancelled;
        self.completed_at = Some(Utc::now());
        self.updated_at = Utc::now();
    }

    /// Increment total tasks
    pub fn increment_total_tasks(&mut self) {
        self.total_tasks += 1;
        self.updated_at = Utc::now();
    }

    /// Increment completed tasks
    pub fn increment_completed_tasks(&mut self) {
        self.completed_tasks += 1;
        self.updated_at = Utc::now();
    }

    /// Increment failed tasks
    pub fn increment_failed_tasks(&mut self) {
        self.failed_tasks += 1;
        self.updated_at = Utc::now();
    }

    /// Set total tasks
    pub fn set_total_tasks(&mut self, count: i32) {
        self.total_tasks = count;
        self.updated_at = Utc::now();
    }
}

/// Crawl status enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum CrawlStatus {
    /// Queued for processing
    #[default]
    Queued,
    /// Currently processing
    Processing,
    /// Completed successfully
    Completed,
    /// Failed
    Failed,
    /// Cancelled
    Cancelled,
}

/// 终态集合(SQL 条件写与守卫共用;新增终态时只改这里)。
pub const TERMINAL_CRAWL_STATUSES: [&str; 3] = ["completed", "failed", "cancelled"];

/// 非终态(仍可迁移)的 crawl 状态。
///
/// 与 [`TERMINAL_CRAWL_STATUSES`] 互补;用 `IN (...)` 而非 `NOT IN (...)`
/// 可命中 status 索引,避免周期对账/守卫写做全表扫描。
pub const ACTIVE_CRAWL_STATUSES: [&str; 2] = ["queued", "processing"];

impl fmt::Display for CrawlStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CrawlStatus::Queued => write!(f, "queued"),
            CrawlStatus::Processing => write!(f, "processing"),
            CrawlStatus::Completed => write!(f, "completed"),
            CrawlStatus::Failed => write!(f, "failed"),
            CrawlStatus::Cancelled => write!(f, "cancelled"),
        }
    }
}

impl FromStr for CrawlStatus {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "queued" => Ok(CrawlStatus::Queued),
            "processing" => Ok(CrawlStatus::Processing),
            "completed" => Ok(CrawlStatus::Completed),
            "failed" => Ok(CrawlStatus::Failed),
            "cancelled" => Ok(CrawlStatus::Cancelled),
            _ => Err(format!("Invalid crawl status: {}", s)),
        }
    }
}

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

    // Crawl::new tests

    #[test]
    fn test_crawl_new_sets_defaults() {
        let id = crate::domain::id::Id::generate();
        let team_id = crate::domain::id::Id::generate();
        let config = serde_json::json!({"max_depth": 3});

        let before = Utc::now();
        let crawl = Crawl::new(
            id,
            team_id,
            "Test Crawl".to_string(),
            "https://example.com".to_string(),
            "https://example.com/page".to_string(),
            config.clone(),
        );
        let after = Utc::now();

        assert_eq!(crawl.id, id);
        assert_eq!(crawl.team_id, team_id);
        assert_eq!(crawl.name, "Test Crawl");
        assert_eq!(crawl.root_url, "https://example.com");
        assert_eq!(crawl.url, "https://example.com/page");
        assert_eq!(
            crawl.status,
            CrawlStatus::Queued,
            "new crawl should be Queued"
        );
        assert_eq!(crawl.config(), &config);
        assert_eq!(crawl.total_tasks(), 0, "new crawl should have 0 tasks");
        assert_eq!(crawl.completed_tasks(), 0);
        assert_eq!(crawl.failed_tasks(), 0);
        assert!(crawl.completed_at.is_none());
        assert!(
            crawl.created_at >= before && crawl.created_at <= after,
            "created_at should be now"
        );
        assert_eq!(crawl.created_at, crawl.updated_at);
    }

    // Crawl::with_all_fields tests

    #[test]
    fn test_crawl_with_all_fields_sets_everything() {
        let id = crate::domain::id::Id::generate();
        let team_id = crate::domain::id::Id::generate();
        let config = serde_json::json!({"k": "v"});
        let created = Utc::now();
        let updated = created + chrono::Duration::seconds(10);
        let completed = updated + chrono::Duration::seconds(5);

        let crawl = Crawl::with_all_fields(
            id,
            team_id,
            "Full Crawl".to_string(),
            "https://root.com".to_string(),
            "https://root.com/x".to_string(),
            CrawlStatus::Completed,
            config.clone(),
            10,
            8,
            2,
            created,
            updated,
            Some(completed),
        );

        assert_eq!(crawl.id, id);
        assert_eq!(crawl.team_id, team_id);
        assert_eq!(crawl.name, "Full Crawl");
        assert_eq!(crawl.root_url, "https://root.com");
        assert_eq!(crawl.url, "https://root.com/x");
        assert_eq!(crawl.status, CrawlStatus::Completed);
        assert_eq!(crawl.config(), &config);
        assert_eq!(crawl.total_tasks(), 10);
        assert_eq!(crawl.completed_tasks(), 8);
        assert_eq!(crawl.failed_tasks(), 2);
        assert_eq!(crawl.created_at, created);
        assert_eq!(crawl.updated_at, updated);
        assert_eq!(crawl.completed_at, Some(completed));
    }

    // progress_percentage tests

    #[test]
    fn test_progress_percentage_zero_tasks_returns_100() {
        let crawl = make_crawl();
        assert_eq!(
            crawl.progress_percentage(),
            100.0,
            "0 total tasks should return 100%"
        );
    }

    #[test]
    fn test_progress_percentage_partial() {
        let mut crawl = make_crawl();
        crawl.set_total_tasks(10);
        for _ in 0..5 {
            crawl.increment_completed_tasks();
        }
        let pct = crawl.progress_percentage();
        assert!(
            (pct - 50.0).abs() < f64::EPSILON,
            "5/10 completed should be 50%, got {}",
            pct
        );
    }

    #[test]
    fn test_progress_percentage_all_completed() {
        let mut crawl = make_crawl();
        crawl.set_total_tasks(4);
        for _ in 0..4 {
            crawl.increment_completed_tasks();
        }
        let pct = crawl.progress_percentage();
        assert!(
            (pct - 100.0).abs() < f64::EPSILON,
            "4/4 completed should be 100%, got {}",
            pct
        );
    }

    // is_finished tests

    #[test]
    fn test_is_finished_true_for_terminal_statuses() {
        let mut crawl = make_crawl();
        for status in [
            CrawlStatus::Completed,
            CrawlStatus::Failed,
            CrawlStatus::Cancelled,
        ] {
            crawl.status = status;
            assert!(
                crawl.is_finished(),
                "{:?} should be a finished status",
                status
            );
        }
    }

    #[test]
    fn test_is_finished_false_for_non_terminal_statuses() {
        let mut crawl = make_crawl();
        for status in [CrawlStatus::Queued, CrawlStatus::Processing] {
            crawl.status = status;
            assert!(
                !crawl.is_finished(),
                "{:?} should not be a finished status",
                status
            );
        }
    }

    // start / complete / fail / cancel tests

    #[test]
    fn test_start_sets_processing() {
        let mut crawl = make_crawl();
        let before = Utc::now();
        crawl.start();

        assert_eq!(crawl.status, CrawlStatus::Processing);
        assert!(crawl.updated_at >= before);
    }

    #[test]
    fn test_complete_sets_completed_and_completed_at() {
        let mut crawl = make_crawl();
        crawl.status = CrawlStatus::Processing;
        let before = Utc::now();
        crawl.complete();

        assert_eq!(crawl.status, CrawlStatus::Completed);
        assert!(crawl.completed_at.is_some());
        assert!(crawl.completed_at.expect("completed_at set") >= before);
        assert!(crawl.updated_at >= before);
    }

    #[test]
    fn test_fail_sets_failed_and_completed_at() {
        let mut crawl = make_crawl();
        crawl.status = CrawlStatus::Processing; // 状态守卫要求 Processing
        let before = Utc::now();
        crawl.fail();

        assert_eq!(crawl.status, CrawlStatus::Failed);
        assert!(crawl.completed_at.is_some());
        assert!(crawl.updated_at >= before);
    }

    #[test]
    fn test_cancel_sets_cancelled_and_completed_at() {
        let mut crawl = make_crawl();
        let before = Utc::now();
        crawl.cancel();

        assert_eq!(crawl.status, CrawlStatus::Cancelled);
        assert!(crawl.completed_at.is_some());
        assert!(crawl.updated_at >= before);
    }

    // increment / set task counters

    #[test]
    fn test_increment_total_tasks() {
        let mut crawl = make_crawl();
        assert_eq!(crawl.total_tasks(), 0);

        crawl.increment_total_tasks();
        crawl.increment_total_tasks();
        assert_eq!(crawl.total_tasks(), 2, "should increment by 1 each call");
    }

    #[test]
    fn test_increment_completed_tasks() {
        let mut crawl = make_crawl();
        crawl.increment_completed_tasks();
        assert_eq!(crawl.completed_tasks(), 1);
    }

    #[test]
    fn test_increment_failed_tasks() {
        let mut crawl = make_crawl();
        crawl.increment_failed_tasks();
        crawl.increment_failed_tasks();
        assert_eq!(crawl.failed_tasks(), 2);
    }

    #[test]
    fn test_set_total_tasks_overrides_count() {
        let mut crawl = make_crawl();
        crawl.increment_total_tasks();
        crawl.increment_total_tasks();
        crawl.set_total_tasks(50);
        assert_eq!(crawl.total_tasks(), 50, "set_total_tasks should override");
    }

    #[test]
    fn test_set_total_tasks_zero() {
        let mut crawl = make_crawl();
        crawl.set_total_tasks(0);
        assert_eq!(crawl.total_tasks(), 0);
        assert_eq!(crawl.progress_percentage(), 100.0, "0 tasks still 100%");
    }

    // CrawlStatus Display / FromStr tests

    #[test]
    fn test_crawl_status_display_all_variants() {
        assert_eq!(CrawlStatus::Queued.to_string(), "queued");
        assert_eq!(CrawlStatus::Processing.to_string(), "processing");
        assert_eq!(CrawlStatus::Completed.to_string(), "completed");
        assert_eq!(CrawlStatus::Failed.to_string(), "failed");
        assert_eq!(CrawlStatus::Cancelled.to_string(), "cancelled");
    }

    #[test]
    fn test_crawl_status_from_str_valid() {
        assert_eq!(
            CrawlStatus::from_str("queued").expect("valid"),
            CrawlStatus::Queued
        );
        assert_eq!(
            CrawlStatus::from_str("processing").expect("valid"),
            CrawlStatus::Processing
        );
        assert_eq!(
            CrawlStatus::from_str("completed").expect("valid"),
            CrawlStatus::Completed
        );
        assert_eq!(
            CrawlStatus::from_str("failed").expect("valid"),
            CrawlStatus::Failed
        );
        assert_eq!(
            CrawlStatus::from_str("cancelled").expect("valid"),
            CrawlStatus::Cancelled
        );
    }

    #[test]
    fn test_crawl_status_from_str_invalid_returns_error() {
        let err = CrawlStatus::from_str("unknown").expect_err("invalid status should error");
        assert!(
            err.contains("Invalid crawl status"),
            "error should describe invalid status: {}",
            err
        );
        assert!(
            err.contains("unknown"),
            "error should include the bad value"
        );
    }

    #[test]
    fn test_crawl_status_default_is_queued() {
        assert_eq!(CrawlStatus::default(), CrawlStatus::Queued);
    }

    #[test]
    fn test_crawl_status_serde_roundtrip() {
        for status in [
            CrawlStatus::Queued,
            CrawlStatus::Processing,
            CrawlStatus::Completed,
            CrawlStatus::Failed,
            CrawlStatus::Cancelled,
        ] {
            let json = serde_json::to_string(&status).expect("serialize");
            let back: CrawlStatus = serde_json::from_str(&json).expect("deserialize");
            assert_eq!(status, back, "roundtrip should preserve: {}", json);
        }
    }

    // Crawl serde roundtrip

    #[test]
    fn test_crawl_serde_roundtrip() {
        let mut crawl = make_crawl();
        crawl.set_total_tasks(10);
        crawl.increment_completed_tasks();

        let json = serde_json::to_string(&crawl).expect("serialize");
        let back: Crawl = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(crawl, back, "serde roundtrip should preserve crawl");
    }

    // Helper

    fn make_crawl() -> Crawl {
        Crawl::new(
            crate::domain::id::Id::generate(),
            crate::domain::id::Id::generate(),
            "Test".to_string(),
            "https://example.com".to_string(),
            "https://example.com".to_string(),
            serde_json::json!({}),
        )
    }

    /// 状态字符串分区必须覆盖全部枚举变体且互斥。`canonical` 的 match
    /// 在新增状态时非穷尽编译失败,强制同步 ACTIVE/TERMINAL 常量。
    #[test]
    fn crawl_status_strings_partition_active_and_terminal() {
        fn canonical(status: &CrawlStatus) -> &'static str {
            match status {
                CrawlStatus::Queued => "queued",
                CrawlStatus::Processing => "processing",
                CrawlStatus::Completed => "completed",
                CrawlStatus::Failed => "failed",
                CrawlStatus::Cancelled => "cancelled",
            }
        }
        let all: [CrawlStatus; 5] = [
            CrawlStatus::Queued,
            CrawlStatus::Processing,
            CrawlStatus::Completed,
            CrawlStatus::Failed,
            CrawlStatus::Cancelled,
        ];
        for status in &all {
            let value = status.to_string();
            assert_eq!(canonical(status), value, "Display must match canonical");
            let in_active = ACTIVE_CRAWL_STATUSES.contains(&value.as_str());
            let in_terminal = TERMINAL_CRAWL_STATUSES.contains(&value.as_str());
            assert!(
                in_active ^ in_terminal,
                "status {value} must be exactly one of active/terminal"
            );
        }
        assert_eq!(
            ACTIVE_CRAWL_STATUSES.len() + TERMINAL_CRAWL_STATUSES.len(),
            all.len(),
            "constants must cover every status exactly once"
        );
    }
}