summaryrefslogtreecommitdiffstats
path: root/crates/core/thin_edge_json/src/event.rs
blob: 474128ed0a079db06cdef9a04424fc7436d80afe (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
use clock::Timestamp;
use serde::Deserialize;

use self::error::ThinEdgeJsonDeserializerError;

/// In-memory representation of ThinEdge JSON event.
#[derive(Debug, Deserialize, PartialEq)]
pub struct ThinEdgeEvent {
    pub name: String,
    pub data: Option<ThinEdgeEventData>,
}

/// In-memory representation of ThinEdge JSON event payload
#[derive(Debug, Deserialize, PartialEq)]
pub struct ThinEdgeEventData {
    pub text: Option<String>,

    #[serde(default)]
    #[serde(with = "clock::serde::rfc3339::option")]
    pub time: Option<Timestamp>,
}

pub mod error {
    #[derive(thiserror::Error, Debug)]
    pub enum ThinEdgeJsonDeserializerError {
        #[error("Unsupported topic: {0}")]
        UnsupportedTopic(String),

        #[error("Event name can not be empty")]
        EmptyEventName,

        #[error(transparent)]
        SerdeJsonError(#[from] serde_json::error::Error),
    }
}

impl ThinEdgeEvent {
    pub fn try_from(
        mqtt_topic: &str,
        mqtt_payload: &str,
    ) -> Result<Self, ThinEdgeJsonDeserializerError> {
        let topic_split: Vec<&str> = mqtt_topic.split('/').collect();
        if topic_split.len() == 3 {
            let event_name = topic_split[2];
            if event_name.is_empty() {
                return Err(ThinEdgeJsonDeserializerError::EmptyEventName);
            }

            let event_data = if mqtt_payload.is_empty() {
                None
            } else {
                Some(serde_json::from_str(mqtt_payload)?)
            };

            Ok(Self {
                name: event_name.into(),
                data: event_data,
            })
        } else {
            Err(ThinEdgeJsonDeserializerError::UnsupportedTopic(
                mqtt_topic.into(),
            ))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use anyhow::Result;
    use assert_matches::assert_matches;
    use serde_json::{json, Value};
    use test_case::test_case;
    use time::macros::datetime;

    #[test_case(
        "tedge/events/click_event",
        json!({
            "text": "Someone clicked",
            "time": "2021-04-23T19:00:00+05:00",
        }),
        ThinEdgeEvent {
            name: "click_event".into(),
            data: Some(ThinEdgeEventData {
                text: Some("Someone clicked".into()),
                time: Some(datetime!(2021-04-23 19:00:00 +05:00)),
            }),
        };
        "event parsing"
    )]
    #[test_case(
        "tedge/events/click_event",
        json!({
            "text": "Someone clicked",
        }),
        ThinEdgeEvent {
            name: "click_event".into(),
            data: Some(ThinEdgeEventData {
                text: Some("Someone clicked".into()),
                time: None,
            }),
        };
        "event parsing without timestamp"
    )]
    #[test_case(
        "tedge/events/click_event",
        json!({
            "time": "2021-04-23T19:00:00+05:00",
        }),
        ThinEdgeEvent {
            name: "click_event".into(),
            data: Some(ThinEdgeEventData {
                text: None,
                time: Some(datetime!(2021-04-23 19:00:00 +05:00)),
            }),
        };
        "event parsing without text"
    )]
    #[test_case(
        "tedge/events/click_event",
        json!({}),
        ThinEdgeEvent {
            name: "click_event".into(),
            data: Some(ThinEdgeEventData {
                text: None,
                time: None,
            }),
        };
        "event parsing without text or timestamp"
    )]
    fn parse_thin_edge_event_json(
        event_topic: &str,
        event_payload: Value,
        expected_event: ThinEdgeEvent,
    ) {
        let event =
            ThinEdgeEvent::try_from(event_topic, event_payload.to_string().as_str()).unwrap();

        assert_eq!(event, expected_event);
    }

    #[test]
    fn event_translation_empty_event_name() {
        let result = ThinEdgeEvent::try_from("tedge/events/", "{}");

        assert_matches!(result, Err(ThinEdgeJsonDeserializerError::EmptyEventName));
    }

    #[test]
    fn event_translation_more_than_three_topic_levels() {
        let result = ThinEdgeEvent::try_from("tedge/events/page/click", "{}");

        assert_matches!(
            result,
            Err(ThinEdgeJsonDeserializerError::UnsupportedTopic(_))
        );
    }

    #[test]
    fn event_translation_empty_payload() -> Result<()> {
        let result = ThinEdgeEvent::try_from("tedge/events/click_event", "")?;
        assert_eq!(result.name, "click_event".to_string());
        assert_matches!(result.data, None);

        Ok(())
    }
}