1#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md"))]
2
3use std::{
5 collections::VecDeque,
6 num::ParseIntError,
7 str::Utf8Error,
8 task::{Context, Poll, ready},
9};
10
11use bytes::Buf;
12use futures_util::{Stream, TryStreamExt, stream::MapOk};
13use http_body::{Body, Frame};
14use http_body_util::{BodyDataStream, StreamBody};
15
16pin_project_lite::pin_project! {
17 pub struct SseStream<B: Body> {
18 #[pin]
19 body: BodyDataStream<B>,
20 parsed: VecDeque<Sse>,
21 current: Option<Sse>,
22 unfinished_line: Vec<u8>,
23 }
24}
25
26pub type ByteStreamBody<S, D> = StreamBody<MapOk<S, fn(D) -> Frame<D>>>;
27impl<E, S, D> SseStream<ByteStreamBody<S, D>>
28where
29 S: Stream<Item = Result<D, E>>,
30 E: std::error::Error,
31 D: Buf,
32 StreamBody<ByteStreamBody<S, D>>: Body,
33{
34 pub fn from_byte_stream(stream: S) -> Self {
38 let stream = stream.map_ok(http_body::Frame::data as fn(D) -> Frame<D>);
39 let body = StreamBody::new(stream);
40 Self {
41 body: BodyDataStream::new(body),
42 parsed: VecDeque::new(),
43 current: None,
44 unfinished_line: Vec::new(),
45 }
46 }
47}
48
49impl<B: Body> SseStream<B> {
50 pub fn new(body: B) -> Self {
52 Self {
53 body: BodyDataStream::new(body),
54 parsed: VecDeque::new(),
55 current: None,
56 unfinished_line: Vec::new(),
57 }
58 }
59}
60
61#[derive(Default, Debug)]
62pub struct Sse {
63 pub event: Option<String>,
64 pub data: Option<String>,
65 pub id: Option<String>,
66 pub retry: Option<u64>,
67}
68
69impl Sse {
70 pub fn is_event(&self) -> bool {
71 self.event.is_some()
72 }
73 pub fn is_message(&self) -> bool {
74 self.event.is_none()
75 }
76}
77
78pub enum Error {
79 Body(Box<dyn std::error::Error + Send + Sync>),
80 InvalidLine,
81 DuplicatedEventLine,
82 DuplicatedIdLine,
83 DuplicatedRetry,
84 Utf8Parse(Utf8Error),
85 IntParse(ParseIntError),
86}
87
88impl std::fmt::Display for Error {
89 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90 match self {
91 Error::Body(e) => write!(f, "body error: {}", e),
92 Error::InvalidLine => write!(f, "invalid line"),
93 Error::DuplicatedEventLine => write!(f, "duplicated event line"),
94 Error::DuplicatedIdLine => write!(f, "duplicated id line"),
95 Error::DuplicatedRetry => write!(f, "duplicated retry line"),
96 Error::Utf8Parse(e) => write!(f, "utf8 parse error: {}", e),
97 Error::IntParse(e) => write!(f, "int parse error: {}", e),
98 }
99 }
100}
101
102impl std::fmt::Debug for Error {
103 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104 match self {
105 Error::Body(e) => write!(f, "Body({:?})", e),
106 Error::InvalidLine => write!(f, "InvalidLine"),
107 Error::DuplicatedEventLine => write!(f, "DuplicatedEventLine"),
108 Error::DuplicatedIdLine => write!(f, "DuplicatedIdLine"),
109 Error::DuplicatedRetry => write!(f, "DuplicatedRetry"),
110 Error::Utf8Parse(e) => write!(f, "Utf8Parse({:?})", e),
111 Error::IntParse(e) => write!(f, "IntParse({:?})", e),
112 }
113 }
114}
115
116impl std::error::Error for Error {
117 fn description(&self) -> &str {
118 match self {
119 Error::Body(_) => "body error",
120 Error::InvalidLine => "invalid line",
121 Error::DuplicatedEventLine => "duplicated event line",
122 Error::DuplicatedIdLine => "duplicated id line",
123 Error::DuplicatedRetry => "duplicated retry line",
124 Error::Utf8Parse(_) => "utf8 parse error",
125 Error::IntParse(_) => "int parse error",
126 }
127 }
128
129 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
130 match self {
131 Error::Body(e) => Some(e.as_ref()),
132 Error::Utf8Parse(e) => Some(e),
133 Error::IntParse(e) => Some(e),
134 _ => None,
135 }
136 }
137}
138
139impl<B: Body> Stream for SseStream<B>
140where
141 B::Error: std::error::Error + Send + Sync + 'static,
142{
143 type Item = Result<Sse, Error>;
144
145 fn poll_next(
146 mut self: std::pin::Pin<&mut Self>,
147 cx: &mut Context<'_>,
148 ) -> Poll<Option<Self::Item>> {
149 let this = self.as_mut().project();
150 if let Some(sse) = this.parsed.pop_front() {
151 return Poll::Ready(Some(Ok(sse)));
152 }
153 let next_data = ready!(this.body.poll_next(cx));
154 match next_data {
155 Some(Ok(data)) => {
156 let chunk = data.chunk();
157 if chunk.is_empty() {
158 return self.poll_next(cx);
159 }
160 let mut lines = chunk.chunk_by(|maybe_nl, _| *maybe_nl != b'\n');
161 let first_line = lines.next().expect("frame is empty");
162 let mut new_unfinished_line = Vec::new();
163 let first_line = if !this.unfinished_line.is_empty() {
164 this.unfinished_line.extend(first_line);
165 std::mem::swap(&mut new_unfinished_line, this.unfinished_line);
166 new_unfinished_line.as_ref()
167 } else {
168 first_line
169 };
170 let mut lines = std::iter::once(first_line).chain(lines);
171 *this.unfinished_line = loop {
172 let Some(line) = lines.next() else {
173 break Vec::new();
174 };
175 if line.last().copied() != Some(b'\n') {
176 break line.to_vec();
177 }
178 let line = &line[..line.len() - 1];
180 if line.is_empty() {
181 if let Some(sse) = this.current.take() {
182 this.parsed.push_back(sse);
183 }
184 continue;
185 }
186 let Some(comma_index) = line.iter().position(|b| *b == b':') else {
188 return Poll::Ready(Some(Err(Error::InvalidLine)));
189 };
190 let field_name = &line[..comma_index];
191 let field_value = if line.len() > comma_index + 2 {
192 &line[comma_index + 2..]
193 } else {
194 b""
195 };
196 match field_name {
197 b"data" => {
198 let data_line =
199 std::str::from_utf8(field_value).map_err(Error::Utf8Parse)?;
200 if let Some(Sse { data, .. }) = this.current.as_mut() {
202 if data.is_none() {
203 data.replace(data_line.to_owned());
204 } else {
205 let data = data.as_mut().unwrap();
206 data.push('\n');
207 data.push_str(data_line);
208 }
209 } else {
210 this.current.replace(Sse {
211 event: None,
212 data: Some(data_line.to_owned()),
213 id: None,
214 retry: None,
215 });
216 }
217 }
218 b"event" => {
219 let event_value =
220 std::str::from_utf8(field_value).map_err(Error::Utf8Parse)?;
221 if let Some(Sse { event, .. }) = this.current.as_mut() {
222 if event.is_some() {
223 return Poll::Ready(Some(Err(Error::DuplicatedEventLine)));
224 } else {
225 event.replace(event_value.to_owned());
226 }
227 } else {
228 this.current.replace(Sse {
229 event: Some(event_value.to_owned()),
230 ..Default::default()
231 });
232 }
233 }
234 b"id" => {
235 let id_value =
236 std::str::from_utf8(field_value).map_err(Error::Utf8Parse)?;
237 if let Some(Sse { id, .. }) = this.current.as_mut() {
238 if id.is_some() {
239 return Poll::Ready(Some(Err(Error::DuplicatedIdLine)));
240 } else {
241 id.replace(id_value.to_owned());
242 }
243 } else {
244 this.current.replace(Sse {
245 id: Some(id_value.to_owned()),
246 ..Default::default()
247 });
248 }
249 }
250 b"retry" => {
251 let retry_value = std::str::from_utf8(field_value)
252 .map_err(Error::Utf8Parse)?
253 .trim_ascii();
254 let retry_value =
255 retry_value.parse::<u64>().map_err(Error::IntParse)?;
256 if let Some(Sse { retry, .. }) = this.current.as_mut() {
257 if retry.is_some() {
258 return Poll::Ready(Some(Err(Error::DuplicatedRetry)));
259 } else {
260 retry.replace(retry_value);
261 }
262 } else {
263 this.current.replace(Sse {
264 retry: Some(retry_value),
265 ..Default::default()
266 });
267 }
268 }
269 b"" => {
270 #[cfg(feature = "tracing")]
271 if tracing::enabled!(tracing::Level::DEBUG) {
272 let comment =
274 std::str::from_utf8(field_value).map_err(Error::Utf8Parse)?;
275 tracing::debug!(?comment, "sse comment line");
276 }
277 }
278 _ => {
279 return Poll::Ready(Some(Err(Error::InvalidLine)));
280 }
281 }
282 };
283 self.poll_next(cx)
284 }
285 Some(Err(e)) => Poll::Ready(Some(Err(Error::Body(Box::new(e))))),
286 None => {
287 if let Some(sse) = this.current.take() {
288 Poll::Ready(Some(Ok(sse)))
289 } else {
290 Poll::Ready(None)
291 }
292 }
293 }
294 }
295}