use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll, ready};
use bytes::Bytes;
use futures::Stream;
use pin_project_lite::pin_project;
use sse_stream::SseByteStream;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum SseError {
#[error("utf-8 decode error: {0}")]
Utf8(#[source] std::str::Utf8Error),
#[error("stream error: {0}")]
Stream(#[source] Box<dyn std::error::Error + Send + Sync>),
#[error("SSE decode error: {0}")]
Decode(#[source] sse_stream::Error),
}
impl From<sse_stream::Error> for SseError {
fn from(error: sse_stream::Error) -> Self {
match error {
sse_stream::Error::Body(source) => Self::Stream(source),
sse_stream::Error::Utf8Parse(source) => Self::Utf8(source),
other => Self::Decode(other),
}
}
}
#[derive(Debug, Clone, Default)]
pub struct SseEvent {
pub event: Option<String>,
pub data: String,
pub id: Option<String>,
pub retry: Option<u64>,
}
pin_project! {
pub struct SseStream<S, E>
where
S: Stream<Item = Result<Bytes, E>>,
{
#[pin]
inner: SseByteStream<S>,
_err: PhantomData<E>,
}
}
impl<S, E> SseStream<S, E>
where
S: Stream<Item = Result<Bytes, E>>,
{
pub fn new(stream: S) -> Self {
Self {
inner: SseByteStream::new(stream),
_err: PhantomData,
}
}
}
impl<S, E> Stream for SseStream<S, E>
where
S: Stream<Item = Result<Bytes, E>>,
E: std::error::Error + Send + Sync + 'static,
{
type Item = Result<SseEvent, SseError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project();
loop {
match ready!(this.inner.as_mut().poll_next(cx)) {
None => return Poll::Ready(None),
Some(Err(error)) => return Poll::Ready(Some(Err(error.into()))),
Some(Ok(block)) => {
let Some(data) = block.data else { continue };
return Poll::Ready(Some(Ok(SseEvent {
event: block.event.filter(|event| !event.is_empty()),
data,
id: block.id,
retry: block.retry,
})));
}
}
}
}
}