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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
use std::{cmp::Ordering, collections::BTreeMap};

use async_graphql::{Enum, InputObject, Object};

use crate::{
    api::schema::{
        filter::{filter_items, CustomFilter, StringFilter},
        metrics::{self, MetricsFilter},
        relay, sort,
    },
    event::Metric,
    filter_check,
};

#[derive(Clone)]
pub struct FileSourceMetricFile<'a> {
    name: String,
    metrics: Vec<&'a Metric>,
}

impl<'a> FileSourceMetricFile<'a> {
    /// Returns a new FileSourceMetricFile from a (name, Vec<&Metric>) tuple
    #[allow(clippy::missing_const_for_fn)] // const cannot run destructor
    fn from_tuple((name, metrics): (String, Vec<&'a Metric>)) -> Self {
        Self { name, metrics }
    }

    pub fn get_name(&self) -> &str {
        self.name.as_str()
    }
}

#[Object]
impl<'a> FileSourceMetricFile<'a> {
    /// File name
    async fn name(&self) -> &str {
        &*self.name
    }

    /// Metric indicating bytes received for the current file
    async fn received_bytes_total(&self) -> Option<metrics::ReceivedBytesTotal> {
        self.metrics.received_bytes_total()
    }

    /// Metric indicating received events for the current file
    async fn received_events_total(&self) -> Option<metrics::ReceivedEventsTotal> {
        self.metrics.received_events_total()
    }

    /// Metric indicating outgoing events for the current file
    async fn sent_events_total(&self) -> Option<metrics::SentEventsTotal> {
        self.metrics.sent_events_total()
    }
}

#[derive(Debug, Clone)]
pub struct FileSourceMetrics(Vec<Metric>);

impl FileSourceMetrics {
    pub const fn new(metrics: Vec<Metric>) -> Self {
        Self(metrics)
    }

    pub fn get_files(&self) -> Vec<FileSourceMetricFile<'_>> {
        self.0
            .iter()
            .filter_map(|m| m.tag_value("file").map(|file| (file, m)))
            .fold(
                BTreeMap::new(),
                |mut map: BTreeMap<String, Vec<&Metric>>, (file, m)| {
                    map.entry(file).or_default().push(m);
                    map
                },
            )
            .into_iter()
            .map(FileSourceMetricFile::from_tuple)
            .collect()
    }
}

#[derive(Enum, Copy, Clone, Eq, PartialEq)]
pub enum FileSourceMetricFilesSortFieldName {
    Name,
    ReceivedBytesTotal,
    ReceivedEventsTotal,
    SentEventsTotal,
}

impl sort::SortableByField<FileSourceMetricFilesSortFieldName> for FileSourceMetricFile<'_> {
    fn sort(&self, rhs: &Self, field: &FileSourceMetricFilesSortFieldName) -> Ordering {
        match field {
            FileSourceMetricFilesSortFieldName::Name => Ord::cmp(&self.name, &rhs.name),
            FileSourceMetricFilesSortFieldName::ReceivedBytesTotal => Ord::cmp(
                &self
                    .metrics
                    .received_bytes_total()
                    .map(|m| m.get_received_bytes_total() as i64)
                    .unwrap_or(0),
                &rhs.metrics
                    .received_bytes_total()
                    .map(|m| m.get_received_bytes_total() as i64)
                    .unwrap_or(0),
            ),
            FileSourceMetricFilesSortFieldName::ReceivedEventsTotal => Ord::cmp(
                &self
                    .metrics
                    .received_events_total()
                    .map(|m| m.get_received_events_total() as i64)
                    .unwrap_or(0),
                &rhs.metrics
                    .received_events_total()
                    .map(|m| m.get_received_events_total() as i64)
                    .unwrap_or(0),
            ),
            FileSourceMetricFilesSortFieldName::SentEventsTotal => Ord::cmp(
                &self
                    .metrics
                    .sent_events_total()
                    .map(|m| m.get_sent_events_total() as i64)
                    .unwrap_or(0),
                &rhs.metrics
                    .sent_events_total()
                    .map(|m| m.get_sent_events_total() as i64)
                    .unwrap_or(0),
            ),
        }
    }
}

#[derive(Default, InputObject)]
pub struct FileSourceMetricsFilesFilter {
    name: Option<Vec<StringFilter>>,
    or: Option<Vec<Self>>,
}

impl CustomFilter<FileSourceMetricFile<'_>> for FileSourceMetricsFilesFilter {
    fn matches(&self, file: &FileSourceMetricFile<'_>) -> bool {
        filter_check!(self
            .name
            .as_ref()
            .map(|f| f.iter().all(|f| f.filter_value(file.get_name()))));
        true
    }

    fn or(&self) -> Option<&Vec<Self>> {
        self.or.as_ref()
    }
}

#[allow(clippy::too_many_arguments)]
#[Object]
impl FileSourceMetrics {
    /// File metrics
    pub async fn files(
        &self,
        after: Option<String>,
        before: Option<String>,
        first: Option<i32>,
        last: Option<i32>,
        filter: Option<FileSourceMetricsFilesFilter>,
        sort: Option<Vec<sort::SortField<FileSourceMetricFilesSortFieldName>>>,
    ) -> relay::ConnectionResult<FileSourceMetricFile<'_>> {
        let filter = filter.unwrap_or_default();
        let mut files = filter_items(self.get_files().into_iter(), &filter);

        if let Some(sort_fields) = sort {
            sort::by_fields(&mut files, &sort_fields);
        }

        relay::query(
            files.into_iter(),
            relay::Params::new(after, before, first, last),
            10,
        )
        .await
    }

    /// Total received bytes for the current file source
    pub async fn received_bytes_total(&self) -> Option<metrics::ReceivedBytesTotal> {
        self.0.received_bytes_total()
    }

    /// Total received events for the current file source
    pub async fn received_events_total(&self) -> Option<metrics::ReceivedEventsTotal> {
        self.0.received_events_total()
    }

    /// Total sent events for the current file source
    pub async fn sent_events_total(&self) -> Option<metrics::SentEventsTotal> {
        self.0.sent_events_total()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        api::schema::sort::SortField,
        event::{MetricKind, MetricValue},
    };

    struct FileSourceMetricTest {
        name: &'static str,
        events_metric: Metric,
        bytes_metric: Metric,
    }

    impl FileSourceMetricTest {
        fn new(name: &'static str, events_processed: f64, bytes_processed: f64) -> Self {
            Self {
                name,
                events_metric: metric("component_sent_events_total", events_processed),
                bytes_metric: metric("component_received_bytes_total", bytes_processed),
            }
        }

        fn get_metric(&self) -> FileSourceMetricFile {
            FileSourceMetricFile::from_tuple((
                self.name.to_string(),
                vec![&self.bytes_metric, &self.events_metric],
            ))
        }
    }

    fn metric(name: &str, value: f64) -> Metric {
        Metric::new(
            name,
            MetricKind::Incremental,
            MetricValue::Counter { value },
        )
    }

    fn by_name(name: &'static str) -> FileSourceMetricTest {
        FileSourceMetricTest::new(name, 0.00, 0.00)
    }

    #[test]
    fn sort_name_asc() {
        let t1 = by_name("/path/to/file/2");
        let t2 = by_name("/path/to/file/3");
        let t3 = by_name("/path/to/file/1");

        let mut files = vec![t1.get_metric(), t2.get_metric(), t3.get_metric()];
        let fields = vec![SortField::<FileSourceMetricFilesSortFieldName> {
            field: FileSourceMetricFilesSortFieldName::Name,
            direction: sort::Direction::Asc,
        }];

        sort::by_fields(&mut files, &fields);

        for (i, f) in ["1", "2", "3"].iter().enumerate() {
            assert_eq!(files[i].name.as_str(), format!("/path/to/file/{}", f));
        }
    }

    #[test]
    fn sort_name_desc() {
        let t1 = by_name("/path/to/file/2");
        let t2 = by_name("/path/to/file/3");
        let t3 = by_name("/path/to/file/1");

        let mut files = vec![t1.get_metric(), t2.get_metric(), t3.get_metric()];
        let fields = vec![SortField::<FileSourceMetricFilesSortFieldName> {
            field: FileSourceMetricFilesSortFieldName::Name,
            direction: sort::Direction::Desc,
        }];

        sort::by_fields(&mut files, &fields);

        for (i, f) in ["3", "2", "1"].iter().enumerate() {
            assert_eq!(files[i].name.as_str(), format!("/path/to/file/{}", f));
        }
    }

    #[test]
    fn processed_events_asc() {
        let t1 = FileSourceMetricTest::new("a", 1000.00, 100.00);
        let t2 = FileSourceMetricTest::new("b", 500.00, 300.00);
        let t3 = FileSourceMetricTest::new("c", 250.00, 200.00);

        let mut files = vec![t1.get_metric(), t2.get_metric(), t3.get_metric()];
        let fields = vec![SortField::<FileSourceMetricFilesSortFieldName> {
            field: FileSourceMetricFilesSortFieldName::SentEventsTotal,
            direction: sort::Direction::Asc,
        }];

        sort::by_fields(&mut files, &fields);

        for (i, f) in ["c", "b", "a"].iter().enumerate() {
            assert_eq!(&files[i].name, *f);
        }
    }

    #[test]
    fn processed_events_desc() {
        let t1 = FileSourceMetricTest::new("a", 1000.00, 100.00);
        let t2 = FileSourceMetricTest::new("b", 500.00, 300.00);
        let t3 = FileSourceMetricTest::new("c", 250.00, 200.00);

        let mut files = vec![t1.get_metric(), t2.get_metric(), t3.get_metric()];
        let fields = vec![SortField::<FileSourceMetricFilesSortFieldName> {
            field: FileSourceMetricFilesSortFieldName::SentEventsTotal,
            direction: sort::Direction::Desc,
        }];

        sort::by_fields(&mut files, &fields);

        for (i, f) in ["a", "b", "c"].iter().enumerate() {
            assert_eq!(&files[i].name, *f);
        }
    }

    #[test]
    fn received_bytes_asc() {
        let t1 = FileSourceMetricTest::new("a", 1000.00, 100.00);
        let t2 = FileSourceMetricTest::new("b", 500.00, 300.00);
        let t3 = FileSourceMetricTest::new("c", 250.00, 200.00);

        let mut files = vec![t1.get_metric(), t2.get_metric(), t3.get_metric()];
        let fields = vec![SortField::<FileSourceMetricFilesSortFieldName> {
            field: FileSourceMetricFilesSortFieldName::ReceivedBytesTotal,
            direction: sort::Direction::Asc,
        }];

        sort::by_fields(&mut files, &fields);

        for (i, f) in ["a", "c", "b"].iter().enumerate() {
            assert_eq!(&files[i].name, *f);
        }
    }

    #[test]
    fn received_bytes_desc() {
        let t1 = FileSourceMetricTest::new("a", 1000.00, 100.00);
        let t2 = FileSourceMetricTest::new("b", 500.00, 300.00);
        let t3 = FileSourceMetricTest::new("c", 250.00, 200.00);

        let mut files = vec![t1.get_metric(), t2.get_metric(), t3.get_metric()];
        let fields = vec![SortField::<FileSourceMetricFilesSortFieldName> {
            field: FileSourceMetricFilesSortFieldName::ReceivedBytesTotal,
            direction: sort::Direction::Desc,
        }];

        sort::by_fields(&mut files, &fields);

        for (i, f) in ["b", "c", "a"].iter().enumerate() {
            assert_eq!(&files[i].name, *f);
        }
    }
}