Skip to main content

wse_client/
message.rs

1//! What the server sends, read in place: a [`Message`] borrows its frame,
2//! an [`OwnedMessage`] keeps it.
3
4use std::borrow::Cow;
5use std::fmt;
6use std::sync::Arc;
7
8use bytes::Bytes;
9use serde::Deserialize;
10
11use bytestring::ByteString;
12
13use crate::error::Error;
14
15/// Where a topic message stands in its topic: the epoch of the topic's
16/// history on the server that published it, and the offset within it.
17///
18/// A client that comes back asks for its topics from their last positions
19/// and gets what it missed.
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
21pub struct Position {
22    pub epoch: u32,
23    pub offset: u64,
24}
25
26impl fmt::Display for Position {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        write!(f, "{:08x}:{}", self.epoch, self.offset)
29    }
30}
31
32/// What proves who sent a signed message: keep all three.
33#[derive(Clone, Debug, PartialEq, Eq)]
34#[non_exhaustive]
35pub struct Signature {
36    /// The exact text that was signed: a JSON object.
37    pub body: String,
38    /// The ECDSA P-256 signature, `r || s` in base64.
39    pub sig: String,
40    /// The signing key's id: 8 bytes of SHA-256 of its public key, in hex.
41    pub kid: String,
42    /// Checked against a pinned server signing key; false when none is
43    /// pinned.
44    pub verified: bool,
45}
46
47/// The payload as it came: JSON text or a msgpack value.
48#[derive(Clone, Copy, Debug)]
49pub(crate) enum Payload<'a> {
50    None,
51    Json(&'a str),
52    Msgpack(&'a [u8]),
53}
54
55/// A message from the server, read in place from its frame: nothing is
56/// copied until the application asks for it.
57///
58/// [`payload`](Self::payload) decodes the payload into the application's own
59/// type, borrowing from the frame where the type does.
60#[derive(Clone, Debug)]
61pub struct Message<'a> {
62    pub(crate) kind: Cow<'a, str>,
63    pub(crate) category: Option<Cow<'a, str>>,
64    pub(crate) payload: Payload<'a>,
65    pub(crate) topic: Option<Cow<'a, str>>,
66    pub(crate) position: Option<Position>,
67    pub(crate) id: Option<Cow<'a, str>>,
68    pub(crate) correlation_id: Option<Cow<'a, str>>,
69    pub(crate) timestamp: Option<Cow<'a, str>>,
70    pub(crate) priority: Option<u8>,
71    pub(crate) signature: Option<Arc<Signature>>,
72    /// The frame the message was read from, when it is one the message can
73    /// keep without a copy.
74    pub(crate) frame: Option<&'a Bytes>,
75    /// The user generation it was handed out in: a commit counts in it only.
76    pub(crate) generation: u32,
77}
78
79impl<'a> Message<'a> {
80    /// The message type (`t`).
81    pub fn kind(&self) -> &str {
82        &self.kind
83    }
84
85    /// The category (`c`): `"U"` for updates, `"S"` for snapshots, `"WSE"`
86    /// for the server's own messages.
87    pub fn category(&self) -> Option<&str> {
88        self.category.as_deref()
89    }
90
91    /// The topic a topic message was published to.
92    pub fn topic(&self) -> Option<&str> {
93        self.topic.as_deref()
94    }
95
96    /// The message's position in its topic, when the server keeps the
97    /// topic's history.
98    pub fn position(&self) -> Option<Position> {
99        self.position
100    }
101
102    /// The message id (`id`).
103    pub fn id(&self) -> Option<&str> {
104        self.id.as_deref()
105    }
106
107    /// The correlation id (`cid`) pairing a reply with its request.
108    pub fn correlation_id(&self) -> Option<&str> {
109        self.correlation_id.as_deref()
110    }
111
112    /// When the server sent it (`ts`, ISO 8601).
113    pub fn timestamp(&self) -> Option<&str> {
114        self.timestamp.as_deref()
115    }
116
117    /// The priority (`pri`): 1 background, 3 low, 5 normal, 8 high, 10
118    /// critical.
119    pub fn priority(&self) -> Option<u8> {
120        self.priority
121    }
122
123    /// For a message the server signed: the proof.
124    pub fn signature(&self) -> Option<&Signature> {
125        self.signature.as_deref()
126    }
127
128    /// The payload (`p`) decoded into `T`, from JSON or msgpack as the
129    /// connection receives it. A message without a payload decodes as an
130    /// empty map.
131    pub fn payload<T: Deserialize<'a>>(&self) -> Result<T, Error> {
132        decode_payload(self.payload)
133    }
134
135    /// The payload's JSON text, on a JSON connection.
136    pub fn payload_json(&self) -> Option<&'a str> {
137        match self.payload {
138            Payload::Json(text) => Some(text),
139            _ => None,
140        }
141    }
142
143    /// The payload as a JSON value, whatever the wire format.
144    pub fn payload_value(&self) -> Result<serde_json::Value, Error> {
145        self.payload()
146    }
147
148    /// A copy the application can keep. The frame itself is shared, not
149    /// copied, where it can be.
150    pub fn to_owned(&self) -> OwnedMessage {
151        let frame = self.frame;
152        let text = |s: &Option<Cow<'a, str>>| s.as_deref().map(|s| keep_str(frame, s));
153        OwnedMessage {
154            kind: keep_str(frame, &self.kind),
155            category: text(&self.category),
156            topic: text(&self.topic),
157            id: text(&self.id),
158            correlation_id: text(&self.correlation_id),
159            timestamp: text(&self.timestamp),
160            position: self.position,
161            priority: self.priority,
162            signature: self.signature.clone(),
163            payload: match self.payload {
164                Payload::None => OwnedPayload::None,
165                Payload::Json(text) => OwnedPayload::Json(keep_str(frame, text)),
166                Payload::Msgpack(bytes) => OwnedPayload::Msgpack(keep(frame, bytes)),
167            },
168            generation: self.generation,
169        }
170    }
171}
172
173fn decode_payload<'a, T: Deserialize<'a>>(payload: Payload<'a>) -> Result<T, Error> {
174    match payload {
175        Payload::Json(text) => serde_json::from_str(text).map_err(|e| Error::Decode(e.to_string())),
176        Payload::Msgpack(bytes) => {
177            rmp_serde::from_slice(bytes).map_err(|e| Error::Decode(e.to_string()))
178        }
179        Payload::None => serde_json::from_str("{}").map_err(|e| Error::Decode(e.to_string())),
180    }
181}
182
183/// `part` as bytes the owned message keeps: a slice of the frame when it is
184/// one, else a copy.
185fn keep(frame: Option<&Bytes>, part: &[u8]) -> Bytes {
186    match frame {
187        Some(frame) if within(frame, part) => frame.slice_ref(part),
188        _ => Bytes::copy_from_slice(part),
189    }
190}
191
192fn keep_str(frame: Option<&Bytes>, part: &str) -> Text {
193    let bytes = keep(frame, part.as_bytes());
194    // SAFETY: `keep` returns the bytes of `part`, a slice of the frame or a
195    // copy: those of a `str`, UTF-8 already.
196    Text(unsafe { ByteString::from_bytes_unchecked(bytes) })
197}
198
199fn within(frame: &[u8], part: &[u8]) -> bool {
200    let start = frame.as_ptr() as usize;
201    let at = part.as_ptr() as usize;
202    at >= start && at + part.len() <= start + frame.len()
203}
204
205/// UTF-8 text kept as shared bytes, checked once.
206#[derive(Clone, PartialEq, Eq, Hash)]
207pub(crate) struct Text(ByteString);
208
209impl Text {
210    pub(crate) fn as_str(&self) -> &str {
211        &self.0
212    }
213}
214
215impl fmt::Debug for Text {
216    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217        fmt::Debug::fmt(self.as_str(), f)
218    }
219}
220
221#[derive(Clone, Debug)]
222pub(crate) enum OwnedPayload {
223    None,
224    Json(Text),
225    Msgpack(Bytes),
226}
227
228/// A message the application keeps: [`Message::to_owned`], or what the
229/// [`Events`](crate::Events) stream yields.
230#[derive(Clone, Debug)]
231pub struct OwnedMessage {
232    kind: Text,
233    category: Option<Text>,
234    topic: Option<Text>,
235    id: Option<Text>,
236    correlation_id: Option<Text>,
237    timestamp: Option<Text>,
238    position: Option<Position>,
239    priority: Option<u8>,
240    signature: Option<Arc<Signature>>,
241    payload: OwnedPayload,
242    /// The user generation it was handed out in.
243    pub(crate) generation: u32,
244}
245
246impl OwnedMessage {
247    /// A message of `kind` on `topic` at `position`, without a payload.
248    #[cfg(test)]
249    pub(crate) fn for_test(kind: &str, topic: Option<&str>, position: Option<Position>) -> Self {
250        Self {
251            kind: Text(ByteString::from(kind)),
252            category: None,
253            topic: topic.map(|t| Text(ByteString::from(t))),
254            id: None,
255            correlation_id: None,
256            timestamp: None,
257            position,
258            priority: None,
259            signature: None,
260            payload: OwnedPayload::None,
261            generation: 0,
262        }
263    }
264
265    /// The message type (`t`).
266    pub fn kind(&self) -> &str {
267        self.kind.as_str()
268    }
269
270    /// The category (`c`).
271    pub fn category(&self) -> Option<&str> {
272        self.category.as_ref().map(Text::as_str)
273    }
274
275    /// The topic a topic message was published to.
276    pub fn topic(&self) -> Option<&str> {
277        self.topic.as_ref().map(Text::as_str)
278    }
279
280    /// The message's position in its topic.
281    pub fn position(&self) -> Option<Position> {
282        self.position
283    }
284
285    /// The message id (`id`).
286    pub fn id(&self) -> Option<&str> {
287        self.id.as_ref().map(Text::as_str)
288    }
289
290    /// The correlation id (`cid`).
291    pub fn correlation_id(&self) -> Option<&str> {
292        self.correlation_id.as_ref().map(Text::as_str)
293    }
294
295    /// When the server sent it (`ts`).
296    pub fn timestamp(&self) -> Option<&str> {
297        self.timestamp.as_ref().map(Text::as_str)
298    }
299
300    /// The priority (`pri`).
301    pub fn priority(&self) -> Option<u8> {
302        self.priority
303    }
304
305    /// For a message the server signed: the proof.
306    pub fn signature(&self) -> Option<&Signature> {
307        self.signature.as_deref()
308    }
309
310    /// The payload (`p`) decoded into `T`.
311    pub fn payload<'a, T: Deserialize<'a>>(&'a self) -> Result<T, Error> {
312        decode_payload(self.payload_ref())
313    }
314
315    /// The payload's JSON text, on a JSON connection.
316    pub fn payload_json(&self) -> Option<&str> {
317        match &self.payload {
318            OwnedPayload::Json(text) => Some(text.as_str()),
319            _ => None,
320        }
321    }
322
323    /// The message carries a payload (`p`), whatever it is.
324    #[cfg_attr(not(feature = "native"), allow(dead_code))]
325    pub(crate) fn has_payload(&self) -> bool {
326        !matches!(self.payload, OwnedPayload::None)
327    }
328
329    fn payload_ref(&self) -> Payload<'_> {
330        match &self.payload {
331            OwnedPayload::None => Payload::None,
332            OwnedPayload::Json(text) => Payload::Json(text.as_str()),
333            OwnedPayload::Msgpack(bytes) => Payload::Msgpack(bytes),
334        }
335    }
336
337    /// The payload as a JSON value, whatever the wire format.
338    pub fn payload_value(&self) -> Result<serde_json::Value, Error> {
339        self.payload()
340    }
341
342    /// The message as a [`Message`] again, borrowing from this one.
343    pub fn as_message(&self) -> Message<'_> {
344        fn text(t: &Option<Text>) -> Option<Cow<'_, str>> {
345            t.as_ref().map(|t| Cow::Borrowed(t.as_str()))
346        }
347        Message {
348            kind: Cow::Borrowed(self.kind.as_str()),
349            category: text(&self.category),
350            topic: text(&self.topic),
351            id: text(&self.id),
352            correlation_id: text(&self.correlation_id),
353            timestamp: text(&self.timestamp),
354            position: self.position,
355            priority: self.priority,
356            payload: self.payload_ref(),
357            signature: self.signature.clone(),
358            frame: None,
359            generation: self.generation,
360        }
361    }
362}