Skip to main content

rustango_cms/notify/
model.rs

1//! Persisted notification config + the delivery outbox.
2
3use chrono::{DateTime, Utc};
4use rustango::casts::{Cast, EncryptedString};
5use rustango::sql::Auto;
6use rustango::Model;
7use serde::{Deserialize, Serialize};
8
9/// Statuses a delivery row moves through. Strings, not an enum column, to
10/// match how the rest of the CMS stores small vocabularies (page status,
11/// media kind) and to keep a future status from needing a migration.
12pub const STATUS_PENDING: &str = "pending";
13pub const STATUS_SENT: &str = "sent";
14/// Retries exhausted, or the channel said the config is wrong. Terminal
15/// until a human retries it.
16pub const STATUS_FAILED: &str = "failed";
17
18/// A configured destination: which channel, how it is set up, and which
19/// events it wants.
20#[derive(Model, Clone, Serialize, Deserialize)]
21#[rustango(
22    table = "cms_notification_target",
23    app = "cms",
24    display = "label",
25    admin(
26        list_display = "label, kind, enabled, events",
27        ordering = "label",
28    )
29)]
30pub struct NotificationTarget {
31    #[rustango(primary_key)]
32    pub id: Auto<i64>,
33
34    /// Editor-facing name — "#leads in Slack", "Sales inbox".
35    #[rustango(max_length = 150)]
36    pub label: String,
37
38    /// Which [`NotificationChannel`](super::NotificationChannel) handles
39    /// it. A kind with no registered channel is skipped, not an error: a
40    /// host app can register channels this binary does not have.
41    #[rustango(max_length = 32, index)]
42    pub kind: String,
43
44    /// Non-secret settings as a JSON object — the channel decides the
45    /// keys via `config_fields()`. JSON rather than columns because every
46    /// channel wants different ones, and a new channel must not need a
47    /// migration.
48    pub config: String,
49
50    /// The one secret a destination needs: an incoming-webhook URL, a bot
51    /// token. Encrypted at rest (XChaCha20-Poly1305, `RUSTANGO_SECRET_KEY`)
52    /// with the same primitive SSO client secrets use — a Slack webhook URL
53    /// *is* a credential, since anyone holding it can post to the channel.
54    pub secret: Cast<EncryptedString>,
55
56    /// Comma-separated event keys this target wants (`"form.submitted"`).
57    /// Empty means every event — the useful default for "tell me
58    /// everything" destinations.
59    #[rustango(max_length = 512)]
60    pub events: String,
61
62    /// Scope to one source object, e.g. a single form's snippet id. 0 =
63    /// every source of its subscribed events.
64    pub source_id: i64,
65
66    pub enabled: bool,
67
68    #[rustango(auto_now_add)]
69    pub created_at: Auto<DateTime<Utc>>,
70}
71
72/// Debug without the secret: `Cast`'s own Debug prints the
73/// decrypted value, so a derived impl would log a webhook URL or bot token
74/// from any `{:?}` of a target.
75impl std::fmt::Debug for NotificationTarget {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        f.debug_struct("NotificationTarget")
78            .field("id", &self.id)
79            .field("label", &self.label)
80            .field("kind", &self.kind)
81            .field("config", &self.config)
82            .field("secret", &"<redacted>")
83            .field("events", &self.events)
84            .field("source_id", &self.source_id)
85            .field("enabled", &self.enabled)
86            .field("created_at", &self.created_at)
87            .finish()
88    }
89}
90
91impl NotificationTarget {
92    /// Whether this target wants `event` from `source_id`.
93    #[must_use]
94    pub fn wants(&self, event: &str, source_id: i64) -> bool {
95        if !self.enabled {
96            return false;
97        }
98        if self.source_id != 0 && self.source_id != source_id {
99            return false;
100        }
101        let list = self.events.trim();
102        list.is_empty() || list.split(',').any(|e| e.trim() == event)
103    }
104
105    /// Parsed `config`. A row whose JSON has rotted yields an empty map
106    /// rather than failing the send: the channel then reports a missing
107    /// setting, which points at the real problem.
108    #[must_use]
109    pub fn config_map(&self) -> std::collections::BTreeMap<String, String> {
110        serde_json::from_str(&self.config).unwrap_or_default()
111    }
112}
113
114/// One queued attempt to deliver one notification to one target.
115#[derive(Model, Debug, Clone, Serialize, Deserialize)]
116#[rustango(
117    table = "cms_notification_delivery",
118    app = "cms",
119    display = "event",
120    admin(
121        list_display = "event, target_id, status, attempts, created_at",
122        ordering = "-created_at",
123    )
124)]
125pub struct NotificationDelivery {
126    #[rustango(primary_key)]
127    pub id: Auto<i64>,
128
129    #[rustango(fk = "cms_notification_target", on = "id", index)]
130    pub target_id: i64,
131
132    #[rustango(max_length = 64, index)]
133    pub event: String,
134
135    /// The serialized [`Notification`](super::Notification). Stored rather
136    /// than re-derived so a retry days later sends what actually happened,
137    /// not what the source looks like now — the submission may have been
138    /// edited or deleted in between.
139    pub payload: String,
140
141    #[rustango(max_length = 16, index)]
142    pub status: String,
143
144    pub attempts: i32,
145
146    /// Why the last attempt failed, shown in the admin so a broken
147    /// destination is diagnosable without reading logs.
148    #[rustango(max_length = 512)]
149    pub last_error: String,
150
151    /// Earliest time the worker may try again — backoff lives here rather
152    /// than in the worker's memory so it survives a restart.
153    pub next_attempt_at: Option<DateTime<Utc>>,
154
155    #[rustango(auto_now_add)]
156    pub created_at: Auto<DateTime<Utc>>,
157
158    pub sent_at: Option<DateTime<Utc>>,
159}
160
161/// Give up after this many tries. Roughly 1s + 5s + 25s + 125s + 625s of
162/// backoff — about thirteen minutes, which covers a short outage or a rate
163/// limit without leaving a genuinely broken destination retrying forever.
164pub const MAX_ATTEMPTS: i32 = 5;
165
166/// Backoff before attempt `n` (1-based).
167#[must_use]
168pub fn backoff_secs(attempt: i32) -> i64 {
169    5i64.saturating_pow(u32::try_from(attempt.max(1) - 1).unwrap_or(0).min(6))
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    fn target(events: &str, source_id: i64, enabled: bool) -> NotificationTarget {
177        NotificationTarget {
178            id: Auto::Unset,
179            label: "t".into(),
180            kind: "slack".into(),
181            config: "{}".into(),
182            secret: Cast::new(String::new().into()),
183            events: events.into(),
184            source_id,
185            enabled,
186            created_at: Auto::Unset,
187        }
188    }
189
190    #[test]
191    fn empty_event_list_means_every_event() {
192        let t = target("", 0, true);
193        assert!(t.wants("form.submitted", 1));
194        assert!(t.wants("anything.else", 1));
195    }
196
197    #[test]
198    fn a_listed_event_matches_and_others_do_not() {
199        let t = target("form.submitted, page.published", 0, true);
200        assert!(t.wants("form.submitted", 7));
201        assert!(t.wants("page.published", 7));
202        assert!(!t.wants("form.deleted", 7));
203    }
204
205    #[test]
206    fn source_scope_pins_a_target_to_one_form() {
207        let t = target("form.submitted", 42, true);
208        assert!(t.wants("form.submitted", 42));
209        // The whole point of scoping: another form's submissions must not
210        // reach a destination configured for this one.
211        assert!(!t.wants("form.submitted", 43));
212    }
213
214    #[test]
215    fn source_zero_accepts_every_source() {
216        let t = target("form.submitted", 0, true);
217        assert!(t.wants("form.submitted", 1));
218        assert!(t.wants("form.submitted", 999));
219    }
220
221    #[test]
222    fn disabled_targets_want_nothing() {
223        let t = target("", 0, false);
224        assert!(!t.wants("form.submitted", 1));
225    }
226
227    #[test]
228    fn config_map_survives_rotten_json() {
229        let mut t = target("", 0, true);
230        t.config = "{not json".into();
231        // Must not panic: a bad row should surface as "missing setting" from
232        // the channel, not take the worker down.
233        assert!(t.config_map().is_empty());
234    }
235
236    #[test]
237    fn backoff_grows_and_stays_bounded() {
238        assert_eq!(backoff_secs(1), 1);
239        assert_eq!(backoff_secs(2), 5);
240        assert_eq!(backoff_secs(3), 25);
241        assert!(backoff_secs(MAX_ATTEMPTS) > backoff_secs(MAX_ATTEMPTS - 1));
242        // No overflow panic on a nonsense attempt count.
243        let _ = backoff_secs(i32::MAX);
244        let _ = backoff_secs(0);
245    }
246}
247
248#[cfg(test)]
249mod debug_tests {
250    use super::NotificationTarget;
251
252    #[test]
253    fn debug_never_prints_the_secret() {
254        let t = NotificationTarget {
255            id: rustango::sql::Auto::Unset,
256            label: "Slack".to_owned(),
257            kind: "slack".to_owned(),
258            config: "{}".to_owned(),
259            secret: rustango::casts::Cast::new("https://hooks.example/T0/B0/very-secret".to_owned().into()),
260            events: String::new(),
261            source_id: 0,
262            enabled: true,
263            created_at: rustango::sql::Auto::Unset,
264        };
265        let shown = format!("{t:?}");
266        assert!(!shown.contains("very-secret"), "{shown}");
267        assert!(shown.contains("<redacted>"));
268    }
269}