1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
use std::fmt::Write;
use crate::traits::PointSerialize;
#[derive(Debug, Clone)]
pub enum Value {
Str(String),
Int(i64),
Float(f64),
Bool(bool),
}
impl From<&str> for Value {
fn from(v: &str) -> Value {
Value::Str(v.to_string())
}
}
impl From<f64> for Value {
fn from(v: f64) -> Value {
Value::Float(v)
}
}
impl Value {
fn to_string(self) -> String {
match self {
Value::Str(s) => s.to_string(),
Value::Int(i) => i.to_string(),
Value::Float(f) => f.to_string(),
Value::Bool(b) => b.to_string(),
}
}
}
#[derive(Debug, Clone)]
pub struct Point {
pub measurement: String,
pub timestamp: Option<i64>,
pub tags: Vec<(String, Value)>,
pub fields: Vec<(String, Value)>,
}
impl Point {
pub fn new<T: Into<String>>(measurement: T) -> Self {
Point {
measurement: measurement.into(),
tags: Vec::new(),
fields: Vec::new(),
timestamp: None,
}
}
pub fn tag<T: Into<String>, V: Into<Value>>(mut self, key: T, value: V) -> Self {
self.tags.push((key.into(), value.into()));
self
}
pub fn field<T: Into<String>, V: Into<Value>>(mut self, key: T, value: V) -> Self {
self.fields.push((key.into(), value.into()));
self
}
pub fn timestamp<T: Into<i64>>(mut self, timestamp: T) -> Self {
self.timestamp = Some(timestamp.into());
self
}
}
impl PointSerialize for Point {
fn serialize(&self) -> String {
let mut builder = String::new();
write!(&mut builder, "{}", self.measurement).unwrap();
if !self.tags.is_empty() {
write!(&mut builder, ",").unwrap();
for tag in &self.tags {
write!(
&mut builder,
"{}={}",
tag.0.to_string(),
tag.1.clone().to_string()
)
.unwrap();
}
}
if !self.fields.is_empty() {
write!(&mut builder, " ").unwrap();
for field in &self.fields {
write!(
&mut builder,
"{}={}",
field.0.to_string(),
field.1.clone().to_string()
)
.unwrap();
}
}
builder
}
fn serialize_with_timestamp(&self, timestamp: Option<String>) -> String {
match timestamp {
Some(t) => format!("{} {}", self.serialize(), t),
None => format!(
"{} {}",
self.serialize(),
self.timestamp.unwrap_or_default()
),
}
}
}
#[derive(Debug)]
pub enum InfluxError {
InvalidSyntax(String),
InvalidCredentials(String),
Forbidden(String),
Unknown(String),
}
mod tests {
use super::Point;
use crate::traits::PointSerialize;
#[test]
fn test_point_serialize() {
let expected = "mem,host=host1 used_percent=23.43234543 1556896326";
let point = Point::new("mem")
.tag("host", "host1")
.field("used_percent", 23.43234543)
.timestamp(1556896326);
let actual = point.serialize_with_timestamp(None);
assert_eq!(actual, expected);
}
}