From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id D7D021FF0C0 for ; Wed, 18 Nov 2026 10:51:46 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 4200721DE5; Wed, 18 Nov 2026 10:45:12 +0100 (CET) From: Lukas Wagner To: pve-devel@lists.proxmox.com Subject: [PATCH proxmox v2 02/63] notify: refactor error type Date: Wed, 18 Nov 2026 10:42:46 +0100 Message-ID: <20261118094348.273646-3-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: 1794995035007 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.136 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) PROLO_LEO1 0.1 Meta Catches all Leo drug variations so far 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: 6OQFOLQ5LN66DHUTILMUIK3Y4OZGBAXI X-Message-ID-Hash: 6OQFOLQ5LN66DHUTILMUIK3Y4OZGBAXI 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: The old Error type was quite annoying to use which is why it was replaced by a new one. Instead of manually implementing the expected interfaces, this time we use the `thiserror` crate to derive the appropriate implementations. While this is technically a breaking change, none of the existing users of proxmox-notify match on any concrete error variants, so this change does not require any modifications in application code. Some error messages change slightly due to the restructuring of error variants. One noteworthy change is that the implementations of the Context trait do not return `Error` anymore, instead, they return a Box, which is then wrapped into an appropriate variant of the crate-owned Error type wherever a context method is called. This is a deliberate design decision. Eventually, the implementations of Context should live in the application code, and I want to refrain from instantiating proxmox_notify::Error in application code. Signed-off-by: Lukas Wagner --- proxmox-notify/Cargo.toml | 1 + proxmox-notify/src/api/common.rs | 4 +- proxmox-notify/src/config.rs | 9 +- proxmox-notify/src/context/mod.rs | 9 +- proxmox-notify/src/context/pbs.rs | 8 +- proxmox-notify/src/context/pve.rs | 13 +- proxmox-notify/src/context/test.rs | 4 +- proxmox-notify/src/endpoints/gotify.rs | 7 +- proxmox-notify/src/endpoints/sendmail.rs | 10 +- proxmox-notify/src/endpoints/smtp.rs | 42 +++--- proxmox-notify/src/endpoints/webhook.rs | 44 +++--- proxmox-notify/src/error.rs | 165 +++++++++++++++++++++++ proxmox-notify/src/lib.rs | 75 +---------- proxmox-notify/src/matcher/calendar.rs | 4 +- proxmox-notify/src/matcher/field.rs | 29 ++-- proxmox-notify/src/matcher/mod.rs | 22 +-- proxmox-notify/src/matcher/severity.rs | 8 +- proxmox-notify/src/renderer/mod.rs | 11 +- 18 files changed, 294 insertions(+), 171 deletions(-) create mode 100644 proxmox-notify/src/error.rs diff --git a/proxmox-notify/Cargo.toml b/proxmox-notify/Cargo.toml index 326f5f9e5..6796c2915 100644 --- a/proxmox-notify/Cargo.toml +++ b/proxmox-notify/Cargo.toml @@ -25,6 +25,7 @@ regex.workspace = true serde = { workspace = true, features = ["derive"] } serde_json.workspace = true serde_regex.workspace = true +thiserror.workspace = true proxmox-api-macro.workspace = true proxmox-base64 = { workspace = true, optional = true } diff --git a/proxmox-notify/src/api/common.rs b/proxmox-notify/src/api/common.rs index fa2356e2a..bc89695f8 100644 --- a/proxmox-notify/src/api/common.rs +++ b/proxmox-notify/src/api/common.rs @@ -1,7 +1,7 @@ use proxmox_http_error::HttpError; use super::http_err; -use crate::{Bus, Config, Notification}; +use crate::{Bus, Config, Error, Notification}; /// Send a notification to a given target. /// @@ -33,7 +33,7 @@ pub fn test_target(config: &Config, endpoint: &str) -> Result<(), HttpError> { })?; bus.test_target(endpoint).map_err(|err| match err { - crate::Error::TargetDoesNotExist(endpoint) => { + Error::TargetDoesNotExist(endpoint) => { http_err!(NOT_FOUND, "endpoint '{endpoint}' does not exist") } _ => http_err!(INTERNAL_SERVER_ERROR, "Could not test target: {err}"), diff --git a/proxmox-notify/src/config.rs b/proxmox-notify/src/config.rs index 952e77262..c280e8285 100644 --- a/proxmox-notify/src/config.rs +++ b/proxmox-notify/src/config.rs @@ -124,7 +124,7 @@ pub fn config(raw_config: &str) -> Result<(SectionConfigData, [u8; 32]), Error> let digest = openssl::sha::sha256(raw_config.as_bytes()); let data = config_parser() .parse("notifications.cfg", raw_config) - .map_err(|err| Error::ConfigDeserialization(err.into()))?; + .map_err(Error::config_deserialization)?; Ok((data, digest)) } @@ -133,18 +133,19 @@ pub fn private_config(raw_config: &str) -> Result<(SectionConfigData, [u8; 32]), let digest = openssl::sha::sha256(raw_config.as_bytes()); let data = private_config_parser() .parse("priv/notifications.cfg", raw_config) - .map_err(|err| Error::ConfigDeserialization(err.into()))?; + .map_err(Error::config_deserialization)?; + Ok((data, digest)) } pub fn write(config: &SectionConfigData) -> Result { config_parser() .write("notifications.cfg", config) - .map_err(|err| Error::ConfigSerialization(err.into())) + .map_err(Error::config_serialization) } pub fn write_private(config: &SectionConfigData) -> Result { private_config_parser() .write("priv/notifications.cfg", config) - .map_err(|err| Error::ConfigSerialization(err.into())) + .map_err(Error::config_serialization) } diff --git a/proxmox-notify/src/context/mod.rs b/proxmox-notify/src/context/mod.rs index 87a2a7165..a81a35caa 100644 --- a/proxmox-notify/src/context/mod.rs +++ b/proxmox-notify/src/context/mod.rs @@ -1,7 +1,7 @@ use std::fmt::Debug; use std::sync::Mutex; -use crate::Error; +use crate::error::BoxedError; use crate::renderer::TemplateSource; #[cfg(any(feature = "pve-context", feature = "pbs-context"))] @@ -13,6 +13,11 @@ pub mod pve; #[cfg(test)] mod test; +// NOTE: Don't use proxmox_notify::Error in this trait, rather return a [`BoxedError`]. You +// may wrap the boxed error into an appropriate variant of proxmox_notify::Error at +// the callsite, but product-code (which includes the trait implementations of Context) should +// not have to instantiate proxmox_notify::Error themselves. + /// Product-specific context pub trait Context: Send + Sync + Debug { /// Look up a user's email address from users.cfg @@ -31,7 +36,7 @@ pub trait Context: Send + Sync + Debug { filename: &str, namespace: Option<&str>, source: TemplateSource, - ) -> Result, Error>; + ) -> Result, BoxedError>; } #[cfg(not(test))] diff --git a/proxmox-notify/src/context/pbs.rs b/proxmox-notify/src/context/pbs.rs index a91215488..f484f90c8 100644 --- a/proxmox-notify/src/context/pbs.rs +++ b/proxmox-notify/src/context/pbs.rs @@ -6,8 +6,8 @@ use tracing::error; use proxmox_schema::{ObjectSchema, Schema, StringSchema}; use proxmox_section_config::{SectionConfig, SectionConfigPlugin}; -use crate::Error; use crate::context::{Context, common}; +use crate::error::BoxedError; use crate::renderer::TemplateSource; const PBS_USER_CFG_FILENAME: &str = "/etc/proxmox-backup/user.cfg"; @@ -111,7 +111,7 @@ impl Context for PBSContext { filename: &str, namespace: Option<&str>, source: TemplateSource, - ) -> Result, Error> { + ) -> Result, BoxedError> { let path = match source { TemplateSource::Vendor => "/usr/share/proxmox-backup/templates", TemplateSource::Override => "/etc/proxmox-backup/notification-templates", @@ -121,8 +121,8 @@ impl Context for PBSContext { .join(namespace.unwrap_or("default")) .join(filename); - let template_string = proxmox_sys::fs::file_read_optional_string(path) - .map_err(|err| Error::Generic(format!("could not load template: {err}")))?; + let template_string = proxmox_sys::fs::file_read_optional_string(path)?; + Ok(template_string) } } diff --git a/proxmox-notify/src/context/pve.rs b/proxmox-notify/src/context/pve.rs index 3d9ff92e9..ba84da920 100644 --- a/proxmox-notify/src/context/pve.rs +++ b/proxmox-notify/src/context/pve.rs @@ -1,8 +1,9 @@ -use crate::Error; -use crate::context::{Context, common}; -use crate::renderer::TemplateSource; use std::path::Path; +use crate::context::{Context, common}; +use crate::error::BoxedError; +use crate::renderer::TemplateSource; + fn lookup_mail_address(content: &str, user: &str) -> Option { common::normalize_for_return(content.lines().find_map(|line| { let fields: Vec<&str> = line.split(':').collect(); @@ -60,7 +61,7 @@ impl Context for PVEContext { filename: &str, namespace: Option<&str>, source: TemplateSource, - ) -> Result, Error> { + ) -> Result, BoxedError> { let path = match source { TemplateSource::Vendor => "/usr/share/pve-manager/templates", TemplateSource::Override => "/etc/pve/notification-templates", @@ -70,8 +71,8 @@ impl Context for PVEContext { .join(namespace.unwrap_or("default")) .join(filename); - let template_string = proxmox_sys::fs::file_read_optional_string(path) - .map_err(|err| Error::Generic(format!("could not load template: {err}")))?; + let template_string = proxmox_sys::fs::file_read_optional_string(path)?; + Ok(template_string) } } diff --git a/proxmox-notify/src/context/test.rs b/proxmox-notify/src/context/test.rs index 22da38d3e..7380a0545 100644 --- a/proxmox-notify/src/context/test.rs +++ b/proxmox-notify/src/context/test.rs @@ -1,5 +1,5 @@ -use crate::Error; use crate::context::Context; +use crate::error::BoxedError; use crate::renderer::TemplateSource; #[derive(Debug)] @@ -37,7 +37,7 @@ impl Context for TestContext { _filename: &str, _namespace: Option<&str>, _source: TemplateSource, - ) -> Result, Error> { + ) -> Result, BoxedError> { Ok(Some(String::new())) } } diff --git a/proxmox-notify/src/endpoints/gotify.rs b/proxmox-notify/src/endpoints/gotify.rs index 7d0f5cdc6..5ef82fd01 100644 --- a/proxmox-notify/src/endpoints/gotify.rs +++ b/proxmox-notify/src/endpoints/gotify.rs @@ -129,7 +129,8 @@ impl Endpoint for GotifyEndpoint { }); let body = serde_json::to_vec(&body) - .map_err(|err| Error::NotifyFailed(self.name().to_string(), err.into()))?; + .map_err(|err| Error::other_with_source("could not serialize JSON body", err))?; + let extra_headers = HashMap::from([ ( http::header::AUTHORIZATION.to_string(), @@ -146,7 +147,7 @@ impl Endpoint for GotifyEndpoint { .http_proxy_config() .map(|url| ProxyConfig::parse_proxy_url(&url)) .transpose() - .map_err(|err| Error::NotifyFailed(self.name().to_string(), err.into()))?; + .map_err(|err| Error::invalid_config_with_source("invalid proxy configuration", err))?; let options = HttpOptions { proxy_config, @@ -163,7 +164,7 @@ impl Endpoint for GotifyEndpoint { Some("application/json"), Some(&extra_headers), ) - .map_err(|err| Error::NotifyFailed(self.name().to_string(), err.into()))?; + .map_err(Error::http_request_failed)?; Ok(()) } diff --git a/proxmox-notify/src/endpoints/sendmail.rs b/proxmox-notify/src/endpoints/sendmail.rs index 4f26a1214..70f37eced 100644 --- a/proxmox-notify/src/endpoints/sendmail.rs +++ b/proxmox-notify/src/endpoints/sendmail.rs @@ -141,13 +141,15 @@ impl Endpoint for SendmailEndpoint { recipients_str.iter().for_each(|r| mail.add_recipient(r)); - mail.send() - .map_err(|err| Error::NotifyFailed(self.config.name.clone(), err.into())) + mail.send().map_err(|err| { + Error::other_with_source("could not send mail via sendmail", err) + }) } #[cfg(feature = "mail-forwarder")] Content::ForwardedMail { raw, uid, .. } => { - Mail::forward(&recipients_str, &mailfrom, raw, *uid) - .map_err(|err| Error::NotifyFailed(self.config.name.clone(), err.into())) + Mail::forward(&recipients_str, &mailfrom, raw, *uid).map_err(|err| { + Error::other_with_source("could not forward mail via sendmail", err) + }) } } } diff --git a/proxmox-notify/src/endpoints/smtp.rs b/proxmox-notify/src/endpoints/smtp.rs index b3d6e103c..49617e70c 100644 --- a/proxmox-notify/src/endpoints/smtp.rs +++ b/proxmox-notify/src/endpoints/smtp.rs @@ -160,7 +160,7 @@ pub struct SmtpEndpoint { impl Endpoint for SmtpEndpoint { fn send(&self, notification: &Notification) -> Result<(), Error> { let tls_parameters = TlsParameters::new(self.config.server.clone()) - .map_err(|err| Error::NotifyFailed(self.name().into(), Box::new(err)))?; + .map_err(|err| Error::invalid_config_with_source("invalid smtp server URL", err))?; let (port, tls) = match self.config.mode.unwrap_or_default() { SmtpMode::Insecure => { @@ -186,11 +186,8 @@ impl Endpoint for SmtpEndpoint { if let Some(password) = self.private_config.password.as_deref() { transport_builder = transport_builder.credentials((username, password).into()); } else { - return Err(Error::NotifyFailed( - self.name().into(), - Box::new(Error::Generic( - "username is set but no password was provided".to_owned(), - )), + return Err(Error::invalid_config( + "username is set but no password was provided", )); } } @@ -204,8 +201,12 @@ impl Endpoint for SmtpEndpoint { let mail_from = self.config.from_address.clone(); let parse_address = |addr: &str| -> Result { - addr.parse() - .map_err(|err| Error::NotifyFailed(self.name().into(), Box::new(err))) + addr.parse().map_err(|err| { + Error::invalid_config_with_source( + format!("could not parse email address '{addr}'"), + err, + ) + }) }; let author = self @@ -251,12 +252,12 @@ impl Endpoint for SmtpEndpoint { .body(html_part), ), ) - .map_err(|err| Error::NotifyFailed(self.name().into(), Box::new(err)))? + .map_err(|err| { + Error::invalid_config_with_source("could not build email message", err) + })? } #[cfg(feature = "mail-forwarder")] - Content::ForwardedMail { raw, .. } => { - build_forwarded_message(email_builder, self.name(), raw)? - } + Content::ForwardedMail { raw, .. } => build_forwarded_message(email_builder, raw)?, }; // `Auto-Submitted` is defined in RFC 5436 and describes how @@ -268,9 +269,7 @@ impl Endpoint for SmtpEndpoint { "auto-generated;".into(), )); - transport - .send(&email) - .map_err(|err| Error::NotifyFailed(self.name().into(), err.into()))?; + transport.send(&email).map_err(Error::smtp_error)?; Ok(()) } @@ -289,7 +288,6 @@ impl Endpoint for SmtpEndpoint { #[cfg(feature = "mail-forwarder")] fn build_forwarded_message( email_builder: lettre::message::MessageBuilder, - endpoint_name: &str, raw: &[u8], ) -> Result { use lettre::message::Body; @@ -298,11 +296,11 @@ fn build_forwarded_message( let parsed_message = mail_parser::MessageParser::default() .parse(raw) - .ok_or_else(|| Error::Generic("could not parse forwarded email".to_string()))?; + .ok_or_else(|| Error::invalid_forwarded_message("could not parse forwarded email"))?; let root_part = parsed_message .part(0) - .ok_or_else(|| Error::Generic("root message part not present".to_string()))?; + .ok_or_else(|| Error::invalid_forwarded_message("root message part not present"))?; let raw_body = &parsed_message.raw_message() [root_part.offset_body as usize..root_part.offset_end as usize]; @@ -320,11 +318,13 @@ fn build_forwarded_message( proxmox_sendmail::normalize_line_endings(raw_body), ContentTransferEncoding::Binary, ) - .map_err(|_| Error::Generic("could not create body".into()))?; + .map_err(|_| Error::invalid_forwarded_message("could not create body from raw bytes"))?; let mut message = email_builder .subject(parsed_message.subject().unwrap_or_default()) .body(body) - .map_err(|err| Error::NotifyFailed(endpoint_name.into(), Box::new(err)))?; + .map_err(|err| { + Error::invalid_forwarded_message_with_source("could not build email message", err) + })?; message .headers_mut() .remove_raw("Content-Transfer-Encoding"); @@ -450,7 +450,7 @@ mod tests { email_builder = email_builder.to("Recipient ".parse().unwrap()); let raw_mail = std::fs::read(input).unwrap(); - let mut message = build_forwarded_message(email_builder, "test", &raw_mail).unwrap(); + let mut message = build_forwarded_message(email_builder, &raw_mail).unwrap(); // The Date header contains the current time, let's just remove it // for this test. diff --git a/proxmox-notify/src/endpoints/webhook.rs b/proxmox-notify/src/endpoints/webhook.rs index f0fd5b6ab..cbb3b1299 100644 --- a/proxmox-notify/src/endpoints/webhook.rs +++ b/proxmox-notify/src/endpoints/webhook.rs @@ -215,13 +215,13 @@ impl KeyAndBase64Val { pub fn decode_value(&self) -> Result { let value = self.value.as_deref().unwrap_or_default(); let bytes = proxmox_base64::decode(value).map_err(|_| { - Error::Generic(format!( + Error::invalid_config(format!( "could not decode base64 value with key '{}'", self.name )) })?; let value = String::from_utf8(bytes).map_err(|_| { - Error::Generic(format!( + Error::invalid_config(format!( "could not decode UTF8 string from base64, key '{}'", self.name )) @@ -245,7 +245,8 @@ impl Endpoint for WebhookEndpoint { self.create_client()? .request(request) - .map_err(|err| self.mask_secret_in_error(err))?; + .map_err(|err| self.mask_secret_in_error(err)) + .map_err(Error::http_request_failed)?; Ok(()) } @@ -267,7 +268,7 @@ impl WebhookEndpoint { .http_proxy_config() .map(|url| ProxyConfig::parse_proxy_url(&url)) .transpose() - .map_err(|err| Error::NotifyFailed(self.name().to_string(), err.into()))?; + .map_err(|err| Error::invalid_config_with_source("invalid proxy configuration", err))?; let options = HttpOptions { proxy_config, @@ -322,12 +323,14 @@ impl WebhookEndpoint { let body = handlebars .render_template(&body_template, &data) .map_err(|err| self.mask_secret_in_error(err)) - .map_err(|err| Error::Generic(format!("failed to render webhook body: {err}")))?; + .map_err(|err| { + Error::invalid_config(format!("failed to render webhook body: {err}")) + })?; let url = handlebars .render_template(&self.config.url, &data) .map_err(|err| self.mask_secret_in_error(err)) - .map_err(|err| Error::Generic(format!("failed to render webhook url: {err}")))?; + .map_err(|err| Error::invalid_config(format!("failed to render webhook url: {err}")))?; let method: &str = self.config.method.into(); let mut builder = http::Request::builder().uri(url).method(method); @@ -339,7 +342,7 @@ impl WebhookEndpoint { .render_template(&value, &data) .map_err(|err| self.mask_secret_in_error(err)) .map_err(|err| { - Error::Generic(format!( + Error::invalid_config(format!( "failed to render header value template: {value}: {err}" )) })?; @@ -367,20 +370,21 @@ impl WebhookEndpoint { let request = builder .body(body) .map_err(|err| self.mask_secret_in_error(err)) - .map_err(|err| Error::Generic(format!("failed to build http request: {err}")))?; + .map_err(|err| Error::invalid_config(format!("failed to build http request: {err}")))?; Ok(request) } fn base64_decode(&self, s: &str) -> Result { - // Also here, TODO: revisit Error variants for the *whole* crate. - let s = proxmox_base64::decode(s) - .map_err(|err| Error::Generic(format!("could not decode base64 value: {err}")))?; + let s = proxmox_base64::decode(s).map_err(|err| { + Error::invalid_config_with_source("could not decode base64 value", err) + })?; String::from_utf8(s).map_err(|err| { - Error::Generic(format!( - "base64 encoded value did not contain valid utf8: {err}" - )) + Error::invalid_config_with_source( + "base64 encoded value did not contain valid utf8", + err, + ) }) } @@ -393,17 +397,17 @@ impl WebhookEndpoint { /// /// This function will only mask exact matches, but this should suffice /// for the majority of cases. - fn mask_secret_in_error(&self, error: impl std::fmt::Display) -> Error { + fn mask_secret_in_error(&self, error: impl std::fmt::Display) -> String { let mut s = error.to_string(); for secret_value in &self.private_config.secret { match secret_value.decode_value() { Ok(value) => s = s.replace(&value, ""), - Err(e) => return e, + Err(e) => return format!("could not decode secret while masking error: {e}"), } } - Error::Generic(s) + s } } @@ -508,7 +512,7 @@ mod tests { use crate::Severity; #[test] - fn test_build_request() -> Result<(), Error> { + fn test_build_request() { let data = HashMap::from_iter([ ("hello".into(), "hello world".into()), ("test".into(), "escaped\nstring".into()), @@ -560,14 +564,12 @@ hello%20world let notification = Notification::from_template(Severity::Info, "foo", json!({}), data); - let request = endpoint.build_request(¬ification)?; + let request = endpoint.build_request(¬ification).unwrap(); assert_eq!(request.uri(), "http://localhost/hello%20world"); assert_eq!(request.body(), expected_body); assert_eq!(request.method(), "POST"); assert_eq!(request.headers().get("X-Severity").unwrap(), "info"); - - Ok(()) } } diff --git a/proxmox-notify/src/error.rs b/proxmox-notify/src/error.rs new file mode 100644 index 000000000..9655a02de --- /dev/null +++ b/proxmox-notify/src/error.rs @@ -0,0 +1,165 @@ +#![allow(dead_code)] + +use std::borrow::Cow; + +/// Boxed, type-erased error that can be sent and shared across threads. +pub type BoxedError = Box; + +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +/// Error type for `proxmox_notify`. +pub enum Error { + /// The notification target with the given name does not exist. + #[error("target '{0}' does not exist")] + TargetDoesNotExist(String), + + /// A notification template could not be rendered. + #[error("could not render notification template: {0}")] + TemplateRendering(String), + + /// A notification template could not be loaded. + #[error("could not load notification template: {0}")] + TemplateCouldNotBeRead(#[source] BoxedError), + + /// The notification configuration is invalid. + #[error("invalid configuration: {err}", err = print_optional_error(.message, .source))] + InvalidConfig { + /// Description of the error. + message: String, + /// Underlying error, if any. + source: Option, + }, + + /// An HTTP request to a notification endpoint failed. + #[error("HTTP request failed: {0}")] + HttpRequestFailed(#[source] BoxedError), + + /// Sending a mail via SMTP failed. + #[error("SMTP request failed: {0}")] + SmtpError(#[source] BoxedError), + + /// 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 { + /// Description of the error. + message: String, + /// Underlying error, if any. + source: Option, + }, + + /// The notification configuration could not be serialized. + #[error("could not serialize config: {0}")] + ConfigSerialization(#[source] BoxedError), + + /// The notification configuration could not be deserialized. + #[error("could not deserialize config: {0}")] + ConfigDeserialization(#[source] BoxedError), + + /// Any other error. + #[error("{err}", err = print_optional_error(.message, .source))] + Other { + /// Description of the error. + message: String, + /// Underlying error, if any. + source: Option, + }, +} + +fn print_optional_error<'a>(message: &'a str, err: &Option) -> Cow<'a, str> { + if let Some(err) = err { + Cow::Owned(format!("{message}: {err}")) + } else { + Cow::Borrowed(message) + } +} + +impl Error { + /// Create an [`Error::InvalidForwardedMessage`] without an underlying error. + pub(crate) fn invalid_forwarded_message(s: impl Into) -> Self { + Self::InvalidForwardedMessage { + message: s.into(), + source: None, + } + } + + /// Create an [`Error::HttpRequestFailed`] from the given error. + pub(crate) fn http_request_failed(err: impl Into) -> Self { + Self::HttpRequestFailed(err.into()) + } + + /// Create an [`Error::SmtpError`] from the given error. + pub(crate) fn smtp_error(err: impl Into) -> Self { + Self::SmtpError(err.into()) + } + + /// Create an [`Error::InvalidForwardedMessage`] with an underlying error. + pub(crate) fn invalid_forwarded_message_with_source( + s: impl Into, + source: impl Into, + ) -> Self { + Self::InvalidForwardedMessage { + message: s.into(), + source: Some(source.into()), + } + } + + /// Create an [`Error::TemplateCouldNotBeRead`] from the given error. + pub(crate) fn template_could_not_be_read(err: impl Into) -> Self { + Self::TemplateCouldNotBeRead(err.into()) + } + + /// Create an [`Error::InvalidConfig`] without an underlying error. + pub(crate) fn invalid_config(s: impl Into) -> Self { + Self::InvalidConfig { + message: s.into(), + source: None, + } + } + + /// Create an [`Error::InvalidConfig`] with an underlying error. + pub(crate) fn invalid_config_with_source( + s: impl Into, + source: impl Into, + ) -> Self { + Self::InvalidConfig { + 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()) + } + + /// Create an [`Error::ConfigSerialization`] from the given error. + pub(crate) fn config_serialization(err: impl Into) -> Self { + Self::ConfigSerialization(err.into()) + } + + /// Create an [`Error::TargetDoesNotExist`] for the given target name. + pub(crate) fn target_does_not_exist(target: impl Into) -> Self { + Self::TargetDoesNotExist(target.into()) + } + + /// Create an [`Error::TemplateRendering`] with the given message. + pub(crate) fn template_rendering(message: impl Into) -> Self { + Self::TemplateRendering(message.into()) + } + + /// Create an [`Error::Other`]. + pub(crate) fn other(s: impl Into) -> Self { + Self::Other { + message: s.into(), + source: None, + } + } + + /// Create an [`Error::Other`] with an underlying error. + pub(crate) fn other_with_source(s: impl Into, source: impl Into) -> Self { + Self::Other { + message: s.into(), + source: Some(source.into()), + } + } +} diff --git a/proxmox-notify/src/lib.rs b/proxmox-notify/src/lib.rs index 1ce6f89e6..270087ffc 100644 --- a/proxmox-notify/src/lib.rs +++ b/proxmox-notify/src/lib.rs @@ -2,7 +2,6 @@ #![deny(unsafe_code)] use std::collections::HashMap; -use std::error::Error as StdError; use std::fmt::Display; use std::str::FromStr; @@ -26,71 +25,9 @@ pub mod endpoints; pub mod renderer; pub mod schema; -#[derive(Debug)] -pub enum Error { - /// There was an error serializing the config - ConfigSerialization(Box), - /// There was an error deserializing the config - ConfigDeserialization(Box), - /// An endpoint failed to send a notification - NotifyFailed(String, Box), - /// A target does not exist - TargetDoesNotExist(String), - /// Testing one or more notification targets failed - TargetTestFailed(Vec>), - /// A filter could not be applied - FilterFailed(String), - /// The notification's template string could not be rendered - RenderError(Box), - /// Generic error for anything else - Generic(String), -} +mod error; +pub use error::Error; -impl Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Error::ConfigSerialization(err) => { - write!(f, "could not serialize configuration: {err}") - } - Error::ConfigDeserialization(err) => { - write!(f, "could not deserialize configuration: {err}") - } - Error::NotifyFailed(endpoint, err) => { - write!(f, "could not notify via endpoint(s): {endpoint}: {err}") - } - Error::TargetDoesNotExist(target) => { - write!(f, "notification target '{target}' does not exist") - } - Error::TargetTestFailed(errs) => { - for err in errs { - writeln!(f, "{err}")?; - } - - Ok(()) - } - Error::FilterFailed(message) => { - write!(f, "could not apply filter: {message}") - } - Error::RenderError(err) => write!(f, "could not render notification template: {err}"), - Error::Generic(message) => f.write_str(message), - } - } -} - -impl StdError for Error { - fn source(&self) -> Option<&(dyn StdError + 'static)> { - match self { - Error::ConfigSerialization(err) => Some(&**err), - Error::ConfigDeserialization(err) => Some(&**err), - Error::NotifyFailed(_, err) => Some(&**err), - Error::TargetDoesNotExist(_) => None, - Error::TargetTestFailed(errs) => Some(&*errs[0]), - Error::FilterFailed(_) => None, - Error::RenderError(err) => Some(&**err), - Error::Generic(_) => None, - } - } -} #[api()] #[derive(Clone, Debug, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd)] @@ -123,14 +60,14 @@ impl Display for Severity { impl FromStr for Severity { type Err = Error; - fn from_str(s: &str) -> Result { + fn from_str(s: &str) -> Result { match s { "info" => Ok(Self::Info), "notice" => Ok(Self::Notice), "warning" => Ok(Self::Warning), "error" => Ok(Self::Error), "unknown" => Ok(Self::Unknown), - _ => Err(Error::Generic(format!("invalid severity {s}"))), + _ => Err(Error::invalid_config(format!("invalid severity {s}"))), } } } @@ -233,7 +170,7 @@ impl Notification { pub fn new_forwarded_mail(raw_mail: &[u8], uid: Option) -> Result { let message = mail_parser::MessageParser::default() .parse(raw_mail) - .ok_or_else(|| Error::Generic("could not parse forwarded email".to_string()))?; + .ok_or_else(|| Error::invalid_forwarded_message("could not parse forwarded email"))?; let title = message.subject().unwrap_or_default().into(); let body = message.body_text(0).unwrap_or_default().into(); @@ -589,7 +526,7 @@ impl Bus { if let Some(endpoint) = self.endpoints.get(target) { endpoint.send(¬ification)?; } else { - return Err(Error::TargetDoesNotExist(target.to_string())); + return Err(Error::target_does_not_exist(target)); } Ok(()) diff --git a/proxmox-notify/src/matcher/calendar.rs b/proxmox-notify/src/matcher/calendar.rs index a0377259a..72af94102 100644 --- a/proxmox-notify/src/matcher/calendar.rs +++ b/proxmox-notify/src/matcher/calendar.rs @@ -29,7 +29,7 @@ impl FromStr for DailyDurationWrapper { fn from_str(s: &str) -> Result { let daily_duration = proxmox_time::parse_daily_duration(s) - .map_err(|e| Error::Generic(format!("could not parse schedule: {e}")))?; + .map_err(|err| Error::invalid_config_with_source("could not parse schedule", err))?; Ok(Self { daily_duration, @@ -65,7 +65,7 @@ impl MatchDirective for CalendarMatcher { self.schedule .daily_duration .time_match(notification.metadata.timestamp, false) - .map_err(|err| Error::Generic(format!("could not match timestamp: {err}"))) + .map_err(|err| Error::invalid_config_with_source("could not match timestamp", err)) } fn validate(&self) -> Result<(), Error> { diff --git a/proxmox-notify/src/matcher/field.rs b/proxmox-notify/src/matcher/field.rs index e0d362383..0e145f81b 100644 --- a/proxmox-notify/src/matcher/field.rs +++ b/proxmox-notify/src/matcher/field.rs @@ -59,21 +59,21 @@ impl MatchDirective for FieldMatcher { match self { FieldMatcher::Exact { field, values } => { if values.is_empty() { - return Err(Error::Generic( - "field matcher must contain values to match".to_string(), + return Err(Error::invalid_config( + "field matcher must contain values to match", )); } if !SAFE_ID_REGEX.is_match(field) { - return Err(Error::Generic( - "field name does not match regex pattern".to_string(), - )); + return Err(Error::invalid_config(format!( + "field name '{field}' does not match regex pattern", + ))); } } FieldMatcher::Regex { field, .. } => { if !SAFE_ID_REGEX.is_match(field) { - return Err(Error::Generic( - "field name does not match regex pattern".to_string(), - )); + return Err(Error::invalid_config(format!( + "field name '{field}' does not match regex pattern", + ))); } } } @@ -156,19 +156,20 @@ pub mod inline { type Err = Error; fn from_str(s: &str) -> Result { if !MATCH_FIELD_ENTRY_REGEX.is_match(s) { - return Err(Error::FilterFailed(format!( + return Err(Error::invalid_config(format!( "invalid match-field statement: {s}" ))); } if let Some(remaining) = s.strip_prefix("regex:") { match remaining.split_once('=') { - None => Err(Error::FilterFailed(format!( + None => Err(Error::invalid_config(format!( "invalid match-field statement: {s}" ))), Some((field, expected_value_regex)) => { - let regex = Regex::new(expected_value_regex) - .map_err(|err| Error::FilterFailed(format!("invalid regex: {err}")))?; + let regex = Regex::new(expected_value_regex).map_err(|err| { + Error::invalid_config_with_source("invalid regex", err) + })?; Ok(Self(FieldMatcher::Regex { field: field.into(), @@ -178,7 +179,7 @@ pub mod inline { } } else if let Some(remaining) = s.strip_prefix("exact:") { match remaining.split_once('=') { - None => Err(Error::FilterFailed(format!( + None => Err(Error::invalid_config(format!( "invalid match-field statement: {s}" ))), Some((field, expected_values)) => { @@ -194,7 +195,7 @@ pub mod inline { } } } else { - Err(Error::FilterFailed(format!( + Err(Error::invalid_config(format!( "invalid match-field statement: {s}" ))) } diff --git a/proxmox-notify/src/matcher/mod.rs b/proxmox-notify/src/matcher/mod.rs index af87a4ef3..59baeae4e 100644 --- a/proxmox-notify/src/matcher/mod.rs +++ b/proxmox-notify/src/matcher/mod.rs @@ -155,7 +155,10 @@ impl MatcherConfig { let expression: Expression = { if let Some(expression_str) = &self.expression { serde_json::from_str(expression_str).map_err(|err| { - Error::FilterFailed(format!("could not deserialize filter expression: {err:#}")) + Error::invalid_config_with_source( + "could not deserialize matcher expression", + err, + ) })? } else { #[cfg(feature = "legacy-matchers")] @@ -234,7 +237,7 @@ impl MatcherConfig { if !conflicting_properties.is_empty() { let joined = conflicting_properties.join(", "); - return Err(Error::Generic(format!( + return Err(Error::invalid_config(format!( "'expression' property is mutually exclusive with: {joined}" ))); } @@ -252,13 +255,14 @@ impl MatcherConfig { // Storing the *serialized* expression makes sure that // we have a minified, single-line JSON string self.expression = Some(serde_json::to_string(&expr).map_err(|err| { - Error::Generic(format!("could not serialize expression: {err:#}")) + Error::other_with_source("could not serialize expression", err) })?); } Err(err) => { - return Err(Error::Generic(format!( - "'expression' is not valid: {err:#}" - ))); + return Err(Error::invalid_config_with_source( + "'expression' is not valid", + err, + )); } } } @@ -277,21 +281,21 @@ impl MatcherConfig { match expr { Expression::AllOf(expressions) => { if expressions.is_empty() { - return Err(Error::Generic( + return Err(Error::invalid_config( "'expression' may not contain an empty 'all-of' rule".to_string(), )); } } Expression::AnyOf(expressions) => { if expressions.is_empty() { - return Err(Error::Generic( + return Err(Error::invalid_config( "'expression' may not contain an empty 'any-of' rule".to_string(), )); } } Expression::OneOf(expressions) => { if expressions.is_empty() { - return Err(Error::Generic( + return Err(Error::invalid_config( "'expression' may not contain an empty 'one-of' rule".to_string(), )); } diff --git a/proxmox-notify/src/matcher/severity.rs b/proxmox-notify/src/matcher/severity.rs index b867d8b74..6818e5c22 100644 --- a/proxmox-notify/src/matcher/severity.rs +++ b/proxmox-notify/src/matcher/severity.rs @@ -25,8 +25,8 @@ impl MatchDirective for SeverityMatcher { fn validate(&self) -> Result<(), Error> { if self.severities.is_empty() { - return Err(Error::Generic( - "severity matcher must contain severities to match".to_string(), + return Err(Error::invalid_config( + "severity matcher must contain severities to match", )); } @@ -75,7 +75,9 @@ pub mod inline { for element in s.split(',') { let element = element.trim(); - let severity: Severity = element.parse()?; + let severity: Severity = element + .parse() + .map_err(|err| Error::invalid_config_with_source("invalid severity", err))?; severities.push(severity) } diff --git a/proxmox-notify/src/renderer/mod.rs b/proxmox-notify/src/renderer/mod.rs index a0b7df7bc..1bccf75bf 100644 --- a/proxmox-notify/src/renderer/mod.rs +++ b/proxmox-notify/src/renderer/mod.rs @@ -272,7 +272,9 @@ fn render_template_impl( filename: &str, source: TemplateSource, ) -> Result, Error> { - let template_string = context::context().lookup_template(filename, None, source)?; + let template_string = context::context() + .lookup_template(filename, None, source) + .map_err(Error::template_could_not_be_read)?; if let Some(template_string) = template_string { let mut handlebars = Handlebars::new(); @@ -290,7 +292,7 @@ fn render_template_impl( let rendered_template = handlebars .render_template(&template_string, data) - .map_err(|err| Error::RenderError(err.into()))?; + .map_err(|err| Error::template_rendering(err.to_string()))?; let rendered_template = renderer.postprocess(rendered_template); @@ -357,9 +359,8 @@ pub fn render_template( } } - Err(Error::Generic( - "failed to render notification template, all template candidates are erroneous or missing" - .into(), + Err(Error::template_rendering( + "all template candidates are erroneous or missing", )) } -- 2.47.3