Skip to main content

hookburn_core/
service.rs

1// crates/hookburn-core/src/service.rs
2use crate::error::CoreError;
3use crate::retry::RetryPolicy;
4use crate::webhook_service::BoxedWebhookSender;
5use rustc_hash::FxHashMap;
6use serde::{Deserialize, Serialize};
7use std::sync::Arc;
8use std::time::Duration;
9
10/// Metadata about a webhook service (Discord, Slack, etc.).
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct ServiceInfo {
13    /// Service name (e.g., "discord", "slack")
14    pub name: String,
15    /// Service version
16    pub version: String,
17    /// Human-readable description
18    pub description: String,
19    /// URL format template
20    pub webhook_url_format: String,
21    /// Whether the service supports rich embeds
22    pub supports_embeds: bool,
23    /// Maximum content length in characters
24    pub max_content_length: usize,
25    /// List of supported features
26    pub features: Vec<String>,
27    /// Recommended retry delay when rate limited
28    pub rate_limit_retry_after: Option<Duration>,
29    /// Link to service documentation
30    pub documentation_url: Option<String>,
31    /// URL to service icon
32    pub icon_url: Option<String>,
33    /// Supported platforms
34    pub platforms: Vec<Platform>,
35}
36
37/// Platforms that can be targeted by webhook services.
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub enum Platform {
40    /// Discord Connection
41    Discord,
42    /// Slack Connection
43    Slack,
44    /// Microsoft Teams Connection
45    Teams,
46    /// Mattermost Connection
47    Mattermost,
48    /// Generic Webhook Connection
49    Generic,
50    /// Custom Connection
51    Custom(String),
52}
53
54/// Configuration for creating a webhook service sender.
55#[derive(Debug, Clone)]
56pub struct ServiceConfig {
57    /// Webhook URL
58    pub url: String,
59    /// Request timeout
60    pub timeout: Duration,
61    /// Retry policy for failed requests
62    pub retry_policy: RetryPolicy,
63    /// Custom HTTP headers
64    pub custom_headers: FxHashMap<String, String>,
65    /// Service-specific configuration
66    pub additional_config: FxHashMap<String, serde_json::Value>,
67}
68
69impl ServiceConfig {
70    /// Create a new configuration with the given URL.
71    #[must_use]
72    pub fn new(url: impl Into<String>) -> Self {
73        Self {
74            url: url.into(),
75            timeout: Duration::from_secs(30),
76            retry_policy: RetryPolicy::default(),
77            custom_headers: FxHashMap::default(),
78            additional_config: FxHashMap::default(),
79        }
80    }
81
82    /// Set the request timeout.
83    #[must_use]
84    pub const fn with_timeout(mut self, timeout: Duration) -> Self {
85        self.timeout = timeout;
86        self
87    }
88
89    /// Set the retry policy.
90    #[must_use]
91    pub const fn with_retry_policy(mut self, policy: RetryPolicy) -> Self {
92        self.retry_policy = policy;
93        self
94    }
95
96    /// Add a custom HTTP header.
97    #[must_use]
98    pub fn with_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
99        self.custom_headers.insert(key.into(), value.into());
100        self
101    }
102
103    /// Add service-specific configuration.
104    ///
105    /// # Errors
106    ///
107    /// Returns `CoreError::Json` if the value cannot be serialized to JSON.
108    #[must_use]
109    pub fn with_config(
110        mut self,
111        key: impl Into<String>,
112        value: impl Serialize,
113    ) -> Result<Self, CoreError> {
114        self.additional_config
115            .insert(key.into(), serde_json::to_value(value)?);
116        Ok(self)
117    }
118}
119
120/// Creates webhook service senders.
121///
122/// Each service (Discord, Slack, etc.) implements this trait to provide
123/// a consistent way to build senders.
124pub trait ServiceBuilder: Send + Sync {
125    /// Build a sender from configuration.
126    ///
127    /// # Errors
128    ///
129    /// Returns an error if the service cannot be created (invalid URL,
130    /// missing credentials, etc.).
131    fn build(
132        &self,
133        config: ServiceConfig,
134    ) -> Result<BoxedWebhookSender, Box<dyn std::error::Error + Send + Sync>>;
135
136    /// Get service metadata.
137    fn info(&self) -> Arc<ServiceInfo>;
138
139    /// Validate if a URL is valid for this service.
140    ///
141    /// Default implementation always returns `true`. Override for service-specific
142    /// validation (e.g., Discord requires HTTPS and specific domain).
143    #[must_use]
144    fn validate_url(&self, _url: &str) -> bool {
145        true
146    }
147}