From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [45.144.208.40]) by lore.proxmox.com (Postfix) with ESMTPS id C38971FF0C0 for ; Wed, 18 Nov 2026 10:51:28 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 6A44121D78; Wed, 18 Nov 2026 10:45:11 +0100 (CET) From: Lukas Wagner To: pve-devel@lists.proxmox.com Subject: [PATCH proxmox v2 38/63] notify: replace notification instantiation with builder pattern Date: Wed, 18 Nov 2026 10:43:22 +0100 Message-ID: <20261118094348.273646-39-l.wagner@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261118094348.273646-1-l.wagner@proxmox.com> References: <20261118094348.273646-1-l.wagner@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1794995039750 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.187 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: OAPLJT3GDPOON7SAZHDV5COZT44SMFQ7 X-Message-ID-Hash: OAPLJT3GDPOON7SAZHDV5COZT44SMFQ7 X-MailFrom: l.wagner@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: This makes constructing a notification quite a bit more ergonomic, and allows us to add new optional fields later without issues. For the template data, we now handle serialization ourselves instead of taking serde_json::Value. It would have been possible to provide the old functions alongside the new ones, but since this change is performed in the context of larger, breaking changes anyway, a clean break seemed appropriate. Signed-off-by: Lukas Wagner --- .../src/api_types/matcher/calendar.rs | 6 +- proxmox-notify/src/api_types/matcher/field.rs | 27 ++- proxmox-notify/src/api_types/matcher/mod.rs | 6 +- .../src/api_types/matcher/severity.rs | 10 +- proxmox-notify/src/endpoints/webhook.rs | 14 +- proxmox-notify/src/error.rs | 28 +++ proxmox-notify/src/notification.rs | 174 +++++++++++++----- proxmox-notify/src/send.rs | 20 +- 8 files changed, 200 insertions(+), 85 deletions(-) diff --git a/proxmox-notify/src/api_types/matcher/calendar.rs b/proxmox-notify/src/api_types/matcher/calendar.rs index 65fd9bb4b..772e9832b 100644 --- a/proxmox-notify/src/api_types/matcher/calendar.rs +++ b/proxmox-notify/src/api_types/matcher/calendar.rs @@ -149,8 +149,10 @@ mod test { #[test] fn test_calendar_matcher() { - let mut notification = - Notification::from_template(Severity::Notice, "test", Value::Null, Default::default()); + let mut notification = Notification::template_builder("test", Value::Null) + .severity(Severity::Notice) + .build() + .unwrap(); // Fr 22 Mai 2026 12:45:00 CEST notification.metadata.timestamp = 1779446700; diff --git a/proxmox-notify/src/api_types/matcher/field.rs b/proxmox-notify/src/api_types/matcher/field.rs index a00d46c3e..0bd0e5387 100644 --- a/proxmox-notify/src/api_types/matcher/field.rs +++ b/proxmox-notify/src/api_types/matcher/field.rs @@ -231,10 +231,13 @@ pub mod inline { #[test] fn test_matching() { let mut fields = HashMap::new(); - fields.insert("foo".into(), "bar".into()); + fields.insert("foo".to_string(), "bar".to_string()); - let notification = - Notification::from_template(Severity::Notice, "test", Value::Null, fields); + let notification = Notification::template_builder("test", Value::Null) + .fields(fields) + .severity(Severity::Notice) + .build() + .unwrap(); let matcher: InlineFieldMatcher = "exact:foo=bar".parse().unwrap(); assert!(matcher.matches(¬ification).unwrap()); @@ -249,17 +252,23 @@ pub mod inline { assert!(matcher.matches(¬ification).unwrap()); let mut fields = HashMap::new(); - fields.insert("foo".into(), "test".into()); + fields.insert("foo".to_string(), "test".to_string()); - let notification = - Notification::from_template(Severity::Notice, "test", Value::Null, fields); + let notification = Notification::template_builder("test", Value::Null) + .fields(fields) + .severity(Severity::Notice) + .build() + .unwrap(); assert!(matcher.matches(¬ification).unwrap()); let mut fields = HashMap::new(); - fields.insert("foo".into(), "notthere".into()); + fields.insert("foo".to_string(), "notthere".to_string()); - let notification = - Notification::from_template(Severity::Notice, "test", Value::Null, fields); + let notification = Notification::template_builder("test", Value::Null) + .fields(fields) + .severity(Severity::Notice) + .build() + .unwrap(); assert!(!matcher.matches(¬ification).unwrap()); assert!("regex:'3=b.*".parse::().is_err()); diff --git a/proxmox-notify/src/api_types/matcher/mod.rs b/proxmox-notify/src/api_types/matcher/mod.rs index e65063c5e..fe2b61a9d 100644 --- a/proxmox-notify/src/api_types/matcher/mod.rs +++ b/proxmox-notify/src/api_types/matcher/mod.rs @@ -395,8 +395,10 @@ mod tests { use crate::Severity; use serde_json::Value; - let notification = - Notification::from_template(Severity::Notice, "test", Value::Null, Default::default()); + let notification = Notification::template_builder("test", Value::Null) + .severity(Severity::Notice) + .build() + .unwrap(); for mode in [MatchModeOperator::All, MatchModeOperator::Any] { let config = MatcherConfig { diff --git a/proxmox-notify/src/api_types/matcher/severity.rs b/proxmox-notify/src/api_types/matcher/severity.rs index ed0278888..9bd3019f1 100644 --- a/proxmox-notify/src/api_types/matcher/severity.rs +++ b/proxmox-notify/src/api_types/matcher/severity.rs @@ -103,12 +103,10 @@ pub mod inline { #[test] fn test_severities() { - let notification = Notification::from_template( - Severity::Notice, - "test", - Value::Null, - Default::default(), - ); + let notification = Notification::template_builder("test", Value::Null) + .severity(Severity::Notice) + .build() + .unwrap(); let matcher: InlineSeverityMatcher = "info,notice,warning,error".parse().unwrap(); assert!(matcher.matches(¬ification).unwrap()); diff --git a/proxmox-notify/src/endpoints/webhook.rs b/proxmox-notify/src/endpoints/webhook.rs index 2eaa71633..05ae325ea 100644 --- a/proxmox-notify/src/endpoints/webhook.rs +++ b/proxmox-notify/src/endpoints/webhook.rs @@ -309,18 +309,11 @@ fn handlebars_escape( #[cfg(test)] mod tests { - use std::collections::HashMap; - use super::*; use crate::{Severity, api_types::KeyAndBase64Val, context::test}; #[test] fn test_build_request() { - let data = HashMap::from_iter([ - ("hello".into(), "hello world".into()), - ("test".into(), "escaped\nstring".into()), - ]); - let body_template = r#" {{ fields.test }} {{ escape fields.test }} @@ -365,7 +358,12 @@ hello%20world }, }; - let notification = Notification::from_template(Severity::Info, "foo", json!({}), data); + let notification = Notification::template_builder("foo", json!({})) + .severity(Severity::Info) + .field("hello", "hello world") + .field("test", "escaped\nstring") + .build() + .unwrap(); let context = test::test_context(); diff --git a/proxmox-notify/src/error.rs b/proxmox-notify/src/error.rs index 9655a02de..c8747f39f 100644 --- a/proxmox-notify/src/error.rs +++ b/proxmox-notify/src/error.rs @@ -38,6 +38,15 @@ pub enum Error { #[error("SMTP request failed: {0}")] SmtpError(#[source] BoxedError), + /// A notification passed to proxmox_notify is invalid. + #[error("notification is invalid: {err}", err = print_optional_error(.message, .source))] + InvalidNotification { + /// Description of the error. + message: String, + /// Underlying error, if any. + source: Option, + }, + /// A mail message to be forwarded could not be parsed or rebuilt. #[error("forwarded email message is invalid: {err}", err = print_optional_error(.message, .source))] InvalidForwardedMessage { @@ -127,6 +136,25 @@ impl Error { } } + /// Create an [`Error::InvalidNotification`] without an underlying error. + pub(crate) fn invalid_notification(s: impl Into) -> Self { + Self::InvalidNotification { + message: s.into(), + source: None, + } + } + + /// Create an [`Error::InvalidNotification`] with an underlying error. + pub(crate) fn invalid_notification_with_source( + s: impl Into, + source: impl Into, + ) -> Self { + Self::InvalidNotification { + message: s.into(), + source: Some(source.into()), + } + } + /// Create an [`Error::ConfigDeserialization`] from the given error. pub(crate) fn config_deserialization(err: impl Into) -> Self { Self::ConfigDeserialization(err.into()) diff --git a/proxmox-notify/src/notification.rs b/proxmox-notify/src/notification.rs index 455982c61..b1756a5d7 100644 --- a/proxmox-notify/src/notification.rs +++ b/proxmox-notify/src/notification.rs @@ -133,42 +133,41 @@ pub struct Notification { } impl Notification { - pub fn from_template>( - severity: Severity, + /// Create a builder for a notification that is rendered from a template. + pub fn template_builder, D: Serialize>( template_name: S, - template_data: Value, - fields: HashMap, - ) -> Self { - Self { - metadata: Metadata { - severity, - additional_fields: fields, - timestamp: proxmox_time::epoch_i64(), - }, - content: Content::Template { - template_name: template_name.as_ref().to_string(), - data: template_data, - }, - id: Uuid::generate(), - recipient: Recipient::Matcher, + template_data: D, + ) -> NotificationBuilder { + let template_name = template_name.into(); + + let content = serde_json::to_value(template_data) + .map_err(|err| { + Error::invalid_notification_with_source( + "could not serialize template data type", + err, + ) + }) + .map(move |value| Content::Template { + template_name, + data: value, + }); + + NotificationBuilder { + severity: None, + content, + fields: Default::default(), + recipient: Default::default(), } } - pub fn new_forwarded_mail( - severity: Severity, - raw_mail: Vec, - fields: HashMap, - ) -> Result { - Ok(Self { - content: Content::ForwardedMail { raw: raw_mail }, - metadata: Metadata { - severity, - additional_fields: fields, - timestamp: proxmox_time::epoch_i64(), - }, - id: Uuid::generate(), - recipient: Recipient::Matcher, - }) + /// Create a builder for a notification that forwards a raw mail. + pub fn forwarded_mail_builder(raw_mail: Vec) -> NotificationBuilder { + NotificationBuilder { + severity: None, + content: Ok(Content::ForwardedMail { raw: raw_mail }), + fields: Default::default(), + recipient: Default::default(), + } } /// Return the unique ID of this notification. @@ -202,6 +201,65 @@ impl Notification { } } +/// Builder for [`Notification`]. +/// +/// Created via [`Notification::template_builder`] or [`Notification::forwarded_mail_builder`]. +#[derive(Debug)] +pub struct NotificationBuilder { + severity: Option, + content: Result, + fields: HashMap, + recipient: Recipient, +} + +impl NotificationBuilder { + /// Set the severity of the notification. + /// + /// If not set, the severity will default to [`Severity::Unknown`]. + pub fn severity(mut self, severity: Severity) -> Self { + self.severity = Some(severity); + self + } + + /// Add a single metadata field, replacing any previous value for the same key. + pub fn field, V: Into>(mut self, key: K, value: V) -> Self { + self.fields.insert(key.into(), value.into()); + self + } + + /// Add multiple metadata fields, replacing any previous values for the same keys. + pub fn fields(mut self, fields: I) -> Self + where + I: IntoIterator, + K: Into, + V: Into, + { + self.fields + .extend(fields.into_iter().map(|(k, v)| (k.into(), v.into()))); + self + } + + /// Set the recipient of the notification. Defaults to [`Recipient::Matcher`]. + pub fn recipient(mut self, recipient: Recipient) -> Self { + self.recipient = recipient; + self + } + + /// Build the notification, assigning a new unique ID and the current time as timestamp. + pub fn build(self) -> Result { + Ok(Notification { + content: self.content?, + metadata: Metadata { + severity: self.severity.unwrap_or(Severity::Unknown), + timestamp: proxmox_time::epoch_i64(), + additional_fields: self.fields, + }, + id: Uuid::generate(), + recipient: self.recipient, + }) + } +} + #[cfg(test)] mod tests { use serde_json::json; @@ -249,15 +307,29 @@ mod tests { } #[test] - fn from_template() { - let fields = HashMap::from([("hostname".to_string(), "pve".to_string())]); + fn template_builder() { let data = json!({"key": "value"}); - let notification = - Notification::from_template(Severity::Warning, "test", data.clone(), fields.clone()); + let notification = Notification::template_builder("test", data.clone()) + .severity(Severity::Error) + .field("hostname", "pve") + .fields([("type", "vzdump"), ("hostname", "pbs")]) + .recipient(Recipient::Target("mail-to-root".into())) + .build() + .unwrap(); - assert_eq!(notification.severity(), Severity::Warning); - assert_eq!(notification.fields(), &fields); + assert_eq!(notification.severity(), Severity::Error); + assert_eq!( + notification.fields(), + &HashMap::from([ + ("hostname".to_string(), "pbs".to_string()), + ("type".to_string(), "vzdump".to_string()), + ]) + ); + assert_eq!( + notification.recipient, + Recipient::Target("mail-to-root".into()) + ); assert_eq!( notification.content, Content::Template { @@ -268,22 +340,24 @@ mod tests { } #[test] - fn new_forwarded_mail() { + fn forwarded_mail_builder() { let raw = TEST_MAIL.to_vec(); - let notification = - Notification::new_forwarded_mail(Severity::Unknown, raw.clone(), HashMap::new()) - .unwrap(); + let notification = Notification::forwarded_mail_builder(raw.clone()) + .build() + .unwrap(); assert_eq!(notification.severity(), Severity::Unknown); assert!(notification.fields().is_empty()); + assert_eq!(notification.recipient, Recipient::Matcher); assert_eq!(notification.content, Content::ForwardedMail { raw }); } #[test] fn fields_mut() { - let mut notification = - Notification::from_template(Severity::Info, "test", Value::Null, HashMap::new()); + let mut notification = Notification::template_builder("test", Value::Null) + .build() + .unwrap(); notification .fields_mut() @@ -331,9 +405,17 @@ mod tests { #[test] fn serde_roundtrip() { let fields = HashMap::from([("hostname".to_string(), "pve".to_string())]); + let notifications = [ - Notification::from_template(Severity::Error, "test", json!({"a": [1, 2]}), fields), - Notification::new_forwarded_mail(Severity::Info, TEST_MAIL.to_vec(), HashMap::new()) + Notification::template_builder("test", json!({"a": [1, 2]})) + .severity(Severity::Info) + .fields(fields.clone()) + .build() + .unwrap(), + Notification::forwarded_mail_builder(TEST_MAIL.to_vec()) + .severity(Severity::Unknown) + .fields(fields) + .build() .unwrap(), ]; diff --git a/proxmox-notify/src/send.rs b/proxmox-notify/src/send.rs index 42cd0bb1a..d08d5af30 100644 --- a/proxmox-notify/src/send.rs +++ b/proxmox-notify/src/send.rs @@ -308,12 +308,10 @@ mod tests { // Send directly to endpoint bus.send( &context, - &Notification::from_template( - Severity::Info, - "test", - Default::default(), - Default::default(), - ), + &Notification::template_builder("test", None::<()>) + .severity(Severity::Info) + .build() + .unwrap(), ); let messages = mock.messages(); assert_eq!(messages.len(), 1); @@ -358,12 +356,10 @@ mod tests { }); let send_with_severity = |severity| { - let notification = Notification::from_template( - severity, - "test", - Default::default(), - Default::default(), - ); + let notification = Notification::template_builder("test", None::<()>) + .severity(severity) + .build() + .unwrap(); bus.send(&context, ¬ification); }; -- 2.47.3