hookburn-core 0.2.2

Shared HTTP client and WebhookSender trait for the Hookburn crates
Documentation
// crates/hookburn-core/src/service.rs
use crate::error::CoreError;
use crate::retry::RetryPolicy;
use crate::webhook_service::BoxedWebhookSender;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::Duration;

/// Metadata about a webhook service (Discord, Slack, etc.).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceInfo {
    /// Service name (e.g., "discord", "slack")
    pub name: String,
    /// Service version
    pub version: String,
    /// Human-readable description
    pub description: String,
    /// URL format template
    pub webhook_url_format: String,
    /// Whether the service supports rich embeds
    pub supports_embeds: bool,
    /// Maximum content length in characters
    pub max_content_length: usize,
    /// List of supported features
    pub features: Vec<String>,
    /// Recommended retry delay when rate limited
    pub rate_limit_retry_after: Option<Duration>,
    /// Link to service documentation
    pub documentation_url: Option<String>,
    /// URL to service icon
    pub icon_url: Option<String>,
    /// Supported platforms
    pub platforms: Vec<Platform>,
}

/// Platforms that can be targeted by webhook services.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Platform {
    /// Discord Connection
    Discord,
    /// Slack Connection
    Slack,
    /// Microsoft Teams Connection
    Teams,
    /// Mattermost Connection
    Mattermost,
    /// Generic Webhook Connection
    Generic,
    /// Custom Connection
    Custom(String),
}

/// Configuration for creating a webhook service sender.
#[derive(Debug, Clone)]
pub struct ServiceConfig {
    /// Webhook URL
    pub url: String,
    /// Request timeout
    pub timeout: Duration,
    /// Retry policy for failed requests
    pub retry_policy: RetryPolicy,
    /// Custom HTTP headers
    pub custom_headers: FxHashMap<String, String>,
    /// Service-specific configuration
    pub additional_config: FxHashMap<String, serde_json::Value>,
}

impl ServiceConfig {
    /// Create a new configuration with the given URL.
    #[must_use]
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            timeout: Duration::from_secs(30),
            retry_policy: RetryPolicy::default(),
            custom_headers: FxHashMap::default(),
            additional_config: FxHashMap::default(),
        }
    }

    /// Set the request timeout.
    #[must_use]
    pub const fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

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

    /// Add a custom HTTP header.
    #[must_use]
    pub fn with_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.custom_headers.insert(key.into(), value.into());
        self
    }

    /// Add service-specific configuration.
    ///
    /// # Errors
    ///
    /// Returns `CoreError::Json` if the value cannot be serialized to JSON.
    #[must_use]
    pub fn with_config(
        mut self,
        key: impl Into<String>,
        value: impl Serialize,
    ) -> Result<Self, CoreError> {
        self.additional_config
            .insert(key.into(), serde_json::to_value(value)?);
        Ok(self)
    }
}

/// Creates webhook service senders.
///
/// Each service (Discord, Slack, etc.) implements this trait to provide
/// a consistent way to build senders.
pub trait ServiceBuilder: Send + Sync {
    /// Build a sender from configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if the service cannot be created (invalid URL,
    /// missing credentials, etc.).
    fn build(
        &self,
        config: ServiceConfig,
    ) -> Result<BoxedWebhookSender, Box<dyn std::error::Error + Send + Sync>>;

    /// Get service metadata.
    fn info(&self) -> Arc<ServiceInfo>;

    /// Validate if a URL is valid for this service.
    ///
    /// Default implementation always returns `true`. Override for service-specific
    /// validation (e.g., Discord requires HTTPS and specific domain).
    #[must_use]
    fn validate_url(&self, _url: &str) -> bool {
        true
    }
}