hookburn-core 0.2.2

Shared HTTP client and WebhookSender trait for the Hookburn crates
Documentation
// crates/hookburn-core/src/webhook_service.rs
use crate::client::HttpClient;
use crate::error::CoreError;
use crate::message::GenericMessage;
use crate::retry::RetryPolicy;
use crate::sender::WebhookSender;
use crate::service::ServiceInfo;
use async_trait::async_trait;
use std::sync::Arc;

/// Type alias for a boxed sender that accepts `GenericMessage` and returns `CoreError`.
pub type BoxedWebhookSender =
    Box<dyn WebhookSender<Message = GenericMessage, Error = CoreError> + Send + Sync>;

/// A generic webhook service that can send messages to any service.
#[derive(Clone)]
pub struct WebhookService {
    /// The underlying sender implementation
    sender: Arc<BoxedWebhookSender>,
    /// Service name (e.g., "discord", "slack")
    name: String,
    /// HTTP client for making requests
    client: HttpClient,
    /// Webhook URL
    url: String,
    /// Default username override
    default_username: Option<String>,
    /// Default avatar URL override
    default_avatar_url: Option<String>,
    /// Service metadata
    service_info: Arc<ServiceInfo>,
    /// Retry policy for failed requests
    retry_policy: RetryPolicy,
}

impl WebhookService {
    /// Create a new webhook service with full configuration.
    #[must_use]
    pub fn new(
        name: String,
        url: String,
        client: HttpClient,
        service_info: Arc<ServiceInfo>,
        sender: BoxedWebhookSender,
    ) -> Self {
        Self {
            name,
            client,
            url,
            default_username: None,
            default_avatar_url: None,
            service_info,
            sender: Arc::new(sender),
            retry_policy: RetryPolicy::default(),
        }
    }

    /// Create a new webhook service with just a sender (minimal constructor).
    ///
    /// # Example
    /// ```rust
    /// use hookburn_core::{WebhookService, BoxedWebhookSender};
    ///
    /// let sender: BoxedWebhookSender = Box::new(my_sender);
    /// let service = WebhookService::with_sender(sender);
    /// ```
    #[must_use]
    pub fn with_sender(sender: BoxedWebhookSender) -> Self {
        Self {
            sender: Arc::new(sender),
            name: String::new(),
            client: HttpClient::new(),
            url: String::new(),
            default_username: None,
            default_avatar_url: None,
            service_info: Arc::new(ServiceInfo {
                name: "unknown".to_string(),
                version: "0.1.0".to_string(),
                description: "Unknown service".to_string(),
                webhook_url_format: String::new(),
                supports_embeds: false,
                max_content_length: 0,
                features: vec![],
                rate_limit_retry_after: None,
                documentation_url: None,
                icon_url: None,
                platforms: vec![],
            }),
            retry_policy: RetryPolicy::default(),
        }
    }

    /// Set a default username for all messages.
    #[must_use]
    pub fn with_default_username(mut self, username: impl Into<String>) -> Self {
        self.default_username = Some(username.into());
        self
    }

    /// Set a default avatar URL for all messages.
    #[must_use]
    pub fn with_default_avatar(mut self, avatar_url: impl Into<String>) -> Self {
        self.default_avatar_url = Some(avatar_url.into());
        self
    }

    /// Set the retry policy for this service.
    #[must_use]
    pub const fn with_retry_policy(mut self, policy: RetryPolicy) -> Self {
        self.retry_policy = policy;
        self
    }

    /// Set the service name.
    #[must_use]
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    /// Set the service info.
    #[must_use]
    pub fn with_service_info(mut self, info: Arc<ServiceInfo>) -> Self {
        self.service_info = info;
        self
    }

    /// Send a generic message to the webhook service.
    ///
    /// # Errors
    ///
    /// Returns `CoreError` if the message fails to send.
    pub async fn send_generic(&self, message: &GenericMessage) -> Result<(), CoreError> {
        // Apply defaults if not set in the message
        let mut enriched_message = message.clone();
        if enriched_message.username.is_none() {
            enriched_message.username = self.default_username.clone();
        }
        if enriched_message.avatar_url.is_none() {
            enriched_message.avatar_url = self.default_avatar_url.clone();
        }

        // Send using the service-specific sender
        self.sender.send(&enriched_message).await
    }

    /// Send with retry support.
    ///
    /// # Errors
    ///
    /// Returns `CoreError::RetryExhausted` if all retry attempts fail.
    pub async fn send_generic_with_retry(&self, message: &GenericMessage) -> Result<(), CoreError> {
        let max_attempts = self.retry_policy.max_attempts.max(1);
        let mut last_error = None;

        for attempt in 0..max_attempts {
            match self.send_generic(message).await {
                Ok(result) => return Ok(result),
                Err(err) => {
                    let is_last = attempt + 1 >= max_attempts;
                    if !is_last {
                        let delay = self.retry_policy.calculate_delay(attempt);
                        tokio::time::sleep(delay).await;
                    }
                    last_error = Some(err);
                }
            }
        }

        Err(last_error
            .unwrap_or_else(|| CoreError::RetryExhausted("All retry attempts failed".to_string())))
    }

    /// Get the service name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the service info.
    #[must_use]
    pub const fn info(&self) -> &Arc<ServiceInfo> {
        &self.service_info
    }

    /// Get the underlying HTTP client.
    #[must_use]
    pub const fn client(&self) -> &HttpClient {
        &self.client
    }

    /// Get the webhook URL.
    #[must_use]
    pub fn url(&self) -> &str {
        &self.url
    }
}

#[async_trait]
impl WebhookSender for WebhookService {
    type Message = GenericMessage;
    type Error = CoreError;

    async fn send(&self, message: &Self::Message) -> Result<(), Self::Error> {
        self.send_generic(message).await
    }
}