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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

use async_trait::async_trait;
use serde::{Deserialize, Serialize};

/// 限流策略类型
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RateLimitStrategy {
    /// 令牌桶算法
    TokenBucket,
    /// 漏桶算法
    LeakyBucket,
    /// 固定窗口计数器
    FixedWindow,
    /// 滑动窗口计数器
    SlidingWindow,
}

/// 并发控制策略
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ConcurrencyStrategy {
    /// 分布式信号量
    DistributedSemaphore,
    /// 信号量
    Semaphore,
    /// 数据库级别的并发控制
    DatabaseLevel,
}

/// 限流配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitConfig {
    /// 限流策略
    pub strategy: RateLimitStrategy,
    /// 每秒允许的请求数
    pub requests_per_second: u32,
    /// 每分钟允许的请求数
    pub requests_per_minute: u32,
    /// 每小时允许的请求数
    pub requests_per_hour: u32,
    /// 令牌桶容量(如果使用令牌桶算法)
    pub bucket_capacity: Option<u32>,
    /// 是否启用限流
    pub enabled: bool,
}

impl RateLimitConfig {
    /// 验证配置的有效性
    pub fn validate(&self) -> Result<(), ValidationError> {
        if self.requests_per_second == 0 {
            return Err(ValidationError::ZeroRate(
                "requests_per_second cannot be zero",
            ));
        }
        if self.requests_per_minute == 0 {
            return Err(ValidationError::ZeroRate(
                "requests_per_minute cannot be zero",
            ));
        }
        if self.requests_per_hour == 0 {
            return Err(ValidationError::ZeroRate(
                "requests_per_hour cannot be zero",
            ));
        }
        // 确保速率一致:每秒速率不应超过每分钟速率/60,每分钟速率不应超过每小时速率/60
        if self.requests_per_second > self.requests_per_minute / 60 {
            return Err(ValidationError::InconsistentRates(
                "requests_per_second exceeds requests_per_minute / 60".to_string(),
            ));
        }
        if self.requests_per_minute > self.requests_per_hour / 60 {
            return Err(ValidationError::InconsistentRates(
                "requests_per_minute exceeds requests_per_hour / 60".to_string(),
            ));
        }
        if let Some(capacity) = self.bucket_capacity {
            if capacity == 0 {
                return Err(ValidationError::ZeroCapacity(
                    "bucket_capacity cannot be zero".to_string(),
                ));
            }
        }
        Ok(())
    }
}

impl Default for RateLimitConfig {
    fn default() -> Self {
        Self {
            strategy: RateLimitStrategy::TokenBucket,
            requests_per_second: 10,
            requests_per_minute: 100,
            requests_per_hour: 1000,
            bucket_capacity: Some(100),
            enabled: true,
        }
    }
}

/// 并发控制配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConcurrencyConfig {
    /// 并发控制策略
    pub strategy: ConcurrencyStrategy,
    /// 最大并发数
    pub max_concurrent_tasks: u32,
    /// 团队级别的最大并发数
    pub max_concurrent_per_team: u32,
    /// 锁的超时时间(秒)
    pub lock_timeout_seconds: u64,
    /// 是否启用并发控制
    pub enabled: bool,
}

impl ConcurrencyConfig {
    /// 验证配置的有效性
    pub fn validate(&self) -> Result<(), ValidationError> {
        if self.max_concurrent_tasks == 0 {
            return Err(ValidationError::ZeroCapacity(
                "max_concurrent_tasks cannot be zero".to_string(),
            ));
        }
        if self.max_concurrent_per_team == 0 {
            return Err(ValidationError::ZeroCapacity(
                "max_concurrent_per_team cannot be zero".to_string(),
            ));
        }
        if self.lock_timeout_seconds == 0 {
            return Err(ValidationError::InvalidTimeout(
                "lock_timeout_seconds cannot be zero".to_string(),
            ));
        }
        if self.lock_timeout_seconds < 60 {
            return Err(ValidationError::InvalidTimeout(
                "lock_timeout_seconds should be at least 60 seconds".to_string(),
            ));
        }
        if self.max_concurrent_per_team > self.max_concurrent_tasks {
            return Err(ValidationError::InconsistentRates(
                "max_concurrent_per_team exceeds max_concurrent_tasks".to_string(),
            ));
        }
        Ok(())
    }
}

impl Default for ConcurrencyConfig {
    fn default() -> Self {
        Self {
            strategy: ConcurrencyStrategy::DistributedSemaphore,
            max_concurrent_tasks: 100,
            max_concurrent_per_team: 10,
            lock_timeout_seconds: 300, // 5分钟
            enabled: true,
        }
    }
}

/// 限流与并发控制结果
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RateLimitResult {
    /// 允许通过
    Allowed,
    /// 被拒绝
    Denied { reason: String },
    /// 需要等待(包含等待时间)
    RetryAfter { retry_after_seconds: u64 },
}

/// 并发控制结果
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConcurrencyResult {
    /// 允许执行
    Allowed,
    /// 被拒绝(并发限制已达到)
    Denied { reason: String },
    /// 任务已加入积压队列
    Queued { backlog_id: crate::domain::id::Id },
}

// 拆分后的接口

/// 限流服务接口(核心限流功能)
#[async_trait]
pub trait RateLimitService: Send + Sync {
    /// 检查API限流
    async fn check_rate_limit(
        &self,
        api_key: &str,
        endpoint: &str,
    ) -> Result<RateLimitResult, RateLimitingError>;

    /// 获取团队的限流配置
    async fn get_team_rate_limit_config(
        &self,
        team_id: crate::domain::id::Id,
    ) -> Result<RateLimitConfig, RateLimitingError>;

    /// 更新团队的限流配置
    async fn update_team_rate_limit_config(
        &self,
        team_id: crate::domain::id::Id,
        config: RateLimitConfig,
    ) -> Result<(), RateLimitingError>;

    /// 清理过期的限流记录
    async fn cleanup_expired_rate_limits(&self) -> Result<u64, RateLimitingError>;
}

/// 并发控制服务接口
#[async_trait]
pub trait ConcurrencyControlService: Send + Sync {
    /// 检查团队并发限制
    async fn check_team_concurrency(
        &self,
        team_id: crate::domain::id::Id,
        task_id: crate::domain::id::Id,
    ) -> Result<ConcurrencyResult, RateLimitingError>;

    /// 释放团队并发槽位
    async fn release_team_concurrency_slot(
        &self,
        team_id: crate::domain::id::Id,
        task_id: crate::domain::id::Id,
    ) -> Result<(), RateLimitingError>;

    /// 获取团队的当前并发数
    async fn get_team_current_concurrency(
        &self,
        team_id: crate::domain::id::Id,
    ) -> Result<u32, RateLimitingError>;

    /// 获取团队的并发配置
    async fn get_team_concurrency_config(
        &self,
        team_id: crate::domain::id::Id,
    ) -> Result<ConcurrencyConfig, RateLimitingError>;

    /// 更新团队的并发配置
    async fn update_team_concurrency_config(
        &self,
        team_id: crate::domain::id::Id,
        config: ConcurrencyConfig,
    ) -> Result<(), RateLimitingError>;
}

/// 积压任务服务接口
#[async_trait]
pub trait BacklogService: Send + Sync {
    /// 处理积压任务
    async fn process_backlog_tasks(
        &self,
        team_id: crate::domain::id::Id,
    ) -> Result<u32, RateLimitingError>;
}

/// 配额/积分服务接口
#[async_trait]
pub trait QuotaService: Send + Sync {
    /// 检查并扣除团队配额(Credits)
    async fn check_and_deduct_quota(
        &self,
        team_id: crate::domain::id::Id,
        amount: i64,
        transaction_type: crate::domain::models::CreditsTransactionType,
        description: String,
        reference_id: Option<crate::domain::id::Id>,
    ) -> Result<(), RateLimitingError>;

    /// 退还配额积分(入队失败等场景的补偿)
    ///
    /// 以 `Refund` 交易类型将已扣积分加回团队余额;补偿失败仅记录错误,
    /// 不应阻断原始错误路径的返回。
    async fn refund_quota(
        &self,
        team_id: crate::domain::id::Id,
        amount: i64,
        description: String,
        reference_id: Option<crate::domain::id::Id>,
    ) -> Result<(), RateLimitingError>;

    /// 获取团队配额余额
    async fn get_quota_balance(
        &self,
        team_id: crate::domain::id::Id,
    ) -> Result<i64, RateLimitingError>;
}

/// 组合接口:提供所有限流与并发控制功能(向后兼容)
#[async_trait]
pub trait RateLimitingService:
    RateLimitService + ConcurrencyControlService + BacklogService + QuotaService + Send + Sync
{
}

/// 限流与并发控制错误类型
#[derive(Debug, thiserror::Error)]
pub enum RateLimitingError {
    #[error("Rate limit exceeded: {0}")]
    RateLimitExceeded(String),

    #[error("Concurrency limit exceeded: {0}")]
    ConcurrencyLimitExceeded(String),

    #[error("Configuration error: {0}")]
    ConfigurationError(String),

    #[error("Database operation failed, please try again later")]
    DatabaseError,

    #[error("Credits service temporarily unavailable")]
    CreditsError,

    #[error("Other error: {0}")]
    Other(#[from] anyhow::Error),
}

/// 配置验证错误类型
#[derive(Debug, thiserror::Error)]
pub enum ValidationError {
    #[error("Rate limit cannot be zero: {0}")]
    ZeroRate(&'static str),

    #[error("Capacity cannot be zero: {0}")]
    ZeroCapacity(String),

    #[error("Invalid timeout: {0}")]
    InvalidTimeout(String),

    #[error("Inconsistent rate configuration: {0}")]
    InconsistentRates(String),
}

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

    // RateLimitStrategy tests

    #[test]
    fn test_rate_limit_strategy_serde_all_variants() {
        for strategy in [
            RateLimitStrategy::TokenBucket,
            RateLimitStrategy::LeakyBucket,
            RateLimitStrategy::FixedWindow,
            RateLimitStrategy::SlidingWindow,
        ] {
            let json = serde_json::to_string(&strategy).expect("serialize");
            let back: RateLimitStrategy = serde_json::from_str(&json).expect("deserialize");
            assert_eq!(strategy, back, "roundtrip should preserve: {}", json);
        }
    }

    #[test]
    fn test_rate_limit_strategy_equality() {
        assert_eq!(
            RateLimitStrategy::TokenBucket,
            RateLimitStrategy::TokenBucket
        );
        assert_ne!(
            RateLimitStrategy::TokenBucket,
            RateLimitStrategy::LeakyBucket
        );
        assert_ne!(
            RateLimitStrategy::FixedWindow,
            RateLimitStrategy::SlidingWindow
        );
    }

    #[test]
    fn test_rate_limit_strategy_clone_copy() {
        let s1 = RateLimitStrategy::TokenBucket;
        let s2 = s1; // Copy
        assert_eq!(s1, s2);
        let s3 = s1;
        assert_eq!(s1, s3);
    }

    // ConcurrencyStrategy tests

    #[test]
    fn test_concurrency_strategy_serde_all_variants() {
        for strategy in [
            ConcurrencyStrategy::DistributedSemaphore,
            ConcurrencyStrategy::Semaphore,
            ConcurrencyStrategy::DatabaseLevel,
        ] {
            let json = serde_json::to_string(&strategy).expect("serialize");
            let back: ConcurrencyStrategy = serde_json::from_str(&json).expect("deserialize");
            assert_eq!(strategy, back, "roundtrip should preserve: {}", json);
        }
    }

    #[test]
    fn test_concurrency_strategy_equality() {
        assert_eq!(
            ConcurrencyStrategy::DistributedSemaphore,
            ConcurrencyStrategy::DistributedSemaphore
        );
        assert_ne!(
            ConcurrencyStrategy::DistributedSemaphore,
            ConcurrencyStrategy::Semaphore
        );
        assert_ne!(
            ConcurrencyStrategy::Semaphore,
            ConcurrencyStrategy::DatabaseLevel
        );
    }

    // RateLimitConfig::default tests

    #[test]
    fn test_rate_limit_config_default_values() {
        let config = RateLimitConfig::default();
        assert_eq!(config.strategy, RateLimitStrategy::TokenBucket);
        assert_eq!(config.requests_per_second, 10);
        assert_eq!(config.requests_per_minute, 100);
        assert_eq!(config.requests_per_hour, 1000);
        assert_eq!(config.bucket_capacity, Some(100));
        assert!(config.enabled);
    }

    #[test]
    fn test_rate_limit_config_default_has_expected_values() {
        let config = RateLimitConfig::default();
        assert_eq!(config.strategy, RateLimitStrategy::TokenBucket);
        assert_eq!(config.requests_per_second, 10);
        assert_eq!(config.requests_per_minute, 100);
        assert_eq!(config.requests_per_hour, 1000);
        assert_eq!(config.bucket_capacity, Some(100));
        assert!(config.enabled);
    }

    // RateLimitConfig::validate tests

    #[test]
    fn test_rate_limit_config_validate_success() {
        let config = RateLimitConfig {
            strategy: RateLimitStrategy::TokenBucket,
            requests_per_second: 1,
            requests_per_minute: 100,
            requests_per_hour: 6000,
            bucket_capacity: Some(50),
            enabled: true,
        };
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_rate_limit_config_validate_success_without_bucket_capacity() {
        let config = RateLimitConfig {
            strategy: RateLimitStrategy::FixedWindow,
            requests_per_second: 1,
            requests_per_minute: 60,
            requests_per_hour: 3600,
            bucket_capacity: None,
            enabled: true,
        };
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_rate_limit_config_validate_zero_requests_per_second() {
        let config = RateLimitConfig {
            requests_per_second: 0,
            ..Default::default()
        };
        let err = config.validate().expect_err("should fail");
        assert!(matches!(err, ValidationError::ZeroRate(_)));
        assert!(err.to_string().contains("requests_per_second"));
    }

    #[test]
    fn test_rate_limit_config_validate_zero_requests_per_minute() {
        let config = RateLimitConfig {
            requests_per_minute: 0,
            ..Default::default()
        };
        let err = config.validate().expect_err("should fail");
        assert!(matches!(err, ValidationError::ZeroRate(_)));
        assert!(err.to_string().contains("requests_per_minute"));
    }

    #[test]
    fn test_rate_limit_config_validate_zero_requests_per_hour() {
        let config = RateLimitConfig {
            requests_per_hour: 0,
            ..Default::default()
        };
        let err = config.validate().expect_err("should fail");
        assert!(matches!(err, ValidationError::ZeroRate(_)));
        assert!(err.to_string().contains("requests_per_hour"));
    }

    #[test]
    fn test_rate_limit_config_validate_per_second_exceeds_per_minute() {
        // requests_per_second > requests_per_minute / 60
        let config = RateLimitConfig {
            strategy: RateLimitStrategy::TokenBucket,
            requests_per_second: 5,
            requests_per_minute: 100, // 100/60 = 1.66, 5 > 1.66
            requests_per_hour: 6000,
            bucket_capacity: Some(100),
            enabled: true,
        };
        let err = config.validate().expect_err("should fail");
        assert!(matches!(err, ValidationError::InconsistentRates(_)));
        assert!(err
            .to_string()
            .contains("requests_per_second exceeds requests_per_minute"));
    }

    #[test]
    fn test_rate_limit_config_validate_per_minute_exceeds_per_hour() {
        // requests_per_minute > requests_per_hour / 60
        let config = RateLimitConfig {
            strategy: RateLimitStrategy::TokenBucket,
            requests_per_second: 1,
            requests_per_minute: 100,
            requests_per_hour: 6000, // 6000/60 = 100, 100 > 100 is false, need to push minute higher
            bucket_capacity: Some(100),
            enabled: true,
        };
        // The above should pass; construct one that fails
        let config_fail = RateLimitConfig {
            strategy: RateLimitStrategy::TokenBucket,
            requests_per_second: 1,
            requests_per_minute: 200,
            requests_per_hour: 6000, // 6000/60 = 100, 200 > 100
            bucket_capacity: Some(100),
            enabled: true,
        };
        let err = config_fail.validate().expect_err("should fail");
        assert!(matches!(err, ValidationError::InconsistentRates(_)));
        assert!(err
            .to_string()
            .contains("requests_per_minute exceeds requests_per_hour"));
        // Sanity: the valid one passes
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_rate_limit_config_validate_zero_bucket_capacity() {
        // Use consistent rates so validation reaches the bucket_capacity check
        let mut config = RateLimitConfig {
            strategy: RateLimitStrategy::TokenBucket,
            requests_per_second: 1,
            requests_per_minute: 100,
            requests_per_hour: 6000,
            bucket_capacity: Some(50),
            enabled: true,
        };
        config.bucket_capacity = Some(0);
        let err = config.validate().expect_err("should fail");
        assert!(matches!(err, ValidationError::ZeroCapacity(_)));
        assert!(err.to_string().contains("bucket_capacity cannot be zero"));
    }

    #[test]
    fn test_rate_limit_config_serde_roundtrip() {
        let config = RateLimitConfig::default();
        let json = serde_json::to_string(&config).expect("serialize");
        let back: RateLimitConfig = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back.strategy, config.strategy);
        assert_eq!(back.requests_per_second, config.requests_per_second);
        assert_eq!(back.requests_per_minute, config.requests_per_minute);
        assert_eq!(back.requests_per_hour, config.requests_per_hour);
        assert_eq!(back.bucket_capacity, config.bucket_capacity);
        assert_eq!(back.enabled, config.enabled);
    }

    // ConcurrencyConfig::default tests

    #[test]
    fn test_concurrency_config_default_values() {
        let config = ConcurrencyConfig::default();
        assert_eq!(config.strategy, ConcurrencyStrategy::DistributedSemaphore);
        assert_eq!(config.max_concurrent_tasks, 100);
        assert_eq!(config.max_concurrent_per_team, 10);
        assert_eq!(config.lock_timeout_seconds, 300);
        assert!(config.enabled);
    }

    #[test]
    fn test_concurrency_config_default_passes_validation() {
        let config = ConcurrencyConfig::default();
        assert!(config.validate().is_ok(), "default config should be valid");
    }

    // ConcurrencyConfig::validate tests

    #[test]
    fn test_concurrency_config_validate_success() {
        let config = ConcurrencyConfig {
            strategy: ConcurrencyStrategy::Semaphore,
            max_concurrent_tasks: 50,
            max_concurrent_per_team: 10,
            lock_timeout_seconds: 120,
            enabled: true,
        };
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_concurrency_config_validate_zero_max_concurrent_tasks() {
        let config = ConcurrencyConfig {
            max_concurrent_tasks: 0,
            ..Default::default()
        };
        let err = config.validate().expect_err("should fail");
        assert!(matches!(err, ValidationError::ZeroCapacity(_)));
        assert!(err
            .to_string()
            .contains("max_concurrent_tasks cannot be zero"));
    }

    #[test]
    fn test_concurrency_config_validate_zero_max_concurrent_per_team() {
        let config = ConcurrencyConfig {
            max_concurrent_per_team: 0,
            ..Default::default()
        };
        let err = config.validate().expect_err("should fail");
        assert!(matches!(err, ValidationError::ZeroCapacity(_)));
        assert!(err
            .to_string()
            .contains("max_concurrent_per_team cannot be zero"));
    }

    #[test]
    fn test_concurrency_config_validate_zero_lock_timeout() {
        let config = ConcurrencyConfig {
            lock_timeout_seconds: 0,
            ..Default::default()
        };
        let err = config.validate().expect_err("should fail");
        assert!(matches!(err, ValidationError::InvalidTimeout(_)));
        assert!(err
            .to_string()
            .contains("lock_timeout_seconds cannot be zero"));
    }

    #[test]
    fn test_concurrency_config_validate_lock_timeout_below_minimum() {
        let config = ConcurrencyConfig {
            lock_timeout_seconds: 30,
            ..Default::default()
        };
        let err = config.validate().expect_err("should fail");
        assert!(matches!(err, ValidationError::InvalidTimeout(_)));
        assert!(err.to_string().contains("at least 60 seconds"));
    }

    #[test]
    fn test_concurrency_config_validate_lock_timeout_exactly_60_is_valid() {
        let config = ConcurrencyConfig {
            lock_timeout_seconds: 60,
            ..Default::default()
        };
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_concurrency_config_validate_per_team_exceeds_total() {
        let config = ConcurrencyConfig {
            strategy: ConcurrencyStrategy::DistributedSemaphore,
            max_concurrent_tasks: 10,
            max_concurrent_per_team: 20, // > max_concurrent_tasks
            lock_timeout_seconds: 120,
            enabled: true,
        };
        let err = config.validate().expect_err("should fail");
        assert!(matches!(err, ValidationError::InconsistentRates(_)));
        assert!(err
            .to_string()
            .contains("max_concurrent_per_team exceeds max_concurrent_tasks"));
    }

    #[test]
    fn test_concurrency_config_validate_per_team_equals_total_is_valid() {
        let config = ConcurrencyConfig {
            strategy: ConcurrencyStrategy::DistributedSemaphore,
            max_concurrent_tasks: 10,
            max_concurrent_per_team: 10, // == max_concurrent_tasks is OK
            lock_timeout_seconds: 120,
            enabled: true,
        };
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_concurrency_config_serde_roundtrip() {
        let config = ConcurrencyConfig::default();
        let json = serde_json::to_string(&config).expect("serialize");
        let back: ConcurrencyConfig = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back.strategy, config.strategy);
        assert_eq!(back.max_concurrent_tasks, config.max_concurrent_tasks);
        assert_eq!(back.max_concurrent_per_team, config.max_concurrent_per_team);
        assert_eq!(back.lock_timeout_seconds, config.lock_timeout_seconds);
        assert_eq!(back.enabled, config.enabled);
    }

    // RateLimitResult tests

    #[test]
    fn test_rate_limit_result_allowed_equality() {
        assert_eq!(RateLimitResult::Allowed, RateLimitResult::Allowed);
    }

    #[test]
    fn test_rate_limit_result_denied_carries_reason() {
        let r = RateLimitResult::Denied {
            reason: "too many requests".to_string(),
        };
        match r {
            RateLimitResult::Denied { reason } => {
                assert_eq!(reason, "too many requests");
            }
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn test_rate_limit_result_retry_after_carries_seconds() {
        let r = RateLimitResult::RetryAfter {
            retry_after_seconds: 30,
        };
        match r {
            RateLimitResult::RetryAfter {
                retry_after_seconds,
            } => {
                assert_eq!(retry_after_seconds, 30);
            }
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn test_rate_limit_result_variants_not_equal() {
        assert_ne!(
            RateLimitResult::Allowed,
            RateLimitResult::Denied {
                reason: "x".to_string(),
            }
        );
    }

    // ConcurrencyResult tests

    #[test]
    fn test_concurrency_result_allowed_equality() {
        assert_eq!(ConcurrencyResult::Allowed, ConcurrencyResult::Allowed);
    }

    #[test]
    fn test_concurrency_result_denied_carries_reason() {
        let r = ConcurrencyResult::Denied {
            reason: "limit reached".to_string(),
        };
        match r {
            ConcurrencyResult::Denied { reason } => {
                assert_eq!(reason, "limit reached");
            }
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn test_concurrency_result_queued_carries_backlog_id() {
        let id = crate::domain::id::Id::generate();
        let r = ConcurrencyResult::Queued { backlog_id: id };
        match r {
            ConcurrencyResult::Queued { backlog_id } => {
                assert_eq!(backlog_id, id);
            }
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn test_concurrency_result_variants_not_equal() {
        assert_ne!(
            ConcurrencyResult::Allowed,
            ConcurrencyResult::Queued {
                backlog_id: crate::domain::id::Id::generate(),
            }
        );
    }

    // RateLimitingError Display tests

    #[test]
    fn test_rate_limiting_error_rate_limit_exceeded_display() {
        let err = RateLimitingError::RateLimitExceeded("100/min".to_string());
        assert!(err.to_string().contains("Rate limit exceeded"));
        assert!(err.to_string().contains("100/min"));
    }

    #[test]
    fn test_rate_limiting_error_concurrency_limit_exceeded_display() {
        let err = RateLimitingError::ConcurrencyLimitExceeded("5 tasks".to_string());
        assert!(err.to_string().contains("Concurrency limit exceeded"));
        assert!(err.to_string().contains("5 tasks"));
    }

    #[test]
    fn test_rate_limiting_error_configuration_error_display() {
        let err = RateLimitingError::ConfigurationError("bad config".to_string());
        assert!(err.to_string().contains("Configuration error"));
        assert!(err.to_string().contains("bad config"));
    }

    #[test]
    fn test_rate_limiting_error_database_error_display() {
        let err = RateLimitingError::DatabaseError;
        assert!(err.to_string().contains("Database operation failed"));
    }

    #[test]
    fn test_rate_limiting_error_credits_error_display() {
        let err = RateLimitingError::CreditsError;
        assert!(err
            .to_string()
            .contains("Credits service temporarily unavailable"));
    }

    #[test]
    fn test_rate_limiting_error_other_from_anyhow() {
        let err = RateLimitingError::Other(anyhow::anyhow!("something broke"));
        assert!(err.to_string().contains("Other error"));
        assert!(err.to_string().contains("something broke"));
    }

    // ValidationError Display tests

    #[test]
    fn test_validation_error_zero_rate_display() {
        let err = ValidationError::ZeroRate("requests_per_second cannot be zero");
        assert!(err.to_string().contains("Rate limit cannot be zero"));
        assert!(err
            .to_string()
            .contains("requests_per_second cannot be zero"));
    }

    #[test]
    fn test_validation_error_zero_capacity_display() {
        let err = ValidationError::ZeroCapacity("bucket_capacity cannot be zero".to_string());
        assert!(err.to_string().contains("Capacity cannot be zero"));
        assert!(err.to_string().contains("bucket_capacity cannot be zero"));
    }

    #[test]
    fn test_validation_error_invalid_timeout_display() {
        let err = ValidationError::InvalidTimeout("timeout too short".to_string());
        assert!(err.to_string().contains("Invalid timeout"));
        assert!(err.to_string().contains("timeout too short"));
    }

    #[test]
    fn test_validation_error_inconsistent_rates_display() {
        let err = ValidationError::InconsistentRates("mismatch".to_string());
        assert!(err.to_string().contains("Inconsistent rate configuration"));
        assert!(err.to_string().contains("mismatch"));
    }

    // RateLimitingError From<anyhow::Error> test

    #[test]
    fn test_rate_limiting_error_from_anyhow_preserves_message() {
        let anyhow_err = anyhow::anyhow!("custom failure");
        let err: RateLimitingError = anyhow_err.into();
        match err {
            RateLimitingError::Other(inner) => {
                assert!(inner.to_string().contains("custom failure"));
            }
            other => panic!("expected Other variant, got {:?}", other),
        }
    }
}