Skip to main content

hookburn_core/
webhook_service.rs

1// crates/hookburn-core/src/webhook_service.rs
2use crate::client::HttpClient;
3use crate::error::CoreError;
4use crate::message::GenericMessage;
5use crate::retry::RetryPolicy;
6use crate::sender::WebhookSender;
7use crate::service::ServiceInfo;
8use async_trait::async_trait;
9use std::sync::Arc;
10
11/// Type alias for a boxed sender that accepts `GenericMessage` and returns `CoreError`.
12pub type BoxedWebhookSender =
13    Box<dyn WebhookSender<Message = GenericMessage, Error = CoreError> + Send + Sync>;
14
15/// A generic webhook service that can send messages to any service.
16#[derive(Clone)]
17pub struct WebhookService {
18    /// The underlying sender implementation
19    sender: Arc<BoxedWebhookSender>,
20    /// Service name (e.g., "discord", "slack")
21    name: String,
22    /// HTTP client for making requests
23    client: HttpClient,
24    /// Webhook URL
25    url: String,
26    /// Default username override
27    default_username: Option<String>,
28    /// Default avatar URL override
29    default_avatar_url: Option<String>,
30    /// Service metadata
31    service_info: Arc<ServiceInfo>,
32    /// Retry policy for failed requests
33    retry_policy: RetryPolicy,
34}
35
36impl WebhookService {
37    /// Create a new webhook service with full configuration.
38    #[must_use]
39    pub fn new(
40        name: String,
41        url: String,
42        client: HttpClient,
43        service_info: Arc<ServiceInfo>,
44        sender: BoxedWebhookSender,
45    ) -> Self {
46        Self {
47            name,
48            client,
49            url,
50            default_username: None,
51            default_avatar_url: None,
52            service_info,
53            sender: Arc::new(sender),
54            retry_policy: RetryPolicy::default(),
55        }
56    }
57
58    /// Create a new webhook service with just a sender (minimal constructor).
59    ///
60    /// # Example
61    /// ```rust
62    /// use hookburn_core::{WebhookService, BoxedWebhookSender};
63    ///
64    /// let sender: BoxedWebhookSender = Box::new(my_sender);
65    /// let service = WebhookService::with_sender(sender);
66    /// ```
67    #[must_use]
68    pub fn with_sender(sender: BoxedWebhookSender) -> Self {
69        Self {
70            sender: Arc::new(sender),
71            name: String::new(),
72            client: HttpClient::new(),
73            url: String::new(),
74            default_username: None,
75            default_avatar_url: None,
76            service_info: Arc::new(ServiceInfo {
77                name: "unknown".to_string(),
78                version: "0.1.0".to_string(),
79                description: "Unknown service".to_string(),
80                webhook_url_format: String::new(),
81                supports_embeds: false,
82                max_content_length: 0,
83                features: vec![],
84                rate_limit_retry_after: None,
85                documentation_url: None,
86                icon_url: None,
87                platforms: vec![],
88            }),
89            retry_policy: RetryPolicy::default(),
90        }
91    }
92
93    /// Set a default username for all messages.
94    #[must_use]
95    pub fn with_default_username(mut self, username: impl Into<String>) -> Self {
96        self.default_username = Some(username.into());
97        self
98    }
99
100    /// Set a default avatar URL for all messages.
101    #[must_use]
102    pub fn with_default_avatar(mut self, avatar_url: impl Into<String>) -> Self {
103        self.default_avatar_url = Some(avatar_url.into());
104        self
105    }
106
107    /// Set the retry policy for this service.
108    #[must_use]
109    pub const fn with_retry_policy(mut self, policy: RetryPolicy) -> Self {
110        self.retry_policy = policy;
111        self
112    }
113
114    /// Set the service name.
115    #[must_use]
116    pub fn with_name(mut self, name: impl Into<String>) -> Self {
117        self.name = name.into();
118        self
119    }
120
121    /// Set the service info.
122    #[must_use]
123    pub fn with_service_info(mut self, info: Arc<ServiceInfo>) -> Self {
124        self.service_info = info;
125        self
126    }
127
128    /// Send a generic message to the webhook service.
129    ///
130    /// # Errors
131    ///
132    /// Returns `CoreError` if the message fails to send.
133    pub async fn send_generic(&self, message: &GenericMessage) -> Result<(), CoreError> {
134        // Apply defaults if not set in the message
135        let mut enriched_message = message.clone();
136        if enriched_message.username.is_none() {
137            enriched_message.username = self.default_username.clone();
138        }
139        if enriched_message.avatar_url.is_none() {
140            enriched_message.avatar_url = self.default_avatar_url.clone();
141        }
142
143        // Send using the service-specific sender
144        self.sender.send(&enriched_message).await
145    }
146
147    /// Send with retry support.
148    ///
149    /// # Errors
150    ///
151    /// Returns `CoreError::RetryExhausted` if all retry attempts fail.
152    pub async fn send_generic_with_retry(&self, message: &GenericMessage) -> Result<(), CoreError> {
153        let max_attempts = self.retry_policy.max_attempts.max(1);
154        let mut last_error = None;
155
156        for attempt in 0..max_attempts {
157            match self.send_generic(message).await {
158                Ok(result) => return Ok(result),
159                Err(err) => {
160                    let is_last = attempt + 1 >= max_attempts;
161                    if !is_last {
162                        let delay = self.retry_policy.calculate_delay(attempt);
163                        tokio::time::sleep(delay).await;
164                    }
165                    last_error = Some(err);
166                }
167            }
168        }
169
170        Err(last_error
171            .unwrap_or_else(|| CoreError::RetryExhausted("All retry attempts failed".to_string())))
172    }
173
174    /// Get the service name.
175    #[must_use]
176    pub fn name(&self) -> &str {
177        &self.name
178    }
179
180    /// Get the service info.
181    #[must_use]
182    pub const fn info(&self) -> &Arc<ServiceInfo> {
183        &self.service_info
184    }
185
186    /// Get the underlying HTTP client.
187    #[must_use]
188    pub const fn client(&self) -> &HttpClient {
189        &self.client
190    }
191
192    /// Get the webhook URL.
193    #[must_use]
194    pub fn url(&self) -> &str {
195        &self.url
196    }
197}
198
199#[async_trait]
200impl WebhookSender for WebhookService {
201    type Message = GenericMessage;
202    type Error = CoreError;
203
204    async fn send(&self, message: &Self::Message) -> Result<(), Self::Error> {
205        self.send_generic(message).await
206    }
207}