discourse-webhooks 0.2.0

Type-safe Rust library for handling Discourse webhook events
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
//! # Discourse Webhooks
//!
//! A type-safe Rust library for handling Discourse webhook events.
//!
//! This crate provides:
//! - Type-safe event parsing for Discourse webhooks
//! - HMAC-SHA256 signature verification
//! - Trait-based event handling system with async support
//! - Support for all major Discourse webhook events
//!
//! ## Quick Start
//!
//! ```rust
//! use discourse_webhooks::{WebhookEventHandler, WebhookProcessor, TopicWebhookEvent};
//! use async_trait::async_trait;
//!
//! struct MyHandler;
//!
//! #[async_trait]
//! impl WebhookEventHandler for MyHandler {
//!     type Error = String;
//!
//!     async fn handle_topic_created(&mut self, event: &TopicWebhookEvent) -> Result<(), Self::Error> {
//!         println!("New topic: {}", event.topic.title);
//!         Ok(())
//!     }
//! }
//!
//! // Process webhook events
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let processor = WebhookProcessor::new();
//! let mut handler = MyHandler;
//! // processor.process_json(&mut handler, "topic_created", payload, None).await?;
//! # Ok(())
//! # }
//! ```

pub mod error;
pub mod events;
pub mod signature;

#[cfg(feature = "async")]
pub use async_trait::async_trait;
pub use error::{Result, WebhookError};
pub use events::{
    parse_webhook_payload, PostWebhookEvent, TopicWebhookEvent, WebhookEventPayload, WebhookPost,
    WebhookTopic, WebhookUser,
};
pub use signature::{verify_json_signature, verify_signature, SignatureVerificationError};

use serde::{Deserialize, Serialize};

/// Represents a Discourse webhook payload structure
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DiscourseWebhookPayload {
    /// The event type (e.g., "topic_created", "post_edited")
    #[serde(default)]
    pub event: Option<String>,
    /// The webhook data payload
    #[serde(default)]
    pub data: Option<serde_json::Value>,
    /// Unix timestamp when the event occurred
    #[serde(default)]
    pub timestamp: Option<i64>,
}

/// Trait for handling different types of webhook events
///
/// Implement this trait to define custom behavior for each event type.
/// All methods have default implementations that do nothing, so you only
/// need to implement the events you care about.
///
/// # Examples (Sync)
/// ```rust
/// use discourse_webhooks::{WebhookEventHandler, TopicWebhookEvent};
///
/// struct MyHandler;
///
/// impl WebhookEventHandler for MyHandler {
///     type Error = String;
///
///     fn handle_topic_created(&mut self, event: &TopicWebhookEvent) -> Result<(), Self::Error> {
///         println!("Topic created: {}", event.topic.title);
///         Ok(())
///     }
/// }
/// ```
///
/// # Examples (Async - requires "async" feature)
/// ```rust
/// # #[cfg(feature = "async")]
/// # {
/// use discourse_webhooks::{WebhookEventHandler, TopicWebhookEvent, async_trait};
///
/// struct MyHandler;
///
/// #[async_trait]
/// impl WebhookEventHandler for MyHandler {
///     type Error = String;
///
///     async fn handle_topic_created(&mut self, event: &TopicWebhookEvent) -> Result<(), Self::Error> {
///         // Your async logic here
///         println!("Topic created: {}", event.topic.title);
///         Ok(())
///     }
/// }
/// # }
/// ```
#[cfg(not(feature = "async"))]
pub trait WebhookEventHandler {
    /// The error type returned by event handlers
    type Error;

    /// Called when a new topic is created
    fn handle_topic_created(
        &mut self,
        event: &TopicWebhookEvent,
    ) -> std::result::Result<(), Self::Error> {
        let _ = event;
        Ok(())
    }

    /// Called when a topic is edited
    fn handle_topic_edited(
        &mut self,
        event: &TopicWebhookEvent,
    ) -> std::result::Result<(), Self::Error> {
        let _ = event;
        Ok(())
    }

    /// Called when a topic is deleted/destroyed
    fn handle_topic_destroyed(
        &mut self,
        event: &TopicWebhookEvent,
    ) -> std::result::Result<(), Self::Error> {
        let _ = event;
        Ok(())
    }

    /// Called when a deleted topic is recovered
    fn handle_topic_recovered(
        &mut self,
        event: &TopicWebhookEvent,
    ) -> std::result::Result<(), Self::Error> {
        let _ = event;
        Ok(())
    }

    /// Called when a new post is created
    fn handle_post_created(
        &mut self,
        event: &PostWebhookEvent,
    ) -> std::result::Result<(), Self::Error> {
        let _ = event;
        Ok(())
    }

    /// Called when a post is edited
    fn handle_post_edited(
        &mut self,
        event: &PostWebhookEvent,
    ) -> std::result::Result<(), Self::Error> {
        let _ = event;
        Ok(())
    }

    /// Called when a post is deleted/destroyed
    fn handle_post_destroyed(
        &mut self,
        event: &PostWebhookEvent,
    ) -> std::result::Result<(), Self::Error> {
        let _ = event;
        Ok(())
    }

    /// Called when a deleted post is recovered
    fn handle_post_recovered(
        &mut self,
        event: &PostWebhookEvent,
    ) -> std::result::Result<(), Self::Error> {
        let _ = event;
        Ok(())
    }

    /// Called when a ping event is received
    fn handle_ping(&mut self) -> std::result::Result<(), Self::Error> {
        Ok(())
    }
}

#[cfg(feature = "async")]
#[async_trait]
pub trait WebhookEventHandler {
    /// The error type returned by event handlers
    type Error;

    /// Called when a new topic is created
    async fn handle_topic_created(
        &mut self,
        event: &TopicWebhookEvent,
    ) -> std::result::Result<(), Self::Error> {
        let _ = event;
        Ok(())
    }

    /// Called when a topic is edited
    async fn handle_topic_edited(
        &mut self,
        event: &TopicWebhookEvent,
    ) -> std::result::Result<(), Self::Error> {
        let _ = event;
        Ok(())
    }

    /// Called when a topic is deleted/destroyed
    async fn handle_topic_destroyed(
        &mut self,
        event: &TopicWebhookEvent,
    ) -> std::result::Result<(), Self::Error> {
        let _ = event;
        Ok(())
    }

    /// Called when a deleted topic is recovered
    async fn handle_topic_recovered(
        &mut self,
        event: &TopicWebhookEvent,
    ) -> std::result::Result<(), Self::Error> {
        let _ = event;
        Ok(())
    }

    /// Called when a new post is created
    async fn handle_post_created(
        &mut self,
        event: &PostWebhookEvent,
    ) -> std::result::Result<(), Self::Error> {
        let _ = event;
        Ok(())
    }

    /// Called when a post is edited
    async fn handle_post_edited(
        &mut self,
        event: &PostWebhookEvent,
    ) -> std::result::Result<(), Self::Error> {
        let _ = event;
        Ok(())
    }

    /// Called when a post is deleted/destroyed
    async fn handle_post_destroyed(
        &mut self,
        event: &PostWebhookEvent,
    ) -> std::result::Result<(), Self::Error> {
        let _ = event;
        Ok(())
    }

    /// Called when a deleted post is recovered
    async fn handle_post_recovered(
        &mut self,
        event: &PostWebhookEvent,
    ) -> std::result::Result<(), Self::Error> {
        let _ = event;
        Ok(())
    }

    /// Called when a ping event is received
    async fn handle_ping(&mut self) -> std::result::Result<(), Self::Error> {
        Ok(())
    }
}

/// Process a webhook event using the provided handler (synchronous version)
///
/// This function parses the payload based on the event type and calls
/// the appropriate handler method.
///
/// # Arguments
/// * `handler` - Mutable reference to an event handler
/// * `event_type` - The type of event (e.g., "topic_created")
/// * `payload` - The JSON payload from the webhook
///
/// # Returns
/// * `Ok(())` if the event was processed successfully
/// * `Err(WebhookError)` if parsing or handling failed
#[cfg(not(feature = "async"))]
pub fn process_webhook_event<H: WebhookEventHandler>(
    handler: &mut H,
    event_type: &str,
    payload: serde_json::Value,
) -> std::result::Result<(), WebhookError<H::Error>> {
    match event_type {
        "topic_created" | "topic_edited" | "topic_destroyed" | "topic_recovered" => {
            let event = parse_webhook_payload(event_type, payload)?;
            if let WebhookEventPayload::TopicEvent(topic_event) = event {
                let result = match event_type {
                    "topic_created" => handler.handle_topic_created(&topic_event),
                    "topic_edited" => handler.handle_topic_edited(&topic_event),
                    "topic_destroyed" => handler.handle_topic_destroyed(&topic_event),
                    "topic_recovered" => handler.handle_topic_recovered(&topic_event),
                    _ => unreachable!(),
                };
                result.map_err(WebhookError::HandlerError)?;
            }
        }
        "post_created" | "post_edited" | "post_destroyed" | "post_recovered" => {
            let event = parse_webhook_payload(event_type, payload)?;
            if let WebhookEventPayload::PostEvent(post_event) = event {
                let result = match event_type {
                    "post_created" => handler.handle_post_created(&post_event),
                    "post_edited" => handler.handle_post_edited(&post_event),
                    "post_destroyed" => handler.handle_post_destroyed(&post_event),
                    "post_recovered" => handler.handle_post_recovered(&post_event),
                    _ => unreachable!(),
                };
                result.map_err(WebhookError::HandlerError)?;
            }
        }
        "ping" => {
            handler.handle_ping().map_err(WebhookError::HandlerError)?;
        }
        _ => {
            return Err(WebhookError::UnknownEventType(event_type.to_string()));
        }
    }

    Ok(())
}

/// Process a webhook event using the provided handler (asynchronous version)
///
/// This function parses the payload based on the event type and calls
/// the appropriate handler method.
///
/// # Arguments
/// * `handler` - Mutable reference to an event handler
/// * `event_type` - The type of event (e.g., "topic_created")
/// * `payload` - The JSON payload from the webhook
///
/// # Returns
/// * `Ok(())` if the event was processed successfully
/// * `Err(WebhookError)` if parsing or handling failed
#[cfg(feature = "async")]
pub async fn process_webhook_event<H: WebhookEventHandler + Send>(
    handler: &mut H,
    event_type: &str,
    payload: serde_json::Value,
) -> std::result::Result<(), WebhookError<H::Error>> {
    match event_type {
        "topic_created" | "topic_edited" | "topic_destroyed" | "topic_recovered" => {
            let event = parse_webhook_payload(event_type, payload)?;
            if let WebhookEventPayload::TopicEvent(topic_event) = event {
                let result = match event_type {
                    "topic_created" => handler.handle_topic_created(&topic_event).await,
                    "topic_edited" => handler.handle_topic_edited(&topic_event).await,
                    "topic_destroyed" => handler.handle_topic_destroyed(&topic_event).await,
                    "topic_recovered" => handler.handle_topic_recovered(&topic_event).await,
                    _ => unreachable!(),
                };
                result.map_err(WebhookError::HandlerError)?;
            }
        }
        "post_created" | "post_edited" | "post_destroyed" | "post_recovered" => {
            let event = parse_webhook_payload(event_type, payload)?;
            if let WebhookEventPayload::PostEvent(post_event) = event {
                let result = match event_type {
                    "post_created" => handler.handle_post_created(&post_event).await,
                    "post_edited" => handler.handle_post_edited(&post_event).await,
                    "post_destroyed" => handler.handle_post_destroyed(&post_event).await,
                    "post_recovered" => handler.handle_post_recovered(&post_event).await,
                    _ => unreachable!(),
                };
                result.map_err(WebhookError::HandlerError)?;
            }
        }
        "ping" => {
            handler
                .handle_ping()
                .await
                .map_err(WebhookError::HandlerError)?;
        }
        _ => {
            return Err(WebhookError::UnknownEventType(event_type.to_string()));
        }
    }

    Ok(())
}

/// A webhook processor that handles signature verification and event dispatching
///
/// This struct provides a convenient way to process webhook events with
/// optional signature verification.
///
/// # Examples
///
/// ```rust
/// use discourse_webhooks::WebhookProcessor;
///
/// // Without signature verification
/// let processor = WebhookProcessor::new();
///
/// // With signature verification
/// let processor = WebhookProcessor::new()
///     .with_secret("your_webhook_secret");
/// ```
#[derive(Debug, Clone)]
pub struct WebhookProcessor {
    secret: Option<String>,
    verify_signatures: bool,
}

impl WebhookProcessor {
    /// Create a new webhook processor with default settings
    ///
    /// By default, signature verification is disabled.
    pub fn new() -> Self {
        Self {
            secret: None,
            verify_signatures: false,
        }
    }

    /// Enable signature verification with the provided secret
    ///
    /// # Arguments
    /// * `secret` - The shared secret key for HMAC verification
    pub fn with_secret<S: Into<String>>(mut self, secret: S) -> Self {
        self.secret = Some(secret.into());
        self.verify_signatures = true;
        self
    }

    /// Disable signature verification
    ///
    /// This can be useful for development or when webhooks are received
    /// through a trusted channel.
    pub fn without_signature_verification(mut self) -> Self {
        self.verify_signatures = false;
        self
    }

    /// Check if signature verification is enabled
    pub fn verifies_signatures(&self) -> bool {
        self.verify_signatures
    }

    /// Get the configured secret (if any)
    pub fn secret(&self) -> Option<&str> {
        self.secret.as_deref()
    }

    /// Process a webhook from a string payload
    ///
    /// # Arguments
    /// * `handler` - Mutable reference to an event handler
    /// * `event_type` - The type of event (e.g., "topic_created")
    /// * `payload` - The raw JSON payload as a string
    /// * `signature` - Optional signature header for verification
    #[cfg(not(feature = "async"))]
    pub fn process<H: WebhookEventHandler>(
        &self,
        handler: &mut H,
        event_type: &str,
        payload: &str,
        signature: Option<&str>,
    ) -> Result<(), H::Error> {
        if self.verify_signatures {
            if let Some(secret) = &self.secret {
                if let Some(sig) = signature {
                    signature::verify_signature(secret, payload, sig)
                        .map_err(|_| WebhookError::InvalidSignature)?;
                } else {
                    return Err(WebhookError::InvalidSignature);
                }
            }
        }

        let json_payload: serde_json::Value = serde_json::from_str(payload)?;
        process_webhook_event(handler, event_type, json_payload)
    }

    /// Process a webhook from a string payload (async)
    ///
    /// # Arguments
    /// * `handler` - Mutable reference to an event handler
    /// * `event_type` - The type of event (e.g., "topic_created")
    /// * `payload` - The raw JSON payload as a string
    /// * `signature` - Optional signature header for verification
    #[cfg(feature = "async")]
    pub async fn process<H: WebhookEventHandler + Send>(
        &self,
        handler: &mut H,
        event_type: &str,
        payload: &str,
        signature: Option<&str>,
    ) -> Result<(), H::Error> {
        if self.verify_signatures {
            if let Some(secret) = &self.secret {
                if let Some(sig) = signature {
                    signature::verify_signature(secret, payload, sig)
                        .map_err(|_| WebhookError::InvalidSignature)?;
                } else {
                    return Err(WebhookError::InvalidSignature);
                }
            }
        }

        let json_payload: serde_json::Value = serde_json::from_str(payload)?;
        process_webhook_event(handler, event_type, json_payload).await
    }

    /// Process a webhook from a JSON value
    ///
    /// # Arguments
    /// * `handler` - Mutable reference to an event handler
    /// * `event_type` - The type of event (e.g., "topic_created")
    /// * `payload` - The JSON payload as a serde_json::Value
    /// * `signature` - Optional signature header for verification
    #[cfg(not(feature = "async"))]
    pub fn process_json<H: WebhookEventHandler>(
        &self,
        handler: &mut H,
        event_type: &str,
        payload: serde_json::Value,
        signature: Option<&str>,
    ) -> Result<(), H::Error> {
        if self.verify_signatures {
            if let Some(secret) = &self.secret {
                if let Some(sig) = signature {
                    signature::verify_json_signature(secret, &payload, sig)
                        .map_err(|_| WebhookError::InvalidSignature)?;
                } else {
                    return Err(WebhookError::InvalidSignature);
                }
            }
        }

        process_webhook_event(handler, event_type, payload)
    }

    /// Process a webhook from a JSON value (async)
    ///
    /// # Arguments
    /// * `handler` - Mutable reference to an event handler
    /// * `event_type` - The type of event (e.g., "topic_created")
    /// * `payload` - The JSON payload as a serde_json::Value
    /// * `signature` - Optional signature header for verification
    #[cfg(feature = "async")]
    pub async fn process_json<H: WebhookEventHandler + Send>(
        &self,
        handler: &mut H,
        event_type: &str,
        payload: serde_json::Value,
        signature: Option<&str>,
    ) -> Result<(), H::Error> {
        if self.verify_signatures {
            if let Some(secret) = &self.secret {
                if let Some(sig) = signature {
                    signature::verify_json_signature(secret, &payload, sig)
                        .map_err(|_| WebhookError::InvalidSignature)?;
                } else {
                    return Err(WebhookError::InvalidSignature);
                }
            }
        }

        process_webhook_event(handler, event_type, payload).await
    }
}

impl Default for WebhookProcessor {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use hmac::Mac;
    use serde_json::json;

    struct TestHandler {
        pub topic_created_count: usize,
        pub post_created_count: usize,
        pub ping_count: usize,
    }

    impl TestHandler {
        fn new() -> Self {
            Self {
                topic_created_count: 0,
                post_created_count: 0,
                ping_count: 0,
            }
        }
    }

    // Sync tests
    #[cfg(not(feature = "async"))]
    impl WebhookEventHandler for TestHandler {
        type Error = String;

        fn handle_topic_created(
            &mut self,
            _event: &TopicWebhookEvent,
        ) -> std::result::Result<(), Self::Error> {
            self.topic_created_count += 1;
            Ok(())
        }

        fn handle_post_created(
            &mut self,
            _event: &PostWebhookEvent,
        ) -> std::result::Result<(), Self::Error> {
            self.post_created_count += 1;
            Ok(())
        }

        fn handle_ping(&mut self) -> std::result::Result<(), Self::Error> {
            self.ping_count += 1;
            Ok(())
        }
    }

    #[cfg(not(feature = "async"))]
    #[test]
    fn test_webhook_handler_ping() {
        let mut handler = TestHandler::new();
        let result = process_webhook_event(&mut handler, "ping", json!({}));
        assert!(result.is_ok());
        assert_eq!(handler.ping_count, 1);
    }

    #[cfg(not(feature = "async"))]
    #[test]
    fn test_webhook_handler_invalid_event_type() {
        let mut handler = TestHandler::new();
        let result = process_webhook_event(&mut handler, "hatasj", json!({}));
        assert!(result.is_err());

        if let Err(WebhookError::UnknownEventType(event)) = result {
            assert_eq!(event, "hatasj");
        } else {
            panic!("Expected UnknownEventType error");
        }
    }

    #[cfg(not(feature = "async"))]
    #[test]
    fn test_webhook_processor() {
        let processor = WebhookProcessor::new();
        let mut handler = TestHandler::new();

        let result = processor.process_json(&mut handler, "ping", json!({}), None);

        assert!(result.is_ok());
        assert_eq!(handler.ping_count, 1);
    }

    #[cfg(not(feature = "async"))]
    #[test]
    fn test_webhook_processor_with_signature() {
        let secret = "test_secret";
        let processor = WebhookProcessor::new().with_secret(secret);
        let mut handler = TestHandler::new();

        let payload = json!({});
        let payload_str = serde_json::to_string(&payload).unwrap();

        let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(secret.as_bytes()).unwrap();
        mac.update(payload_str.as_bytes());
        let signature = format!("sha256={}", hex::encode(mac.finalize().into_bytes()));

        let result = processor.process_json(&mut handler, "ping", payload, Some(&signature));

        assert!(result.is_ok());
        assert_eq!(handler.ping_count, 1);
    }

    #[cfg(not(feature = "async"))]
    #[test]
    fn test_unknown_event_type() {
        let mut handler = TestHandler::new();
        let result = process_webhook_event(&mut handler, "unknown_event", json!({}));
        assert!(result.is_err());

        if let Err(WebhookError::UnknownEventType(event)) = result {
            assert_eq!(event, "unknown_event");
        } else {
            panic!("Expected UnknownEventType error");
        }
    }

    // Async tests
    #[cfg(feature = "async")]
    #[async_trait]
    impl WebhookEventHandler for TestHandler {
        type Error = String;

        async fn handle_topic_created(
            &mut self,
            _event: &TopicWebhookEvent,
        ) -> std::result::Result<(), Self::Error> {
            self.topic_created_count += 1;
            Ok(())
        }

        async fn handle_post_created(
            &mut self,
            _event: &PostWebhookEvent,
        ) -> std::result::Result<(), Self::Error> {
            self.post_created_count += 1;
            Ok(())
        }

        async fn handle_ping(&mut self) -> std::result::Result<(), Self::Error> {
            self.ping_count += 1;
            Ok(())
        }
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_webhook_handler_ping() {
        let mut handler = TestHandler::new();
        let result = process_webhook_event(&mut handler, "ping", json!({})).await;
        assert!(result.is_ok());
        assert_eq!(handler.ping_count, 1);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_webhook_handler_invalid_event_type() {
        let mut handler = TestHandler::new();
        let result = process_webhook_event(&mut handler, "hatasj", json!({})).await;
        assert!(result.is_err());

        if let Err(WebhookError::UnknownEventType(event)) = result {
            assert_eq!(event, "hatasj");
        } else {
            panic!("Expected UnknownEventType error");
        }
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_webhook_processor() {
        let processor = WebhookProcessor::new();
        let mut handler = TestHandler::new();

        let result = processor
            .process_json(&mut handler, "ping", json!({}), None)
            .await;

        assert!(result.is_ok());
        assert_eq!(handler.ping_count, 1);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_webhook_processor_with_signature() {
        let secret = "test_secret";
        let processor = WebhookProcessor::new().with_secret(secret);
        let mut handler = TestHandler::new();

        let payload = json!({});
        let payload_str = serde_json::to_string(&payload).unwrap();

        let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(secret.as_bytes()).unwrap();
        mac.update(payload_str.as_bytes());
        let signature = format!("sha256={}", hex::encode(mac.finalize().into_bytes()));

        let result = processor
            .process_json(&mut handler, "ping", payload, Some(&signature))
            .await;

        assert!(result.is_ok());
        assert_eq!(handler.ping_count, 1);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_unknown_event_type() {
        let mut handler = TestHandler::new();
        let result = process_webhook_event(&mut handler, "unknown_event", json!({})).await;
        assert!(result.is_err());

        if let Err(WebhookError::UnknownEventType(event)) = result {
            assert_eq!(event, "unknown_event");
        } else {
            panic!("Expected UnknownEventType error");
        }
    }
}