use reqwest::Response; use std::mem; use tokio_stream::{Stream, StreamExt}; use tokio_util::{ codec::{Decoder, FramedRead, LinesCodec, LinesCodecError}, io::StreamReader, }; use tracing::warn; static EVENT: &str = "event: "; static DATA: &str = "data: "; static ID: &str = "id: "; static RETRY: &str = "retry: "; /// Extension trait for converting an HTTP response into a stream of [`ServerSentEvent`]s. pub trait EventSource { /// Consumes the response and returns a stream of parsed SSE events. fn event_stream(self) -> impl Stream>; } impl EventSource for Response { fn event_stream(self) -> impl Stream> { stream_response(self) } } /// A parsed Server-Sent Event. #[derive(Debug, Default, Clone)] pub struct ServerSentEvent { pub event: Option, /// The event payload (from one or more `data:` fields, joined by `\n`). pub data: Option, pub id: Option, pub retry: Option, } /// [`Decoder`] that parses a byte stream of SSE-formatted data into [`ServerSentEvent`]s. pub struct ServerSentEventsCodec { lines_codec: LinesCodec, next: ServerSentEvent, } impl Default for ServerSentEventsCodec { fn default() -> Self { Self::new() } } impl ServerSentEventsCodec { pub fn new() -> Self { Self { lines_codec: LinesCodec::new(), next: Default::default(), } } } impl Decoder for ServerSentEventsCodec { type Item = ServerSentEvent; type Error = LinesCodecError; fn decode( &mut self, src: &mut tokio_util::bytes::BytesMut, ) -> Result, Self::Error> { // Keep reading lines until an event is complete: returning `None` // tells `FramedRead` to wait for more bytes, even if `src` still // holds the rest of the event. while let Some(mut line) = self.lines_codec.decode(src)? { if line.is_empty() { return Ok(Some(mem::take(&mut self.next))); } if line.starts_with(EVENT) { line.drain(..EVENT.len()); self.next.event = Some(line); } else if line.starts_with(DATA) { line.drain(..DATA.len()); if let Some(ref mut existing) = self.next.data { existing.push('\n'); existing.push_str(&line); } else { self.next.data = Some(line); } } else if line.starts_with(ID) { line.drain(..ID.len()); self.next.id = Some(line); } else if line.starts_with(RETRY) { line.drain(..RETRY.len()); let Ok(retry) = line.parse() else { warn!(line, "Received invalid retry value"); continue; }; self.next.retry = Some(retry); } } Ok(None) } } /// Converts a [`Response`] into a stream of [`ServerSentEvent`]s. pub fn stream_response( response: Response, ) -> impl Stream> { let bytes_stream = response.bytes_stream(); let body_reader = StreamReader::new(bytes_stream.map(|r| r.map_err(std::io::Error::other))); FramedRead::new(body_reader, ServerSentEventsCodec::new()) } #[cfg(test)] #[path = "event_source_tests.rs"] mod tests;