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
use chrono;

use std::collections::BTreeMap;

use ::metadata;
use ::errors::Errors;

pub mod types;
pub mod ops;
pub mod generate;


/// The standard way of storing numerical data in this crate.
pub type Number = f64;

/// The standard way of representing a time interval in this crate
type Interval = i64;

/// Represents a time series.
type RawTimeSeries = BTreeMap<chrono::DateTime<chrono::Utc>, types::MetricTypes>;

/// A TimeSeries corresponds to a group of metrics that
/// share common MetaData.
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
pub struct TimeSeries {
    pub data: RawTimeSeries,
    #[serde(default)]
    pub meta_data: metadata::MetaData,
}

impl TimeSeries {
    /// Given two time series, some common keys and an vector operator
    /// we can use this to join two time series together.
    /// To do this we find all the common keys and then apply the vector operator
    /// to the metrics.
    pub fn join(&self, rhs: &Self, terms: Vec<String>, vo: ops::Ops) -> Option<Self> {
        let mut joined = Self::default();
        // Don't use MetaDataFilters here to avoid compiling regexes
        let own_labels = self.meta_data.get_labels();
        let rhs_labels = rhs.meta_data.get_labels();

        // Ensure that all of the terms exist in both LHS and RHS
        // and if they don't then return `None`. Otherwise create
        // the joined `TimeSeries`.
        for term in terms {
            match own_labels.get(&term) {
                Some(t1) => match rhs_labels.get(&term) {
                    Some(t2) => {
                        if t1 == t2 {
                            joined.meta_data.add_label(&term, t1);
                        }
                    }
                    None => return None,
                },
                None => return None,
            }
        }
        Some(joined)
    }

    /// Shifts a TimeSeries backwards by an offset of time
    pub fn shift(&self, offset: chrono::Duration) -> Self {
        TimeSeries {
            data: self.data
                .iter()
                .map(|(&t, m)| (t + offset, m.clone()))
                .collect::<RawTimeSeries>(),
            meta_data: self.meta_data.clone(),
        }
    }

    /// Merges two TimeSeries into a single `TimeSeries`. If a common
    /// key exists then the value of the RHS is dropped.
    /// If one of the LHS or RHS contains a superset of `MetaData`
    /// of the other then those specific fields are dropped to
    /// create a single `TimeSeries`
    pub fn merge(&self, rhs: Self) -> Result<Self, Errors> {
        // We don't need to check for equality because a superset
        // includes equality
        let mut s = self.clone();
        let mut r = rhs.clone();
        if s.meta_data.superset(&r.meta_data) {
            // Check if LHS is a superset of RHS.
            r.clone().data.append(&mut s.data);
            return Ok(r);
        } else if r.meta_data.superset(&s.meta_data) {
            // Check if RHS is a superset of LHS.
            s.clone().data.append(&mut r.data);
            return Ok(s);
        }
        return Err(Errors::MergeError);
    }
}