use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;
use serde_json::Value;
use std::sync::Arc;
use crate::remote_error::RemoteError;
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct StreamMetadata {
#[serde(default)]
pub provenance: Vec<String>,
#[serde(default)]
pub plexus_hash: String,
#[serde(default)]
pub timestamp: i64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum StreamItem {
Data {
#[serde(default, skip_serializing_if = "Option::is_none")]
metadata: Option<StreamMetadata>,
#[serde(default, skip_serializing_if = "Option::is_none")]
content_type: Option<String>,
content: Value,
},
Progress {
#[serde(default, skip_serializing_if = "Option::is_none")]
metadata: Option<StreamMetadata>,
#[serde(default, skip_serializing_if = "Option::is_none")]
content_type: Option<String>,
content: Value,
},
Error {
#[serde(default, skip_serializing_if = "Option::is_none")]
metadata: Option<StreamMetadata>,
#[serde(default)]
recoverable: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
code: Option<String>,
error: RemoteError,
#[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
fields: serde_json::Map<String, Value>,
},
Done {
#[serde(default, skip_serializing_if = "Option::is_none")]
metadata: Option<StreamMetadata>,
},
}
impl StreamItem {
pub fn data(content: Value) -> Self {
StreamItem::Data {
metadata: None,
content_type: None,
content,
}
}
pub fn done() -> Self {
StreamItem::Done { metadata: None }
}
pub fn is_terminal(&self) -> bool {
matches!(self, StreamItem::Done { .. } | StreamItem::Error { .. })
}
pub fn metadata(&self) -> Option<&StreamMetadata> {
match self {
StreamItem::Data { metadata, .. }
| StreamItem::Progress { metadata, .. }
| StreamItem::Error { metadata, .. }
| StreamItem::Done { metadata } => metadata.as_ref(),
}
}
}
#[derive(Debug, Clone)]
pub struct Content(Repr);
#[derive(Debug, Clone)]
enum Repr {
Text(Box<RawValue>),
Value(Value),
#[cfg_attr(not(any(feature = "ws-native", feature = "ws-web")), allow(dead_code))]
Frame(Box<str>, Option<(usize, usize)>),
}
#[derive(Deserialize)]
struct InFrame<C> {
params: InParams<C>,
}
#[derive(Deserialize)]
struct InParams<C> {
result: InItem<C>,
}
#[derive(Deserialize)]
struct InItem<C> {
content: C,
}
impl Content {
#[cfg_attr(not(any(feature = "ws-native", feature = "ws-web")), allow(dead_code))]
pub(crate) fn frame(text: &str, span: Option<std::ops::Range<usize>>) -> Self {
Content(Repr::Frame(text.into(), span.map(|s| (s.start, s.end))))
}
#[cfg(test)]
pub(crate) fn in_frame(&self) -> Option<bool> {
match self.0 {
Repr::Frame(_, span) => Some(span.is_some()),
_ => None,
}
}
pub fn as_text(&self) -> Option<&str> {
match &self.0 {
Repr::Text(text) => Some(text.get()),
Repr::Value(_) => None,
Repr::Frame(frame, _) => serde_json::from_str::<InFrame<&RawValue>>(frame).ok().map(|f| f.params.result.content.get()),
}
}
pub fn decode<E: DeserializeOwned>(self) -> Result<E, serde_json::Error> {
match self.0 {
Repr::Text(text) => serde_json::from_str(text.get()),
Repr::Value(value) => serde_json::from_value(value),
Repr::Frame(frame, span) => {
if let Some(event) = span.and_then(|(start, end)| serde_json::from_str(&frame[start..end]).ok()) {
return Ok(event);
}
serde_json::from_str::<InFrame<E>>(&frame).map(|f| f.params.result.content)
}
}
}
pub fn into_value(self) -> Result<Value, serde_json::Error> {
match self.0 {
Repr::Text(text) => serde_json::from_str(text.get()),
Repr::Value(value) => Ok(value),
Repr::Frame(..) => self.decode(),
}
}
}
impl From<Box<RawValue>> for Content {
fn from(text: Box<RawValue>) -> Self {
Content(Repr::Text(text))
}
}
impl From<Value> for Content {
fn from(value: Value) -> Self {
Content(Repr::Value(value))
}
}
#[derive(Debug, Clone)]
pub enum RawItem {
Data {
content_type: Option<Arc<str>>,
content: Content,
},
Progress {
content_type: Option<Arc<str>>,
content: Content,
},
Error {
message: Option<String>,
code: Option<String>,
recoverable: bool,
error: Box<RemoteError>,
},
Done,
}
impl RawItem {
pub fn is_terminal(&self) -> bool {
matches!(self, RawItem::Done | RawItem::Error { .. })
}
}
impl From<StreamItem> for RawItem {
fn from(item: StreamItem) -> Self {
match item {
StreamItem::Data { content_type, content, .. } => RawItem::Data {
content_type: content_type.map(Arc::from),
content: content.into(),
},
StreamItem::Progress { content_type, content, .. } => RawItem::Progress {
content_type: content_type.map(Arc::from),
content: content.into(),
},
StreamItem::Error { message, code, recoverable, error, .. } => RawItem::Error {
message,
code,
recoverable,
error: Box::new(error),
},
StreamItem::Done { .. } => RawItem::Done,
}
}
}