Skip to content

Commit

Permalink
chore(sse): add space between event name and value for compatibility
Browse files Browse the repository at this point in the history
according to https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
using `field: value` style is OK.

> Collect the characters on the line after the first U+003A COLON character (:), and let value be that string. If value starts with a U+0020 SPACE character, remove it from value.

other client side tools may detect the `data` field rely on the space,

like this one https://github.com/openai/openai-python/blob/b82a3f7e4c462a8a10fa445193301a3cefef9a4a/openai/api_requestor.py#L106

and this one: https://github.com/sashabaranov/go-openai/blob/71a24931dbc5b7029901ff963dc4d0d2509aa7ed/stream_reader.go#L14
  • Loading branch information
ttys3 committed Aug 4, 2023
1 parent cc611b8 commit c76299c
Showing 1 changed file with 6 additions and 9 deletions.
15 changes: 6 additions & 9 deletions axum/src/response/sse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,9 @@ pub struct Event {
}

impl Event {
/// Set the event's data data field(s) (`data:<content>`)
/// Set the event's data data field(s) (`data: <content>`)
///
/// Newlines in `data` will automatically be broken across `data:` fields.
/// Newlines in `data` will automatically be broken across `data: ` fields.
///
/// This corresponds to [`MessageEvent`'s data field].
///
Expand Down Expand Up @@ -202,7 +202,7 @@ impl Event {
self
}

/// Set the event's data field to a value serialized as unformatted JSON (`data:<content>`).
/// Set the event's data field to a value serialized as unformatted JSON (`data: <content>`).
///
/// This corresponds to [`MessageEvent`'s data field].
///
Expand All @@ -220,7 +220,7 @@ impl Event {
panic!("Called `EventBuilder::json_data` multiple times");
}

self.buffer.extend_from_slice(b"data:");
self.buffer.extend_from_slice(b"data: ");
serde_json::to_writer((&mut self.buffer).writer(), &data).map_err(axum_core::Error::new)?;
self.buffer.put_u8(b'\n');

Expand Down Expand Up @@ -358,10 +358,7 @@ impl Event {
);
self.buffer.extend_from_slice(name.as_bytes());
self.buffer.put_u8(b':');
// Prevent values that start with spaces having that space stripped
if value.starts_with(b" ") {
self.buffer.put_u8(b' ');
}
self.buffer.put_u8(b' ');
self.buffer.extend_from_slice(value);
self.buffer.put_u8(b'\n');
}
Expand Down Expand Up @@ -538,7 +535,7 @@ mod tests {
#[test]
fn leading_space_is_not_stripped() {
let no_leading_space = Event::default().data("\tfoobar");
assert_eq!(&*no_leading_space.finalize(), b"data:\tfoobar\n\n");
assert_eq!(&*no_leading_space.finalize(), b"data: \tfoobar\n\n");

let leading_space = Event::default().data(" foobar");
assert_eq!(&*leading_space.finalize(), b"data: foobar\n\n");
Expand Down

0 comments on commit c76299c

Please sign in to comment.