use std::convert::Infallible;
use std::pin::Pin;
use std::task::{Context, Poll, ready};
use std::time::Duration;
use crate::encode::sse;
use crate::serve::CancellationToken;
use crate::{Event, EventStreamFormatter, RunErrorEvent, SSE_MEDIA_TYPE, SseFormatter, media_type};
use axum::body::{Body, Bytes};
use axum::http::{HeaderValue, header};
use axum::response::Response;
use futures_util::stream::Stream;
use tokio::time::{Instant, Sleep, sleep_until};
use crate::axum::error::{Error, Result};
const KEEP_ALIVE_FRAME: &[u8] = b":\n\n";
pub fn negotiate(accept: Option<&str>) -> Result<SseFormatter> {
let refuse = || Error::NotAcceptable {
accept: accept.unwrap_or("*/*").to_owned(),
};
match media_type(accept).map_err(|_| refuse())? {
SSE_MEDIA_TYPE => Ok(SseFormatter::new()),
_ => Err(refuse()),
}
}
#[derive(Clone, Debug)]
#[must_use = "an SseResponse does nothing until a stream is attached"]
pub struct SseResponse {
formatter: SseFormatter,
cancellation: Option<CancellationToken>,
keep_alive: Option<Duration>,
}
impl SseResponse {
pub fn negotiate(accept: Option<&str>) -> Result<Self> {
Ok(Self {
formatter: self::negotiate(accept)?,
cancellation: None,
keep_alive: None,
})
}
pub fn cancellation(mut self, token: CancellationToken) -> Self {
self.cancellation = Some(token);
self
}
pub fn keep_alive(mut self, interval: Duration) -> Self {
self.keep_alive = Some(interval);
self
}
pub fn stream<S>(self, events: S) -> Response
where
S: Stream<Item = crate::serve::Result<Event>> + Send + 'static,
{
let body = EventBody {
guard: DisconnectGuard {
token: self.cancellation,
armed: true,
},
events: Box::pin(events),
formatter: self.formatter,
keep_alive: self.keep_alive.map(KeepAlive::new),
done: false,
};
let mut response = Response::new(Body::from_stream(body));
let headers = response.headers_mut();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static(SSE_MEDIA_TYPE),
);
headers.insert(
header::CACHE_CONTROL,
HeaderValue::from_static("no-cache, no-store, no-transform"),
);
headers.insert(
header::HeaderName::from_static("x-accel-buffering"),
HeaderValue::from_static("no"),
);
headers.insert(header::VARY, HeaderValue::from_static("accept"));
response
}
}
struct EventBody {
guard: DisconnectGuard,
events: Pin<Box<dyn Stream<Item = crate::serve::Result<Event>> + Send>>,
formatter: SseFormatter,
keep_alive: Option<KeepAlive>,
done: bool,
}
impl EventBody {
fn encode(&self, event: &Event) -> Bytes {
match self.formatter.encode(event) {
Ok(bytes) => Bytes::from(bytes),
Err(error) => Bytes::from(sse::frame(
&serde_json::json!({
"type": "RUN_ERROR",
"message": error.to_string(),
"code": "SERIALIZATION",
})
.to_string(),
)),
}
}
fn finish(&mut self) {
self.done = true;
self.guard.disarm();
}
fn reset_keep_alive(&mut self) {
if let Some(keep_alive) = self.keep_alive.as_mut() {
keep_alive.reset();
}
}
fn poll_idle(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes, Infallible>>> {
let Some(keep_alive) = self.keep_alive.as_mut() else {
return Poll::Pending;
};
ready!(keep_alive.poll_tick(cx));
Poll::Ready(Some(Ok(Bytes::from_static(KEEP_ALIVE_FRAME))))
}
}
impl Stream for EventBody {
type Item = Result<Bytes, Infallible>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
if this.done {
return Poll::Ready(None);
}
match this.events.as_mut().poll_next(cx) {
Poll::Ready(Some(Ok(event))) => {
this.reset_keep_alive();
Poll::Ready(Some(Ok(this.encode(&event))))
}
Poll::Ready(Some(Err(error))) => {
this.finish();
let event =
Event::from(RunErrorEvent::new(error.to_string()).with_code(error.code()));
Poll::Ready(Some(Ok(this.encode(&event))))
}
Poll::Ready(None) => {
this.finish();
Poll::Ready(None)
}
Poll::Pending => this.poll_idle(cx),
}
}
}
struct DisconnectGuard {
token: Option<CancellationToken>,
armed: bool,
}
impl DisconnectGuard {
fn disarm(&mut self) {
self.armed = false;
}
}
impl Drop for DisconnectGuard {
fn drop(&mut self) {
if !self.armed {
return;
}
if let Some(token) = &self.token {
token.cancel();
}
}
}
struct KeepAlive {
interval: Duration,
sleep: Option<Pin<Box<Sleep>>>,
}
impl KeepAlive {
fn new(interval: Duration) -> Self {
Self {
interval,
sleep: None,
}
}
fn poll_tick(&mut self, cx: &mut Context<'_>) -> Poll<()> {
let interval = self.interval;
let sleep = self
.sleep
.get_or_insert_with(|| Box::pin(sleep_until(Instant::now() + interval)));
ready!(sleep.as_mut().poll(cx));
self.reset();
Poll::Ready(())
}
fn reset(&mut self) {
let deadline = Instant::now() + self.interval;
if let Some(sleep) = self.sleep.as_mut() {
sleep.as_mut().reset(deadline);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::StatusCode;
use axum::response::IntoResponse;
#[test]
fn a_refused_accept_is_a_406() {
let error = negotiate(Some("application/xml")).expect_err("should refuse");
assert_eq!(error.status(), StatusCode::NOT_ACCEPTABLE);
assert_eq!(
error.into_response().status(),
StatusCode::NOT_ACCEPTABLE,
"the rendered response should carry the status too"
);
}
#[test]
fn a_quality_of_zero_is_a_refusal() {
assert!(negotiate(Some("text/event-stream;q=0")).is_err());
}
#[test]
fn an_empty_accept_header_means_anything() {
assert!(negotiate(Some("")).is_ok());
assert!(negotiate(Some(" ")).is_ok());
}
#[test]
fn the_message_names_what_the_endpoint_can_emit() {
let error = negotiate(Some("application/xml")).expect_err("should refuse");
assert!(error.to_string().contains(SSE_MEDIA_TYPE), "{error}");
}
}