public inbox for pve-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Lukas Wagner <l.wagner@proxmox.com>
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	[thread overview]
Message-ID: <20261113150828.756836-6-l.wagner@proxmox.com> (raw)
In-Reply-To: <20261113150828.756836-1-l.wagner@proxmox.com>

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 <l.wagner@proxmox.com>
---
 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<dyn ContextImpl>);
+
+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<String>;
     /// Default mail author for mail-based targets
@@ -38,21 +61,3 @@ pub trait Context: Send + Sync + Debug {
         source: TemplateSource,
     ) -> Result<Option<String>, BoxedError>;
 }
-
-#[cfg(not(test))]
-static CONTEXT: Mutex<Option<&'static dyn Context>> = Mutex::new(None);
-#[cfg(test)]
-static CONTEXT: Mutex<Option<&'static dyn Context>> = 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<String> {
         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<String> {
         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<String> {
         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<String> {
+pub(crate) fn get_recipients(
+    context: &Context,
+    email_addrs: &[String],
+    users: &[String],
+) -> Vec<String> {
     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<St
     }
 
     for user in users {
-        match context::context().lookup_email_for_user(user) {
+        match context.lookup_email_for_user(user) {
             Some(address) => {
                 if !recipients.contains(&address) {
                     recipients.push(address);
@@ -32,6 +36,8 @@ pub(crate) fn get_recipients(email_addrs: &[String], users: &[String]) -> Vec<St
 
 #[cfg(test)]
 mod tests {
+    use crate::context::test;
+
     use super::*;
 
     #[test]
@@ -54,7 +60,9 @@ mod tests {
             "user2@example.com",
         ];
 
-        let addrs = get_recipients(&emails, &users);
+        let context = test::test_context();
+
+        let addrs = get_recipients(&context, &emails, &users);
 
         assert_eq!(addrs, expected);
     }
diff --git a/proxmox-notify/src/endpoints/gotify.rs b/proxmox-notify/src/endpoints/gotify.rs
index 6b8499827..7fe74f862 100644
--- a/proxmox-notify/src/endpoints/gotify.rs
+++ b/proxmox-notify/src/endpoints/gotify.rs
@@ -9,10 +9,9 @@ use proxmox_http::{HttpClient, HttpOptions, ProxyConfig};
 use proxmox_schema::api_types::COMMENT_SCHEMA;
 use proxmox_schema::{Updater, api};
 
-use crate::context::context;
 use crate::renderer::TemplateType;
 use crate::schema::ENTITY_NAME_SCHEMA;
-use crate::{Content, Error, Notification, Origin, Severity, renderer};
+use crate::{Content, Context, Error, Notification, Origin, Severity, renderer};
 
 use super::Endpoint;
 
@@ -98,16 +97,20 @@ pub enum DeleteableGotifyProperty {
 }
 
 impl Endpoint for GotifyEndpoint {
-    fn send(&self, notification: &Notification) -> Result<(), Error> {
+    fn send(&self, context: &Context, notification: &Notification) -> Result<(), Error> {
         let (title, message) = match &notification.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 &notification.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<Client, Error> {
-        let proxy_config = context()
+    fn create_client(&self, context: &Context) -> Result<Client, Error> {
+        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<Request<String>, Error> {
+    fn build_request(
+        &self,
+        context: &Context,
+        notification: &Notification,
+    ) -> Result<Request<String>, Error> {
         let (title, message) = match &notification.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(&notification).unwrap();
+        let context = test::test_context();
+
+        let request = endpoint.build_request(&context, &notification).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<Self, Error> {
+    pub fn new(
+        context: &Context,
+        raw_config: &str,
+        raw_private_config: &str,
+    ) -> Result<Self, Error> {
         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("<builtin>", 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(&notification)?;
+            endpoint.send(context, &notification)?;
         } 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(&notification);
+            bus.send(&context, &notification);
         };
 
         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<String> {
 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<Option<String>, 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 (<pre>).
 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





  parent reply	other threads:[~2026-11-13 15:14 UTC|newest]

Thread overview: 58+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-13 15:07 [PATCH many 00/55] notify: maintenance, PDM preparations, queue + worker Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 01/55] notify: disallow `unsafe` code Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 02/55] notify: refactor error type Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 03/55] notify: move `Endpoint` trait to endpoint module as pub(crate) Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 04/55] notify: use ConfigDigest instead of raw byte arrays Lukas Wagner
2026-11-13 15:07 ` Lukas Wagner [this message]
2026-11-13 15:07 ` [PATCH proxmox 06/55] notify: matcher: drop unused field matcher verifiers Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 07/55] notify: introduce 'send-impl', 'api-impl' and 'api-types' features Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 08/55] notify: matcher: make matcher validation methods public Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 09/55] notify: make SendmailEndpoint and SmtpEndpoint private types Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 10/55] notify: move `send`, `test_target` and `Bus` to new `send` module Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 11/55] notify: move Origin type to api_types module Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 12/55] notify: move Target " Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 13/55] notify: move Config to config module Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 14/55] notify: move Notification and sub-types to `notification` module Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 15/55] notify: move schema module to api_types Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 16/55] notify: move check_matches from api_types::matcher to send::Bus Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 17/55] notify: move TemplateSource to context module Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 18/55] notify: config: cleanup helpers names and visibility Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 19/55] notify: config: rename section config parser/writer methods Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 20/55] notify: config: pass builtins explicitly when parsing section config Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 21/55] notify: implement PartialEq for all Config types Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 22/55] notify: use typed SectionConfigData Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 23/55] notify: api: api types: rename Deleteable* -> Deletable* Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 24/55] notify: context: parse builtin config only once Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 25/55] notify: context: parse proxy config in trait impl, not at the callsite Lukas Wagner
2026-11-13 15:07 ` [PATCH proxmox 26/55] notify: gate sub-modules with the appropriate feature flags Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox 27/55] notify: fold mail-forwarder feature into send-impl Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox 28/55] notify: forwarded mails: don't hardcode severity and metadata fields Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox 29/55] notify: don't pass uid when instantiating forwarded mail notifications Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox 30/55] notify: derive PartialEq for Notification type Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox 31/55] notify: add getters for severity and fields on " Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox 32/55] notify: add test suite for " Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox 33/55] notify: serialize raw, forwarded mail content as base64 Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox 34/55] notify: unify code paths for legacy-sendmail and regular notifications Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox 35/55] notify: add backwards-compat note to Notification type Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox 36/55] notify: remove 'test_target' API Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox 37/55] notify: replace notification instantiation with builder pattern Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox 38/55] notify: add send receipts Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox 39/55] notify: implement notification queue submitter Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox 40/55] notify: context: add read_config Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox 41/55] notify: queue: add queue consumer Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox 42/55] notify: queue: add worker task Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox-backup 43/55] notifications: don't ignore verification errors in legacy-sendmail mode Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox-backup 44/55] notifications: adapt to proxmox-notify API changes Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox-backup 45/55] api: notification: send test notification via proxmox_notify::send Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox-backup 46/55] notifications: send all notifications via proxmox-notify's queue Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox-perl-rs 47/55] pve: notify: adapt to changes in the public API of proxmox-notify Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox-perl-rs 48/55] pve: notify: add `PVE::RS::Notify::enqueue` method Lukas Wagner
2026-11-13 15:08 ` [PATCH pve-cluster 49/55] notify: send notifications via notification queue Lukas Wagner
2026-11-13 15:08 ` [PATCH manager 50/55] vzdump: send legacy-sendmail notifications via simplified API Lukas Wagner
2026-11-13 15:08 ` [PATCH manager 51/55] pve-notify-worker: add new rust-based notification worker daemon Lukas Wagner
2026-11-13 15:08 ` [PATCH manager 52/55] debian: add 'pve-notify-worker' as a dependency Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox-mail-forward 53/55] forward mails via notification queue Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox-mail-forward 54/55] use return code to signal permanent or temporary failure Lukas Wagner
2026-11-13 15:08 ` [PATCH proxmox-mail-forward 55/55] limit size of mail read from stdin Lukas Wagner
2026-11-17  9:35 ` [PATCH many 00/55] notify: maintenance, PDM preparations, queue + worker Lukas Wagner
2026-11-18  9:55 ` superseded: " Lukas Wagner

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261113150828.756836-6-l.wagner@proxmox.com \
    --to=l.wagner@proxmox.com \
    --cc=pve-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal