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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! Handler state management module.
//!
//! This module provides the `HandlerState` trait for type-safe state access in handlers.
//! The main `CrawlRsState` is defined in `crate::di::axum_state` and provides centralized
//! dependency management through the trait-kit AsyncKit container.
//!
//! # Architecture
//!
//! The application uses a single unified `CrawlRsState` (defined in `di::axum_state`) that
//! contains all dependencies. This module provides:
//!
//! - `HandlerState` trait: A marker trait for handlers that need state access
//! - `CrawlHandlerState`: A convenience wrapper for crawl-specific operations
//!
//! # Example
//!
//! ```ignore
//! use crate::di::{CrawlRsState, CrawlRsStateExt};
//! use crate::presentation::state::HandlerState;
//!
//! async fn my_handler(state: HandlerState) {
//!     let task_repo = state.task_repo;
//!     // ... use task_repo
//! }
//! ```

use std::sync::Arc;

use crate::application::use_cases::crawl_use_case::CrawlUseCase;
use crate::di::{CrawlRsState, CrawlRsStateExt};
use crate::domain::repositories::{
    crawl_repository::CrawlRepository, scrape_result_repository::ScrapeResultRepository,
    task_repository::TaskRepository,
};
// teams feature 关闭时不导入 teams 相关类型
#[cfg(feature = "teams")]
use crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository;
#[cfg(feature = "teams")]
use crate::domain::services::team_service::TeamService;
// webhook feature 关闭时不导入 WebhookRepository
#[cfg(feature = "webhook")]
use crate::domain::repositories::webhook_repository::WebhookRepository;
use crate::domain::services::rate_limiting_service::RateLimitingService;

/// Trait for handler state access.
///
/// This trait provides type-safe access to application state for HTTP handlers.
/// It is implemented by `Arc<CrawlRsState>` and provides ergonomic accessors for
/// commonly used dependencies.
///
/// # Type Safety
///
/// Using this trait ensures that handlers receive properly typed state and
/// can only access dependencies they are authorized to use.
pub trait HandlerState: Clone + Send + Sync + 'static {
    /// Get task repository
    fn task_repo(&self) -> Arc<dyn TaskRepository>;

    /// Get crawl repository
    fn crawl_repo(&self) -> Arc<dyn CrawlRepository>;

    /// Get scrape result repository
    fn result_repo(&self) -> Arc<dyn ScrapeResultRepository>;

    /// Get webhook repository
    ///
    /// webhook feature 关闭时不编译此 accessor。
    #[cfg(feature = "webhook")]
    fn webhook_repo(&self) -> Arc<dyn WebhookRepository>;

    /// Get geo restriction repository
    ///
    /// teams feature 关闭时不编译此 accessor。
    #[cfg(feature = "teams")]
    fn geo_restriction_repo(&self) -> Arc<dyn GeoRestrictionRepository>;

    /// Get team service
    ///
    /// teams feature 关闭时不编译此 accessor。
    #[cfg(feature = "teams")]
    fn team_service(&self) -> Arc<TeamService>;

    /// Get rate limiting service
    fn rate_limiting_service(&self) -> Arc<dyn RateLimitingService>;
}

impl HandlerState for Arc<CrawlRsState> {
    fn task_repo(&self) -> Arc<dyn TaskRepository> {
        CrawlRsStateExt::task_repo(self)
    }

    fn crawl_repo(&self) -> Arc<dyn CrawlRepository> {
        CrawlRsStateExt::crawl_repo(self)
    }

    fn result_repo(&self) -> Arc<dyn ScrapeResultRepository> {
        CrawlRsStateExt::result_repo(self)
    }

    /// webhook feature 关闭时不编译此 accessor 实现。
    #[cfg(feature = "webhook")]
    fn webhook_repo(&self) -> Arc<dyn WebhookRepository> {
        CrawlRsStateExt::webhook_repo(self)
    }

    /// teams feature 关闭时不编译此 accessor 实现。
    #[cfg(feature = "teams")]
    fn geo_restriction_repo(&self) -> Arc<dyn GeoRestrictionRepository> {
        CrawlRsStateExt::geo_restriction_repo(self)
    }

    /// teams feature 关闭时不编译此 accessor 实现。
    #[cfg(feature = "teams")]
    fn team_service(&self) -> Arc<TeamService> {
        CrawlRsStateExt::team_service(self)
    }

    fn rate_limiting_service(&self) -> Arc<dyn RateLimitingService> {
        CrawlRsStateExt::rate_limiting_service(self)
    }
}

/// Crawl handler specific state wrapper.
///
/// This structure provides a convenient interface for crawl handlers,
/// encapsulating all dependencies needed for crawl operations and
/// providing factory methods for creating use cases.
///
/// # Usage
///
/// ```ignore
/// use crate::di::CrawlRsState;
/// use crate::presentation::state::CrawlHandlerState;
///
/// async fn crawl_handler(state: Arc<CrawlRsState>) {
///     let crawl_state = CrawlHandlerState::from_app_state(&state);
///     let use_case = crawl_state.create_use_case;
///     // ... use the use case
/// }
/// ```
#[derive(Clone)]
pub struct CrawlHandlerState {
    /// Crawl repository
    pub crawl_repo: Arc<dyn CrawlRepository>,
    /// Task repository
    pub task_repo: Arc<dyn TaskRepository>,
    /// Webhook repository
    ///
    /// webhook feature 关闭时不编译此字段。
    /// webhook-off 模式下,CrawlHandlerState 不持有 WebhookRepository。
    #[cfg(feature = "webhook")]
    pub webhook_repo: Arc<dyn WebhookRepository>,
    /// Scrape result repository
    pub scrape_result_repo: Arc<dyn ScrapeResultRepository>,
    /// Geo restriction repository
    ///
    /// teams feature 关闭时不编译此字段。
    /// teams-off 模式下,CrawlHandlerState 不持有 GeoRestrictionRepository。
    #[cfg(feature = "teams")]
    pub geo_restriction_repo: Arc<dyn GeoRestrictionRepository>,
    /// Team service
    ///
    /// teams feature 关闭时不编译此字段。
    /// teams-off 模式下,CrawlHandlerState 不持有 TeamService。
    #[cfg(feature = "teams")]
    pub team_service: Arc<TeamService>,
    /// Rate limiting service
    pub rate_limiting_service: Arc<dyn RateLimitingService>,
}

impl CrawlHandlerState {
    /// Create a new CrawlHandlerState from individual dependencies.
    ///
    /// # Parameters
    ///
    /// * `webhook_repo` - Webhook repository(仅 webhook-on 时传入)
    /// * `geo_restriction_repo` - Geo restriction repository(仅 teams-on 时传入)
    /// * `team_service` - Team service(仅 teams-on 时传入)
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        crawl_repo: Arc<dyn CrawlRepository>,
        task_repo: Arc<dyn TaskRepository>,
        scrape_result_repo: Arc<dyn ScrapeResultRepository>,
        rate_limiting_service: Arc<dyn RateLimitingService>,
        #[cfg(feature = "webhook")] webhook_repo: Arc<dyn WebhookRepository>,
        #[cfg(feature = "teams")] geo_restriction_repo: Arc<dyn GeoRestrictionRepository>,
        #[cfg(feature = "teams")] team_service: Arc<TeamService>,
    ) -> Self {
        Self {
            crawl_repo,
            task_repo,
            scrape_result_repo,
            rate_limiting_service,
            #[cfg(feature = "webhook")]
            webhook_repo,
            #[cfg(feature = "teams")]
            geo_restriction_repo,
            #[cfg(feature = "teams")]
            team_service,
        }
    }

    /// Create CrawlHandlerState from CrawlRsState.
    ///
    /// This is the preferred way to create CrawlHandlerState as it
    /// ensures consistency with the main application state.
    pub fn from_app_state(app_state: &Arc<CrawlRsState>) -> Self {
        Self {
            crawl_repo: app_state.crawl_repo.clone(),
            task_repo: app_state.task_repo.clone(),
            scrape_result_repo: app_state.result_repo.clone(),
            rate_limiting_service: app_state.rate_limiting_service.clone(),
            // webhook-on 时从 app_state 取 webhook_repo
            #[cfg(feature = "webhook")]
            webhook_repo: app_state.webhook_repo.clone(),
            // teams-on 时从 app_state 取 geo_restriction_repo / team_service
            #[cfg(feature = "teams")]
            geo_restriction_repo: app_state.geo_restriction_repo.clone(),
            #[cfg(feature = "teams")]
            team_service: app_state.team_service.clone(),
        }
    }

    /// Create a CrawlUseCase instance.
    ///
    /// This factory method creates a new use case with all required
    /// dependencies injected from this state.
    ///
    /// feature-off 时跳过对应字段(CrawlUseCase::new 已门控参数)
    pub fn create_use_case(&self) -> CrawlUseCase {
        CrawlUseCase::new(
            self.crawl_repo.clone(),
            self.task_repo.clone(),
            self.scrape_result_repo.clone(),
            #[cfg(feature = "teams")]
            self.geo_restriction_repo.clone(),
            #[cfg(feature = "teams")]
            self.team_service.clone(),
        )
    }
}

impl HandlerState for CrawlHandlerState {
    fn task_repo(&self) -> Arc<dyn TaskRepository> {
        self.task_repo.clone()
    }

    fn crawl_repo(&self) -> Arc<dyn CrawlRepository> {
        self.crawl_repo.clone()
    }

    fn result_repo(&self) -> Arc<dyn ScrapeResultRepository> {
        self.scrape_result_repo.clone()
    }

    /// webhook feature 关闭时不编译此 accessor 实现。
    #[cfg(feature = "webhook")]
    fn webhook_repo(&self) -> Arc<dyn WebhookRepository> {
        self.webhook_repo.clone()
    }

    /// teams feature 关闭时不编译此 accessor 实现。
    #[cfg(feature = "teams")]
    fn geo_restriction_repo(&self) -> Arc<dyn GeoRestrictionRepository> {
        self.geo_restriction_repo.clone()
    }

    /// teams feature 关闭时不编译此 accessor 实现。
    #[cfg(feature = "teams")]
    fn team_service(&self) -> Arc<TeamService> {
        self.team_service.clone()
    }

    fn rate_limiting_service(&self) -> Arc<dyn RateLimitingService> {
        self.rate_limiting_service.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::models::credits_model::CreditsTransactionType;
    use crate::domain::models::ScrapeResult;
    use crate::domain::models::{Crawl, Task};
    // webhook feature 关闭时不导入 Webhook 模型
    #[cfg(feature = "webhook")]
    use crate::domain::models::Webhook;
    use crate::domain::repositories::task_repository::{RepositoryError, TaskQueryParams};
    // teams feature 关闭时不导入 geo_location 相关类型
    #[cfg(feature = "teams")]
    use crate::domain::services::geo_location::{GeoLocation, GeoLocationService};
    use crate::domain::services::rate_limiting_service::{
        BacklogService, ConcurrencyConfig, ConcurrencyControlService, ConcurrencyResult,
        QuotaService, RateLimitConfig, RateLimitResult, RateLimitService, RateLimitingError,
    };
    // teams feature 关闭时不导入 team_service 相关类型
    #[cfg(feature = "teams")]
    use crate::domain::services::team_service::TeamGeoRestrictions;
    use async_trait::async_trait;
    use std::collections::HashSet;
    // teams-off 时 IpAddr 未使用
    #[cfg(feature = "teams")]
    use std::net::IpAddr;

    // No-op mocks
    // These mocks satisfy the trait bounds required by CrawlHandlerState.
    // Their methods are never invoked by the tests below; they exist only to
    // allow construction of the state wrapper for wiring/clone verification.

    struct MockCrawlRepository;
    #[async_trait]
    impl CrawlRepository for MockCrawlRepository {
        async fn create(&self, crawl: &Crawl) -> Result<Crawl, RepositoryError> {
            Ok(crawl.clone())
        }
        async fn find_by_id(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<Option<Crawl>, RepositoryError> {
            Ok(None)
        }
        async fn update(&self, crawl: &Crawl) -> Result<Crawl, RepositoryError> {
            Ok(crawl.clone())
        }
        async fn increment_completed_tasks(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<(), RepositoryError> {
            Ok(())
        }
        async fn increment_failed_tasks(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<(), RepositoryError> {
            Ok(())
        }
        async fn update_status(
            &self,
            _id: crate::domain::id::Id,
            _status: crate::domain::models::CrawlStatus,
        ) -> Result<(), RepositoryError> {
            Ok(())
        }
        async fn increment_total_tasks(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<(), RepositoryError> {
            Ok(())
        }
        async fn find_by_team_id_paginated(
            &self,
            _team_id: crate::domain::id::Id,
            _limit: u32,
            _offset: u32,
        ) -> Result<Vec<Crawl>, RepositoryError> {
            Ok(vec![])
        }
        async fn count_by_team_id(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }
    }

    struct MockTaskRepository;
    #[async_trait]
    impl TaskRepository for MockTaskRepository {
        async fn create(&self, task: &Task) -> Result<Task, RepositoryError> {
            Ok(task.clone())
        }
        async fn find_by_id(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<Option<Task>, RepositoryError> {
            Ok(None)
        }
        async fn update(&self, task: &Task) -> Result<Task, RepositoryError> {
            Ok(task.clone())
        }
        async fn acquire_next(
            &self,
            _worker_id: crate::domain::id::Id,
        ) -> Result<Option<Task>, RepositoryError> {
            Ok(None)
        }
        async fn mark_completed(
            &self,
            _id: crate::domain::id::Id,
            _lock_token: Option<crate::domain::id::Id>,
        ) -> Result<u64, RepositoryError> {
            Ok(1)
        }
        async fn mark_failed(
            &self,
            _id: crate::domain::id::Id,
            _lock_token: Option<crate::domain::id::Id>,
        ) -> Result<u64, RepositoryError> {
            Ok(1)
        }
        async fn mark_cancelled(&self, _id: crate::domain::id::Id) -> Result<u64, RepositoryError> {
            Ok(1)
        }
        async fn exists_by_url(&self, _url: &str) -> Result<bool, RepositoryError> {
            Ok(false)
        }
        async fn find_existing_urls(
            &self,
            _urls: &[String],
        ) -> Result<HashSet<String>, RepositoryError> {
            Ok(HashSet::new())
        }
        async fn reset_stuck_tasks(
            &self,
            _timeout: chrono::Duration,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }
        async fn cancel_tasks_by_crawl_id(
            &self,
            _crawl_id: crate::domain::id::Id,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }
        async fn expire_tasks(&self) -> Result<u64, RepositoryError> {
            Ok(0)
        }
        async fn find_by_crawl_id(
            &self,
            _crawl_id: crate::domain::id::Id,
        ) -> Result<Vec<Task>, RepositoryError> {
            Ok(vec![])
        }
        async fn query_tasks(
            &self,
            _params: TaskQueryParams,
        ) -> Result<(Vec<Task>, u64), RepositoryError> {
            Ok((vec![], 0))
        }
        async fn batch_cancel(
            &self,
            _task_ids: Vec<crate::domain::id::Id>,
            _team_id: crate::domain::id::Id,
            _force: bool,
        ) -> Result<
            (
                Vec<crate::domain::id::Id>,
                Vec<(crate::domain::id::Id, String)>,
            ),
            RepositoryError,
        > {
            Ok((vec![], vec![]))
        }

        async fn renew_lock(
            &self,
            _task_id: crate::domain::id::Id,
            _worker_id: crate::domain::id::Id,
            _extend_seconds: i64,
        ) -> Result<bool, RepositoryError> {
            Ok(true)
        }
    }

    // webhook feature 关闭时不编译此 mock
    #[cfg(feature = "webhook")]
    struct MockWebhookRepository;
    #[cfg(feature = "webhook")]
    #[async_trait]
    impl WebhookRepository for MockWebhookRepository {
        async fn create(&self, webhook: &Webhook) -> Result<Webhook, RepositoryError> {
            Ok(webhook.clone())
        }
        async fn find_by_id(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<Option<Webhook>, RepositoryError> {
            Ok(None)
        }
        async fn find_by_team_id(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<Vec<Webhook>, RepositoryError> {
            Ok(vec![])
        }
    }

    struct MockScrapeResultRepository;
    #[async_trait]
    impl ScrapeResultRepository for MockScrapeResultRepository {
        async fn save(&self, _result: ScrapeResult) -> anyhow::Result<()> {
            Ok(())
        }
        async fn find_by_task_id(
            &self,
            _task_id: crate::domain::id::Id,
        ) -> anyhow::Result<Option<ScrapeResult>> {
            Ok(None)
        }
        async fn find_by_task_ids(
            &self,
            _task_ids: &[crate::domain::id::Id],
        ) -> anyhow::Result<Vec<ScrapeResult>> {
            Ok(vec![])
        }
        async fn get_team_avg_response_time(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> anyhow::Result<f64> {
            Ok(0.0)
        }

        async fn cleanup_expired(&self, _retention_days: i64) -> anyhow::Result<u64> {
            Ok(0)
        }
    }

    // teams feature 关闭时不编译此 mock
    #[cfg(feature = "teams")]
    struct MockGeoRestrictionRepository;
    #[cfg(feature = "teams")]
    #[async_trait]
    impl GeoRestrictionRepository for MockGeoRestrictionRepository {
        async fn get_team_restrictions(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<
            TeamGeoRestrictions,
            crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepositoryError,
        > {
            Ok(TeamGeoRestrictions::default())
        }
        async fn update_team_restrictions(
            &self,
            _team_id: crate::domain::id::Id,
            _restrictions: &TeamGeoRestrictions,
        ) -> Result<
            (),
            crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepositoryError,
        > {
            Ok(())
        }
        async fn log_geo_restriction_action(
            &self,
            _team_id: crate::domain::id::Id,
            _ip_address: &str,
            _country_code: &str,
            _action: &str,
            _reason: &str,
        ) -> Result<
            (),
            crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepositoryError,
        > {
            Ok(())
        }
    }

    // teams feature 关闭时不编译此 mock
    #[cfg(feature = "teams")]
    struct MockGeoLocationService;
    #[cfg(feature = "teams")]
    #[async_trait]
    impl GeoLocationService for MockGeoLocationService {
        async fn get_location(&self, _ip: &IpAddr) -> anyhow::Result<GeoLocation> {
            Ok(GeoLocation::default())
        }
    }

    struct MockRateLimitingService;
    #[async_trait]
    impl RateLimitService for MockRateLimitingService {
        async fn check_rate_limit(
            &self,
            _api_key: &str,
            _endpoint: &str,
        ) -> Result<RateLimitResult, RateLimitingError> {
            Ok(RateLimitResult::Allowed)
        }
        async fn get_team_rate_limit_config(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<RateLimitConfig, RateLimitingError> {
            Ok(RateLimitConfig::default())
        }
        async fn update_team_rate_limit_config(
            &self,
            _team_id: crate::domain::id::Id,
            _config: RateLimitConfig,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }
        async fn cleanup_expired_rate_limits(&self) -> Result<u64, RateLimitingError> {
            Ok(0)
        }
    }
    #[async_trait]
    impl ConcurrencyControlService for MockRateLimitingService {
        async fn check_team_concurrency(
            &self,
            _team_id: crate::domain::id::Id,
            _task_id: crate::domain::id::Id,
        ) -> Result<ConcurrencyResult, RateLimitingError> {
            Ok(ConcurrencyResult::Allowed)
        }
        async fn release_team_concurrency_slot(
            &self,
            _team_id: crate::domain::id::Id,
            _task_id: crate::domain::id::Id,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }
        async fn get_team_current_concurrency(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<u32, RateLimitingError> {
            Ok(0)
        }
        async fn get_team_concurrency_config(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<ConcurrencyConfig, RateLimitingError> {
            Ok(ConcurrencyConfig::default())
        }
        async fn update_team_concurrency_config(
            &self,
            _team_id: crate::domain::id::Id,
            _config: ConcurrencyConfig,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }
    }
    #[async_trait]
    impl BacklogService for MockRateLimitingService {
        async fn process_backlog_tasks(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<u32, RateLimitingError> {
            Ok(0)
        }
    }
    #[async_trait]
    impl QuotaService for MockRateLimitingService {
        async fn check_and_deduct_quota(
            &self,
            _team_id: crate::domain::id::Id,
            _amount: i64,
            _transaction_type: CreditsTransactionType,
            _description: String,
            _reference_id: Option<crate::domain::id::Id>,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }
        async fn get_quota_balance(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<i64, RateLimitingError> {
            Ok(0)
        }

        async fn refund_quota(
            &self,
            _team_id: crate::domain::id::Id,
            _amount: i64,
            _description: String,
            _reference_id: Option<crate::domain::id::Id>,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }
    }
    impl RateLimitingService for MockRateLimitingService {}

    /// Build a CrawlHandlerState with no-op mocks for wiring/clone tests.
    ///
    /// feature-off 时跳过对应依赖构造。
    fn build_test_state() -> CrawlHandlerState {
        let crawl_repo: Arc<dyn CrawlRepository> = Arc::new(MockCrawlRepository);
        let task_repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository);
        let scrape_result_repo: Arc<dyn ScrapeResultRepository> =
            Arc::new(MockScrapeResultRepository);
        let rate_limiting_service: Arc<dyn RateLimitingService> = Arc::new(MockRateLimitingService);

        // teams-on 时构造 geo_restriction_repo / team_service
        #[cfg(feature = "teams")]
        let geo_restriction_repo: Arc<dyn GeoRestrictionRepository> =
            Arc::new(MockGeoRestrictionRepository);
        #[cfg(feature = "teams")]
        let team_service = Arc::new(TeamService::new(
            Arc::new(MockGeoLocationService),
            geo_restriction_repo.clone(),
        ));

        // webhook-on 时构造 webhook_repo
        #[cfg(feature = "webhook")]
        let webhook_repo: Arc<dyn WebhookRepository> = Arc::new(MockWebhookRepository);

        CrawlHandlerState::new(
            crawl_repo,
            task_repo,
            scrape_result_repo,
            rate_limiting_service,
            #[cfg(feature = "webhook")]
            webhook_repo,
            #[cfg(feature = "teams")]
            geo_restriction_repo,
            #[cfg(feature = "teams")]
            team_service,
        )
    }

    #[test]
    fn test_new_stores_all_dependencies() {
        let state = build_test_state();
        // Verify all fields are populated by accessing each through the trait.
        // Each accessor must return a valid Arc (not panic).
        let _ = state.crawl_repo();
        let _ = state.task_repo();
        let _ = state.result_repo();
        // webhook-on 时验证 webhook_repo accessor
        #[cfg(feature = "webhook")]
        {
            let _ = state.webhook_repo();
        }
        // teams-on 时验证 geo_restriction_repo / team_service accessor
        #[cfg(feature = "teams")]
        {
            let _ = state.geo_restriction_repo();
            let _ = state.team_service();
        }
        let _ = state.rate_limiting_service();
    }

    #[test]
    fn test_handler_state_trait_returns_injected_repositories() {
        let state = build_test_state();
        // The trait accessors must return Arcs pointing to the same underlying
        // objects that were injected via new, verifying correct wiring.
        assert!(Arc::ptr_eq(&state.crawl_repo, &state.crawl_repo(),));
        assert!(Arc::ptr_eq(&state.task_repo, &state.task_repo(),));
        // webhook-on 时验证 webhook_repo 注入一致性
        #[cfg(feature = "webhook")]
        {
            assert!(Arc::ptr_eq(&state.webhook_repo, &state.webhook_repo(),));
        }
        assert!(Arc::ptr_eq(&state.scrape_result_repo, &state.result_repo(),));
        // teams-on 时验证 geo_restriction_repo 注入一致性
        #[cfg(feature = "teams")]
        {
            assert!(Arc::ptr_eq(
                &state.geo_restriction_repo,
                &state.geo_restriction_repo(),
            ));
        }
    }

    #[test]
    fn test_handler_state_trait_returns_injected_services() {
        let state = build_test_state();
        // teams-on 时验证 team_service 注入一致性
        #[cfg(feature = "teams")]
        {
            assert!(Arc::ptr_eq(&state.team_service, &state.team_service(),));
        }
        assert!(Arc::ptr_eq(
            &state.rate_limiting_service,
            &state.rate_limiting_service(),
        ));
    }

    #[test]
    fn test_create_use_case_constructs_without_panic() {
        let state = build_test_state();
        let _use_case = state.create_use_case();
        // Reaching this point means CrawlUseCase::new accepted all injected deps.
    }

    #[test]
    fn test_clone_shares_underlying_state() {
        let state = build_test_state();
        let cloned = state.clone();
        // Clone must share the same underlying Arcs (not deep copies)
        assert!(Arc::ptr_eq(&state.crawl_repo, &cloned.crawl_repo));
        assert!(Arc::ptr_eq(&state.task_repo, &cloned.task_repo));
        // webhook-on 时验证 webhook_repo clone 一致性
        #[cfg(feature = "webhook")]
        {
            assert!(Arc::ptr_eq(&state.webhook_repo, &cloned.webhook_repo));
        }
        assert!(Arc::ptr_eq(
            &state.scrape_result_repo,
            &cloned.scrape_result_repo
        ));
        // teams-on 时验证 geo_restriction_repo / team_service clone 一致性
        #[cfg(feature = "teams")]
        {
            assert!(Arc::ptr_eq(
                &state.geo_restriction_repo,
                &cloned.geo_restriction_repo
            ));
            assert!(Arc::ptr_eq(&state.team_service, &cloned.team_service));
        }
        assert!(Arc::ptr_eq(
            &state.rate_limiting_service,
            &cloned.rate_limiting_service
        ));
    }

    #[test]
    fn test_clone_trait_accessor_returns_same_arc() {
        let state = build_test_state();
        let cloned = state.clone();
        // Trait accessor on the clone must return the same Arc as the original
        assert!(Arc::ptr_eq(&state.crawl_repo(), &cloned.crawl_repo()));
    }
}