[pbs-devel] [PATCH v2 proxmox-backup 3/5] api-types: client: add wrapper api type for TimeSpan

Christian Ebner c.ebner at proxmox.com
Wed Oct 23 11:11:01 CEST 2024


Implementing the `ApiType` for `TimeSpan` directly does not work
since `proxmox-schema` depends on `proxmox-time`.

Add a wrapper type `TimeInterval` and implement the api type on this
as a workaround.

Signed-off-by: Christian Ebner <c.ebner at proxmox.com>
---
changes since version 1:
- Move `LogInterval` to client, it is not an api type anymore
- Implement `TimeInterval` wrapper for `TimeSpan`, to avoid cyclic
  create dependencies for `proxmox-schema` and `proxmox-time` if
  `TimeSpan` would be implemented as api type

 pbs-api-types/src/client.rs | 49 +++++++++++++++++++++++++++++++++++++
 pbs-api-types/src/lib.rs    |  3 +++
 2 files changed, 52 insertions(+)
 create mode 100644 pbs-api-types/src/client.rs

diff --git a/pbs-api-types/src/client.rs b/pbs-api-types/src/client.rs
new file mode 100644
index 000000000..2d2c864dd
--- /dev/null
+++ b/pbs-api-types/src/client.rs
@@ -0,0 +1,49 @@
+use std::str::FromStr;
+
+use anyhow::Error;
+
+use proxmox_schema::{ApiStringFormat, ApiType, Schema, StringSchema};
+use proxmox_time::TimeSpan;
+
+// Wrapper type for `TimeSpan` to avoid cyclic create dependency for `proxmox-time` and `proxmox-schema`
+pub struct TimeInterval(TimeSpan);
+
+impl FromStr for TimeInterval {
+    type Err = Error;
+
+    fn from_str(value: &str) -> Result<Self, Self::Err> {
+        Ok(Self(TimeSpan::from_str(value)?))
+    }
+}
+
+impl From<TimeInterval> for TimeSpan {
+    fn from(time_interval: TimeInterval) -> TimeSpan {
+        time_interval.0
+    }
+}
+
+impl std::fmt::Display for TimeInterval {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        TimeSpan::fmt(&self.0, f)
+    }
+}
+
+impl ApiType for TimeInterval {
+    const API_SCHEMA: Schema = StringSchema::new("Time interval")
+        .format(&ApiStringFormat::VerifyFn(verify_time_interval))
+        .schema();
+}
+
+impl TimeInterval {
+    pub fn as_f64(&self) -> f64 {
+        std::primitive::f64::from(&self.0)
+    }
+}
+
+pub fn verify_time_interval(value: &str) -> Result<(), Error> {
+    let _: TimeSpan = value.parse()?;
+    Ok(())
+}
+
+proxmox_serde::forward_serialize_to_display!(TimeInterval);
+proxmox_serde::forward_deserialize_to_from_str!(TimeInterval);
diff --git a/pbs-api-types/src/lib.rs b/pbs-api-types/src/lib.rs
index 460c7da7c..bd16ab16c 100644
--- a/pbs-api-types/src/lib.rs
+++ b/pbs-api-types/src/lib.rs
@@ -93,6 +93,9 @@ pub const GROUP_OR_SNAPSHOT_PATH_REGEX_STR: &str =
 mod acl;
 pub use acl::*;
 
+mod client;
+pub use client::*;
+
 mod datastore;
 pub use datastore::*;
 
-- 
2.39.5





More information about the pbs-devel mailing list