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
// Author: D.S. Ljungmark <spider@skuggor.se>, Modio AB
// SPDX-License-Identifier: AGPL-3.0-or-later
use log::error;

use crate::types::Metric;

use std::sync::{Arc, Mutex};

#[derive(thiserror::Error, Debug)]
pub enum VecError {
    #[error("Mutex is poisoned")]
    Mutex,
}

use async_trait::async_trait;
// Async traits are unstable, and writing them manually is ugly as sin.  I cheat and use a macro

type BufMetric = (Metric, TimeStatus);
type BufMetrics = Vec<BufMetric>;

#[derive(Debug, Clone, Copy)]
pub(crate) enum TimeStatus {
    TimeFail,
    None,
}

#[async_trait]
pub(crate) trait Buffer {
    type Error: std::error::Error + Send + 'static;
    type Store: Send + 'static;
    async fn new() -> Result<Self::Store, Self::Error>;
    async fn add_metric(&self, metric: Metric, status: TimeStatus) -> Result<(), Self::Error>;
    async fn consume_metrics(&self) -> Result<BufMetrics, Self::Error>;
    async fn has_name(&self, name: &str) -> Result<bool, Self::Error>;
    async fn count(&self) -> Result<usize, Self::Error>;
    async fn oldest(&self) -> Result<i64, Self::Error>;
}

#[derive(Clone)]
pub(crate) struct VecBuffer {
    data: Arc<Mutex<BufMetrics>>,
}

#[async_trait]
impl Buffer for VecBuffer {
    type Error = VecError;
    type Store = VecBuffer;

    async fn new() -> Result<Self, Self::Error> {
        let inner: BufMetrics = Vec::with_capacity(100);
        let data = Arc::new(Mutex::new(inner));

        Ok(Self { data })
    }

    async fn add_metric(&self, metric: Metric, status: TimeStatus) -> Result<(), Self::Error> {
        let pair = (metric, status);
        {
            let inner = &mut self.data.lock().or(Err(VecError::Mutex))?;
            inner.push(pair);
        }
        Ok(())
    }

    async fn has_name(&self, name: &str) -> Result<bool, Self::Error> {
        let res = {
            let inner = &self.data.lock().or(Err(VecError::Mutex))?;
            inner.iter().any(|m| m.0.name == name)
        };
        Ok(res)
    }

    async fn count(&self) -> Result<usize, Self::Error> {
        let res = {
            let inner = &self.data.lock().or(Err(VecError::Mutex))?;
            inner.len()
        };
        Ok(res)
    }

    async fn oldest(&self) -> Result<i64, Self::Error> {
        let value = {
            let inner = &self.data.lock().or(Err(VecError::Mutex))?;
            let eldest = inner.iter().min_by_key(|m| m.0.time);
            if let Some(tup) = eldest {
                tup.0.time
            } else {
                0
            }
        };
        Ok(value)
    }

    async fn consume_metrics(&self) -> Result<BufMetrics, Self::Error> {
        let res = {
            let inner = &mut self.data.lock().or(Err(VecError::Mutex))?;
            inner.drain(..).collect()
        };
        Ok(res)
    }
}

#[must_use]
pub fn inixtime() -> i64 {
    use std::time::SystemTime;
    match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
        // If time wraps we have a bigger problem...
        #[allow(clippy::cast_possible_wrap)]
        Ok(n) => n.as_secs() as i64,
        Err(_) => 0,
    }
}

#[must_use]
pub fn unixtime() -> u64 {
    use std::time::SystemTime;
    match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
        Ok(n) => n.as_secs(),
        Err(_) => 0,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::error::Error;

    fn mtrc(name: &str, value: &str) -> Metric {
        Metric {
            name: name.to_string(),
            value: value.to_string(),
            time: inixtime(),
        }
    }

    #[tokio::test]
    async fn test_insert_remove() -> Result<(), Box<dyn Error>> {
        let ds = VecBuffer::new().await?;
        do_insert_remove(ds).await?;

        Ok(())
    }

    async fn do_insert_remove<T>(ds: T) -> Result<(), Box<dyn Error>>
    where
        T: Buffer,
    {
        let m = mtrc("test.case", "test.value");
        ds.add_metric(m, TimeStatus::None).await?;
        let m = mtrc("test.case", "test.value");
        ds.add_metric(m, TimeStatus::TimeFail).await?;
        // Should have two metrcis
        assert_eq!(2, ds.count().await?);

        // Drain should have two metrics too
        let drain = ds.consume_metrics().await?;
        assert_eq!(drain.len(), 2);

        // Should have zero metrics
        assert_eq!(0, ds.count().await?);

        // Should be zero when draining too
        let drain = ds.consume_metrics().await?;
        assert_eq!(drain.len(), 0);
        Ok(())
    }

    #[tokio::test]
    async fn test_keys() -> Result<(), Box<dyn Error>> {
        let ds = VecBuffer::new().await?;
        println!("Testing vectors");
        do_test_keys(ds).await?;
        Ok(())
    }

    async fn do_test_keys<Store>(ds: Store) -> Result<(), Box<dyn Error>>
    where
        Store: Buffer,
    {
        let m = Metric {
            name: "test.case.one".to_string(),
            value: "null".to_string(),
            time: 1234,
        };
        ds.add_metric(m, TimeStatus::None).await?;
        let m = mtrc("test.case.two", "test.value");
        ds.add_metric(m, TimeStatus::TimeFail).await?;

        // Should exist
        assert!(
            ds.has_name("test.case.one").await?,
            "Test case one should exist"
        );
        assert!(
            ds.has_name("test.case.two").await?,
            "Test case two should exist"
        );
        // Should not exist
        assert!(
            !ds.has_name("test.case.three").await?,
            "Three should not exist"
        );
        assert_eq!(1234, ds.oldest().await?, "1234 should be the oldest value");
        Ok(())
    }
}