Skip to content

Commit 3b33fe0

Browse files
authored
Do not initialize event data on comments (#38)
As we process a stream, we build up the event_data instance with the data as it is parsed. When we receive an empty line (e.g. "\n\r"), we try to dispatch any event we have pending. However, this event_data instance should only be created and / or updated if the line we are parsing isn't a comment. Otherwise, we can skip the initialization and return a comment event without furthering processing.
1 parent 89fde4f commit 3b33fe0

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

eventsource-client/src/event_parser.rs

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -206,14 +206,17 @@ impl EventParser {
206206
}
207207

208208
if let Some((key, value)) = parse_field(&line)? {
209+
if key == "comment" {
210+
self.sse.push_back(SSE::Comment(value.to_string()));
211+
continue;
212+
}
213+
209214
let id = &self.last_event_id;
210215
let event_data = self
211216
.event_data
212217
.get_or_insert_with(|| EventData::new().with_id(id.clone()));
213218

214-
if key == "comment" {
215-
self.sse.push_back(SSE::Comment(value.to_string()));
216-
} else if key == "event" {
219+
if key == "event" {
217220
event_data.event_type = value.to_string()
218221
} else if key == "data" {
219222
event_data.append_data(value);
@@ -534,6 +537,18 @@ mod tests {
534537
assert!(parser.get_event().is_none());
535538
}
536539

540+
#[test]
541+
fn test_comment_with_trailing_blank_line() {
542+
let mut parser = EventParser::new();
543+
let result = parser.process_bytes(Bytes::from(":comment\n\r\n\r"));
544+
assert!(result.is_ok());
545+
546+
let comment = parser.get_event();
547+
assert!(matches!(comment, Some(SSE::Comment(_))));
548+
549+
assert!(parser.get_event().is_none());
550+
}
551+
537552
#[test_case(&["data:", "hello\n\n"], event("message", "hello"); "data split")]
538553
#[test_case(&["data:hell", "o\n\n"], event("message", "hello"); "data truncated")]
539554
fn test_decode_message_split_across_chunks(chunks: &[&'static str], event: SSE) {

0 commit comments

Comments
 (0)