use crate::error::Result;
use bytes::Bytes;
use futures::stream::Stream;
use std::pin::Pin;
use std::task::{Context as TaskContext, Poll};
use std::time::Duration;
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SseEvent {
id: Option<String>,
event: Option<String>,
data: Option<String>,
retry: Option<Duration>,
comment: Option<String>,
}
impl SseEvent {
pub fn new(data: impl Into<String>) -> Self {
Self {
data: Some(data.into()),
..Self::default()
}
}
pub fn json<T: serde::Serialize>(value: &T) -> Result<Self> {
Ok(Self::new(serde_json::to_string(value)?))
}
pub fn comment(text: impl Into<String>) -> Self {
Self {
comment: Some(text.into()),
..Self::default()
}
}
pub fn id(mut self, id: impl Into<String>) -> Self {
self.id = Some(id.into());
self
}
pub fn event(mut self, name: impl Into<String>) -> Self {
self.event = Some(name.into());
self
}
pub fn retry(mut self, delay: Duration) -> Self {
self.retry = Some(delay);
self
}
pub fn to_bytes(&self) -> Bytes {
let mut out = String::new();
if let Some(comment) = &self.comment {
let lines = field_lines(comment);
if lines.is_empty() {
out.push_str(":\n");
}
for line in lines {
out.push(':');
out.push_str(line);
out.push('\n');
}
}
if let Some(id) = &self.id {
for line in field_lines(id) {
out.push_str("id: ");
push_without_nul(&mut out, line);
out.push('\n');
}
}
if let Some(event) = &self.event {
for line in field_lines(event) {
out.push_str("event: ");
push_without_nul(&mut out, line);
out.push('\n');
}
}
if let Some(retry) = &self.retry {
out.push_str("retry: ");
out.push_str(&retry.as_millis().to_string());
out.push('\n');
}
if let Some(data) = &self.data {
let lines = field_lines(data);
if lines.is_empty() {
out.push_str("data: \n");
}
for line in lines {
out.push_str("data: ");
out.push_str(line);
out.push('\n');
}
}
out.push('\n');
Bytes::from(out)
}
}
fn field_lines(value: &str) -> Vec<&str> {
let bytes = value.as_bytes();
let mut lines = Vec::new();
let mut start = 0;
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'\n' => {
lines.push(&value[start..i]);
i += 1;
start = i;
}
b'\r' => {
lines.push(&value[start..i]);
i += 1;
if i < bytes.len() && bytes[i] == b'\n' {
i += 1;
}
start = i;
}
_ => i += 1,
}
}
if start < bytes.len() {
lines.push(&value[start..]);
}
lines
}
fn push_without_nul(out: &mut String, line: &str) {
if line.contains('\0') {
out.push_str(&line.replace('\0', ""));
} else {
out.push_str(line);
}
}
mod sealed {
pub trait Sealed {}
impl Sealed for super::SseEvent {}
impl Sealed for crate::error::Result<super::SseEvent> {}
}
pub trait SseItem: sealed::Sealed + Send + 'static {
fn into_event(self) -> Result<SseEvent>;
fn from_event(event: SseEvent) -> Self;
}
impl SseItem for SseEvent {
fn into_event(self) -> Result<SseEvent> {
Ok(self)
}
fn from_event(event: SseEvent) -> Self {
event
}
}
impl SseItem for Result<SseEvent> {
fn into_event(self) -> Result<SseEvent> {
self
}
fn from_event(event: SseEvent) -> Self {
Ok(event)
}
}
pub fn keep_alive<S>(events: S, interval: Duration) -> KeepAlive<S>
where
S: Stream,
S::Item: SseItem,
{
let mut timer = tokio::time::interval_at(tokio::time::Instant::now() + interval, interval);
timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
KeepAlive {
events: Box::pin(events),
timer,
done: false,
}
}
pub struct KeepAlive<S> {
events: Pin<Box<S>>,
timer: tokio::time::Interval,
done: bool,
}
impl<S> Stream for KeepAlive<S>
where
S: Stream,
S::Item: SseItem,
{
type Item = S::Item;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Option<S::Item>> {
if self.done {
return Poll::Ready(None);
}
match self.events.as_mut().poll_next(cx) {
Poll::Ready(Some(item)) => {
self.timer.reset();
Poll::Ready(Some(item))
}
Poll::Ready(None) => {
self.done = true;
Poll::Ready(None)
}
Poll::Pending => match self.timer.poll_tick(cx) {
Poll::Ready(_) => Poll::Ready(Some(S::Item::from_event(SseEvent::comment("")))),
Poll::Pending => Poll::Pending,
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::StreamExt;
fn text(event: &SseEvent) -> String {
String::from_utf8(event.to_bytes().to_vec()).unwrap()
}
#[test]
fn data_only_event_is_one_data_line_and_a_blank_line() {
assert_eq!(text(&SseEvent::new("hello")), "data: hello\n\n");
}
#[test]
fn all_fields_are_written_in_spec_order() {
let event = SseEvent::new("payload")
.id("42")
.event("update")
.retry(Duration::from_millis(2500));
assert_eq!(
text(&event),
"id: 42\nevent: update\nretry: 2500\ndata: payload\n\n"
);
}
#[test]
fn multi_line_data_becomes_one_data_line_per_line() {
assert_eq!(
text(&SseEvent::new("line one\nline two")),
"data: line one\ndata: line two\n\n"
);
assert_eq!(text(&SseEvent::new("trailing\n")), "data: trailing\n\n");
assert_eq!(text(&SseEvent::new("a\r\nb")), "data: a\ndata: b\n\n");
assert_eq!(text(&SseEvent::new("a\rb")), "data: a\ndata: b\n\n");
assert_eq!(
text(&SseEvent::new("a\n\nb")),
"data: a\ndata: \ndata: b\n\n"
);
}
#[test]
fn empty_data_still_dispatches_an_event() {
assert_eq!(text(&SseEvent::new("")), "data: \n\n");
}
#[test]
fn line_breaks_in_any_field_cannot_forge_other_fields() {
let event = SseEvent::new("x")
.id("7\nretry: 1")
.event("a\ndata: forged");
assert_eq!(
text(&event),
"id: 7\nid: retry: 1\nevent: a\nevent: data: forged\ndata: x\n\n"
);
let cr = SseEvent::new("ok\rretry: 0")
.id("1\rretry: 0")
.event("e\rretry: 0");
assert_eq!(
text(&cr),
"id: 1\nid: retry: 0\nevent: e\nevent: retry: 0\ndata: ok\ndata: retry: 0\n\n"
);
let comment = SseEvent::comment("c\rdata: forged");
assert_eq!(text(&comment), ":c\n:data: forged\n\n");
}
#[test]
fn nul_is_stripped_from_id_and_event() {
let event = SseEvent::new("x").id("a\0b").event("e\0v");
assert_eq!(text(&event), "id: ab\nevent: ev\ndata: x\n\n");
}
#[test]
fn json_event_serialises_the_value() {
let event = SseEvent::json(&serde_json::json!({"n": 1, "s": "a\nb"})).unwrap();
assert_eq!(text(&event), "data: {\"n\":1,\"s\":\"a\\nb\"}\n\n");
}
#[test]
fn comment_is_a_colon_line() {
assert_eq!(text(&SseEvent::comment("")), ":\n\n");
assert_eq!(text(&SseEvent::comment("ping")), ":ping\n\n");
}
#[tokio::test(start_paused = true)]
async fn keep_alive_emits_comments_only_after_a_full_idle_interval() {
let (tx, rx) = tokio::sync::mpsc::channel::<SseEvent>(4);
let mut stream = keep_alive(
tokio_stream::wrappers::ReceiverStream::new(rx),
Duration::from_secs(15),
);
assert!(
tokio::time::timeout(Duration::from_secs(14), stream.next())
.await
.is_err(),
"no keep-alive may be sent before the interval has elapsed"
);
tx.send(SseEvent::new("real")).await.unwrap();
assert_eq!(stream.next().await, Some(SseEvent::new("real")));
let next = tokio::time::timeout(Duration::from_secs(16), stream.next())
.await
.expect("keep-alive must fire within one interval");
assert_eq!(next, Some(SseEvent::comment("")));
drop(tx);
assert_eq!(stream.next().await, None);
}
#[tokio::test(start_paused = true)]
async fn keep_alive_wraps_comments_in_the_source_item_type() {
let source = futures::stream::iter(vec![
Ok(SseEvent::new("one")),
Err(crate::error::Error::internal("channel closed")),
])
.chain(futures::stream::pending());
let mut stream = keep_alive(source, Duration::from_secs(1));
assert!(matches!(stream.next().await, Some(Ok(e)) if e == SseEvent::new("one")));
assert!(matches!(stream.next().await, Some(Err(_))));
let next = tokio::time::timeout(Duration::from_secs(2), stream.next())
.await
.expect("keep-alive must fire once the source idles");
assert!(matches!(next, Some(Ok(e)) if e == SseEvent::comment("")));
}
}