rustango_cms/notify/mod.rs
1//! Notifications — one delivery path, many destinations.
2//!
3//! Before this, every notification in the CMS was an email loop written
4//! where it was needed: form submissions built theirs inline in the submit
5//! handler, page publishes built theirs in `page_subscription`, workflow
6//! events in `workflow_mail`. Adding Slack meant writing a fourth loop, and
7//! adding Teams a fifth — per event, forever.
8//!
9//! So the destination is a plugin, not a branch:
10//!
11//! * [`Notification`] is what happened, in channel-agnostic terms — a
12//! title, a summary, some labelled fields, maybe a link. It never knows
13//! who will render it.
14//! * [`NotificationChannel`] renders and delivers one. Email writes a
15//! message, Slack posts blocks, Telegram sends Markdown. Register one
16//! with [`register_notification_channel!`](crate::register_notification_channel!) and it is available
17//! everywhere, including from a host app's own crate.
18//! * A [`Target`](model::NotificationTarget) row is a configured
19//! destination: which channel, its settings, its secret, and which
20//! events it wants.
21//!
22//! ## Delivery is durable on purpose
23//!
24//! [`enqueue`](worker::enqueue) writes a row per target and returns; a worker
25//! ([`worker::drain`]) sends with backoff. Notifications are the part of a
26//! form nobody watches until it silently stops working, and the failure
27//! modes here are all *transient and external* — a rate limit, an expired
28//! webhook, a five-minute Slack outage. Sending inline would mean the
29//! visitor waits on Slack, and a failure would be a log line nobody reads
30//! while the lead is gone. A row that says `failed, 3 attempts, 429` is
31//! recoverable; a warning in yesterday's journal is not.
32
33pub mod channels;
34pub mod model;
35pub mod targets;
36pub mod worker;
37
38/// Event keys. Constants rather than literals so a typo at the emit site
39/// cannot silently produce an event no target subscribes to.
40pub mod events {
41 /// A visitor submitted a form. `source_id` is the form's snippet id.
42 pub const FORM_SUBMITTED: &str = "form.submitted";
43}
44
45use std::collections::BTreeMap;
46
47/// What happened, in terms every channel can render.
48///
49/// Deliberately not a string: a channel that only gets pre-formatted text
50/// can do nothing intelligent with it. Slack wants fields it can lay out,
51/// email wants a subject distinct from a body, and a webhook wants the
52/// structure back as JSON. Keeping the parts separate lets each decide.
53#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
54pub struct Notification {
55 /// Event key this arose from (`"form.submitted"`), matched against a
56 /// target's subscriptions.
57 pub event: String,
58 /// One line: "New submission: Contact form".
59 pub title: String,
60 /// Optional prose under the title.
61 #[serde(default)]
62 pub summary: String,
63 /// Ordered label → value pairs. `BTreeMap` would sort them; a form's
64 /// fields must arrive in the order the form asks them.
65 #[serde(default)]
66 pub fields: Vec<(String, String)>,
67 /// Where to go to act on this — an admin URL, absolute or relative.
68 #[serde(default)]
69 pub url: String,
70 /// Free-form extras for channels that want the raw shape (webhooks).
71 #[serde(default)]
72 pub meta: BTreeMap<String, String>,
73}
74
75impl Notification {
76 #[must_use]
77 pub fn new(event: impl Into<String>, title: impl Into<String>) -> Self {
78 Self {
79 event: event.into(),
80 title: title.into(),
81 summary: String::new(),
82 fields: Vec::new(),
83 url: String::new(),
84 meta: BTreeMap::new(),
85 }
86 }
87
88 #[must_use]
89 pub fn summary(mut self, s: impl Into<String>) -> Self {
90 self.summary = s.into();
91 self
92 }
93
94 #[must_use]
95 pub fn field(mut self, label: impl Into<String>, value: impl Into<String>) -> Self {
96 self.fields.push((label.into(), value.into()));
97 self
98 }
99
100 #[must_use]
101 pub fn url(mut self, u: impl Into<String>) -> Self {
102 self.url = u.into();
103 self
104 }
105
106 /// Plain-text rendering — the fallback every channel can use, and what
107 /// email sends verbatim.
108 #[must_use]
109 pub fn as_text(&self) -> String {
110 let mut out = String::new();
111 if !self.summary.is_empty() {
112 out.push_str(&self.summary);
113 out.push_str("\n\n");
114 }
115 for (k, v) in &self.fields {
116 out.push_str(k);
117 out.push_str(": ");
118 out.push_str(v);
119 out.push('\n');
120 }
121 if !self.url.is_empty() {
122 out.push('\n');
123 out.push_str(&self.url);
124 out.push('\n');
125 }
126 out
127 }
128}
129
130/// Why a delivery failed, which decides whether the worker tries again.
131#[derive(Debug)]
132pub enum DeliverError {
133 /// The destination is wrong and will stay wrong — a malformed webhook
134 /// URL, a revoked token, a 404 channel. Retrying just burns attempts
135 /// and delays the dead-letter that tells someone to fix the config.
136 Permanent(String),
137 /// A rate limit, a timeout, a 5xx. Worth another go.
138 Transient(String),
139}
140
141impl DeliverError {
142 #[must_use]
143 pub fn is_permanent(&self) -> bool {
144 matches!(self, Self::Permanent(_))
145 }
146
147 #[must_use]
148 pub fn message(&self) -> &str {
149 match self {
150 Self::Permanent(m) | Self::Transient(m) => m,
151 }
152 }
153}
154
155impl std::fmt::Display for DeliverError {
156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157 match self {
158 Self::Permanent(m) => write!(f, "permanent: {m}"),
159 Self::Transient(m) => write!(f, "transient: {m}"),
160 }
161 }
162}
163
164/// One configurable setting on a channel, rendered into the admin form.
165/// Reuses the widget vocabulary the rest of the admin speaks rather than
166/// inventing a second one.
167pub struct ConfigField {
168 pub name: &'static str,
169 pub label: &'static str,
170 pub help: &'static str,
171 /// Held in the target's encrypted column instead of its plain config.
172 pub secret: bool,
173 pub required: bool,
174}
175
176/// Everything a channel needs to deliver: its resolved configuration and
177/// the decrypted secret.
178pub struct Delivery<'a> {
179 pub config: &'a BTreeMap<String, String>,
180 pub secret: &'a str,
181 /// The tenant's outbound mailer, when one is wired. Only the email
182 /// channel needs it; it is here rather than in the trait so channels
183 /// stay constructible without one.
184 pub mailer: Option<&'a dyn rustango::email::Mailer>,
185 pub mailer_from: &'a str,
186}
187
188/// A destination kind. Implement it, register it, and it appears in the
189/// admin's channel picker with its own settings.
190#[async_trait::async_trait]
191pub trait NotificationChannel: Send + Sync {
192 /// Stable key stored on the target row (`"slack"`). Changing it
193 /// orphans existing targets, so treat it as data, not a label.
194 fn kind(&self) -> &'static str;
195
196 /// Human name for the picker.
197 fn label(&self) -> &'static str;
198
199 /// One line describing what the admin has to go and fetch.
200 fn help(&self) -> &'static str {
201 ""
202 }
203
204 fn config_fields(&self) -> Vec<ConfigField>;
205
206 async fn deliver(&self, d: &Delivery<'_>, msg: &Notification) -> Result<(), DeliverError>;
207}
208
209/// Registration slot — see [`register_notification_channel!`](crate::register_notification_channel!).
210pub struct ChannelRegistration {
211 pub factory: fn() -> Box<dyn NotificationChannel>,
212}
213
214inventory::collect!(ChannelRegistration);
215
216/// Register a [`NotificationChannel`] so the admin can configure it.
217///
218/// ```ignore
219/// register_notification_channel!(MyPagerDutyChannel);
220/// ```
221#[macro_export]
222macro_rules! register_notification_channel {
223 ($ty:ty) => {
224 $crate::inventory::submit! {
225 $crate::notify::ChannelRegistration {
226 factory: || Box::new(<$ty>::default()),
227 }
228 }
229 };
230 ($factory:expr) => {
231 $crate::inventory::submit! {
232 $crate::notify::ChannelRegistration { factory: $factory }
233 }
234 };
235}
236
237/// Every registered channel, in registration order.
238pub fn registered_channels() -> impl Iterator<Item = Box<dyn NotificationChannel>> {
239 inventory::iter::<ChannelRegistration>
240 .into_iter()
241 .map(|r| (r.factory)())
242}
243
244/// The channel handling `kind`, or `None` when a target names a channel
245/// this binary was not built with — a real case for host-registered
246/// channels, so it must not panic.
247#[must_use]
248pub fn channel_for(kind: &str) -> Option<Box<dyn NotificationChannel>> {
249 registered_channels().find(|c| c.kind() == kind)
250}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255
256 #[test]
257 fn as_text_renders_summary_fields_and_link() {
258 let n = Notification::new(events::FORM_SUBMITTED, "New submission")
259 .summary("Someone got in touch.")
260 .field("Name", "Ada")
261 .field("Email", "ada@example.com")
262 .url("https://example.com/admin");
263 let t = n.as_text();
264 assert!(t.contains("Someone got in touch."));
265 assert!(t.contains("Name: Ada"));
266 assert!(t.contains("Email: ada@example.com"));
267 assert!(t.contains("https://example.com/admin"));
268 // Field order is the form's order, not sorted — a submission read
269 // out of order is harder to scan than the form that produced it.
270 assert!(t.find("Name: Ada").unwrap() < t.find("Email:").unwrap());
271 }
272
273 /// Every built-in must be registered, or it silently cannot be chosen in
274 /// the admin — the failure looks like "Slack isn't supported".
275 #[test]
276 fn built_in_channels_are_registered() {
277 let kinds: Vec<&str> = registered_channels().map(|c| c.kind()).collect();
278 for want in ["email", "slack", "teams", "telegram", "webhook"] {
279 assert!(kinds.contains(&want), "channel `{want}` not registered; have {kinds:?}");
280 }
281 }
282
283 #[test]
284 fn channel_kinds_are_unique() {
285 let mut kinds: Vec<String> =
286 registered_channels().map(|c| c.kind().to_owned()).collect();
287 kinds.sort();
288 let before = kinds.len();
289 kinds.dedup();
290 // A duplicate kind means `channel_for` silently picks one of them and
291 // half the targets deliver through the wrong adapter.
292 assert_eq!(before, kinds.len(), "duplicate channel kind: {kinds:?}");
293 }
294
295 #[test]
296 fn unknown_channel_is_none_not_a_panic() {
297 // A target can name a channel a host registered but this binary
298 // lacks; that must degrade, not crash the worker.
299 assert!(channel_for("pagerduty-not-built-in").is_none());
300 }
301
302 #[test]
303 fn every_channel_declares_at_least_one_config_field() {
304 for c in registered_channels() {
305 assert!(
306 !c.config_fields().is_empty(),
307 "channel `{}` has no config fields, so the admin form would \
308 render an empty box that saves an unusable target",
309 c.kind()
310 );
311 }
312 }
313}