summaryrefslogtreecommitdiffstats
path: root/crates/core/thin_edge_json/src/group.rs
blob: 706812dc255e7ce52b3d95f7b2093f1ece36ae26 (plain)
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
351
352
353
354
355
use std::collections::HashMap;
use time::OffsetDateTime;

use crate::measurement::MeasurementVisitor;

#[derive(Debug)]
pub struct MeasurementGroup {
    timestamp: Option<OffsetDateTime>,
    values: HashMap<String, Measurement>,
}

impl MeasurementGroup {
    fn new() -> Self {
        Self {
            timestamp: None,
            values: HashMap::new(),
        }
    }

    pub fn timestamp(&self) -> Option<OffsetDateTime> {
        self.timestamp
    }

    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    pub fn get_measurement_value(
        &self,
        group_key: Option<&str>,
        measurement_key: &str,
    ) -> Option<f64> {
        match group_key {
            Some(group_key) => match self.values.get(group_key) {
                Some(Measurement::Multi(map)) => map.get(measurement_key).cloned(),
                _ => None,
            },
            None => match self.values.get(measurement_key) {
                Some(Measurement::Single(val)) => Some(*val),
                _ => None,
            },
        }
    }

    pub fn accept<V, E>(&self, visitor: &mut V) -> Result<(), E>
    where
        V: MeasurementVisitor<Error = E>,
        E: std::error::Error + std::fmt::Debug,
    {
        if let Some(timestamp) = self.timestamp {
            visitor.visit_timestamp(timestamp)?;
        }

        for (key, value) in self.values.iter() {
            match value {
                Measurement::Single(sv) => {
                    visitor.visit_measurement(key, *sv)?;
                }
                Measurement::Multi(m) => {
                    visitor.visit_start_group(key)?;
                    for (key, value) in m.iter() {
                        visitor.visit_measurement(key, *value)?;
                    }
                    visitor.visit_end_group()?;
                }
            }
        }
        Ok(())
    }
}

#[derive(Debug)]
pub struct MeasurementGrouper {
    measurement_group: MeasurementGroup,
    group_state: GroupState,
}

/// Keeps track whether we are currently in a group or not.
/// This serves the same purpose an `Option<String>` would do, just that
/// the `String` is not allocated over and over again.
#[derive(Debug)]
struct GroupState {
    in_group: bool,
    group: String,
}

#[derive(Debug)]
pub enum Measurement {
    Single(f64),
    Multi(HashMap<String, f64>),
}

#[derive(thiserror::Error, Debug)]
pub enum MeasurementGrouperError {
    #[error("Duplicated measurement: {0}")]
    DuplicatedMeasurement(String),

    #[error("Duplicated measurement: {0}.{1}")]
    DuplicatedSubMeasurement(String, String),

    #[error("Unexpected end")]
    UnexpectedEnd,

    #[error("Unexpected start of group")]
    UnexpectedStartOfGroup,

    #[error("Unexpected end of group")]
    UnexpectedEndOfGroup,
}

impl MeasurementGrouper {
    pub fn new() -> Self {
        Self {
            measurement_group: MeasurementGroup::new(),
            group_state: GroupState {
                in_group: false,
                group: String::with_capacity(20),
            },
        }
    }

    pub fn end(self) -> Result<MeasurementGroup, MeasurementGrouperError> {
        if self.group_state.in_group {
            Err(MeasurementGrouperError::UnexpectedEnd)
        } else {
            Ok(self.measurement_group)
        }
    }
}

impl Default for MeasurementGrouper {
    fn default() -> Self {
        Self::new()
    }
}

impl MeasurementVisitor for MeasurementGrouper {
    type Error = MeasurementGrouperError;

    fn visit_timestamp(&mut self, time: OffsetDateTime) -> Result<(), Self::Error> {
        self.measurement_group.timestamp = Some(time);
        Ok(())
    }

    fn visit_start_group(&mut self, group: &str) -> Result<(), Self::Error> {
        if self.group_state.in_group {
            Err(MeasurementGrouperError::UnexpectedStartOfGroup)
        } else {
            self.group_state.in_group = true;
            self.group_state.group.replace_range(.., group);
            Ok(())
        }
    }

    fn visit_end_group(&mut self) -> Result<(), Self::Error> {
        if self.group_state.in_group {
            self.group_state.in_group = false;
            self.group_state.group.clear();
            Ok(())
        } else {
            Err(MeasurementGrouperError::UnexpectedEndOfGroup)
        }
    }

    fn visit_measurement(&mut self, name: &str, value: f64) -> Result<(), Self::Error> {
        let key = name.to_owned();

        match self.group_state.in_group {
            false => {
                self.measurement_group
                    .values
                    .insert(key, Measurement::Single(value));
                Ok(())
            }
            true => {
                let group_key = self.group_state.group.clone();
                if let Measurement::Multi(group_map) = self
                    .measurement_group
                    .values
                    .entry(group_key)
                    .or_insert_with(|| Measurement::Multi(HashMap::new()))
                {
                    group_map.insert(name.to_owned(), value);
                }
                Ok(())
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use mockall::predicate::*;
    use mockall::*;
    use time::{macros::datetime, Duration};

    #[derive(thiserror::Error, Debug, Clone)]
    pub enum TestError {
        #[error("test")]
        _Test,
    }

    mock! {
        pub GroupedVisitor {
        }

        impl MeasurementVisitor for GroupedVisitor {
            type Error = TestError;

            fn visit_timestamp(&mut self, value: OffsetDateTime) -> Result<(), TestError>;
            fn visit_measurement(&mut self, name: &str, value: f64) -> Result<(), TestError>;
            fn visit_start_group(&mut self, group: &str) -> Result<(), TestError>;
            fn visit_end_group(&mut self) -> Result<(), TestError>;
        }
    }

    // XXX: These test cases should be split into those test cases that test the MeasurementGrouper and
    // those that test the MeasurementGroup.
    #[test]
    fn new_measurement_grouper_is_empty() -> anyhow::Result<()> {
        let grouper = MeasurementGrouper::new();
        let group = grouper.end()?;
        assert!(group.is_empty());

        Ok(())
    }

    #[test]
    fn empty_measurement_group_visits_nothing() -> anyhow::Result<()> {
        let group = MeasurementGroup::new();

        let mut mock = MockGroupedVisitor::new();
        mock.expect_visit_measurement().never();
        mock.expect_visit_start_group().never();
        mock.expect_visit_end_group().never();

        let _ = group.accept(&mut mock)?;

        Ok(())
    }

    #[test]
    fn new_measurement_grouper_with_a_timestamp_is_empty() -> anyhow::Result<()> {
        let mut grouper = MeasurementGrouper::new();
        let _ = grouper.visit_timestamp(test_timestamp(4));

        let