Skip to main content

cent/
payload.rs

1//! Payloads to and from application types: [`json`] and [`PayloadExt`].
2
3use serde::{Deserialize, Serialize};
4use serde_json::value::RawValue;
5
6use crate::Error;
7use crate::error::PayloadError;
8
9/// Encodes `value` as a payload, for the `data`, `info` and other payload
10/// fields of requests and proxy results:
11///
12/// ```
13/// # fn run() -> Result<(), cent::Error> {
14/// #[derive(serde::Serialize)]
15/// struct Message { text: String }
16///
17/// let request = cent::PublishRequest::new("news")
18///     .data(cent::json(&Message { text: "hello".into() })?);
19/// let request = cent::PublishRequest::new("news")
20///     .data(cent::json(&serde_json::json!({"text": "hello"}))?);
21/// # Ok(()) }
22/// ```
23///
24/// A [`serde_json::Value`] - or any type serde can encode - goes in as it
25/// encodes; a payload already JSON text is [`RawValue::from_string`].
26///
27/// # Errors
28///
29/// [`Error::Payload`] when `value` cannot be encoded: a map whose keys are not
30/// strings, or a `Serialize` impl's own error.
31pub fn json<T: Serialize + ?Sized>(value: &T) -> Result<Box<RawValue>, Error> {
32    serde_json::value::to_raw_value(value).map_err(|e| Error::Payload(PayloadError::encode(e)))
33}
34
35/// Decodes a payload into an application type: a publication's `data`, a
36/// proxy request's `data`, a presence entry's `conn_info`.
37///
38/// ```
39/// use cent::PayloadExt;
40///
41/// #[derive(serde::Deserialize)]
42/// struct Message { text: String }
43///
44/// # fn run(publication: cent::Publication) -> Result<(), cent::Error> {
45/// let message: Message = publication.data.decode()?;
46/// # Ok(()) }
47/// ```
48///
49/// It works on a payload field - an `Option<Box<RawValue>>`, where `None`
50/// is an error - and on a [`RawValue`] itself.
51pub trait PayloadExt: sealed::Sealed {
52    /// Decodes the payload as a `T`.
53    ///
54    /// # Errors
55    ///
56    /// [`Error::Payload`] when the payload is not a `T`, or is unset.
57    fn decode<'a, T: Deserialize<'a>>(&'a self) -> Result<T, Error>;
58}
59
60impl PayloadExt for RawValue {
61    fn decode<'a, T: Deserialize<'a>>(&'a self) -> Result<T, Error> {
62        serde_json::from_str(self.get()).map_err(|e| Error::Payload(PayloadError::decode(e)))
63    }
64}
65
66impl PayloadExt for Box<RawValue> {
67    fn decode<'a, T: Deserialize<'a>>(&'a self) -> Result<T, Error> {
68        (**self).decode()
69    }
70}
71
72impl PayloadExt for Option<Box<RawValue>> {
73    fn decode<'a, T: Deserialize<'a>>(&'a self) -> Result<T, Error> {
74        self.as_deref()
75            .ok_or_else(|| Error::Payload(PayloadError::missing()))?
76            .decode()
77    }
78}
79
80mod sealed {
81    use serde_json::value::RawValue;
82
83    pub trait Sealed {}
84    impl Sealed for RawValue {}
85    impl Sealed for Box<RawValue> {}
86    impl Sealed for Option<Box<RawValue>> {}
87}
88
89#[cfg(test)]
90mod tests {
91    #![allow(clippy::unwrap_used)]
92    use super::*;
93
94    #[derive(Debug, PartialEq, Serialize, Deserialize)]
95    struct Message {
96        text: String,
97    }
98
99    #[test]
100    fn round_trip() {
101        let raw = json(&Message { text: "hi".into() }).unwrap();
102        assert_eq!(raw.get(), r#"{"text":"hi"}"#);
103        assert_eq!(
104            raw.decode::<Message>().unwrap(),
105            Message { text: "hi".into() }
106        );
107        assert_eq!(
108            Some(raw).decode::<Message>().unwrap(),
109            Message { text: "hi".into() }
110        );
111        // Borrowed from the payload.
112        let raw = json("x").unwrap();
113        assert_eq!(raw.decode::<&str>().unwrap(), "x");
114    }
115
116    #[test]
117    fn errors() {
118        let mut keys = std::collections::HashMap::new();
119        keys.insert((1, 2), 3);
120        let e = json(&keys).unwrap_err();
121        assert!(matches!(e, Error::Payload(_)), "{e}");
122        assert!(e.to_string().starts_with("encoding the payload: "), "{e}");
123        assert!(!e.is_retryable());
124
125        let e = json("x").unwrap().decode::<Message>().unwrap_err();
126        assert!(e.to_string().starts_with("decoding the payload: "), "{e}");
127        assert!(std::error::Error::source(&e).is_some());
128        let e = None::<Box<RawValue>>.decode::<Message>().unwrap_err();
129        assert_eq!(e.to_string(), "decoding the payload: no payload");
130    }
131}