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 D918F1FF0B7 for ; Fri, 13 Nov 2026 16:14:32 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 5DEB921AE6; Fri, 13 Nov 2026 16:10:08 +0100 (CET) From: Lukas Wagner To: pve-devel@lists.proxmox.com Subject: [PATCH proxmox 05/55] notify: remove static context and pass context as parameter Date: Fri, 13 Nov 2026 16:07:38 +0100 Message-ID: <20261113150828.756836-6-l.wagner@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261113150828.756836-1-l.wagner@proxmox.com> References: <20261113150828.756836-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: 1794582523569 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.204 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: 4NYJIXIVWRXOFR7P3TMWIO7SVRA36BE6 X-Message-ID-Hash: 4NYJIXIVWRXOFR7P3TMWIO7SVRA36BE6 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: Having static state in library code is not really a great practice for various reasons, such as a less clear concurrency semantics, worse testability and the possibility to forget to initialize context before first use. Instead of injecting the context once via set_context as an initialization step, we now pass it as a &dyn Context parameter at the API level when sending notifications. As a result, the context object now effectively lives in the application code instead of proxmox_notify. The context is now hidden behind a thin wrapper around the actual trait object. The trait was renamed to `ContextImpl`, with the wrapper taking the old name of `Context`. This makes the trait object easier to use and is a preparation to injecting the context to API handlers via #[state]. This is a breaking change; callers need to be adapted. Signed-off-by: Lukas Wagner --- proxmox-notify/src/api/common.rs | 25 ++++++----- proxmox-notify/src/api/matcher.rs | 10 +++-- proxmox-notify/src/api/mod.rs | 5 ++- proxmox-notify/src/context/mod.rs | 47 ++++++++++++--------- proxmox-notify/src/context/pbs.rs | 4 +- proxmox-notify/src/context/pve.rs | 4 +- proxmox-notify/src/context/test.rs | 11 +++-- proxmox-notify/src/endpoints/common/mail.rs | 16 +++++-- proxmox-notify/src/endpoints/gotify.rs | 17 +++++--- proxmox-notify/src/endpoints/mod.rs | 6 ++- proxmox-notify/src/endpoints/sendmail.rs | 28 +++++++----- proxmox-notify/src/endpoints/smtp.rs | 26 ++++++++---- proxmox-notify/src/endpoints/webhook.rs | 35 +++++++++------ proxmox-notify/src/lib.rs | 44 ++++++++++++------- proxmox-notify/src/renderer/mod.rs | 15 ++++--- 15 files changed, 183 insertions(+), 110 deletions(-) diff --git a/proxmox-notify/src/api/common.rs b/proxmox-notify/src/api/common.rs index bc89695f8..56a9797a9 100644 --- a/proxmox-notify/src/api/common.rs +++ b/proxmox-notify/src/api/common.rs @@ -1,13 +1,17 @@ use proxmox_http_error::HttpError; use super::http_err; -use crate::{Bus, Config, Error, Notification}; +use crate::{Bus, Config, Context, Error, Notification}; /// Send a notification to a given target. /// /// The caller is responsible for any needed permission checks. /// Returns an `anyhow::Error` in case of an error. -pub fn send(config: &Config, notification: &Notification) -> Result<(), HttpError> { +pub fn send( + context: &Context, + config: &Config, + notification: &Notification, +) -> Result<(), HttpError> { let bus = Bus::from_config(config).map_err(|err| { http_err!( INTERNAL_SERVER_ERROR, @@ -15,7 +19,7 @@ pub fn send(config: &Config, notification: &Notification) -> Result<(), HttpErro ) })?; - bus.send(notification); + bus.send(context, notification); Ok(()) } @@ -24,7 +28,7 @@ pub fn send(config: &Config, notification: &Notification) -> Result<(), HttpErro /// /// The caller is responsible for any needed permission checks. /// Returns an `anyhow::Error` if sending via the endpoint failed. -pub fn test_target(config: &Config, endpoint: &str) -> Result<(), HttpError> { +pub fn test_target(context: &Context, config: &Config, endpoint: &str) -> Result<(), HttpError> { let bus = Bus::from_config(config).map_err(|err| { http_err!( INTERNAL_SERVER_ERROR, @@ -32,12 +36,13 @@ pub fn test_target(config: &Config, endpoint: &str) -> Result<(), HttpError> { ) })?; - bus.test_target(endpoint).map_err(|err| match err { - Error::TargetDoesNotExist(endpoint) => { - http_err!(NOT_FOUND, "endpoint '{endpoint}' does not exist") - } - _ => http_err!(INTERNAL_SERVER_ERROR, "Could not test target: {err}"), - })?; + bus.test_target(context, endpoint) + .map_err(|err| match err { + Error::TargetDoesNotExist(endpoint) => { + http_err!(NOT_FOUND, "endpoint '{endpoint}' does not exist") + } + _ => http_err!(INTERNAL_SERVER_ERROR, "Could not test target: {err}"), + })?; Ok(()) } diff --git a/proxmox-notify/src/api/matcher.rs b/proxmox-notify/src/api/matcher.rs index 3302c2c31..4600063e2 100644 --- a/proxmox-notify/src/api/matcher.rs +++ b/proxmox-notify/src/api/matcher.rs @@ -210,14 +210,17 @@ mod tests { use super::*; - use crate::matcher::expression::NotificationMatcher; + use crate::{context::test::test_context, matcher::expression::NotificationMatcher}; fn empty_config() -> Config { - Config::new("", "").unwrap() + let context = test_context(); + Config::new(&context, "", "").unwrap() } fn config_with_two_matchers() -> Config { + let context = test_context(); Config::new( + &context, " sendmail: foo mailto test@example.com @@ -499,7 +502,8 @@ matcher: matcher2 // The normalized expression should stay the same after // a read/write cycle of the config let (raw_config, raw_private_config) = config.write().unwrap(); - let config = Config::new(&raw_config, &raw_private_config).unwrap(); + let context = test_context(); + let config = Config::new(&context, &raw_config, &raw_private_config).unwrap(); let matcher = get_matcher(&config, "matcher1")?; assert_eq!(matcher.expression, Some(stored)); diff --git a/proxmox-notify/src/api/mod.rs b/proxmox-notify/src/api/mod.rs index bd73eac65..0ae71acfe 100644 --- a/proxmox-notify/src/api/mod.rs +++ b/proxmox-notify/src/api/mod.rs @@ -291,11 +291,12 @@ fn remove_private_config_entry(config: &mut Config, name: &str) -> Result<(), Ht #[cfg(test)] mod test_helpers { - use crate::Config; + use crate::{Config, context::test}; #[allow(unused)] pub fn empty_config() -> Config { - Config::new("", "").unwrap() + let context = test::test_context(); + Config::new(&context, "", "").unwrap() } } diff --git a/proxmox-notify/src/context/mod.rs b/proxmox-notify/src/context/mod.rs index a81a35caa..71d94c6e3 100644 --- a/proxmox-notify/src/context/mod.rs +++ b/proxmox-notify/src/context/mod.rs @@ -1,5 +1,6 @@ use std::fmt::Debug; -use std::sync::Mutex; +use std::ops::Deref; +use std::sync::Arc; use crate::error::BoxedError; use crate::renderer::TemplateSource; @@ -11,7 +12,29 @@ pub mod pbs; #[cfg(feature = "pve-context")] pub mod pve; #[cfg(test)] -mod test; +pub(crate) mod test; + +/// Product-specific context. +/// +/// This is a thin convenience wrapper around the actual [`ContextImpl`] trait object. +#[derive(Clone)] +pub struct Context(Arc); + +impl Context { + /// Create notification context by wrapping the product-specific context + /// implementation. + pub fn new(context_impl: impl ContextImpl + 'static) -> Self { + Self(Arc::new(context_impl)) + } +} + +impl Deref for Context { + type Target = dyn ContextImpl; + + fn deref(&self) -> &Self::Target { + self.0.as_ref() + } +} // 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 @@ -19,7 +42,7 @@ mod test; // not have to instantiate proxmox_notify::Error themselves. /// Product-specific context -pub trait Context: Send + Sync + Debug { +pub trait ContextImpl: Send + Sync + Debug { /// Look up a user's email address from users.cfg fn lookup_email_for_user(&self, user: &str) -> Option; /// Default mail author for mail-based targets @@ -38,21 +61,3 @@ pub trait Context: Send + Sync + Debug { source: TemplateSource, ) -> Result, BoxedError>; } - -#[cfg(not(test))] -static CONTEXT: Mutex> = Mutex::new(None); -#[cfg(test)] -static CONTEXT: Mutex> = Mutex::new(Some(&test::TestContext)); - -/// Set the product-specific context -pub fn set_context(context: &'static dyn Context) { - *CONTEXT.lock().unwrap() = Some(context); -} - -/// Get product-specific context. -/// -/// Panics if the context has not been set yet. -#[allow(unused)] // context is not used if all endpoint features are disabled -pub(crate) fn context() -> &'static dyn Context { - (*CONTEXT.lock().unwrap()).expect("context for proxmox-notify has not been set yet") -} diff --git a/proxmox-notify/src/context/pbs.rs b/proxmox-notify/src/context/pbs.rs index f484f90c8..a979f25d6 100644 --- a/proxmox-notify/src/context/pbs.rs +++ b/proxmox-notify/src/context/pbs.rs @@ -6,7 +6,7 @@ use tracing::error; use proxmox_schema::{ObjectSchema, Schema, StringSchema}; use proxmox_section_config::{SectionConfig, SectionConfigPlugin}; -use crate::context::{Context, common}; +use crate::context::{ContextImpl, common}; use crate::error::BoxedError; use crate::renderer::TemplateSource; @@ -80,7 +80,7 @@ pub struct PBSContext; pub static PBS_CONTEXT: PBSContext = PBSContext; -impl Context for PBSContext { +impl ContextImpl for PBSContext { fn lookup_email_for_user(&self, user: &str) -> Option { let content = common::attempt_file_read(PBS_USER_CFG_FILENAME); content.and_then(|content| lookup_mail_address(&content, user)) diff --git a/proxmox-notify/src/context/pve.rs b/proxmox-notify/src/context/pve.rs index ba84da920..b2d08acc2 100644 --- a/proxmox-notify/src/context/pve.rs +++ b/proxmox-notify/src/context/pve.rs @@ -1,6 +1,6 @@ use std::path::Path; -use crate::context::{Context, common}; +use crate::context::{ContextImpl, common}; use crate::error::BoxedError; use crate::renderer::TemplateSource; @@ -30,7 +30,7 @@ matcher: default-matcher #[derive(Debug)] pub struct PVEContext; -impl Context for PVEContext { +impl ContextImpl for PVEContext { fn lookup_email_for_user(&self, user: &str) -> Option { let content = common::attempt_file_read("/etc/pve/user.cfg"); content.and_then(|content| lookup_mail_address(&content, user)) diff --git a/proxmox-notify/src/context/test.rs b/proxmox-notify/src/context/test.rs index 7380a0545..b959cb929 100644 --- a/proxmox-notify/src/context/test.rs +++ b/proxmox-notify/src/context/test.rs @@ -1,11 +1,12 @@ -use crate::context::Context; +use crate::Context; +use crate::context::ContextImpl; use crate::error::BoxedError; use crate::renderer::TemplateSource; #[derive(Debug)] -pub struct TestContext; +pub(crate) struct TestContext; -impl Context for TestContext { +impl ContextImpl for TestContext { fn lookup_email_for_user(&self, user: &str) -> Option { user.split_once('@').and_then(|(user, realm)| { if realm == "pve" { @@ -41,3 +42,7 @@ impl Context for TestContext { Ok(Some(String::new())) } } + +pub(crate) fn test_context() -> Context { + Context::new(TestContext) +} diff --git a/proxmox-notify/src/endpoints/common/mail.rs b/proxmox-notify/src/endpoints/common/mail.rs index 074712cff..736f2ac66 100644 --- a/proxmox-notify/src/endpoints/common/mail.rs +++ b/proxmox-notify/src/endpoints/common/mail.rs @@ -1,11 +1,15 @@ -use crate::context; +use crate::Context; /// Get list of email recipients from a list of email addresses and users. /// /// Any user passed in the user list will be looked up in the user configuration to /// obtain this user's email address. The list of returned email addresses does /// not contain any duplicates. -pub(crate) fn get_recipients(email_addrs: &[String], users: &[String]) -> Vec { +pub(crate) fn get_recipients( + context: &Context, + email_addrs: &[String], + users: &[String], +) -> Vec { let mut recipients = Vec::new(); for addr in email_addrs { @@ -15,7 +19,7 @@ pub(crate) fn get_recipients(email_addrs: &[String], users: &[String]) -> Vec { if !recipients.contains(&address) { recipients.push(address); @@ -32,6 +36,8 @@ pub(crate) fn get_recipients(email_addrs: &[String], users: &[String]) -> Vec Result<(), Error> { + fn send(&self, context: &Context, notification: &Notification) -> Result<(), Error> { let (title, message) = match ¬ification.content { Content::Template { template_name, data, } => { let rendered_title = - renderer::render_template(TemplateType::Subject, template_name, data)?; - let rendered_message = - renderer::render_template(TemplateType::PlaintextBody, template_name, data)?; + renderer::render_template(context, TemplateType::Subject, template_name, data)?; + let rendered_message = renderer::render_template( + context, + TemplateType::PlaintextBody, + template_name, + data, + )?; (rendered_title, rendered_message) } @@ -145,7 +148,7 @@ impl Endpoint for GotifyEndpoint { ), ]); - let proxy_config = context() + let proxy_config = context .http_proxy_config() .map(|url| ProxyConfig::parse_proxy_url(&url)) .transpose() diff --git a/proxmox-notify/src/endpoints/mod.rs b/proxmox-notify/src/endpoints/mod.rs index 757b251c1..ea77d4243 100644 --- a/proxmox-notify/src/endpoints/mod.rs +++ b/proxmox-notify/src/endpoints/mod.rs @@ -1,4 +1,6 @@ -use crate::{Error, Notification}; +use crate::Context; +use crate::Error; +use crate::Notification; #[cfg(feature = "gotify")] pub mod gotify; @@ -14,7 +16,7 @@ mod common; /// Notification endpoint trait, implemented by all endpoint plugins pub(crate) trait Endpoint { /// Send a notification to this endpoint. - fn send(&self, notification: &Notification) -> Result<(), Error>; + fn send(&self, context: &Context, notification: &Notification) -> Result<(), Error>; /// The name/identifier for this endpoint fn name(&self) -> &str; diff --git a/proxmox-notify/src/endpoints/sendmail.rs b/proxmox-notify/src/endpoints/sendmail.rs index 3f5f66db6..0d60308d2 100644 --- a/proxmox-notify/src/endpoints/sendmail.rs +++ b/proxmox-notify/src/endpoints/sendmail.rs @@ -4,11 +4,10 @@ use serde::{Deserialize, Serialize}; use proxmox_schema::api_types::COMMENT_SCHEMA; use proxmox_schema::{Updater, api}; -use crate::context; use crate::endpoints::common::mail; use crate::renderer::TemplateType; use crate::schema::{EMAIL_SCHEMA, ENTITY_NAME_SCHEMA, USER_SCHEMA}; -use crate::{Content, Error, Notification, Origin, renderer}; +use crate::{Content, Context, Error, Notification, Origin, renderer}; use super::Endpoint; @@ -106,8 +105,9 @@ pub struct SendmailEndpoint { } impl Endpoint for SendmailEndpoint { - fn send(&self, notification: &Notification) -> Result<(), Error> { + fn send(&self, context: &Context, notification: &Notification) -> Result<(), Error> { let recipients = mail::get_recipients( + context, self.config.mailto.as_slice(), self.config.mailto_user.as_slice(), ); @@ -117,7 +117,7 @@ impl Endpoint for SendmailEndpoint { .config .from_address .clone() - .unwrap_or_else(|| context().default_sendmail_from()); + .unwrap_or_else(|| context.default_sendmail_from()); match ¬ification.content { Content::Template { @@ -125,17 +125,25 @@ impl Endpoint for SendmailEndpoint { data, } => { let subject = - renderer::render_template(TemplateType::Subject, template_name, data)?; - let html_part = - renderer::render_template(TemplateType::HtmlBody, template_name, data)?; - let text_part = - renderer::render_template(TemplateType::PlaintextBody, template_name, data)?; + renderer::render_template(context, TemplateType::Subject, template_name, data)?; + let html_part = renderer::render_template( + context, + TemplateType::HtmlBody, + template_name, + data, + )?; + let text_part = renderer::render_template( + context, + TemplateType::PlaintextBody, + template_name, + data, + )?; let author = self .config .author .clone() - .unwrap_or_else(|| context().default_sendmail_author()); + .unwrap_or_else(|| context.default_sendmail_author()); let mut mail = Mail::new(&author, &mailfrom, &subject, &text_part) .with_html_alt(&html_part) diff --git a/proxmox-notify/src/endpoints/smtp.rs b/proxmox-notify/src/endpoints/smtp.rs index e73151797..b64bb5596 100644 --- a/proxmox-notify/src/endpoints/smtp.rs +++ b/proxmox-notify/src/endpoints/smtp.rs @@ -10,11 +10,10 @@ use serde::{Deserialize, Serialize}; use proxmox_schema::api_types::COMMENT_SCHEMA; use proxmox_schema::{Updater, api}; -use crate::context::context; use crate::endpoints::common::mail; use crate::renderer::TemplateType; use crate::schema::{EMAIL_SCHEMA, ENTITY_NAME_SCHEMA, USER_SCHEMA}; -use crate::{Content, Error, Notification, Origin, renderer}; +use crate::{Content, Context, Error, Notification, Origin, renderer}; use super::Endpoint; @@ -160,7 +159,7 @@ pub struct SmtpEndpoint { } impl Endpoint for SmtpEndpoint { - fn send(&self, notification: &Notification) -> Result<(), Error> { + fn send(&self, context: &Context, notification: &Notification) -> Result<(), Error> { let tls_parameters = TlsParameters::new(self.config.server.clone()) .map_err(|err| Error::invalid_config_with_source("invalid smtp server URL", err))?; @@ -197,6 +196,7 @@ impl Endpoint for SmtpEndpoint { let transport = transport_builder.build(); let recipients = mail::get_recipients( + context, self.config.mailto.as_slice(), self.config.mailto_user.as_slice(), ); @@ -215,7 +215,7 @@ impl Endpoint for SmtpEndpoint { .config .author .clone() - .unwrap_or_else(|| context().default_sendmail_author()); + .unwrap_or_else(|| context.default_sendmail_author()); let quoted_author = quote_name_if_needed(&author); @@ -232,11 +232,19 @@ impl Endpoint for SmtpEndpoint { data, } => { let subject = - renderer::render_template(TemplateType::Subject, template_name, data)?; - let html_part = - renderer::render_template(TemplateType::HtmlBody, template_name, data)?; - let text_part = - renderer::render_template(TemplateType::PlaintextBody, template_name, data)?; + renderer::render_template(context, TemplateType::Subject, template_name, data)?; + let html_part = renderer::render_template( + context, + TemplateType::HtmlBody, + template_name, + data, + )?; + let text_part = renderer::render_template( + context, + TemplateType::PlaintextBody, + template_name, + data, + )?; email_builder = email_builder.subject(subject); diff --git a/proxmox-notify/src/endpoints/webhook.rs b/proxmox-notify/src/endpoints/webhook.rs index 47d9e0586..e3ec9e5ef 100644 --- a/proxmox-notify/src/endpoints/webhook.rs +++ b/proxmox-notify/src/endpoints/webhook.rs @@ -24,10 +24,9 @@ use proxmox_http::{HttpClient, HttpOptions, ProxyConfig}; use proxmox_schema::api_types::{COMMENT_SCHEMA, HTTP_URL_SCHEMA}; use proxmox_schema::{ApiStringFormat, ApiType, Schema, StringSchema, Updater, api}; -use crate::context::context; use crate::renderer::TemplateType; use crate::schema::ENTITY_NAME_SCHEMA; -use crate::{Content, Error, Notification, Origin, renderer}; +use crate::{Content, Context, Error, Notification, Origin, renderer}; use super::Endpoint; @@ -242,10 +241,10 @@ pub const KEY_AND_BASE64_VALUE_SCHEMA: Schema = impl Endpoint for WebhookEndpoint { /// Send a notification to a webhook endpoint. - fn send(&self, notification: &Notification) -> Result<(), Error> { - let request = self.build_request(notification)?; + fn send(&self, context: &Context, notification: &Notification) -> Result<(), Error> { + let request = self.build_request(context, notification)?; - self.create_client()? + self.create_client(context)? .request(request) .map_err(|err| self.mask_secret_in_error(err)) .map_err(Error::http_request_failed)?; @@ -265,8 +264,8 @@ impl Endpoint for WebhookEndpoint { } impl WebhookEndpoint { - fn create_client(&self) -> Result { - let proxy_config = context() + fn create_client(&self, context: &Context) -> Result { + let proxy_config = context .http_proxy_config() .map(|url| ProxyConfig::parse_proxy_url(&url)) .transpose() @@ -280,16 +279,24 @@ impl WebhookEndpoint { Ok(Client::new_with_timeout(options, HTTP_TIMEOUT)) } - fn build_request(&self, notification: &Notification) -> Result, Error> { + fn build_request( + &self, + context: &Context, + notification: &Notification, + ) -> Result, Error> { let (title, message) = match ¬ification.content { Content::Template { template_name, data, } => { let rendered_title = - renderer::render_template(TemplateType::Subject, template_name, data)?; - let rendered_message = - renderer::render_template(TemplateType::PlaintextBody, template_name, data)?; + renderer::render_template(context, TemplateType::Subject, template_name, data)?; + let rendered_message = renderer::render_template( + context, + TemplateType::PlaintextBody, + template_name, + data, + )?; (rendered_title, rendered_message) } @@ -511,7 +518,7 @@ mod tests { use std::collections::HashMap; use super::*; - use crate::Severity; + use crate::{Severity, context::test}; #[test] fn test_build_request() { @@ -566,7 +573,9 @@ hello%20world let notification = Notification::from_template(Severity::Info, "foo", json!({}), data); - let request = endpoint.build_request(¬ification).unwrap(); + let context = test::test_context(); + + let request = endpoint.build_request(&context, ¬ification).unwrap(); assert_eq!(request.uri(), "http://localhost/hello%20world"); assert_eq!(request.body(), expected_body); diff --git a/proxmox-notify/src/lib.rs b/proxmox-notify/src/lib.rs index 0a851239d..6675a9f76 100644 --- a/proxmox-notify/src/lib.rs +++ b/proxmox-notify/src/lib.rs @@ -5,7 +5,6 @@ use std::collections::HashMap; use std::fmt::Display; use std::str::FromStr; -use context::context; use serde::{Deserialize, Serialize}; use serde_json::Value; use serde_json::json; @@ -29,8 +28,10 @@ pub mod schema; mod error; pub use error::Error; -use endpoints::Endpoint; +pub use context::Context; +pub use context::ContextImpl; +use endpoints::Endpoint; #[api()] #[derive(Clone, Debug, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd)] @@ -210,11 +211,15 @@ pub struct Config { impl Config { /// Parse raw config - pub fn new(raw_config: &str, raw_private_config: &str) -> Result { + pub fn new( + context: &Context, + raw_config: &str, + raw_private_config: &str, + ) -> Result { let (mut config, digest) = config::config(raw_config)?; let (private_config, _) = config::private_config(raw_private_config)?; - let default_config = context().default_config(); + let default_config = context.default_config(); let builtin_config = config::config_parser() .parse("", default_config) @@ -467,7 +472,7 @@ impl Bus { /// the notification. /// /// Any errors will not be returned but only logged. - pub fn send(&self, notification: &Notification) { + pub fn send(&self, context: &Context, notification: &Notification) { let targets = matcher::check_matches(self.matchers.as_slice(), notification); for target in targets { @@ -480,7 +485,7 @@ impl Bus { continue; } - match endpoint.send(notification) { + match endpoint.send(context, notification) { Ok(_) => { info!("notified via target `{name}`"); } @@ -499,7 +504,7 @@ impl Bus { /// /// In contrast to the `send` function, this function will return /// any errors to the caller. - pub fn test_target(&self, target: &str) -> Result<(), Error> { + pub fn test_target(&self, context: &Context, target: &str) -> Result<(), Error> { let notification = Notification { metadata: Metadata { severity: Severity::Info, @@ -515,7 +520,7 @@ impl Bus { }; if let Some(endpoint) = self.endpoints.get(target) { - endpoint.send(¬ification)?; + endpoint.send(context, ¬ification)?; } else { return Err(Error::target_does_not_exist(target)); } @@ -530,6 +535,7 @@ mod tests { use proxmox_match_expression::Expression; + use crate::context::test; use crate::matcher::{expression::NotificationMatcher, severity::SeverityMatcher}; use super::*; @@ -543,7 +549,7 @@ mod tests { } impl Endpoint for MockEndpoint { - fn send(&self, message: &Notification) -> Result<(), Error> { + fn send(&self, _context: &Context, message: &Notification) -> Result<(), Error> { self.messages.borrow_mut().push(message.clone()); Ok(()) @@ -577,6 +583,7 @@ mod tests { #[test] fn test_add_mock_endpoint() -> Result<(), Error> { + let context = test::test_context(); let mock = MockEndpoint::new("endpoint"); let mut bus = Bus::default(); @@ -591,12 +598,15 @@ mod tests { bus.add_matcher(matcher); // Send directly to endpoint - bus.send(&Notification::from_template( - Severity::Info, - "test", - Default::default(), - Default::default(), - )); + bus.send( + &context, + &Notification::from_template( + Severity::Info, + "test", + Default::default(), + Default::default(), + ), + ); let messages = mock.messages(); assert_eq!(messages.len(), 1); @@ -605,6 +615,8 @@ mod tests { #[test] fn test_multiple_endpoints_with_different_matchers() -> Result<(), Error> { + let context = test::test_context(); + let endpoint1 = MockEndpoint::new("mock1"); let endpoint2 = MockEndpoint::new("mock2"); @@ -645,7 +657,7 @@ mod tests { Default::default(), ); - bus.send(¬ification); + bus.send(&context, ¬ification); }; send_with_severity(Severity::Info); diff --git a/proxmox-notify/src/renderer/mod.rs b/proxmox-notify/src/renderer/mod.rs index 1bccf75bf..da6279a1d 100644 --- a/proxmox-notify/src/renderer/mod.rs +++ b/proxmox-notify/src/renderer/mod.rs @@ -2,8 +2,9 @@ use std::{fmt::Display, time::Duration}; +use handlebars::Context as HandlebarsContext; use handlebars::{ - Context, Handlebars, Helper, HelperDef, HelperResult, Output, RenderContext, RenderErrorReason, + Handlebars, Helper, HelperDef, HelperResult, Output, RenderContext, RenderErrorReason, }; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -12,7 +13,7 @@ use tracing::error; use proxmox_human_byte::HumanByte; use proxmox_time::TimeSpan; -use crate::{Error, context}; +use crate::{Context, Error}; mod html; mod plaintext; @@ -76,7 +77,7 @@ fn value_to_timestamp(val: &Value) -> Option { fn handlebars_relative_percentage_helper( h: &Helper, _: &Handlebars, - _: &Context, + _: &HandlebarsContext, _rc: &mut RenderContext, out: &mut dyn Output, ) -> HelperResult { @@ -159,7 +160,7 @@ impl ValueRenderFunction { Box::new( move |h: &Helper, _r: &Handlebars, - _: &Context, + _: &HandlebarsContext, _rc: &mut RenderContext, out: &mut dyn Output| -> HelperResult { @@ -267,12 +268,13 @@ impl BlockRenderFunctions { } fn render_template_impl( + context: &Context, data: &Value, renderer: TemplateType, filename: &str, source: TemplateSource, ) -> Result, Error> { - let template_string = context::context() + let template_string = context .lookup_template(filename, None, source) .map_err(Error::template_could_not_be_read)?; @@ -310,6 +312,7 @@ fn render_template_impl( /// HTML template is found or renderable, it falls back to use a plaintext /// template encapsulated in a pre-formatted HTML block (
).
 pub fn render_template(
+    context: &Context,
     mut ty: TemplateType,
     template: &str,
     data: &Value,
@@ -318,7 +321,7 @@ pub fn render_template(
 
     loop {
         let filename = format!("{template}-{suffix}", suffix = ty.file_suffix());
-        let result = render_template_impl(data, ty, &filename, source);
+        let result = render_template_impl(context, data, ty, &filename, source);
 
         match result {
             Ok(Some(s)) => {
-- 
2.47.3