1use chrono::{DateTime, Utc};
4use rustango::casts::{Cast, EncryptedString};
5use rustango::sql::Auto;
6use rustango::Model;
7use serde::{Deserialize, Serialize};
8
9pub const STATUS_PENDING: &str = "pending";
13pub const STATUS_SENT: &str = "sent";
14pub const STATUS_FAILED: &str = "failed";
17
18#[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 #[rustango(max_length = 150)]
36 pub label: String,
37
38 #[rustango(max_length = 32, index)]
42 pub kind: String,
43
44 pub config: String,
49
50 pub secret: Cast<EncryptedString>,
55
56 #[rustango(max_length = 512)]
60 pub events: String,
61
62 pub source_id: i64,
65
66 pub enabled: bool,
67
68 #[rustango(auto_now_add)]
69 pub created_at: Auto<DateTime<Utc>>,
70}
71
72impl 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 #[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 #[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#[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 pub payload: String,
140
141 #[rustango(max_length = 16, index)]
142 pub status: String,
143
144 pub attempts: i32,
145
146 #[rustango(max_length = 512)]
149 pub last_error: String,
150
151 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
161pub const MAX_ATTEMPTS: i32 = 5;
165
166#[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 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 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 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}