hookburn-slack 0.2.2

A Rust crate for sending messages to Slack via webhooks
Documentation
// crates/hookburn-slack/src/client.rs
use async_trait::async_trait;
use hookburn_core::{HttpClient, RetryPolicy, WebhookSender};
use reqwest::Client;
use secrecy::{ExposeSecret, SecretString};
use std::time::Duration;

use crate::{SlackError, SlackMessage};

/// Validate that a webhook URL is HTTPS and targets the Slack API.
fn validate_url(url: &str) -> Result<(), SlackError> {
    if !url.starts_with("https://") {
        return Err(SlackError::InvalidUrl { reason: "webhook URL must use HTTPS".to_string() });
    }
    if !url.contains("hooks.slack.com/services/") {
        return Err(SlackError::InvalidUrl {
            reason: "URL must target hooks.slack.com/services/".to_string(),
        });
    }
    Ok(())
}

/// An async Slack webhook client.
///
/// # Example
///
/// ```rust,no_run
/// use hookburn_slack::{SlackClient, SlackMessage, SlackBlock};
///
/// #[tokio::main]
/// async fn main() -> Result<(), hookburn_slack::SlackError> {
///     let client = SlackClient::new("https://hooks.slack.com/services/T/B/X")?;
///
///     let message = SlackMessage::builder()
///         .text("Hello from hookburn_slack! 👋")
///         .build()?;
///
///     client.send(&message).await
/// }
/// ```
#[derive(Clone)]
pub struct SlackClient {
    /// The full webhook URL stored as a secret.
    url: SecretString,
    client: HttpClient,
}

impl SlackClient {
    /// Create a new client with a default [`reqwest::Client`].
    pub fn new(url: impl Into<String>) -> Result<Self, SlackError> {
        let url = url.into();
        validate_url(&url)?;
        Ok(Self { url: SecretString::from(url), client: HttpClient::new() })
    }

    /// Create a client that reuses a pre-configured [`reqwest::Client`].
    pub fn with_client(url: impl Into<String>, client: Client) -> Result<Self, SlackError> {
        let url = url.into();
        validate_url(&url)?;
        Ok(Self {
            url: SecretString::from(url),
            client: HttpClient::with_reqwest(client),
        })
    }

    /// Send a [`SlackMessage`] to Slack.
    ///
    /// # Errors
    ///
    /// - [`SlackError::Http`] – transport-level failure.
    /// - [`SlackError::RateLimited`] – Slack returned HTTP 429.
    /// - [`SlackError::ApiError`] – any other non-2xx response.
    pub async fn send(&self, message: &SlackMessage) -> Result<(), SlackError> {
        self.execute(message).await
    }

    /// Send a [`SlackMessage`] with automatic retries.
    pub async fn send_with_retry(
        &self,
        message: &SlackMessage,
        policy: &RetryPolicy,
    ) -> Result<(), SlackError> {
        let url = self.url.expose_secret();
        let response = self
            .client
            .post_json_with_retry(url, message, policy)
            .await?;

        let status = response.status();

        if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
            let retry_after_ms = response
                .headers()
                .get("retry-after")
                .and_then(|v| v.to_str().ok())
                .and_then(|s| s.parse::<f64>().ok())
                .map(|secs| (secs * 1000.0) as u64)
                .unwrap_or(1_000);
            return Err(SlackError::RateLimited { retry_after_ms });
        }

        if !status.is_success() {
            let body = response
                .bytes()
                .await
                .map(|b| {
                    let slice = &b[..b.len().min(4096)];
                    String::from_utf8_lossy(slice).into_owned()
                })
                .unwrap_or_else(|_| status.to_string());
            return Err(SlackError::ApiError { status: status.as_u16(), message: body });
        }

        Ok(())
    }

    async fn execute(&self, message: &SlackMessage) -> Result<(), SlackError> {
        let url = self.url.expose_secret();
        let response = self.client.post_json(url, message).await?;

        let status = response.status();

        if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
            let retry_after_ms = response
                .headers()
                .get("retry-after")
                .and_then(|v| v.to_str().ok())
                .and_then(|s| s.parse::<f64>().ok())
                .map(|secs| (secs * 1000.0) as u64)
                .unwrap_or(1_000);

            return Err(SlackError::RateLimited { retry_after_ms });
        }

        if !status.is_success() {
            let body = response
                .bytes()
                .await
                .map(|b| {
                    let slice = &b[..b.len().min(4096)];
                    String::from_utf8_lossy(slice).into_owned()
                })
                .unwrap_or_else(|_| status.to_string());
            return Err(SlackError::ApiError { status: status.as_u16(), message: body });
        }

        Ok(())
    }
}

impl std::fmt::Debug for SlackClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let raw = self.url.expose_secret();
        let redacted = match raw.rfind('/') {
            Some(idx) => format!("{}/", &raw[..idx]),
            None => String::new(),
        };
        f.debug_struct("SlackClient")
            .field("url", &format_args!("{}<REDACTED>", redacted))
            .finish_non_exhaustive()
    }
}

#[async_trait]
impl WebhookSender for SlackClient {
    type Message = SlackMessage;
    type Error = SlackError;

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

// ---------------------------------------------------------------------------
// SlackClientBuilder
// ---------------------------------------------------------------------------

/// Builder for [`SlackClient`] with configurable timeout settings.
pub struct SlackClientBuilder {
    url: String,
    connect_timeout: Option<Duration>,
    request_timeout: Option<Duration>,
}

impl SlackClientBuilder {
    /// Start building a client for the given Slack webhook URL.
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            connect_timeout: None,
            request_timeout: Some(Duration::from_secs(30)),
        }
    }

    /// Set the maximum time allowed to establish a TCP connection.
    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = Some(timeout);
        self
    }

    /// Set the maximum time allowed for a complete request/response cycle.
    pub fn request_timeout(mut self, timeout: Duration) -> Self {
        self.request_timeout = Some(timeout);
        self
    }

    /// Validate the URL and build the [`SlackClient`].
    pub fn build(self) -> Result<SlackClient, SlackError> {
        validate_url(&self.url)?;
        let mut builder = Client::builder();
        if let Some(t) = self.connect_timeout {
            builder = builder.connect_timeout(t);
        }
        if let Some(t) = self.request_timeout {
            builder = builder.timeout(t);
        }
        let client = builder.build().map_err(SlackError::Http)?;
        Ok(SlackClient {
            url: SecretString::from(self.url),
            client: HttpClient::with_reqwest(client),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rejects_http_url() {
        let err = validate_url("http://hooks.slack.com/services/T/B/X").unwrap_err();
        assert!(matches!(err, SlackError::InvalidUrl { .. }));
    }

    #[test]
    fn rejects_non_slack_url() {
        let err = validate_url("https://example.com/webhook").unwrap_err();
        assert!(matches!(err, SlackError::InvalidUrl { .. }));
    }

    #[test]
    fn accepts_valid_slack_url() {
        assert!(validate_url("https://hooks.slack.com/services/T/B/X").is_ok());
    }

    #[test]
    fn debug_output_redacts_token() {
        let client = SlackClient::new("https://hooks.slack.com/services/T/B/SECRET_TOKEN").unwrap();
        let debug = format!("{client:?}");
        assert!(!debug.contains("SECRET_TOKEN"));
        assert!(debug.contains("T/B"));
    }
}