use std::{
convert::Infallible,
fmt,
panic::{AssertUnwindSafe, catch_unwind},
pin::Pin,
sync::{
Arc, OnceLock,
atomic::{AtomicBool, Ordering},
},
task::{Context, Poll},
time::Duration,
};
use axum::{
body::Body,
http::{self, StatusCode, header},
response::{
IntoResponse,
sse::{Event, KeepAlive, Sse},
},
};
use futures_core::Stream;
use serde::Serialize;
use super::{
handler::{BoxError, Failure, panic_text},
invocations::{error_response, refused},
};
pub(crate) const DEFAULT_STREAM_HEARTBEAT: Duration = Duration::from_secs(30);
const MAX_STREAM_HEARTBEAT: Duration = Duration::from_secs(86400 * 365 * 30);
tokio::task_local! {
pub(crate) static ROUTE_HEARTBEAT: Duration;
}
const STREAM_NOT_ACCEPTED: &str = "Streaming response requires Accept: text/event-stream header. \
Please include this header in your request to receive streaming data.";
type Events = Pin<Box<dyn Stream<Item = Result<Event, Infallible>> + Send>>;
pub struct Response {
kind: Kind,
}
enum Kind {
Value { status: StatusCode, json: Result<Vec<u8>, serde_json::Error> },
Http(Box<http::Response<Body>>),
Stream(Events, StreamFailed),
}
impl Response {
pub fn json<T: Serialize>(value: T) -> Self {
Self::with_status(StatusCode::OK, value)
}
pub fn with_status<T: Serialize>(status: StatusCode, value: T) -> Self {
Self { kind: Kind::Value { status, json: serde_json::to_vec(&value) } }
}
pub fn from_http(response: http::Response<Body>) -> Self {
Self { kind: Kind::Http(Box::new(response)) }
}
pub fn stream<S, T, E>(stream: S) -> Self
where
S: Stream<Item = Result<T, E>> + Send + 'static,
T: Serialize,
E: Into<BoxError>,
{
let failed = StreamFailed::default();
Self { kind: Kind::Stream(Box::pin(EventStream(Some(Box::pin(stream)), failed.clone())), failed) }
}
pub(crate) fn into_http(self, accept: Option<&str>, heartbeat: Duration) -> axum::response::Response {
let (status, json) = match self.kind {
Kind::Http(response) => return *response,
Kind::Stream(events, failed) => {
let allows_stream = |accept: &str| {
let ranges = media_ranges(accept);
ranges.is_empty() || allows(&ranges, "text/event-stream")
};
if accept.is_some_and(|accept| !allows_stream(accept)) {
let _ = catch_unwind(AssertUnwindSafe(|| drop(events)));
return refused(StatusCode::NOT_ACCEPTABLE, STREAM_NOT_ACCEPTED, None);
}
let keep_alive = KeepAlive::new().interval(heartbeat.min(MAX_STREAM_HEARTBEAT));
let mut response = Sse::new(events).keep_alive(keep_alive).into_response();
response.extensions_mut().insert(failed);
return response;
}
Kind::Value { json: Err(error), .. } => {
tracing::error!(%error, "failed to serialize the invocation response");
return error_response(StatusCode::INTERNAL_SERVER_ERROR, "Failed to serialize response", None);
}
Kind::Value { status, .. }
if status.is_informational()
|| status == StatusCode::NO_CONTENT
|| status == StatusCode::NOT_MODIFIED =>
{
return status.into_response();
}
Kind::Value { status, json: Ok(json) } => (status, json),
};
let (content_type, body) = match negotiate(accept.unwrap_or_default()) {
Encoding::Json => ("application/json", json),
Encoding::Binary => ("application/octet-stream", json),
Encoding::Text => match json.first() {
Some(b'"') => (
"text/plain; charset=utf-8",
serde_json::from_slice::<String>(&json).map_or(json, String::into_bytes),
),
_ => ("text/plain; charset=utf-8", json),
},
};
(status, [(header::CONTENT_TYPE, content_type)], body).into_response()
}
}
impl IntoResponse for Response {
fn into_response(self) -> axum::response::Response {
let heartbeat = ROUTE_HEARTBEAT.try_with(|heartbeat| *heartbeat).unwrap_or(DEFAULT_STREAM_HEARTBEAT);
self.into_http(None, heartbeat)
}
}
impl fmt::Debug for Response {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Response").finish_non_exhaustive()
}
}
#[derive(Debug, PartialEq)]
enum Encoding {
Json,
Text,
Binary,
}
fn media_ranges(accept: &str) -> Vec<(String, bool)> {
accept
.split(',')
.filter_map(|range| {
let mut parts = range.split(';').map(str::trim);
let media = parts.next().filter(|media| !media.is_empty())?.to_ascii_lowercase();
let refused = parts.any(|parameter| {
let quality = parameter.split_once('=').filter(|(name, _)| name.trim().eq_ignore_ascii_case("q"));
quality.is_some_and(|(_, value)| value.trim().parse::<f32>() == Ok(0.0))
});
Some((media, !refused))
})
.collect()
}
fn allows(ranges: &[(String, bool)], media_type: &str) -> bool {
let kind = media_type.split('/').next().unwrap_or_default();
[media_type.to_owned(), format!("{kind}/*"), "*/*".to_owned()]
.iter()
.find_map(|candidate| ranges.iter().find(|(range, _)| range == candidate).map(|(_, allowed)| *allowed))
.unwrap_or(false)
}
fn negotiate(accept: &str) -> Encoding {
let ranges = media_ranges(accept);
if allows(&ranges, "application/json") {
Encoding::Json
} else if allows(&ranges, "text/plain") {
Encoding::Text
} else if allows(&ranges, "application/octet-stream") {
Encoding::Binary
} else {
Encoding::Json
}
}
struct EventStream<S>(Option<Pin<Box<S>>>, StreamFailed);
#[derive(Clone, Default)]
pub(crate) struct StreamFailed(Arc<(OnceLock<Failure>, AtomicBool)>);
impl StreamFailed {
pub(crate) fn get(&self) -> Option<&Failure> {
self.0.0.get()
}
pub(crate) fn claim(&self) {
self.0.1.store(true, Ordering::Relaxed);
}
fn set(&self, failure: Failure) {
if !self.0.1.load(Ordering::Relaxed) {
tracing::error!(error = failure.error, causes = failure.causes, "the response stream failed");
}
let _ = self.0.0.set(failure);
}
}
enum Step {
Pending,
End,
Data(String),
Failure(Failure),
}
fn internal_error(cause: &str) -> Failure {
Failure { error: "Internal error".to_owned(), causes: Some(cause.to_owned()) }
}
impl<S> EventStream<S> {
fn drop_stream(&mut self) -> bool {
let stream = self.0.take();
catch_unwind(AssertUnwindSafe(|| drop(stream))).is_err()
}
}
impl<S, T, E> Stream for EventStream<S>
where
S: Stream<Item = Result<T, E>>,
T: Serialize,
E: Into<BoxError>,
{
type Item = Result<Event, Infallible>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let Some(stream) = self.0.as_mut() else { return Poll::Ready(None) };
let step = catch_unwind(AssertUnwindSafe(|| match stream.as_mut().poll_next(cx) {
Poll::Pending => Step::Pending,
Poll::Ready(None) => Step::End,
Poll::Ready(Some(Ok(item))) => match serde_json::to_string(&item) {
Ok(json) => Step::Data(json),
Err(error) => Step::Failure(Failure {
error: "Failed to serialize response".to_owned(),
causes: Some(error.to_string()),
}),
},
Poll::Ready(Some(Err(error))) => Step::Failure(Failure::of(error.into())),
}));
let step = step.unwrap_or_else(|panic| Step::Failure(internal_error(panic_text(panic.as_ref()))));
let failure = match step {
Step::Pending => return Poll::Pending,
Step::Data(json) => return Poll::Ready(Some(Ok(Event::default().data(json)))),
Step::End if self.drop_stream() => internal_error("a destructor of the stream panicked"),
Step::End => return Poll::Ready(None),
Step::Failure(failure) => {
self.drop_stream();
failure
}
};
let data = serde_json::json!({ "error": failure.error }).to_string();
self.1.set(failure);
Poll::Ready(Some(Ok(Event::default().event("error").data(data))))
}
}
pub trait IntoInvocationResponse {
fn into_invocation_response(self) -> Response;
}
impl<T: Serialize> IntoInvocationResponse for T {
fn into_invocation_response(self) -> Response {
Response::json(self)
}
}
impl IntoInvocationResponse for Response {
fn into_invocation_response(self) -> Response {
self
}
}
#[cfg(test)]
mod tests {
use super::{Encoding::*, *};
#[test]
fn accept_negotiation() {
let cases = [
("", Json),
("application/json", Json),
("*/*", Json),
("application/*", Json),
("text/plain", Text),
("text/*", Text),
("TEXT/Plain; charset=utf-8", Text),
("application/octet-stream", Binary),
("text/html", Json),
("text/event-stream", Json),
("text/plain, application/json", Json),
("application/octet-stream, text/plain", Text),
("text/plain;q=0.1, application/octet-stream;q=0.9", Text),
("application/json;q=0, text/plain", Text),
("*/*; Q=0.0, application/octet-stream", Binary),
("text/plain;q=0", Json),
("application/jsonx", Json),
("application/json;q=0, */*;q=1, text/plain;q=0.5", Text),
("application/json;q=0, text/plain;q=0, */*", Binary),
("application/*;q=0, application/json", Json),
("application/json;q=0, application/*", Binary),
("text/event-stream, text/plain", Text),
("text/plain,application/json", Json),
];
for (accept, encoding) in cases {
assert_eq!(negotiate(accept), encoding, "Accept: {accept:?}");
}
}
#[test]
fn response_returned_from_another_axum_route_is_json() {
let response = Response::with_status(StatusCode::CREATED, "text").into_response();
assert_eq!(response.status(), StatusCode::CREATED);
assert_eq!(response.headers()[header::CONTENT_TYPE], "application/json");
}
}