cloudevents/event/
message.rs

1use super::Data;
2use super::Event;
3use super::{Attributes, AttributesReader};
4use crate::event::SpecVersion;
5use crate::message::{
6    BinaryDeserializer, BinarySerializer, MessageAttributeValue, Result, StructuredDeserializer,
7    StructuredSerializer,
8};
9use crate::{EventBuilder, EventBuilderV03, EventBuilderV10};
10
11impl StructuredDeserializer for Event {
12    fn deserialize_structured<R, V: StructuredSerializer<R>>(self, visitor: V) -> Result<R> {
13        let vec: Vec<u8> = serde_json::to_vec(&self)?;
14        visitor.set_structured_event(vec)
15    }
16}
17
18impl BinaryDeserializer for Event {
19    fn deserialize_binary<R: Sized, V: BinarySerializer<R>>(self, mut visitor: V) -> Result<R> {
20        visitor = visitor.set_spec_version(self.specversion())?;
21        visitor = self.attributes.deserialize_attributes(visitor)?;
22        for (k, v) in self.extensions.into_iter() {
23            visitor = visitor.set_extension(&k, v.into())?;
24        }
25        match self.data {
26            Some(Data::String(s)) => visitor.end_with_data(s.into_bytes()),
27            Some(Data::Binary(v)) => visitor.end_with_data(v),
28            Some(Data::Json(j)) => {
29                let vec: Vec<u8> = serde_json::to_vec(&j)?;
30                visitor.end_with_data(vec)
31            }
32            None => visitor.end(),
33        }
34    }
35}
36
37pub(crate) trait AttributesDeserializer {
38    fn deserialize_attributes<R: Sized, V: BinarySerializer<R>>(self, visitor: V) -> Result<V>;
39}
40
41impl AttributesDeserializer for Attributes {
42    fn deserialize_attributes<R: Sized, V: BinarySerializer<R>>(self, visitor: V) -> Result<V> {
43        match self {
44            Attributes::V03(v03) => v03.deserialize_attributes(visitor),
45            Attributes::V10(v10) => v10.deserialize_attributes(visitor),
46        }
47    }
48}
49
50pub(crate) trait AttributesSerializer {
51    fn serialize_attribute(&mut self, name: &str, value: MessageAttributeValue) -> Result<()>;
52}
53
54#[derive(Debug)]
55pub(crate) struct EventStructuredSerializer {}
56
57impl StructuredSerializer<Event> for EventStructuredSerializer {
58    fn set_structured_event(self, bytes: Vec<u8>) -> Result<Event> {
59        Ok(serde_json::from_slice(&bytes)?)
60    }
61}
62
63#[derive(Debug)]
64pub(crate) enum EventBinarySerializer {
65    V10(EventBuilderV10),
66    V03(EventBuilderV03),
67}
68
69impl EventBinarySerializer {
70    pub(crate) fn new() -> Self {
71        EventBinarySerializer::V10(EventBuilderV10::new())
72    }
73}
74
75impl BinarySerializer<Event> for EventBinarySerializer {
76    fn set_spec_version(self, spec_version: SpecVersion) -> Result<Self> {
77        Ok(match spec_version {
78            SpecVersion::V03 => EventBinarySerializer::V03(EventBuilderV03::new()),
79            SpecVersion::V10 => EventBinarySerializer::V10(EventBuilderV10::new()),
80        })
81    }
82
83    fn set_attribute(mut self, name: &str, value: MessageAttributeValue) -> Result<Self> {
84        match &mut self {
85            EventBinarySerializer::V03(eb) => eb.serialize_attribute(name, value)?,
86            EventBinarySerializer::V10(eb) => eb.serialize_attribute(name, value)?,
87        }
88        Ok(self)
89    }
90
91    fn set_extension(self, name: &str, value: MessageAttributeValue) -> Result<Self> {
92        Ok(match self {
93            EventBinarySerializer::V03(eb) => EventBinarySerializer::V03(eb.extension(name, value)),
94            EventBinarySerializer::V10(eb) => EventBinarySerializer::V10(eb.extension(name, value)),
95        })
96    }
97
98    fn end_with_data(self, bytes: Vec<u8>) -> Result<Event> {
99        Ok(match self {
100            EventBinarySerializer::V03(eb) => {
101                eb.data_without_content_type(Data::Binary(bytes)).build()
102            }
103            EventBinarySerializer::V10(eb) => {
104                eb.data_without_content_type(Data::Binary(bytes)).build()
105            }
106        }?)
107    }
108
109    fn end(self) -> Result<Event> {
110        Ok(match self {
111            EventBinarySerializer::V03(eb) => eb.build(),
112            EventBinarySerializer::V10(eb) => eb.build(),
113        }?)
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120    use crate::message::Error;
121    use crate::test::fixtures;
122    use std::convert::TryInto;
123
124    #[test]
125    fn binary_deserializer_unrecognized_attribute_v03() {
126        assert_eq!(
127            Error::UnknownAttribute {
128                name: "dataschema".to_string()
129            }
130            .to_string(),
131            EventBinarySerializer::new()
132                .set_spec_version(SpecVersion::V03)
133                .unwrap()
134                .set_attribute("dataschema", MessageAttributeValue::Boolean(true))
135                .expect_err("Should return an error")
136                .to_string()
137        )
138    }
139
140    #[test]
141    fn binary_deserializer_missing_id() {
142        assert_eq!(
143            Error::EventBuilderError {
144                source: crate::event::EventBuilderError::MissingRequiredAttribute {
145                    attribute_name: "id"
146                },
147            }
148            .to_string(),
149            EventBinarySerializer::new()
150                .set_spec_version(SpecVersion::V10)
151                .unwrap()
152                .end()
153                .unwrap_err()
154                .to_string()
155        )
156    }
157
158    #[test]
159    fn binary_deserializer_unrecognized_attribute_v10() {
160        assert_eq!(
161            Error::UnknownAttribute {
162                name: "schemaurl".to_string()
163            }
164            .to_string(),
165            EventBinarySerializer::new()
166                .set_spec_version(SpecVersion::V10)
167                .unwrap()
168                .set_attribute("schemaurl", MessageAttributeValue::Boolean(true))
169                .expect_err("Should return an error")
170                .to_string()
171        )
172    }
173
174    #[test]
175    fn message_v03_roundtrip_structured() -> Result<()> {
176        assert_eq!(
177            fixtures::v03::full_json_data(),
178            StructuredDeserializer::into_event(fixtures::v03::full_json_data())?
179        );
180        Ok(())
181    }
182
183    #[test]
184    fn message_v03_roundtrip_binary() -> Result<()> {
185        //TODO this code smells because we're missing a proper way in the public APIs
186        // to destructure an event and rebuild it
187        let wanna_be_expected = fixtures::v03::full_json_data();
188        let data: serde_json::Value = wanna_be_expected.data().unwrap().clone().try_into()?;
189        let bytes = serde_json::to_vec(&data)?;
190        let expected = EventBuilderV03::from(wanna_be_expected.clone())
191            .data(wanna_be_expected.datacontenttype().unwrap(), bytes)
192            .build()
193            .unwrap();
194
195        assert_eq!(
196            expected,
197            BinaryDeserializer::into_event(fixtures::v03::full_json_data())?
198        );
199        Ok(())
200    }
201
202    #[test]
203    fn message_v03_msgpack() {
204        let buff = rmp_serde::to_vec(&fixtures::v03::full_json_data()).unwrap();
205        let event = rmp_serde::from_slice::<Event>(buff.as_slice()).unwrap();
206        assert_eq!(event, fixtures::v03::full_json_data(),);
207    }
208
209    #[test]
210    fn message_v10_roundtrip_structured() -> Result<()> {
211        assert_eq!(
212            fixtures::v10::full_json_data(),
213            StructuredDeserializer::into_event(fixtures::v10::full_json_data())?
214        );
215        Ok(())
216    }
217
218    #[test]
219    fn message_v10_roundtrip_binary() -> Result<()> {
220        //TODO this code smells because we're missing a proper way in the public APIs
221        // to destructure an event and rebuild it
222        let wanna_be_expected = fixtures::v10::full_json_data();
223        let data: serde_json::Value = wanna_be_expected
224            .data()
225            .cloned()
226            .unwrap()
227            .try_into()
228            .unwrap();
229        let bytes = serde_json::to_vec(&data)?;
230        let expected = EventBuilderV10::from(wanna_be_expected.clone())
231            .data(wanna_be_expected.datacontenttype().unwrap(), bytes)
232            .build()
233            .unwrap();
234
235        assert_eq!(
236            expected,
237            BinaryDeserializer::into_event(fixtures::v10::full_json_data())?
238        );
239        Ok(())
240    }
241
242    #[test]
243    fn message_v10_msgpack() {
244        let buff = rmp_serde::to_vec(&fixtures::v10::full_json_data()).unwrap();
245        let event = rmp_serde::from_slice::<Event>(buff.as_slice()).unwrap();
246        assert_eq!(event, fixtures::v10::full_json_data(),);
247    }
248}