axum_extra/json_lines.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
//! Newline delimited JSON extractor and response.
use axum::{
async_trait,
body::Body,
extract::{FromRequest, Request},
response::{IntoResponse, Response},
BoxError,
};
use bytes::{BufMut, BytesMut};
use futures_util::stream::{BoxStream, Stream, TryStream, TryStreamExt};
use pin_project_lite::pin_project;
use serde::{de::DeserializeOwned, Serialize};
use std::{
convert::Infallible,
io::{self, Write},
marker::PhantomData,
pin::Pin,
task::{Context, Poll},
};
use tokio::io::AsyncBufReadExt;
use tokio_stream::wrappers::LinesStream;
use tokio_util::io::StreamReader;
pin_project! {
/// A stream of newline delimited JSON.
///
/// This can be used both as an extractor and as a response.
///
/// # As extractor
///
/// ```rust
/// use axum_extra::json_lines::JsonLines;
/// use futures_util::stream::StreamExt;
///
/// async fn handler(mut stream: JsonLines<serde_json::Value>) {
/// while let Some(value) = stream.next().await {
/// // ...
/// }
/// }
/// ```
///
/// # As response
///
/// ```rust
/// use axum::{BoxError, response::{IntoResponse, Response}};
/// use axum_extra::json_lines::JsonLines;
/// use futures_util::stream::Stream;
///
/// fn stream_of_values() -> impl Stream<Item = Result<serde_json::Value, BoxError>> {
/// # futures_util::stream::empty()
/// }
///
/// async fn handler() -> Response {
/// JsonLines::new(stream_of_values()).into_response()
/// }
/// ```
// we use `AsExtractor` as the default because you're more likely to name this type if it's used
// as an extractor
#[must_use]
pub struct JsonLines<S, T = AsExtractor> {
#[pin]
inner: Inner<S>,
_marker: PhantomData<T>,
}
}
pin_project! {
#[project = InnerProj]
enum Inner<S> {
Response {
#[pin]
stream: S,
},
Extractor {
#[pin]
stream: BoxStream<'static, Result<S, axum::Error>>,
},
}
}
/// Marker type used to prove that an `JsonLines` was constructed via `FromRequest`.
#[derive(Debug)]
#[non_exhaustive]
pub struct AsExtractor;
/// Marker type used to prove that an `JsonLines` was constructed via `JsonLines::new`.
#[derive(Debug)]
#[non_exhaustive]
pub struct AsResponse;
impl<S> JsonLines<S, AsResponse> {
/// Create a new `JsonLines` from a stream of items.
pub fn new(stream: S) -> Self {
Self {
inner: Inner::Response { stream },
_marker: PhantomData,
}
}
}
#[async_trait]
impl<S, T> FromRequest<S> for JsonLines<T, AsExtractor>
where
T: DeserializeOwned,
S: Send + Sync,
{
type Rejection = Infallible;
async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
// `Stream::lines` isn't a thing so we have to convert it into an `AsyncRead`
// so we can call `AsyncRead::lines` and then convert it back to a `Stream`
let body = req.into_body();
let stream = body.into_data_stream();
let stream = stream.map_err(|err| io::Error::new(io::ErrorKind::Other, err));
let read = StreamReader::new(stream);
let lines_stream = LinesStream::new(read.lines());
let deserialized_stream =
lines_stream
.map_err(axum::Error::new)
.and_then(|value| async move {
serde_json::from_str::<T>(&value).map_err(axum::Error::new)
});
Ok(Self {
inner: Inner::Extractor {
stream: Box::pin(deserialized_stream),
},
_marker: PhantomData,
})
}
}
impl<T> Stream for JsonLines<T, AsExtractor> {
type Item = Result<T, axum::Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match self.project().inner.project() {
InnerProj::Extractor { stream } => stream.poll_next(cx),
// `JsonLines<_, AsExtractor>` can only be constructed via `FromRequest`
// which doesn't use this variant
InnerProj::Response { .. } => unreachable!(),
}
}
}
impl<S> IntoResponse for JsonLines<S, AsResponse>
where
S: TryStream + Send + 'static,
S::Ok: Serialize + Send,
S::Error: Into<BoxError>,
{
fn into_response(self) -> Response {
let inner = match self.inner {
Inner::Response { stream } => stream,
// `JsonLines<_, AsResponse>` can only be constructed via `JsonLines::new`
// which doesn't use this variant
Inner::Extractor { .. } => unreachable!(),
};
let stream = inner.map_err(Into::into).and_then(|value| async move {
let mut buf = BytesMut::new().writer();
serde_json::to_writer(&mut buf, &value)?;
buf.write_all(b"\n")?;
Ok::<_, BoxError>(buf.into_inner().freeze())
});
let stream = Body::from_stream(stream);
// there is no consensus around mime type yet
// https://github.com/wardi/jsonlines/issues/36
stream.into_response()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_helpers::*;
use axum::{
routing::{get, post},
Router,
};
use futures_util::StreamExt;
use http::StatusCode;
use serde::Deserialize;
use std::error::Error;
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
struct User {
id: i32,
}
#[tokio::test]
async fn extractor() {
let app = Router::new().route(
"/",
post(|mut stream: JsonLines<User>| async move {
assert_eq!(stream.next().await.unwrap().unwrap(), User { id: 1 });
assert_eq!(stream.next().await.unwrap().unwrap(), User { id: 2 });
assert_eq!(stream.next().await.unwrap().unwrap(), User { id: 3 });
// sources are downcastable to `serde_json::Error`
let err = stream.next().await.unwrap().unwrap_err();
let _: &serde_json::Error = err
.source()
.unwrap()
.downcast_ref::<serde_json::Error>()
.unwrap();
}),
);
let client = TestClient::new(app);
let res = client
.post("/")
.body(
[
"{\"id\":1}",
"{\"id\":2}",
"{\"id\":3}",
// to trigger an error for source downcasting
"{\"id\":false}",
]
.join("\n"),
)
.await;
assert_eq!(res.status(), StatusCode::OK);
}
#[tokio::test]
async fn response() {
let app = Router::new().route(
"/",
get(|| async {
let values = futures_util::stream::iter(vec![
Ok::<_, Infallible>(User { id: 1 }),
Ok::<_, Infallible>(User { id: 2 }),
Ok::<_, Infallible>(User { id: 3 }),
]);
JsonLines::new(values)
}),
);
let client = TestClient::new(app);
let res = client.get("/").await;
let values = res
.text()
.await
.lines()
.map(|line| serde_json::from_str::<User>(line).unwrap())
.collect::<Vec<_>>();
assert_eq!(
values,
vec![User { id: 1 }, User { id: 2 }, User { id: 3 },]
);
}
}