dw_models/
event.rs

1use chrono::DateTime;
2use chrono::Duration;
3use chrono::Utc;
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6use serde_json::Map;
7use serde_json::Value;
8
9use crate::duration::DurationSerialization;
10use crate::TimeInterval;
11
12#[derive(Serialize, Deserialize, JsonSchema, Clone, Debug)]
13pub struct Event {
14    /// An unique id for this event.
15    /// Will be assigned once the event has reached the servers datastore.
16    ///
17    /// **WARNING:** If you set the ID and insert the event to the server it will replace the previous
18    /// event with that ID. Only do this if you are completely sure what you are doing.
19    pub id: Option<i64>,
20    /// An rfc3339 timestamp which represents the start of the event
21    pub timestamp: DateTime<Utc>,
22    /// Duration of the event as a floating point number in seconds.
23    /// Appended to the timestamp it can represent the end of the event
24    /// Maximum precision is nanoseconds.
25    #[serde(with = "DurationSerialization", default = "default_duration")]
26    #[schemars(with = "f64")]
27    pub duration: Duration,
28    /// Can contain any arbitrary JSON data that represents the value of the event.
29    /// All events in a bucket should follow the format of it's respective bucket-type.
30    pub data: Map<String, Value>,
31}
32
33impl Event {
34    pub fn calculate_endtime(&self) -> DateTime<Utc> {
35        self.timestamp
36            + chrono::Duration::nanoseconds(self.duration.num_nanoseconds().unwrap() as i64)
37    }
38    pub fn interval(&self) -> TimeInterval {
39        TimeInterval::new(self.timestamp, self.calculate_endtime())
40    }
41}
42
43impl PartialEq for Event {
44    fn eq(&self, other: &Event) -> bool {
45        !(self.timestamp != other.timestamp
46            || self.duration != other.duration
47            || self.data != other.data)
48    }
49}
50
51impl Default for Event {
52    fn default() -> Self {
53        Event {
54            id: None,
55            timestamp: Utc::now(),
56            duration: Duration::seconds(0),
57            data: serde_json::Map::new(),
58        }
59    }
60}
61
62fn default_duration() -> Duration {
63    Duration::seconds(0)
64}
65
66#[test]
67fn test_event() {
68    use serde_json::json;
69
70    let e = Event {
71        id: None,
72        timestamp: Utc::now(),
73        duration: Duration::seconds(1),
74        data: json_map! {"test": json!(1)},
75    };
76    debug!("event: {:?}", e);
77}