1use 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#[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#[derive(Clone, Debug, PartialEq, Eq)]
34#[non_exhaustive]
35pub struct Signature {
36 pub body: String,
38 pub sig: String,
40 pub kid: String,
42 pub verified: bool,
45}
46
47#[derive(Clone, Copy, Debug)]
49pub(crate) enum Payload<'a> {
50 None,
51 Json(&'a str),
52 Msgpack(&'a [u8]),
53}
54
55#[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 pub(crate) frame: Option<&'a Bytes>,
75 pub(crate) generation: u32,
77}
78
79impl<'a> Message<'a> {
80 pub fn kind(&self) -> &str {
82 &self.kind
83 }
84
85 pub fn category(&self) -> Option<&str> {
88 self.category.as_deref()
89 }
90
91 pub fn topic(&self) -> Option<&str> {
93 self.topic.as_deref()
94 }
95
96 pub fn position(&self) -> Option<Position> {
99 self.position
100 }
101
102 pub fn id(&self) -> Option<&str> {
104 self.id.as_deref()
105 }
106
107 pub fn correlation_id(&self) -> Option<&str> {
109 self.correlation_id.as_deref()
110 }
111
112 pub fn timestamp(&self) -> Option<&str> {
114 self.timestamp.as_deref()
115 }
116
117 pub fn priority(&self) -> Option<u8> {
120 self.priority
121 }
122
123 pub fn signature(&self) -> Option<&Signature> {
125 self.signature.as_deref()
126 }
127
128 pub fn payload<T: Deserialize<'a>>(&self) -> Result<T, Error> {
132 decode_payload(self.payload)
133 }
134
135 pub fn payload_json(&self) -> Option<&'a str> {
137 match self.payload {
138 Payload::Json(text) => Some(text),
139 _ => None,
140 }
141 }
142
143 pub fn payload_value(&self) -> Result<serde_json::Value, Error> {
145 self.payload()
146 }
147
148 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
183fn 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 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#[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#[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 pub(crate) generation: u32,
244}
245
246impl OwnedMessage {
247 #[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 pub fn kind(&self) -> &str {
267 self.kind.as_str()
268 }
269
270 pub fn category(&self) -> Option<&str> {
272 self.category.as_ref().map(Text::as_str)
273 }
274
275 pub fn topic(&self) -> Option<&str> {
277 self.topic.as_ref().map(Text::as_str)
278 }
279
280 pub fn position(&self) -> Option<Position> {
282 self.position
283 }
284
285 pub fn id(&self) -> Option<&str> {
287 self.id.as_ref().map(Text::as_str)
288 }
289
290 pub fn correlation_id(&self) -> Option<&str> {
292 self.correlation_id.as_ref().map(Text::as_str)
293 }
294
295 pub fn timestamp(&self) -> Option<&str> {
297 self.timestamp.as_ref().map(Text::as_str)
298 }
299
300 pub fn priority(&self) -> Option<u8> {
302 self.priority
303 }
304
305 pub fn signature(&self) -> Option<&Signature> {
307 self.signature.as_deref()
308 }
309
310 pub fn payload<'a, T: Deserialize<'a>>(&'a self) -> Result<T, Error> {
312 decode_payload(self.payload_ref())
313 }
314
315 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 #[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 pub fn payload_value(&self) -> Result<serde_json::Value, Error> {
339 self.payload()
340 }
341
342 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}