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

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

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use super::task_domain::{TaskStatus, TaskType};

/// Task domain model
///
/// Represents a scraping or crawling task in the system.
/// This is a pure domain model without any ORM annotations,
/// following DDD principles for clean architecture.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Task {
    /// Unique identifier for the task
    pub id: crate::domain::id::Id,
    /// Type of task (scrape, crawl, extract)
    pub task_type: TaskType,
    /// Current status of the task
    pub status: TaskStatus,
    /// Priority level (higher = more urgent)
    pub priority: i32,
    /// Team ID for multi-tenancy
    pub team_id: crate::domain::id::Id,
    /// API key ID that created this task
    pub api_key_id: crate::domain::id::Id,
    /// Target URL to scrape/crawl
    pub url: String,
    /// Task payload as JSON (request parameters)
    pub payload: serde_json::Value,
    /// Number of retry attempts made
    pub retry_count: i32,
    /// Total number of attempts (including initial)
    pub attempt_count: i32,
    /// Maximum number of retry attempts allowed
    pub max_retries: i32,
    /// When the task should be executed (scheduled)
    pub scheduled_at: Option<DateTime<Utc>>,
    /// When the task expires
    pub expires_at: Option<DateTime<Utc>>,
    /// When the task was created
    pub created_at: DateTime<Utc>,
    /// When the task started execution
    pub started_at: Option<DateTime<Utc>>,
    /// When the task completed
    pub completed_at: Option<DateTime<Utc>>,
    /// Parent crawl ID if this task is part of a crawl
    pub crawl_id: Option<crate::domain::id::Id>,
    /// When the task was last updated
    pub updated_at: DateTime<Utc>,
    /// Lock token for distributed task acquisition
    pub lock_token: Option<crate::domain::id::Id>,
    /// When the lock expires
    pub lock_expires_at: Option<DateTime<Utc>>,
}

impl Task {
    /// Create a new task with default values
    pub fn new(
        id: crate::domain::id::Id,
        task_type: TaskType,
        team_id: crate::domain::id::Id,
        api_key_id: crate::domain::id::Id,
        url: String,
        payload: serde_json::Value,
    ) -> Self {
        let now = Utc::now();
        Self {
            id,
            task_type,
            status: TaskStatus::Queued,
            priority: 0,
            team_id,
            api_key_id,
            url,
            payload,
            retry_count: 0,
            attempt_count: 0,
            max_retries: 3,
            scheduled_at: None,
            expires_at: None,
            created_at: now,
            started_at: None,
            completed_at: None,
            crawl_id: None,
            updated_at: now,
            lock_token: None,
            lock_expires_at: None,
        }
    }

    /// Check if the task can be retried
    pub fn can_retry(&self) -> bool {
        self.retry_count < self.max_retries
    }

    /// Check if the task is expired
    pub fn is_expired(&self) -> bool {
        self.expires_at
            .is_some_and(|expires_at| Utc::now() > expires_at)
    }

    /// Check if the task is locked
    pub fn is_locked(&self) -> bool {
        self.lock_token.is_some()
            && self
                .lock_expires_at
                .is_some_and(|expires_at| Utc::now() < expires_at)
    }

    /// Mark the task as started.
    ///
    /// MIRROR: the `SET status='active', started_at=NOW, updated_at=NOW`
    /// clause in `TaskRepositoryImpl::acquire_next` raw SQL
    /// (`task_repo_impl.rs`). Changes here must be synchronized with the SQL.
    pub fn start(&mut self) {
        self.status = TaskStatus::Active;
        self.started_at = Some(Utc::now());
        self.updated_at = Utc::now();
    }

    /// Mark the task as completed
    pub fn complete(&mut self) {
        self.status = TaskStatus::Completed;
        self.completed_at = Some(Utc::now());
        self.updated_at = Utc::now();
    }

    /// Mark the task as failed
    pub fn fail(&mut self) {
        self.status = TaskStatus::Failed;
        self.completed_at = Some(Utc::now());
        self.updated_at = Utc::now();
    }

    /// 标记失败并写入失败原因到 `payload["error"]`(API 状态端点回读)。
    ///
    /// 审查 F9:终结逻辑统一收敛到本方法(RetryHandler 与仓储默认实现共用),
    /// 避免三处重复实现产生行为分叉。
    pub fn fail_with_reason(&mut self, reason: &str) {
        self.fail();
        self.lock_token = None;
        self.lock_expires_at = None;
        if reason.is_empty() {
            return;
        }
        if let Some(obj) = self.payload.as_object_mut() {
            obj.insert(
                "error".to_string(),
                serde_json::Value::String(reason.to_string()),
            );
        } else {
            log::warn!(
                "Task {} payload is not an object, cannot record failure reason",
                self.id
            );
        }
    }

    /// Mark the task as cancelled
    pub fn cancel(&mut self) {
        self.status = TaskStatus::Cancelled;
        self.completed_at = Some(Utc::now());
        self.updated_at = Utc::now();
    }

    /// Increment retry count
    pub fn increment_retry(&mut self) {
        self.retry_count += 1;
        self.attempt_count += 1;
        self.updated_at = Utc::now();
    }

    /// Acquire lock for this task.
    ///
    /// MIRROR: the `SET lock_token=$1, lock_expires_at=NOW+($2*INTERVAL'1 second')`
    /// clause in `TaskRepositoryImpl::acquire_next` raw SQL
    /// (`task_repo_impl.rs`). Changes here must be synchronized with the SQL.
    pub fn acquire_lock(
        &mut self,
        worker_id: crate::domain::id::Id,
        lock_duration: chrono::Duration,
    ) {
        self.lock_token = Some(worker_id);
        self.lock_expires_at = Some(Utc::now() + lock_duration);
        self.updated_at = Utc::now();
    }

    /// Release lock on this task
    pub fn release_lock(&mut self) {
        self.lock_token = None;
        self.lock_expires_at = None;
        self.updated_at = Utc::now();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::models::task_domain::{TaskStatus, TaskType};

    // Task::new tests

    #[test]
    fn test_task_new_sets_defaults() {
        let id = crate::domain::id::Id::generate();
        let team_id = crate::domain::id::Id::generate();
        let api_key_id = crate::domain::id::Id::generate();
        let payload = serde_json::json!({"url": "https://example.com"});

        let before = Utc::now();
        let task = Task::new(
            id,
            TaskType::Scrape,
            team_id,
            api_key_id,
            "https://example.com".to_string(),
            payload.clone(),
        );
        let after = Utc::now();

        assert_eq!(task.id, id);
        assert_eq!(task.task_type, TaskType::Scrape);
        assert_eq!(task.status, TaskStatus::Queued, "new task should be Queued");
        assert_eq!(task.priority, 0, "default priority should be 0");
        assert_eq!(task.team_id, team_id);
        assert_eq!(task.api_key_id, api_key_id);
        assert_eq!(task.url, "https://example.com");
        assert_eq!(task.payload, payload);
        assert_eq!(task.retry_count, 0);
        assert_eq!(task.attempt_count, 0);
        assert_eq!(task.max_retries, 3, "default max_retries should be 3");
        assert!(task.scheduled_at.is_none());
        assert!(task.expires_at.is_none());
        assert!(task.started_at.is_none());
        assert!(task.completed_at.is_none());
        assert!(task.crawl_id.is_none());
        assert!(task.lock_token.is_none());
        assert!(task.lock_expires_at.is_none());
        assert!(
            task.created_at >= before && task.created_at <= after,
            "created_at should be now"
        );
        assert_eq!(task.created_at, task.updated_at);
    }

    // can_retry tests

    #[test]
    fn test_can_retry_true_when_below_max() {
        let mut task = make_task();
        task.retry_count = 2;
        task.max_retries = 3;
        assert!(
            task.can_retry(),
            "should retry when retry_count < max_retries"
        );
    }

    #[test]
    fn test_can_retry_false_when_at_max() {
        let mut task = make_task();
        task.retry_count = 3;
        task.max_retries = 3;
        assert!(
            !task.can_retry(),
            "should not retry when retry_count == max_retries"
        );
    }

    #[test]
    fn test_can_retry_false_when_above_max() {
        let mut task = make_task();
        task.retry_count = 5;
        task.max_retries = 3;
        assert!(
            !task.can_retry(),
            "should not retry when retry_count > max_retries"
        );
    }

    // is_expired tests

    #[test]
    fn test_is_expired_false_when_no_expiry() {
        let task = make_task();
        assert!(
            !task.is_expired(),
            "task without expires_at should not be expired"
        );
    }

    #[test]
    fn test_is_expired_true_when_past_expiry() {
        let mut task = make_task();
        task.expires_at = Some(Utc::now() - chrono::Duration::seconds(10));
        assert!(task.is_expired(), "task past expires_at should be expired");
    }

    #[test]
    fn test_is_expired_false_when_future_expiry() {
        let mut task = make_task();
        task.expires_at = Some(Utc::now() + chrono::Duration::seconds(3600));
        assert!(
            !task.is_expired(),
            "task with future expires_at should not be expired"
        );
    }

    // is_locked tests

    #[test]
    fn test_is_locked_false_when_no_lock_token() {
        let task = make_task();
        assert!(
            !task.is_locked(),
            "task without lock_token should not be locked"
        );
    }

    #[test]
    fn test_is_locked_true_when_lock_in_future() {
        let mut task = make_task();
        let worker = crate::domain::id::Id::generate();
        task.acquire_lock(worker, chrono::Duration::seconds(60));
        assert!(
            task.is_locked(),
            "task with future lock expiry should be locked"
        );
    }

    #[test]
    fn test_is_locked_false_when_lock_expired() {
        let mut task = make_task();
        task.lock_token = Some(crate::domain::id::Id::generate());
        task.lock_expires_at = Some(Utc::now() - chrono::Duration::seconds(10));
        assert!(
            !task.is_locked(),
            "task with past lock expiry should not be locked"
        );
    }

    // start / complete / fail / cancel tests

    #[test]
    fn test_start_sets_active_and_started_at() {
        let mut task = make_task();
        let before = Utc::now();
        task.start();

        assert_eq!(task.status, TaskStatus::Active);
        assert!(task.started_at.is_some(), "started_at should be set");
        assert!(task.started_at.expect("started_at set") >= before);
        assert!(task.updated_at >= before);
    }

    #[test]
    fn test_complete_sets_completed_and_completed_at() {
        let mut task = make_task();
        task.status = TaskStatus::Active;
        let before = Utc::now();
        task.complete();

        assert_eq!(task.status, TaskStatus::Completed);
        assert!(task.completed_at.is_some(), "completed_at should be set");
        assert!(task.completed_at.expect("completed_at set") >= before);
        assert!(task.updated_at >= before);
    }

    #[test]
    fn test_fail_sets_failed_and_completed_at() {
        let mut task = make_task();
        task.status = TaskStatus::Active;
        let before = Utc::now();
        task.fail();

        assert_eq!(task.status, TaskStatus::Failed);
        assert!(
            task.completed_at.is_some(),
            "failed task should set completed_at"
        );
        assert!(task.updated_at >= before);
    }

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

        assert_eq!(task.status, TaskStatus::Cancelled);
        assert!(
            task.completed_at.is_some(),
            "cancelled task should set completed_at"
        );
        assert!(task.updated_at >= before);
    }

    // increment_retry tests

    #[test]
    fn test_increment_retry_increments_both_counters() {
        let mut task = make_task();
        assert_eq!(task.retry_count, 0);
        assert_eq!(task.attempt_count, 0);

        let before = Utc::now();
        task.increment_retry();

        assert_eq!(task.retry_count, 1, "retry_count should increment");
        assert_eq!(task.attempt_count, 1, "attempt_count should increment");
        assert!(task.updated_at >= before);
    }

    #[test]
    fn test_increment_retry_multiple_times() {
        let mut task = make_task();
        task.increment_retry();
        task.increment_retry();
        task.increment_retry();
        assert_eq!(task.retry_count, 3);
        assert_eq!(task.attempt_count, 3);
    }

    // acquire_lock / release_lock tests

    #[test]
    fn test_acquire_lock_sets_token_and_expiry() {
        let mut task = make_task();
        let worker = crate::domain::id::Id::generate();
        let duration = chrono::Duration::seconds(30);
        let before = Utc::now();

        task.acquire_lock(worker, duration);

        assert_eq!(
            task.lock_token,
            Some(worker),
            "lock_token should be worker id"
        );
        let expiry = task.lock_expires_at.expect("lock_expires_at should be set");
        assert!(
            expiry >= before + duration,
            "lock_expires_at should be ~duration in the future"
        );
        assert!(task.updated_at >= before);
    }

    #[test]
    fn test_release_lock_clears_token_and_expiry() {
        let mut task = make_task();
        task.acquire_lock(
            crate::domain::id::Id::generate(),
            chrono::Duration::seconds(30),
        );
        assert!(task.lock_token.is_some());

        let before = Utc::now();
        task.release_lock();

        assert!(task.lock_token.is_none(), "lock_token should be cleared");
        assert!(
            task.lock_expires_at.is_none(),
            "lock_expires_at should be cleared"
        );
        assert!(task.updated_at >= before);
    }

    // serde roundtrip

    #[test]
    fn test_task_serde_roundtrip() {
        let mut task = make_task();
        task.priority = 5;
        task.retry_count = 2;
        task.crawl_id = Some(crate::domain::id::Id::generate());

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

    // Helper

    fn make_task() -> Task {
        Task::new(
            crate::domain::id::Id::generate(),
            TaskType::Scrape,
            crate::domain::id::Id::generate(),
            crate::domain::id::Id::generate(),
            "https://example.com".to_string(),
            serde_json::json!({}),
        )
    }
}