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
use crate::encoding::format::common::get_serializer_schema_requirement;
use bytes::{BufMut, BytesMut};
use tokio_util::codec::Encoder;
use vector_config_macros::configurable_component;
use vector_core::{config::DataType, event::Event, schema};

use crate::MetricTagValues;

/// Config used to build a `TextSerializer`.
#[configurable_component]
#[derive(Debug, Clone, Default)]
pub struct TextSerializerConfig {
    /// Controls how metric tag values are encoded.
    ///
    /// When set to `single`, only the last non-bare value of tags are displayed with the
    /// metric.  When set to `full`, all metric tags are exposed as separate assignments.
    #[serde(default, skip_serializing_if = "vector_core::serde::is_default")]
    pub metric_tag_values: MetricTagValues,
}

impl TextSerializerConfig {
    /// Creates a new `TextSerializerConfig`.
    pub const fn new(metric_tag_values: MetricTagValues) -> Self {
        Self { metric_tag_values }
    }

    /// Build the `TextSerializer` from this configuration.
    pub const fn build(&self) -> TextSerializer {
        TextSerializer::new(self.metric_tag_values)
    }

    /// The data type of events that are accepted by `TextSerializer`.
    pub fn input_type(&self) -> DataType {
        DataType::Log | DataType::Metric
    }

    /// The schema required by the serializer.
    pub fn schema_requirement(&self) -> schema::Requirement {
        get_serializer_schema_requirement()
    }
}

/// Serializer that converts a log to bytes by extracting the message key, or converts a metric
/// to bytes by calling its `Display` implementation.
///
/// This serializer exists to emulate the behavior of the `StandardEncoding::Text` for backwards
/// compatibility, until it is phased out completely.
#[derive(Debug, Clone)]
pub struct TextSerializer {
    metric_tag_values: MetricTagValues,
}

impl TextSerializer {
    /// Creates a new `TextSerializer`.
    pub const fn new(metric_tag_values: MetricTagValues) -> Self {
        Self { metric_tag_values }
    }
}

impl Encoder<Event> for TextSerializer {
    type Error = vector_common::Error;

    fn encode(&mut self, event: Event, buffer: &mut BytesMut) -> Result<(), Self::Error> {
        match event {
            Event::Log(log) => {
                if let Some(bytes) = log.get_message().map(|value| value.coerce_to_bytes()) {
                    buffer.put(bytes);
                }
            }
            Event::Metric(mut metric) => {
                if self.metric_tag_values == MetricTagValues::Single {
                    metric.reduce_tags_to_single();
                }
                let bytes = metric.to_string();
                buffer.put(bytes.as_ref());
            }
            Event::Trace(_) => {}
        };

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use bytes::{Bytes, BytesMut};
    use vector_core::event::{LogEvent, Metric, MetricKind, MetricValue};
    use vector_core::metric_tags;

    use super::*;

    #[test]
    fn serialize_log() {
        let buffer = serialize(
            TextSerializerConfig::default(),
            Event::from(LogEvent::from_str_legacy("foo")),
        );
        assert_eq!(buffer, Bytes::from("foo"));
    }

    #[test]
    fn serialize_metric() {
        let buffer = serialize(
            TextSerializerConfig::default(),
            Event::Metric(Metric::new(
                "users",
                MetricKind::Incremental,
                MetricValue::Set {
                    values: vec!["bob".into()].into_iter().collect(),
                },
            )),
        );
        assert_eq!(buffer, Bytes::from("users{} + bob"));
    }

    #[test]
    fn serialize_metric_tags_full() {
        let buffer = serialize(
            TextSerializerConfig {
                metric_tag_values: MetricTagValues::Full,
            },
            metric2(),
        );
        assert_eq!(
            buffer,
            Bytes::from(r#"counter{a="first",a,a="second"} + 1"#)
        );
    }

    #[test]
    fn serialize_metric_tags_single() {
        let buffer = serialize(
            TextSerializerConfig {
                metric_tag_values: MetricTagValues::Single,
            },
            metric2(),
        );
        assert_eq!(buffer, Bytes::from(r#"counter{a="second"} + 1"#));
    }

    fn metric2() -> Event {
        Event::Metric(
            Metric::new(
                "counter",
                MetricKind::Incremental,
                MetricValue::Counter { value: 1.0 },
            )
            .with_tags(Some(metric_tags! (
                "a" => "first",
                "a" => None,
                "a" => "second",
            ))),
        )
    }

    fn serialize(config: TextSerializerConfig, input: Event) -> Bytes {
        let mut buffer = BytesMut::new();
        config.build().encode(input, &mut buffer).unwrap();
        buffer.freeze()
    }
}