use chrono::{DateTime, Utc};
use rustango::casts::{Cast, EncryptedString};
use rustango::sql::Auto;
use rustango::Model;
use serde::{Deserialize, Serialize};
pub const STATUS_PENDING: &str = "pending";
pub const STATUS_SENT: &str = "sent";
pub const STATUS_FAILED: &str = "failed";
#[derive(Model, Clone, Serialize, Deserialize)]
#[rustango(
table = "cms_notification_target",
app = "cms",
display = "label",
admin(
list_display = "label, kind, enabled, events",
ordering = "label",
)
)]
pub struct NotificationTarget {
#[rustango(primary_key)]
pub id: Auto<i64>,
#[rustango(max_length = 150)]
pub label: String,
#[rustango(max_length = 32, index)]
pub kind: String,
pub config: String,
pub secret: Cast<EncryptedString>,
#[rustango(max_length = 512)]
pub events: String,
pub source_id: i64,
pub enabled: bool,
#[rustango(auto_now_add)]
pub created_at: Auto<DateTime<Utc>>,
}
impl std::fmt::Debug for NotificationTarget {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NotificationTarget")
.field("id", &self.id)
.field("label", &self.label)
.field("kind", &self.kind)
.field("config", &self.config)
.field("secret", &"<redacted>")
.field("events", &self.events)
.field("source_id", &self.source_id)
.field("enabled", &self.enabled)
.field("created_at", &self.created_at)
.finish()
}
}
impl NotificationTarget {
#[must_use]
pub fn wants(&self, event: &str, source_id: i64) -> bool {
if !self.enabled {
return false;
}
if self.source_id != 0 && self.source_id != source_id {
return false;
}
let list = self.events.trim();
list.is_empty() || list.split(',').any(|e| e.trim() == event)
}
#[must_use]
pub fn config_map(&self) -> std::collections::BTreeMap<String, String> {
serde_json::from_str(&self.config).unwrap_or_default()
}
}
#[derive(Model, Debug, Clone, Serialize, Deserialize)]
#[rustango(
table = "cms_notification_delivery",
app = "cms",
display = "event",
admin(
list_display = "event, target_id, status, attempts, created_at",
ordering = "-created_at",
)
)]
pub struct NotificationDelivery {
#[rustango(primary_key)]
pub id: Auto<i64>,
#[rustango(fk = "cms_notification_target", on = "id", index)]
pub target_id: i64,
#[rustango(max_length = 64, index)]
pub event: String,
pub payload: String,
#[rustango(max_length = 16, index)]
pub status: String,
pub attempts: i32,
#[rustango(max_length = 512)]
pub last_error: String,
pub next_attempt_at: Option<DateTime<Utc>>,
#[rustango(auto_now_add)]
pub created_at: Auto<DateTime<Utc>>,
pub sent_at: Option<DateTime<Utc>>,
}
pub const MAX_ATTEMPTS: i32 = 5;
#[must_use]
pub fn backoff_secs(attempt: i32) -> i64 {
5i64.saturating_pow(u32::try_from(attempt.max(1) - 1).unwrap_or(0).min(6))
}
#[cfg(test)]
mod tests {
use super::*;
fn target(events: &str, source_id: i64, enabled: bool) -> NotificationTarget {
NotificationTarget {
id: Auto::Unset,
label: "t".into(),
kind: "slack".into(),
config: "{}".into(),
secret: Cast::new(String::new().into()),
events: events.into(),
source_id,
enabled,
created_at: Auto::Unset,
}
}
#[test]
fn empty_event_list_means_every_event() {
let t = target("", 0, true);
assert!(t.wants("form.submitted", 1));
assert!(t.wants("anything.else", 1));
}
#[test]
fn a_listed_event_matches_and_others_do_not() {
let t = target("form.submitted, page.published", 0, true);
assert!(t.wants("form.submitted", 7));
assert!(t.wants("page.published", 7));
assert!(!t.wants("form.deleted", 7));
}
#[test]
fn source_scope_pins_a_target_to_one_form() {
let t = target("form.submitted", 42, true);
assert!(t.wants("form.submitted", 42));
assert!(!t.wants("form.submitted", 43));
}
#[test]
fn source_zero_accepts_every_source() {
let t = target("form.submitted", 0, true);
assert!(t.wants("form.submitted", 1));
assert!(t.wants("form.submitted", 999));
}
#[test]
fn disabled_targets_want_nothing() {
let t = target("", 0, false);
assert!(!t.wants("form.submitted", 1));
}
#[test]
fn config_map_survives_rotten_json() {
let mut t = target("", 0, true);
t.config = "{not json".into();
assert!(t.config_map().is_empty());
}
#[test]
fn backoff_grows_and_stays_bounded() {
assert_eq!(backoff_secs(1), 1);
assert_eq!(backoff_secs(2), 5);
assert_eq!(backoff_secs(3), 25);
assert!(backoff_secs(MAX_ATTEMPTS) > backoff_secs(MAX_ATTEMPTS - 1));
let _ = backoff_secs(i32::MAX);
let _ = backoff_secs(0);
}
}
#[cfg(test)]
mod debug_tests {
use super::NotificationTarget;
#[test]
fn debug_never_prints_the_secret() {
let t = NotificationTarget {
id: rustango::sql::Auto::Unset,
label: "Slack".to_owned(),
kind: "slack".to_owned(),
config: "{}".to_owned(),
secret: rustango::casts::Cast::new("https://hooks.example/T0/B0/very-secret".to_owned().into()),
events: String::new(),
source_id: 0,
enabled: true,
created_at: rustango::sql::Auto::Unset,
};
let shown = format!("{t:?}");
assert!(!shown.contains("very-secret"), "{shown}");
assert!(shown.contains("<redacted>"));
}
}