public inbox for pdm-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Lukas Wagner <l.wagner@proxmox.com>
To: pdm-devel@lists.proxmox.com
Subject: [PATCH datacenter-manager 17/20] context: provide api-cache on the app object
Date: Mon, 17 Aug 2026 14:57:24 +0200	[thread overview]
Message-ID: <20260817125727.454039-18-l.wagner@proxmox.com> (raw)
In-Reply-To: <20260817125727.454039-1-l.wagner@proxmox.com>

Move the ApiCache instance from the global CACHE static onto
PdmApplication, built from the product config's cache directory
instead of the hardcoded PDM_API_CACHE_PATH. The free functions in
api_cache now fetch it via context::pdm_application() instead of the
static.

Add default_file_create_options()/default_dir_create_options() to
ProductConfig so the cache's directory and file permissions can be
derived the same way in both the real application and tests.

Signed-off-by: Lukas Wagner <l.wagner@proxmox.com>
---
 server/src/api_cache.rs                       | 45 ++++++++++---------
 .../bin/proxmox-datacenter-privileged-api.rs  |  7 ++-
 server/src/context/mod.rs                     | 20 ++++++++-
 server/src/context/product_config.rs          | 23 +++++++++-
 server/tests/common/test_application.rs       |  3 ++
 5 files changed, 75 insertions(+), 23 deletions(-)

diff --git a/server/src/api_cache.rs b/server/src/api_cache.rs
index 6dc8a043..fed66483 100644
--- a/server/src/api_cache.rs
+++ b/server/src/api_cache.rs
@@ -54,31 +54,22 @@
 //! ```
 
 use std::path::PathBuf;
-use std::sync::LazyLock;
 use std::time::Duration;
 
-use nix::sys::stat::Mode;
-
 use proxmox_sys::fs::CreateOptions;
 
+use crate::context;
 use crate::namespaced_cache::{
     BlockingReadableCacheNamespace, BlockingWritableCacheNamespace, CacheError, NamespacedCache,
     ReadableCacheNamespace, WritableCacheNamespace,
 };
 
-/// Path at which API responses are cached.
-pub const PDM_API_CACHE_PATH: &str = concat!(pdm_buildcfg::PDM_RUN_DIR_M!(), "/api-cache");
+/// Subdirectory at which API responses are cached.
+pub const PDM_API_CACHE_SUBDIR: &str = "api-cache";
 
 const GLOBAL_NAMESPACE: &str = "global";
 const LOCK_TIMEOUT: Duration = Duration::from_secs(10);
 
-static CACHE: LazyLock<ApiCache> = LazyLock::new(|| {
-    let file_options = proxmox_product_config::default_create_options();
-    let dir_options = file_options.perm(Mode::from_bits_truncate(0o750));
-
-    ApiCache::new(PathBuf::from(PDM_API_CACHE_PATH), dir_options, file_options)
-});
-
 fn format_remote_namespace(remote: &str) -> String {
     format!("remote-{remote}")
 }
@@ -157,40 +148,54 @@ impl ApiCache {
 
 /// Lock the cache for reading remote-specific data (blocking interface).
 pub fn read_remote_blocking(remote: &str) -> Result<BlockingReadableCacheNamespace, CacheError> {
-    CACHE.read_remote_blocking(remote)
+    context::pdm_application()
+        .api_cache()
+        .read_remote_blocking(remote)
 }
 
 /// Lock the cache for writing remote-specific data (blocking interface).
 pub fn write_remote_blocking(remote: &str) -> Result<BlockingWritableCacheNamespace, CacheError> {
-    CACHE.write_remote_blocking(remote)
+    context::pdm_application()
+        .api_cache()
+        .write_remote_blocking(remote)
 }
 
 /// Lock the cache for reading global data (blocking interface).
 pub fn read_global_blocking() -> Result<BlockingReadableCacheNamespace, CacheError> {
-    CACHE.read_global_blocking()
+    context::pdm_application()
+        .api_cache()
+        .read_global_blocking()
 }
 
 /// Lock the cache for writing global data (blocking interface).
 pub fn write_global_blocking() -> Result<BlockingWritableCacheNamespace, CacheError> {
-    CACHE.write_global_blocking()
+    context::pdm_application()
+        .api_cache()
+        .write_global_blocking()
 }
 
 /// Lock the cache for reading remote-specific data (async interface).
 pub async fn read_remote(remote: &str) -> Result<ReadableCacheNamespace, CacheError> {
-    CACHE.read_remote(remote).await
+    context::pdm_application()
+        .api_cache()
+        .read_remote(remote)
+        .await
 }
 
 /// Lock the cache for writing remote-specific data (async interface).
 pub async fn write_remote(remote: &str) -> Result<WritableCacheNamespace, CacheError> {
-    CACHE.write_remote(remote).await
+    context::pdm_application()
+        .api_cache()
+        .write_remote(remote)
+        .await
 }
 
 /// Lock the cache for reading global data (async interface).
 pub async fn read_global() -> Result<ReadableCacheNamespace, CacheError> {
-    CACHE.read_global().await
+    context::pdm_application().api_cache().read_global().await
 }
 
 /// Lock the cache for writing global data (async interface).
 pub async fn write_global() -> Result<WritableCacheNamespace, CacheError> {
-    CACHE.write_global().await
+    context::pdm_application().api_cache().write_global().await
 }
diff --git a/server/src/bin/proxmox-datacenter-privileged-api.rs b/server/src/bin/proxmox-datacenter-privileged-api.rs
index 3815ab03..d32e10c5 100644
--- a/server/src/bin/proxmox-datacenter-privileged-api.rs
+++ b/server/src/bin/proxmox-datacenter-privileged-api.rs
@@ -2,6 +2,7 @@ use std::path::Path;
 use std::pin::pin;
 
 use anyhow::{Context as _, Error, bail, format_err};
+use const_format::concatcp;
 use futures::*;
 use hyper_util::server::graceful::GracefulShutdown;
 use nix::fcntl::AtFlags;
@@ -104,7 +105,11 @@ fn create_directories() -> Result<(), Error> {
     )?;
 
     pdm_config::setup::mkdir_perms(
-        api_cache::PDM_API_CACHE_PATH,
+        concatcp!(
+            pdm_buildcfg::PDM_RUN_DIR_M!(),
+            "/",
+            api_cache::PDM_API_CACHE_SUBDIR,
+        ),
         api_user.uid,
         api_user.gid,
         0o750,
diff --git a/server/src/context/mod.rs b/server/src/context/mod.rs
index bf9c6c2e..5f95d358 100644
--- a/server/src/context/mod.rs
+++ b/server/src/context/mod.rs
@@ -8,6 +8,7 @@ use anyhow::Error;
 
 use pdm_config::{remotes::RemoteConfig, subscriptions::SubscriptionKeyConfig};
 
+use crate::api_cache::ApiCache;
 use crate::connection::{self, ClientFactory};
 
 #[cfg(remote_config = "faked")]
@@ -80,12 +81,22 @@ pub trait ContextFactory {
     }
 
     fn make_pdm_application(&self) -> Result<PdmApplication, Error> {
+        let product_config = self.make_product_config()?;
+
+        let api_cache = ApiCache::new(
+            product_config.run_dir().join("api-cache"),
+            product_config.default_dir_create_options(),
+            product_config.default_file_create_options(),
+        );
+
         Ok(PdmApplication {
             inner: Arc::new(PdmApplicationInner {
                 client_factory: self.make_client_factory()?,
                 remote_config: self.make_remote_config()?,
                 subscription_key_config: self.make_subscription_key_config()?,
-                product_config: self.make_product_config()?,
+                product_config,
+
+                api_cache,
             }),
         })
     }
@@ -140,6 +151,11 @@ impl PdmApplication {
     pub fn product_config(&self) -> &ProductConfig {
         &self.inner.product_config
     }
+
+    /// Get a reference to the [`ApiCache`].
+    pub fn api_cache(&self) -> &ApiCache {
+        &self.inner.api_cache
+    }
 }
 
 struct PdmApplicationInner {
@@ -147,4 +163,6 @@ struct PdmApplicationInner {
     remote_config: Box<dyn RemoteConfig + Send + Sync>,
     subscription_key_config: Box<dyn SubscriptionKeyConfig + Send + Sync>,
     product_config: ProductConfig,
+
+    api_cache: ApiCache,
 }
diff --git a/server/src/context/product_config.rs b/server/src/context/product_config.rs
index 3c1f44ab..a11c5db1 100644
--- a/server/src/context/product_config.rs
+++ b/server/src/context/product_config.rs
@@ -3,7 +3,8 @@
 use std::path::{Path, PathBuf};
 
 use anyhow::Error;
-use nix::unistd::User;
+use nix::{sys::stat::Mode, unistd::User};
+use proxmox_sys::fs::CreateOptions;
 
 #[derive(Clone, Debug)]
 pub struct ProductConfig {
@@ -43,6 +44,26 @@ impl ProductConfig {
     pub fn cache_dir(&self) -> &Path {
         &self.cache_dir
     }
+
+    pub fn default_file_create_options(&self) -> CreateOptions {
+        let api_user = self.api_user();
+        let mode = Mode::from_bits_truncate(0o0640);
+
+        CreateOptions::new()
+            .perm(mode)
+            .owner(api_user.uid)
+            .group(api_user.gid)
+    }
+
+    pub fn default_dir_create_options(&self) -> CreateOptions {
+        let api_user = self.api_user();
+        let mode = Mode::from_bits_truncate(0o0750);
+
+        CreateOptions::new()
+            .perm(mode)
+            .owner(api_user.uid)
+            .group(api_user.gid)
+    }
 }
 
 #[derive(Default)]
diff --git a/server/tests/common/test_application.rs b/server/tests/common/test_application.rs
index cd8409e3..436513f0 100644
--- a/server/tests/common/test_application.rs
+++ b/server/tests/common/test_application.rs
@@ -142,6 +142,9 @@ impl ContextFactory for TestApplication {
         std::fs::create_dir(&run_dir)?;
         std::fs::create_dir(&cache_dir)?;
 
+        // FIXME: Maybe ApiCache::new should do this.
+        std::fs::create_dir(run_dir.join("api-cache"))?;
+
         ProductConfig::builder()
             .api_user(user.clone())
             .priv_user(user)
-- 
2.47.3





  parent reply	other threads:[~2026-08-17 12:58 UTC|newest]

Thread overview: 28+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-08-17 12:57 [PATCH datacenter-manager/proxmox 00/20] inject application context via API macro for easier integration testing Lukas Wagner
2026-08-17 12:57 ` [PATCH proxmox 01/20] router: introduce shared state Lukas Wagner
2026-08-17 13:26   ` Lukas Wagner
2026-08-20 11:23   ` Lukas Wagner
2026-08-21 13:59   ` Robert Obkircher
2026-08-17 12:57 ` [PATCH proxmox 02/20] rest-server: allow to inject " Lukas Wagner
2026-08-17 12:57 ` [PATCH proxmox 03/20] api-macro: support shared state extraction type Lukas Wagner
2026-08-21 13:59   ` Robert Obkircher
2026-08-17 12:57 ` [PATCH datacenter-manager 04/20] context: promote context to a dir-style module Lukas Wagner
2026-08-17 12:57 ` [PATCH datacenter-manager 05/20] pdm-config: remotes: rename trait methods to read/write/lock Lukas Wagner
2026-08-17 12:57 ` [PATCH datacenter-manager 06/20] pdm-config: subscriptions: " Lukas Wagner
2026-08-21 14:00   ` Robert Obkircher
2026-08-17 12:57 ` [PATCH datacenter-manager 07/20] remote iterator: pass remote config reader explicitly Lukas Wagner
2026-08-17 12:57 ` [PATCH datacenter-manager 08/20] context: introduce a ContextFactory to build application context Lukas Wagner
2026-08-17 12:57 ` [PATCH datacenter-manager 09/20] context: establish PdmApplication object Lukas Wagner
2026-08-17 12:57 ` [PATCH datacenter-manager 10/20] context: register PdmApplication in router Lukas Wagner
2026-08-17 12:57 ` [PATCH datacenter-manager 11/20] parallel fetcher: pass arguments to closure in a single type Lukas Wagner
2026-08-21 14:00   ` Robert Obkircher
2026-08-17 12:57 ` [PATCH datacenter-manager 12/20] parallel fetcher: support a custom client factory Lukas Wagner
2026-08-17 12:57 ` [PATCH datacenter-manager 13/20] api: sdn: use PdmApplication handle for accessing remotes Lukas Wagner
2026-08-17 12:57 ` [PATCH datacenter-manager 14/20] tests: add helpers for building API-handler-level integration tests Lukas Wagner
2026-08-17 12:57 ` [PATCH datacenter-manager 15/20] tests: add example tests for SDN API routes Lukas Wagner
2026-08-17 12:57 ` [PATCH datacenter-manager 16/20] api-cache: add wrapper type Lukas Wagner
2026-08-17 12:57 ` Lukas Wagner [this message]
2026-08-17 12:57 ` [PATCH datacenter-manager 18/20] api: subscriptions: use PdmApplication instead of globals Lukas Wagner
2026-08-17 12:57 ` [PATCH datacenter-manager 19/20] pdm-config: subscriptions: drop unused accessor functions Lukas Wagner
2026-08-17 12:57 ` [PATCH datacenter-manager 20/20] tests: add example tests for remote subscription management Lukas Wagner
2026-08-20 14:54 ` superseded: [PATCH datacenter-manager/proxmox 00/20] inject application context via API macro for easier integration testing 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=20260817125727.454039-18-l.wagner@proxmox.com \
    --to=l.wagner@proxmox.com \
    --cc=pdm-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