pub mod channels;
pub mod model;
pub mod targets;
pub mod worker;
pub mod events {
pub const FORM_SUBMITTED: &str = "form.submitted";
}
use std::collections::BTreeMap;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Notification {
pub event: String,
pub title: String,
#[serde(default)]
pub summary: String,
#[serde(default)]
pub fields: Vec<(String, String)>,
#[serde(default)]
pub url: String,
#[serde(default)]
pub meta: BTreeMap<String, String>,
}
impl Notification {
#[must_use]
pub fn new(event: impl Into<String>, title: impl Into<String>) -> Self {
Self {
event: event.into(),
title: title.into(),
summary: String::new(),
fields: Vec::new(),
url: String::new(),
meta: BTreeMap::new(),
}
}
#[must_use]
pub fn summary(mut self, s: impl Into<String>) -> Self {
self.summary = s.into();
self
}
#[must_use]
pub fn field(mut self, label: impl Into<String>, value: impl Into<String>) -> Self {
self.fields.push((label.into(), value.into()));
self
}
#[must_use]
pub fn url(mut self, u: impl Into<String>) -> Self {
self.url = u.into();
self
}
#[must_use]
pub fn as_text(&self) -> String {
let mut out = String::new();
if !self.summary.is_empty() {
out.push_str(&self.summary);
out.push_str("\n\n");
}
for (k, v) in &self.fields {
out.push_str(k);
out.push_str(": ");
out.push_str(v);
out.push('\n');
}
if !self.url.is_empty() {
out.push('\n');
out.push_str(&self.url);
out.push('\n');
}
out
}
}
#[derive(Debug)]
pub enum DeliverError {
Permanent(String),
Transient(String),
}
impl DeliverError {
#[must_use]
pub fn is_permanent(&self) -> bool {
matches!(self, Self::Permanent(_))
}
#[must_use]
pub fn message(&self) -> &str {
match self {
Self::Permanent(m) | Self::Transient(m) => m,
}
}
}
impl std::fmt::Display for DeliverError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Permanent(m) => write!(f, "permanent: {m}"),
Self::Transient(m) => write!(f, "transient: {m}"),
}
}
}
pub struct ConfigField {
pub name: &'static str,
pub label: &'static str,
pub help: &'static str,
pub secret: bool,
pub required: bool,
}
pub struct Delivery<'a> {
pub config: &'a BTreeMap<String, String>,
pub secret: &'a str,
pub mailer: Option<&'a dyn rustango::email::Mailer>,
pub mailer_from: &'a str,
}
#[async_trait::async_trait]
pub trait NotificationChannel: Send + Sync {
fn kind(&self) -> &'static str;
fn label(&self) -> &'static str;
fn help(&self) -> &'static str {
""
}
fn config_fields(&self) -> Vec<ConfigField>;
async fn deliver(&self, d: &Delivery<'_>, msg: &Notification) -> Result<(), DeliverError>;
}
pub struct ChannelRegistration {
pub factory: fn() -> Box<dyn NotificationChannel>,
}
inventory::collect!(ChannelRegistration);
#[macro_export]
macro_rules! register_notification_channel {
($ty:ty) => {
$crate::inventory::submit! {
$crate::notify::ChannelRegistration {
factory: || Box::new(<$ty>::default()),
}
}
};
($factory:expr) => {
$crate::inventory::submit! {
$crate::notify::ChannelRegistration { factory: $factory }
}
};
}
pub fn registered_channels() -> impl Iterator<Item = Box<dyn NotificationChannel>> {
inventory::iter::<ChannelRegistration>
.into_iter()
.map(|r| (r.factory)())
}
#[must_use]
pub fn channel_for(kind: &str) -> Option<Box<dyn NotificationChannel>> {
registered_channels().find(|c| c.kind() == kind)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn as_text_renders_summary_fields_and_link() {
let n = Notification::new(events::FORM_SUBMITTED, "New submission")
.summary("Someone got in touch.")
.field("Name", "Ada")
.field("Email", "ada@example.com")
.url("https://example.com/admin");
let t = n.as_text();
assert!(t.contains("Someone got in touch."));
assert!(t.contains("Name: Ada"));
assert!(t.contains("Email: ada@example.com"));
assert!(t.contains("https://example.com/admin"));
assert!(t.find("Name: Ada").unwrap() < t.find("Email:").unwrap());
}
#[test]
fn built_in_channels_are_registered() {
let kinds: Vec<&str> = registered_channels().map(|c| c.kind()).collect();
for want in ["email", "slack", "teams", "telegram", "webhook"] {
assert!(kinds.contains(&want), "channel `{want}` not registered; have {kinds:?}");
}
}
#[test]
fn channel_kinds_are_unique() {
let mut kinds: Vec<String> =
registered_channels().map(|c| c.kind().to_owned()).collect();
kinds.sort();
let before = kinds.len();
kinds.dedup();
assert_eq!(before, kinds.len(), "duplicate channel kind: {kinds:?}");
}
#[test]
fn unknown_channel_is_none_not_a_panic() {
assert!(channel_for("pagerduty-not-built-in").is_none());
}
#[test]
fn every_channel_declares_at_least_one_config_field() {
for c in registered_channels() {
assert!(
!c.config_fields().is_empty(),
"channel `{}` has no config fields, so the admin form would \
render an empty box that saves an unusable target",
c.kind()
);
}
}
}