Skip to main content

rustango_cms/notify/channels/
webhook.rs

1//! Generic webhook — the escape hatch.
2
3use crate::notify::{ConfigField, DeliverError, Delivery, Notification, NotificationChannel};
4
5/// POSTs the notification as JSON to any URL.
6///
7/// This is what makes "or any other tool" true without new code: Zapier,
8/// n8n, Discord (with `/slack` appended), a PagerDuty Events endpoint, or
9/// something internal. The body is the [`Notification`] itself, so
10/// consumers get the structure rather than a rendered string.
11#[derive(Default)]
12pub struct WebhookChannel;
13
14#[async_trait::async_trait]
15impl NotificationChannel for WebhookChannel {
16    fn kind(&self) -> &'static str {
17        "webhook"
18    }
19    fn label(&self) -> &'static str {
20        "Webhook (JSON)"
21    }
22    fn help(&self) -> &'static str {
23        "POSTs the notification as JSON. Use this for Zapier, n8n, Discord, or your own endpoint."
24    }
25    fn config_fields(&self) -> Vec<ConfigField> {
26        vec![ConfigField {
27            name: "url",
28            label: "Endpoint URL",
29            help: "Receives a JSON POST.",
30            // Not secret by default — a plain endpoint often is not one —
31            // but the shared-secret header below is.
32            secret: false,
33            required: true,
34        }]
35    }
36
37    async fn deliver(&self, d: &Delivery<'_>, msg: &Notification) -> Result<(), DeliverError> {
38        let Some(url) = d.config.get("url").filter(|s| !s.trim().is_empty()) else {
39            return Err(DeliverError::Permanent("no endpoint URL set".to_owned()));
40        };
41        let payload = serde_json::to_value(msg)
42            .map_err(|e| DeliverError::Permanent(format!("serialize: {e}")))?;
43        let mut req = super::client_for(url).await?
44            .post(url.as_str())
45            .json(&payload)
46            .map_err(|e| DeliverError::Permanent(format!("encode: {e}")))?;
47        // Lets the receiver verify the call came from this CMS. Optional:
48        // an internal endpoint behind a VPN does not need one.
49        if !d.secret.is_empty() {
50            req = req
51                .header("X-Rustango-Cms-Token", d.secret)
52                .map_err(|e| DeliverError::Permanent(format!("header: {e}")))?;
53        }
54        let resp = req
55            .send()
56            .await
57            .map_err(|e| DeliverError::Transient(e.to_string()))?;
58        let status = resp.status().as_u16();
59        if (200..300).contains(&status) {
60            return Ok(());
61        }
62        let body = resp.text().await.unwrap_or_default();
63        Err(super::classify(status, &body))
64    }
65}
66
67crate::register_notification_channel!(WebhookChannel);