use std::borrow::Cow;
use std::fmt;
use std::sync::Arc;
use bytes::Bytes;
use serde::Deserialize;
use bytestring::ByteString;
use crate::error::Error;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Position {
pub epoch: u32,
pub offset: u64,
}
impl fmt::Display for Position {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:08x}:{}", self.epoch, self.offset)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Signature {
pub body: String,
pub sig: String,
pub kid: String,
pub verified: bool,
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum Payload<'a> {
None,
Json(&'a str),
Msgpack(&'a [u8]),
}
#[derive(Clone, Debug)]
pub struct Message<'a> {
pub(crate) kind: Cow<'a, str>,
pub(crate) category: Option<Cow<'a, str>>,
pub(crate) payload: Payload<'a>,
pub(crate) topic: Option<Cow<'a, str>>,
pub(crate) position: Option<Position>,
pub(crate) id: Option<Cow<'a, str>>,
pub(crate) correlation_id: Option<Cow<'a, str>>,
pub(crate) timestamp: Option<Cow<'a, str>>,
pub(crate) priority: Option<u8>,
pub(crate) signature: Option<Arc<Signature>>,
pub(crate) frame: Option<&'a Bytes>,
pub(crate) generation: u32,
}
impl<'a> Message<'a> {
pub fn kind(&self) -> &str {
&self.kind
}
pub fn category(&self) -> Option<&str> {
self.category.as_deref()
}
pub fn topic(&self) -> Option<&str> {
self.topic.as_deref()
}
pub fn position(&self) -> Option<Position> {
self.position
}
pub fn id(&self) -> Option<&str> {
self.id.as_deref()
}
pub fn correlation_id(&self) -> Option<&str> {
self.correlation_id.as_deref()
}
pub fn timestamp(&self) -> Option<&str> {
self.timestamp.as_deref()
}
pub fn priority(&self) -> Option<u8> {
self.priority
}
pub fn signature(&self) -> Option<&Signature> {
self.signature.as_deref()
}
pub fn payload<T: Deserialize<'a>>(&self) -> Result<T, Error> {
decode_payload(self.payload)
}
pub fn payload_json(&self) -> Option<&'a str> {
match self.payload {
Payload::Json(text) => Some(text),
_ => None,
}
}
pub fn payload_value(&self) -> Result<serde_json::Value, Error> {
self.payload()
}
pub fn to_owned(&self) -> OwnedMessage {
let frame = self.frame;
let text = |s: &Option<Cow<'a, str>>| s.as_deref().map(|s| keep_str(frame, s));
OwnedMessage {
kind: keep_str(frame, &self.kind),
category: text(&self.category),
topic: text(&self.topic),
id: text(&self.id),
correlation_id: text(&self.correlation_id),
timestamp: text(&self.timestamp),
position: self.position,
priority: self.priority,
signature: self.signature.clone(),
payload: match self.payload {
Payload::None => OwnedPayload::None,
Payload::Json(text) => OwnedPayload::Json(keep_str(frame, text)),
Payload::Msgpack(bytes) => OwnedPayload::Msgpack(keep(frame, bytes)),
},
generation: self.generation,
}
}
}
fn decode_payload<'a, T: Deserialize<'a>>(payload: Payload<'a>) -> Result<T, Error> {
match payload {
Payload::Json(text) => serde_json::from_str(text).map_err(|e| Error::Decode(e.to_string())),
Payload::Msgpack(bytes) => {
rmp_serde::from_slice(bytes).map_err(|e| Error::Decode(e.to_string()))
}
Payload::None => serde_json::from_str("{}").map_err(|e| Error::Decode(e.to_string())),
}
}
fn keep(frame: Option<&Bytes>, part: &[u8]) -> Bytes {
match frame {
Some(frame) if within(frame, part) => frame.slice_ref(part),
_ => Bytes::copy_from_slice(part),
}
}
fn keep_str(frame: Option<&Bytes>, part: &str) -> Text {
let bytes = keep(frame, part.as_bytes());
Text(unsafe { ByteString::from_bytes_unchecked(bytes) })
}
fn within(frame: &[u8], part: &[u8]) -> bool {
let start = frame.as_ptr() as usize;
let at = part.as_ptr() as usize;
at >= start && at + part.len() <= start + frame.len()
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub(crate) struct Text(ByteString);
impl Text {
pub(crate) fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for Text {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.as_str(), f)
}
}
#[derive(Clone, Debug)]
pub(crate) enum OwnedPayload {
None,
Json(Text),
Msgpack(Bytes),
}
#[derive(Clone, Debug)]
pub struct OwnedMessage {
kind: Text,
category: Option<Text>,
topic: Option<Text>,
id: Option<Text>,
correlation_id: Option<Text>,
timestamp: Option<Text>,
position: Option<Position>,
priority: Option<u8>,
signature: Option<Arc<Signature>>,
payload: OwnedPayload,
pub(crate) generation: u32,
}
impl OwnedMessage {
#[cfg(test)]
pub(crate) fn for_test(kind: &str, topic: Option<&str>, position: Option<Position>) -> Self {
Self {
kind: Text(ByteString::from(kind)),
category: None,
topic: topic.map(|t| Text(ByteString::from(t))),
id: None,
correlation_id: None,
timestamp: None,
position,
priority: None,
signature: None,
payload: OwnedPayload::None,
generation: 0,
}
}
pub fn kind(&self) -> &str {
self.kind.as_str()
}
pub fn category(&self) -> Option<&str> {
self.category.as_ref().map(Text::as_str)
}
pub fn topic(&self) -> Option<&str> {
self.topic.as_ref().map(Text::as_str)
}
pub fn position(&self) -> Option<Position> {
self.position
}
pub fn id(&self) -> Option<&str> {
self.id.as_ref().map(Text::as_str)
}
pub fn correlation_id(&self) -> Option<&str> {
self.correlation_id.as_ref().map(Text::as_str)
}
pub fn timestamp(&self) -> Option<&str> {
self.timestamp.as_ref().map(Text::as_str)
}
pub fn priority(&self) -> Option<u8> {
self.priority
}
pub fn signature(&self) -> Option<&Signature> {
self.signature.as_deref()
}
pub fn payload<'a, T: Deserialize<'a>>(&'a self) -> Result<T, Error> {
decode_payload(self.payload_ref())
}
pub fn payload_json(&self) -> Option<&str> {
match &self.payload {
OwnedPayload::Json(text) => Some(text.as_str()),
_ => None,
}
}
#[cfg_attr(not(feature = "native"), allow(dead_code))]
pub(crate) fn has_payload(&self) -> bool {
!matches!(self.payload, OwnedPayload::None)
}
fn payload_ref(&self) -> Payload<'_> {
match &self.payload {
OwnedPayload::None => Payload::None,
OwnedPayload::Json(text) => Payload::Json(text.as_str()),
OwnedPayload::Msgpack(bytes) => Payload::Msgpack(bytes),
}
}
pub fn payload_value(&self) -> Result<serde_json::Value, Error> {
self.payload()
}
pub fn as_message(&self) -> Message<'_> {
fn text(t: &Option<Text>) -> Option<Cow<'_, str>> {
t.as_ref().map(|t| Cow::Borrowed(t.as_str()))
}
Message {
kind: Cow::Borrowed(self.kind.as_str()),
category: text(&self.category),
topic: text(&self.topic),
id: text(&self.id),
correlation_id: text(&self.correlation_id),
timestamp: text(&self.timestamp),
position: self.position,
priority: self.priority,
payload: self.payload_ref(),
signature: self.signature.clone(),
frame: None,
generation: self.generation,
}
}
}