use serde::{Deserialize, Serialize};
use zbus::zvariant::Type;
use crate::unixtime;
pub type Measures = Vec<Measure>;
pub type Transactions = Vec<Transaction>;
pub type Tid = u64;
#[derive(Debug, PartialEq, Eq, Type, Serialize, Deserialize)]
#[must_use]
pub struct Measure {
pub key: String,
pub value: String,
pub timestamp: u64,
}
impl Measure {
pub const fn new_with_ts(key: String, value: String, timestamp: u64) -> Self {
Self {
key,
value,
timestamp,
}
}
pub fn new(key: String, value: String) -> Self {
let timestamp = unixtime();
Self {
key,
value,
timestamp,
}
}
}
impl std::fmt::Display for Measure {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"Measure(key={}, value={}, timestamp={})",
self.key, self.value, self.timestamp
)
}
}
#[derive(Debug, PartialEq, Eq, Type, Serialize, Deserialize)]
#[must_use]
pub struct Transaction {
pub key: String,
pub expected: String,
pub target: String,
pub t_id: Tid,
}
impl std::fmt::Display for Transaction {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"Transaction(key={}, expected={}, target={}, t_id={})",
self.key, self.expected, self.target, self.t_id
)
}
}
#[derive(Debug, PartialEq, Eq, Type, Serialize, Deserialize)]
pub struct PreparedPoint {
pub id: i64,
pub key: String,
pub value: String,
pub timestamp: u64,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_measure() {
let m = Measure::new_with_ts("foo.bar.baz".to_string(), "0.02".to_string(), 1_604_334_179);
let output = format!("Found {}", m);
assert_eq!(
output,
r#"Found Measure(key=foo.bar.baz, value=0.02, timestamp=1604334179)"#
);
let b = Measure::new("foo.bar.baz".to_string(), "0.02".to_string());
assert!(b.timestamp > m.timestamp);
}
#[test]
fn test_transaction() {
let t = Transaction {
key: "foo.bar.baz".into(),
expected: "0.02".into(),
target: "0.03".into(),
t_id: 5,
};
let output = format!("Got {}", t);
assert_eq!(
output,
r#"Got Transaction(key=foo.bar.baz, expected=0.02, target=0.03, t_id=5)"#
);
}
}