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

use crate::domain::models::{WebhookEvent, WebhookStatus};
use crate::domain::repositories::webhook_event_repository::WebhookEventRepository;
use crate::domain::services::webhook_service::WebhookService;
use crate::utils::retry_policy::RetryPolicy;
use crate::workers::worker::{ProcessResult, WorkerProcess};
use anyhow::Result;
use chrono::Utc;
use log::{error, info, warn};
#[cfg(feature = "metrics")]
use metrics::counter;
use std::sync::Arc;

/// Webhook Worker Trait
#[async_trait::async_trait]
pub trait WebhookWorkerTrait: Send + Sync {
    async fn run(&self);
}

/// Webhook工作器
///
/// 负责处理webhook事件的发送和重试
pub struct WebhookWorker {
    /// Webhook事件仓库
    repo: Arc<dyn WebhookEventRepository>,
    /// Webhook服务
    webhook_service: Arc<dyn WebhookService>,
    /// 重试策略
    retry_policy: RetryPolicy,
}

impl WebhookWorker {
    /// 创建新的webhook工作器
    pub fn new(
        repo: Arc<dyn WebhookEventRepository>,
        webhook_service: Arc<dyn WebhookService>,
        retry_policy: RetryPolicy,
    ) -> Self {
        Self {
            repo,
            webhook_service,
            retry_policy,
        }
    }

    /// 使用默认重试策略创建webhook工作器
    pub fn with_default_policy(
        repo: Arc<dyn WebhookEventRepository>,
        webhook_service: Arc<dyn WebhookService>,
    ) -> Self {
        Self::new(repo, webhook_service, RetryPolicy::default())
    }

    /// 处理待处理的webhook事件
    pub async fn process_pending_webhooks(&self) -> Result<()> {
        // 原子认领(置 processing),多实例部署下同一事件只被本进程投递
        let pending_events = self
            .repo
            .claim_pending(100)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to claim pending events: {}", e))?;

        if !pending_events.is_empty() {
            info!("Processing {} pending webhook events", pending_events.len());

            for event in pending_events {
                if let Err(e) = self.process_webhook_event(event).await {
                    error!("Failed to process webhook event: {}", e);
                }
            }
        }

        Ok(())
    }

    /// 处理单个webhook事件
    async fn process_webhook_event(&self, mut event: WebhookEvent) -> Result<()> {
        info!(
            "Processing webhook event {} for URL {} (attempt {})",
            event.id,
            crate::utils::url_redaction::redact_webhook_url_for_log(&event.webhook_url),
            event.attempt_count
        );

        match self.webhook_service.send_webhook(&event).await {
            Ok(status) => {
                info!(
                    "Successfully delivered webhook {} (status {})",
                    event.id, status
                );
                event.status = WebhookStatus::Delivered;
                event.delivered_at = Some(Utc::now());
                // 记录真实响应状态码,替代硬编码 200
                event.response_status = Some(status as i32);
                self.repo
                    .update(&event)
                    .await
                    .map_err(|e| anyhow::anyhow!("Failed to update event: {}", e))?;

                #[cfg(feature = "metrics")]
                counter!("webhook_delivery_success_total").increment(1);
                Ok(())
            }
            Err(e) => {
                error!("Failed to deliver webhook {}: {}", event.id, e);

                // 尝试解析错误中的 HTTP 状态码
                let error_msg = e.to_string();
                if error_msg.contains("status 500") {
                    event.response_status = Some(500);
                } else if error_msg.contains("status 400") {
                    event.response_status = Some(400);
                } else if error_msg.contains("status 404") {
                    event.response_status = Some(404);
                }

                self.handle_webhook_failure(event, e).await
            }
        }
    }

    /// 死信原因有界分类(审查 N1:错误串不得作为指标标签——reqwest 错误
    /// 可能携带完整 webhook URL/凭据,且每 URL 产生一条时间序列)。
    fn classify_dead_letter_reason(error: &anyhow::Error) -> &'static str {
        let msg = error.to_string().to_lowercase();
        if msg.contains("timed out") || msg.contains("timeout") {
            "timeout"
        } else if msg.contains("dns") || msg.contains("resolv") {
            "dns"
        } else if msg.contains("connection refused")
            || msg.contains("connection reset")
            || msg.contains("error sending request")
            || msg.contains("connect")
        {
            "connect"
        } else if msg.contains("status 4") {
            "http_4xx"
        } else if msg.contains("status 5") {
            "http_5xx"
        } else {
            "other"
        }
    }

    /// 处理webhook发送失败
    async fn handle_webhook_failure(
        &self,
        mut event: WebhookEvent,
        error: anyhow::Error,
    ) -> Result<()> {
        let new_attempt_count = event.attempt_count + 1;

        // 检查是否应该重试
        if !self
            .retry_policy
            .should_retry_with_error(new_attempt_count as u32, &error)
        {
            // 达到最大重试次数或错误不可重试,移动到死信队列
            event.status = WebhookStatus::Dead;
            event.error_message = Some(error.to_string());
            event.attempt_count = new_attempt_count;

            warn!(
                "Webhook {} moved to dead letter state after {} attempts: {}",
                event.id, new_attempt_count, error
            );
            #[cfg(feature = "metrics")]
            counter!(
                "webhook_dead_letter_total",
                "reason" => Self::classify_dead_letter_reason(&error)
            )
            .increment(1);
        } else {
            // 计算下次重试时间
            let next_retry = self
                .retry_policy
                .next_retry_time(new_attempt_count as u32, Utc::now());

            event.status = WebhookStatus::Failed;
            event.attempt_count = new_attempt_count;
            event.next_retry_at = Some(next_retry);
            event.error_message = Some(error.to_string());

            info!(
                "Webhook {} will be retried at {} (attempt {})",
                event.id, next_retry, new_attempt_count
            );
            #[cfg(feature = "metrics")]
            counter!("webhook_retry_scheduled_total", "attempt" => new_attempt_count.to_string())
                .increment(1);
        }

        self.repo
            .update(&event)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to update event: {}", e))?;
        Ok(())
    }
}

#[async_trait::async_trait]
impl WorkerProcess for WebhookWorker {
    fn name(&self) -> &str {
        "webhook_worker"
    }

    async fn process(&self) -> ProcessResult {
        if let Err(e) = self.process_pending_webhooks().await {
            return ProcessResult::Error(format!("Error processing pending webhooks: {}", e));
        }
        ProcessResult::Completed
    }
}

#[async_trait::async_trait]
impl WebhookWorkerTrait for WebhookWorker {
    async fn run(&self) {
        info!("Starting webhook worker loop");
        loop {
            if let Err(e) = self.process_pending_webhooks().await {
                error!("Error processing webhook events: {}", e);
            }
            tokio::time::sleep(std::time::Duration::from_secs(1)).await;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::models::{Task, WebhookEvent, WebhookEventType, WebhookStatus};
    use crate::domain::repositories::task_repository::RepositoryError;
    use anyhow::anyhow;
    use async_trait::async_trait;
    use std::sync::atomic::{AtomicU32, Ordering};
    use std::sync::Mutex;
    use std::time::Duration;

    /// Mock WebhookEventRepository with configurable pending events and update tracking
    struct MockWebhookRepo {
        pending_events: Mutex<Vec<WebhookEvent>>,
        updated_events: Mutex<Vec<WebhookEvent>>,
        fail_find_pending: bool,
    }

    impl MockWebhookRepo {
        fn new(pending: Vec<WebhookEvent>) -> Self {
            Self {
                pending_events: Mutex::new(pending),
                updated_events: Mutex::new(vec![]),
                fail_find_pending: false,
            }
        }

        fn new_empty() -> Self {
            Self::new(vec![])
        }

        fn new_failing() -> Self {
            Self {
                pending_events: Mutex::new(vec![]),
                updated_events: Mutex::new(vec![]),
                fail_find_pending: true,
            }
        }

        fn updated_events(&self) -> Vec<WebhookEvent> {
            self.updated_events.lock().unwrap().clone()
        }
    }

    #[async_trait]
    impl WebhookEventRepository for MockWebhookRepo {
        async fn create(&self, event: &WebhookEvent) -> Result<WebhookEvent, RepositoryError> {
            Ok(event.clone())
        }

        async fn find_by_id(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<Option<WebhookEvent>, RepositoryError> {
            Ok(None)
        }

        async fn find_pending(&self, _limit: u64) -> Result<Vec<WebhookEvent>, RepositoryError> {
            if self.fail_find_pending {
                return Err(RepositoryError::Database(anyhow::anyhow!(
                    "repo unavailable"
                )));
            }
            Ok(self.pending_events.lock().unwrap().drain(..).collect())
        }

        async fn claim_pending(&self, limit: u64) -> Result<Vec<WebhookEvent>, RepositoryError> {
            self.find_pending(limit).await
        }

        async fn find_by_team_id_paginated(
            &self,
            _team_id: crate::domain::id::Id,
            _limit: u32,
            _offset: u32,
        ) -> Result<Vec<WebhookEvent>, RepositoryError> {
            Ok(vec![])
        }

        async fn count_by_team_id(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }

        async fn update(&self, event: &WebhookEvent) -> Result<WebhookEvent, RepositoryError> {
            self.updated_events.lock().unwrap().push(event.clone());
            Ok(event.clone())
        }
    }

    /// Mock WebhookService that can be configured to succeed or fail
    struct MockWebhookService {
        send_success: bool,
        send_count: AtomicU32,
    }

    impl MockWebhookService {
        fn new_success() -> Self {
            Self {
                send_success: true,
                send_count: AtomicU32::new(0),
            }
        }

        fn new_failure() -> Self {
            Self {
                send_success: false,
                send_count: AtomicU32::new(0),
            }
        }

        fn send_count(&self) -> u32 {
            self.send_count.load(Ordering::SeqCst)
        }
    }

    #[async_trait]
    impl WebhookService for MockWebhookService {
        async fn send_webhook(&self, _event: &WebhookEvent) -> Result<u16> {
            self.send_count.fetch_add(1, Ordering::SeqCst);
            if self.send_success {
                Ok(200)
            } else {
                Err(anyhow!("Failed to send webhook: connection refused"))
            }
        }

        async fn trigger_completion(&self, _task: &Task) -> Result<()> {
            Ok(())
        }

        async fn trigger_failure(&self, _task: &Task, _error_msg: String) -> Result<()> {
            Ok(())
        }
    }

    /// Mock WebhookService that fails with an HTTP 500 status in the error message
    struct MockWebhookService500;

    #[async_trait]
    impl WebhookService for MockWebhookService500 {
        async fn send_webhook(&self, _event: &WebhookEvent) -> Result<u16> {
            Err(anyhow!(
                "Request failed with status 500: internal server error"
            ))
        }

        async fn trigger_completion(&self, _task: &Task) -> Result<()> {
            Ok(())
        }

        async fn trigger_failure(&self, _task: &Task, _error_msg: String) -> Result<()> {
            Ok(())
        }
    }

    fn make_test_event(attempt_count: i32) -> WebhookEvent {
        let mut event = WebhookEvent::new(
            crate::domain::id::Id::generate(),
            crate::domain::id::Id::generate(),
            crate::domain::id::Id::nil(),
            WebhookEventType::ScrapeCompleted,
            serde_json::json!({"task_id": "abc"}),
            "https://example.com/webhook".to_string(),
        );
        event.attempt_count = attempt_count;
        event
    }

    fn make_worker(
        repo: Arc<dyn WebhookEventRepository>,
        service: Arc<dyn WebhookService>,
    ) -> WebhookWorker {
        WebhookWorker::with_default_policy(repo, service)
    }

    // name

    #[test]
    fn test_worker_name() {
        let repo: Arc<dyn WebhookEventRepository> = Arc::new(MockWebhookRepo::new_empty());
        let service: Arc<dyn WebhookService> = Arc::new(MockWebhookService::new_success());
        let worker = make_worker(repo, service);
        assert_eq!(worker.name(), "webhook_worker");
    }

    // new / with_default_policy

    #[test]
    fn test_new_uses_provided_retry_policy() {
        let repo: Arc<dyn WebhookEventRepository> = Arc::new(MockWebhookRepo::new_empty());
        let service: Arc<dyn WebhookService> = Arc::new(MockWebhookService::new_success());
        let policy = RetryPolicy::fast();
        let worker = WebhookWorker::new(repo, service, policy);
        assert_eq!(worker.retry_policy.max_retries, 5);
        assert_eq!(
            worker.retry_policy.initial_backoff,
            Duration::from_millis(500)
        );
    }

    #[test]
    fn test_with_default_policy_uses_standard_policy() {
        let repo: Arc<dyn WebhookEventRepository> = Arc::new(MockWebhookRepo::new_empty());
        let service: Arc<dyn WebhookService> = Arc::new(MockWebhookService::new_success());
        let worker = make_worker(repo, service);
        assert_eq!(worker.retry_policy.max_retries, 5);
        assert_eq!(worker.retry_policy.initial_backoff, Duration::from_secs(1));
    }

    // process_pending_webhooks

    #[tokio::test]
    async fn test_process_pending_webhooks_empty() {
        let repo = Arc::new(MockWebhookRepo::new_empty());
        let service = Arc::new(MockWebhookService::new_success());
        let worker = make_worker(repo.clone(), service.clone());
        let result = worker.process_pending_webhooks().await;
        assert!(result.is_ok());
        assert_eq!(service.send_count(), 0);
        assert!(repo.updated_events().is_empty());
    }

    #[tokio::test]
    async fn test_process_pending_webhooks_success_delivers_event() {
        let event = make_test_event(0);
        let repo = Arc::new(MockWebhookRepo::new(vec![event]));
        let service = Arc::new(MockWebhookService::new_success());
        let worker = make_worker(repo.clone(), service.clone());
        let result = worker.process_pending_webhooks().await;
        assert!(result.is_ok());
        assert_eq!(service.send_count(), 1);
        let updated = repo.updated_events();
        assert_eq!(updated.len(), 1);
        assert_eq!(updated[0].status, WebhookStatus::Delivered);
        assert!(updated[0].delivered_at.is_some());
        assert_eq!(updated[0].response_status, Some(200));
    }

    #[tokio::test]
    async fn test_process_pending_webhooks_multiple_events() {
        let events = vec![make_test_event(0), make_test_event(1), make_test_event(2)];
        let repo = Arc::new(MockWebhookRepo::new(events));
        let service = Arc::new(MockWebhookService::new_success());
        let worker = make_worker(repo.clone(), service.clone());
        let result = worker.process_pending_webhooks().await;
        assert!(result.is_ok());
        assert_eq!(service.send_count(), 3);
        let updated = repo.updated_events();
        assert_eq!(updated.len(), 3);
        for ev in &updated {
            assert_eq!(ev.status, WebhookStatus::Delivered);
        }
    }

    #[tokio::test]
    async fn test_process_pending_webhooks_repo_failure_returns_error() {
        let repo = Arc::new(MockWebhookRepo::new_failing());
        let service = Arc::new(MockWebhookService::new_success());
        let worker = make_worker(repo, service);
        let result = worker.process_pending_webhooks().await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Failed to claim pending events"));
    }

    // process (WorkerProcess trait)

    #[tokio::test]
    async fn test_process_returns_completed_on_success() {
        let repo = Arc::new(MockWebhookRepo::new_empty());
        let service = Arc::new(MockWebhookService::new_success());
        let worker = make_worker(repo, service);
        let result = worker.process().await;
        assert_eq!(result, ProcessResult::Completed);
    }

    #[tokio::test]
    async fn test_process_returns_error_on_repo_failure() {
        let repo = Arc::new(MockWebhookRepo::new_failing());
        let service = Arc::new(MockWebhookService::new_success());
        let worker = make_worker(repo, service);
        let result = worker.process().await;
        match result {
            ProcessResult::Error(msg) => {
                assert!(msg.contains("Error processing pending webhooks"));
            }
            _ => panic!("Expected ProcessResult::Error, got {:?}", result),
        }
    }

    // webhook failure handling

    #[tokio::test]
    async fn test_webhook_failure_schedules_retry() {
        let event = make_test_event(0);
        let repo = Arc::new(MockWebhookRepo::new(vec![event]));
        let service = Arc::new(MockWebhookService::new_failure());
        let worker = make_worker(repo.clone(), service);
        let result = worker.process_pending_webhooks().await;
        assert!(result.is_ok());
        let updated = repo.updated_events();
        assert_eq!(updated.len(), 1);
        // Should be marked as Failed (retryable) since attempt 1 < max_retries
        assert_eq!(updated[0].status, WebhookStatus::Failed);
        assert_eq!(updated[0].attempt_count, 1);
        assert!(updated[0].next_retry_at.is_some());
        assert!(updated[0].error_message.is_some());
    }

    #[tokio::test]
    async fn test_webhook_failure_moves_to_dead_after_max_retries() {
        // attempt_count starts at 4, new_attempt_count will be 5, which equals max_retries (5)
        let mut event = make_test_event(4);
        event.max_retries = 5;
        let repo = Arc::new(MockWebhookRepo::new(vec![event]));
        let service = Arc::new(MockWebhookService::new_failure());
        let worker = make_worker(repo.clone(), service);
        let result = worker.process_pending_webhooks().await;
        assert!(result.is_ok());
        let updated = repo.updated_events();
        assert_eq!(updated.len(), 1);
        // Should be moved to Dead state since max retries reached
        assert_eq!(updated[0].status, WebhookStatus::Dead);
        assert_eq!(updated[0].attempt_count, 5);
        assert!(updated[0].error_message.is_some());
    }

    #[tokio::test]
    async fn test_webhook_failure_with_non_retryable_error_moves_to_dead() {
        // Use a service that returns a non-retryable error
        struct NonRetryableService;
        #[async_trait]
        impl WebhookService for NonRetryableService {
            async fn send_webhook(&self, _event: &WebhookEvent) -> Result<u16> {
                Err(anyhow!("status 400: bad request"))
            }
            async fn trigger_completion(&self, _task: &Task) -> Result<()> {
                Ok(())
            }
            async fn trigger_failure(&self, _task: &Task, _error_msg: String) -> Result<()> {
                Ok(())
            }
        }
        let event = make_test_event(0);
        let repo = Arc::new(MockWebhookRepo::new(vec![event]));
        let service: Arc<dyn WebhookService> = Arc::new(NonRetryableService);
        let worker = make_worker(repo.clone(), service);
        let result = worker.process_pending_webhooks().await;
        assert!(result.is_ok());
        let updated = repo.updated_events();
        assert_eq!(updated.len(), 1);
        // 400 is not retryable -> Dead
        assert_eq!(updated[0].status, WebhookStatus::Dead);
    }

    // response status parsing

    #[tokio::test]
    async fn test_webhook_failure_parses_500_status() {
        let event = make_test_event(0);
        let repo = Arc::new(MockWebhookRepo::new(vec![event]));
        let service: Arc<dyn WebhookService> = Arc::new(MockWebhookService500);
        let worker = make_worker(repo.clone(), service);
        let result = worker.process_pending_webhooks().await;
        assert!(result.is_ok());
        let updated = repo.updated_events();
        assert_eq!(updated.len(), 1);
        // Error message contains "status 500" -> response_status should be 500
        assert_eq!(updated[0].response_status, Some(500));
    }

    #[tokio::test]
    async fn test_webhook_failure_parses_400_status() {
        struct Service400;
        #[async_trait]
        impl WebhookService for Service400 {
            async fn send_webhook(&self, _event: &WebhookEvent) -> Result<u16> {
                Err(anyhow!("failed with status 400: bad request"))
            }
            async fn trigger_completion(&self, _task: &Task) -> Result<()> {
                Ok(())
            }
            async fn trigger_failure(&self, _task: &Task, _error_msg: String) -> Result<()> {
                Ok(())
            }
        }
        let event = make_test_event(0);
        let repo = Arc::new(MockWebhookRepo::new(vec![event]));
        let service: Arc<dyn WebhookService> = Arc::new(Service400);
        let worker = make_worker(repo.clone(), service);
        worker.process_pending_webhooks().await.unwrap();
        let updated = repo.updated_events();
        assert_eq!(updated[0].response_status, Some(400));
    }

    #[tokio::test]
    async fn test_webhook_failure_parses_404_status() {
        struct Service404;
        #[async_trait]
        impl WebhookService for Service404 {
            async fn send_webhook(&self, _event: &WebhookEvent) -> Result<u16> {
                Err(anyhow!("error: status 404 not found"))
            }
            async fn trigger_completion(&self, _task: &Task) -> Result<()> {
                Ok(())
            }
            async fn trigger_failure(&self, _task: &Task, _error_msg: String) -> Result<()> {
                Ok(())
            }
        }
        let event = make_test_event(0);
        let repo = Arc::new(MockWebhookRepo::new(vec![event]));
        let service: Arc<dyn WebhookService> = Arc::new(Service404);
        let worker = make_worker(repo.clone(), service);
        worker.process_pending_webhooks().await.unwrap();
        let updated = repo.updated_events();
        assert_eq!(updated[0].response_status, Some(404));
    }

    // mixed success/failure

    #[tokio::test]
    async fn test_process_pending_webhooks_continues_after_failure() {
        // First event fails, second succeeds - both should be processed
        let events = vec![make_test_event(0), make_test_event(0)];
        let repo = Arc::new(MockWebhookRepo::new(events));
        // Service that fails for first call, succeeds for second
        struct ToggleService {
            count: AtomicU32,
        }
        #[async_trait]
        impl WebhookService for ToggleService {
            async fn send_webhook(&self, _event: &WebhookEvent) -> Result<u16> {
                let n = self.count.fetch_add(1, Ordering::SeqCst);
                if n == 0 {
                    Err(anyhow!("timeout connecting to server"))
                } else {
                    Ok(200)
                }
            }
            async fn trigger_completion(&self, _task: &Task) -> Result<()> {
                Ok(())
            }
            async fn trigger_failure(&self, _task: &Task, _error_msg: String) -> Result<()> {
                Ok(())
            }
        }
        let service: Arc<dyn WebhookService> = Arc::new(ToggleService {
            count: AtomicU32::new(0),
        });
        let worker = make_worker(repo.clone(), service);
        let result = worker.process_pending_webhooks().await;
        assert!(result.is_ok());
        let updated = repo.updated_events();
        assert_eq!(updated.len(), 2);
        // First event should be Failed (retryable), second should be Delivered
        assert_eq!(updated[0].status, WebhookStatus::Failed);
        assert_eq!(updated[1].status, WebhookStatus::Delivered);
    }

    // retry policy behavior

    #[tokio::test]
    async fn test_retry_policy_fast_changes_retry_behavior() {
        let event = make_test_event(0);
        let repo = Arc::new(MockWebhookRepo::new(vec![event]));
        let service = Arc::new(MockWebhookService::new_failure());
        let worker = WebhookWorker::new(repo.clone(), service, RetryPolicy::fast());
        worker.process_pending_webhooks().await.unwrap();
        let updated = repo.updated_events();
        // With fast policy, attempt 1 < max_retries(5), so should retry
        assert_eq!(updated[0].status, WebhookStatus::Failed);
        assert!(updated[0].next_retry_at.is_some());
    }

    #[test]
    fn test_retry_policy_default_max_retries() {
        let policy = RetryPolicy::default();
        assert_eq!(policy.max_retries, 5);
    }

    // run (WebhookWorkerTrait) error and success loop paths
    // run is an infinite loop. These tests use tokio::time::timeout to verify that:
    // 1. The error branch (error!("Error processing webhook events: {}", e)) is exercised
    //    when process_pending_webhooks returns Err.
    // 2. The success path loops without errors when there are no pending events.

    #[tokio::test]
    async fn test_run_logs_error_and_continues_on_repo_failure() {
        // With a failing repo, process_pending_webhooks returns Err, run logs the error
        // via error!("Error processing webhook events: {}", e) and continues the loop.
        let repo = Arc::new(MockWebhookRepo::new_failing());
        let service = Arc::new(MockWebhookService::new_success());
        let worker = make_worker(repo, service);

        // run is an infinite loop; it should not return within the timeout.
        let result = tokio::time::timeout(Duration::from_millis(150), worker.run()).await;

        // Should time out because run keeps looping after logging the error
        assert!(result.is_err(), "run() should continue looping after error");
    }

    #[tokio::test]
    async fn test_run_loops_successfully_with_empty_repo() {
        // With an empty repo (no pending events), run completes iterations without
        // errors and continues looping.
        let repo = Arc::new(MockWebhookRepo::new_empty());
        let service = Arc::new(MockWebhookService::new_success());
        let worker = make_worker(repo, service);

        let result = tokio::time::timeout(Duration::from_millis(150), worker.run()).await;

        assert!(
            result.is_err(),
            "run() should continue looping (infinite loop)"
        );
    }

    #[tokio::test]
    async fn test_run_with_successful_delivery_continues_looping() {
        // With a pending event that gets delivered successfully, run processes it
        // and continues looping.
        let event = make_test_event(0);
        let repo = Arc::new(MockWebhookRepo::new(vec![event]));
        let service = Arc::new(MockWebhookService::new_success());
        let worker = make_worker(repo, service);

        let result = tokio::time::timeout(Duration::from_millis(150), worker.run()).await;

        // run processes the event then sleeps 1s; timeout fires during sleep
        assert!(
            result.is_err(),
            "run() should continue looping after successful delivery"
        );
    }
}