fix: decode every complete SSE event already in the buffer
Some checks failed
Rust / build (pull_request) Failing after 8m5s
Some checks failed
Rust / build (pull_request) Failing after 8m5s
decode returned None after each non-empty line, which makes FramedRead wait for more bytes before decoding again, so each event was held until the next network read. Loop until an event is complete or the buffer has no full line left.
This commit is contained in:
@@ -63,35 +63,36 @@ impl Decoder for ServerSentEventsCodec {
|
||||
&mut self,
|
||||
src: &mut tokio_util::bytes::BytesMut,
|
||||
) -> Result<Option<Self::Item>, Self::Error> {
|
||||
let Some(mut line) = self.lines_codec.decode(src)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
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);
|
||||
// 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);
|
||||
}
|
||||
} 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");
|
||||
return Ok(None);
|
||||
};
|
||||
self.next.retry = Some(retry);
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
@@ -106,3 +107,7 @@ pub fn stream_response(
|
||||
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;
|
||||
|
||||
Reference in New Issue
Block a user