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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
//! Rust implementation of [InfluxDB's line protocol](https://docs.influxdata.com/influxdb/v2.0/reference/syntax/line-protocol/)
//!
//! # Example
//!
//! ```
//! use influxdb_line_protocol::FieldValue;
//!
//! print!(
//!     "{}",
//!     influxdb_line_protocol::to_string(
//!         "myMeasurement",
//!         vec![("tag1", "value1"), ("tag2", "value2")],
//!         vec![("fieldKey", FieldValue::String("fieldValue"))],
//!         Some(1556813561098000000),
//!     )
//!     .unwrap()
//! );
//! ```

mod field_value;

pub use field_value::FieldValue;
use std::fmt::Write;

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("measurement names, tag keys, and field keys cannot begin with an underscore")]
    NamingRestrictions,
    #[error("points must have at least one field")]
    EmptyFieldSet,
    #[error("length limit 64KB")]
    StringLengthLimit,
    #[error("line protocol does not support the newline character in tag or field values")]
    Newline,
    #[error(transparent)]
    Fmt(#[from] std::fmt::Error),
}

pub fn to_writer<'a, W, T, F>(
    mut writer: W,
    measurement: &str,
    tag_set: T,
    field_set: F,
    timestamp: Option<i64>,
) -> Result<(), Error>
where
    W: Write,
    T: IntoIterator<Item = (&'a str, &'a str)>,
    F: IntoIterator<Item = (&'a str, FieldValue<'a>)>,
{
    check_string_length(measurement)?;
    if measurement.starts_with('_') {
        return Err(Error::NamingRestrictions);
    }
    for c in measurement.chars() {
        match c {
            '\n' => return Err(Error::Newline),
            ',' => writer.write_str(r#"\,"#)?,
            ' ' => writer.write_str(r#"\ "#)?,
            _ => writer.write_char(c)?,
        }
    }

    for (key, value) in tag_set {
        write!(writer, ",")?;
        check_string_length(key)?;
        if key.starts_with('_') {
            return Err(Error::NamingRestrictions);
        }
        escape(&mut writer, key)?;
        write!(writer, "=")?;
        check_string_length(value)?;
        escape(&mut writer, value)?;
    }

    let mut count = 0;
    for (i, (key, value)) in field_set.into_iter().enumerate() {
        if i == 0 {
            write!(writer, " ")?;
        } else {
            write!(writer, ",")?;
        }
        check_string_length(key)?;
        if key.starts_with('_') {
            return Err(Error::NamingRestrictions);
        }
        escape(&mut writer, key)?;
        write!(writer, "=")?;
        value.to_writer(&mut writer)?;

        count += 1;
    }
    if count == 0 {
        return Err(Error::EmptyFieldSet);
    }

    if let Some(timestamp) = timestamp {
        write!(writer, " {}", timestamp)?;
    }
    write!(writer, "\n")?;
    Ok(())
}

pub fn to_string<'a, T, F>(
    measurement: &str,
    tag_set: T,
    field_set: F,
    timestamp: Option<i64>,
) -> Result<String, Error>
where
    T: IntoIterator<Item = (&'a str, &'a str)>,
    F: IntoIterator<Item = (&'a str, FieldValue<'a>)>,
{
    let mut string = String::new();
    to_writer(&mut string, measurement, tag_set, field_set, timestamp)?;
    Ok(string)
}

// For tag key, tag value, and field key
fn escape<W>(mut writer: W, value: &str) -> Result<(), Error>
where
    W: Write,
{
    for c in value.chars() {
        match c {
            '\n' => return Err(Error::Newline),
            ',' => writer.write_str(r#"\,"#)?,
            '=' => writer.write_str(r#"\="#)?,
            ' ' => writer.write_str(r#"\ "#)?,
            _ => writer.write_char(c)?,
        }
    }
    Ok(())
}

fn check_string_length(value: &str) -> Result<(), Error> {
    if value.len() <= 64 << 10 {
        Ok(())
    } else {
        Err(Error::StringLengthLimit)
    }
}

#[cfg(test)]
mod tests {
    use super::{to_string, FieldValue};
    use std::iter;

    #[test]
    fn test_to_string() {
        assert_eq!(
            to_string(
                "myMeasurement",
                vec![("tag1", "value1"), ("tag2", "value2")],
                vec![("fieldKey", FieldValue::String("fieldValue"))],
                Some(1556813561098000000),
            )
            .unwrap(),
            concat!(
                r#"myMeasurement,tag1=value1,tag2=value2 fieldKey="fieldValue" 1556813561098000000"#,
                "\n"
            ),
        );
        assert_eq!(
            to_string(
                "my Measurement",
                iter::empty(),
                vec![("fieldKey", FieldValue::String(r#"string value"#))],
                None,
            )
            .unwrap(),
            concat!(r#"my\ Measurement fieldKey="string value""#, "\n"),
        );
        assert_eq!(
            to_string(
                "myMeasurement",
                iter::empty(),
                vec![(
                    "fieldKey",
                    FieldValue::String(r#""string" within a string"#)
                )],
                None,
            )
            .unwrap(),
            concat!(
                r#"myMeasurement fieldKey="\"string\" within a string""#,
                "\n"
            ),
        );
        assert_eq!(
            to_string(
                "myMeasurement",
                vec![("tag Key1", "tag Value1"), ("tag Key2", "tag Value2")],
                vec![("fieldKey", FieldValue::Float(100.))],
                None,
            )
            .unwrap(),
            concat!(
                r#"myMeasurement,tag\ Key1=tag\ Value1,tag\ Key2=tag\ Value2 fieldKey=100"#,
                "\n"
            ),
        );
        assert_eq!(
            to_string(
                "myMeasurement",
                vec![("tagKey", "🍭")],
                vec![("fieldKey", FieldValue::String(r#"Launch 🚀"#))],
                Some(1556813561098000000),
            )
            .unwrap(),
            concat!(
                r#"myMeasurement,tagKey=🍭 fieldKey="Launch 🚀" 1556813561098000000"#,
                "\n"
            ),
        );

        assert_eq!(
            to_string(
                "myMeasurement",
                iter::empty(),
                vec![
                    ("fieldKey1", FieldValue::Float(1.)),
                    ("fieldKey2", FieldValue::Integer(2))
                ],
                None,
            )
            .unwrap(),
            concat!(r#"myMeasurement fieldKey1=1,fieldKey2=2i"#, "\n"),
        );
    }

    #[test]
    #[should_panic(expected = "NamingRestrictions")]
    fn test_to_string_naming_restrictions() {
        to_string(
            "_myMeasurement",
            iter::empty(),
            vec![("fieldKey", FieldValue::String("fieldValue"))],
            None,
        )
        .unwrap();
    }

    #[test]
    #[should_panic(expected = "EmptyFieldSet")]
    fn test_to_string_empty_field_set() {
        to_string("myMeasurement", iter::empty(), vec![], None).unwrap();
    }

    #[test]
    #[should_panic(expected = "StringLengthLimit")]
    fn test_to_string_string_length_limit() {
        let mut field_value = String::new();
        for _ in 0..=64 << 10 {
            field_value += "a"
        }
        to_string(
            "myMeasurement",
            iter::empty(),
            vec![("fieldKey", FieldValue::String(&field_value))],
            None,
        )
        .unwrap();
    }

    #[test]
    #[should_panic(expected = "Newline")]
    fn test_to_string_newline() {
        to_string(
            "myMeasurement",
            iter::empty(),
            vec![("fieldKey", FieldValue::String("field\nValue"))],
            None,
        )
        .unwrap();
    }
}