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