use axum::extract::Request;
use crate::context::Context;
use crate::document::MEDIA_TYPE;
use crate::error::{ErrorCode, JsonApiError};
use crate::response::Errors;
pub trait FromRequest<S>: Sized + Send + Sync + 'static {
fn from_request(
request: Request,
state: &S,
ctx: &Context,
) -> impl Future<Output = Result<Self, Errors>> + Send;
}
pub fn check_media_type(request: &Request, ctx: &Context) -> Result<(), Errors> {
let content_type = request
.headers()
.get(axum::http::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.unwrap_or_default();
let media_type = content_type.split(';').next().unwrap_or_default().trim();
if media_type.eq_ignore_ascii_case(MEDIA_TYPE) {
return Ok(());
}
Err(
JsonApiError::in_request(ErrorCode::UnsupportedMediaType, ctx)
.detail(format!(
"requests with a body must be sent as `{MEDIA_TYPE}`, not `{media_type}`"
))
.into(),
)
}
pub async fn body_text(request: Request, ctx: &Context) -> Result<String, Errors> {
check_media_type(&request, ctx)?;
let bytes = axum::body::to_bytes(request.into_body(), MAX_BODY)
.await
.map_err(|err| {
JsonApiError::invalid(ctx, format!("could not read the request body: {err}"), "")
})?;
String::from_utf8(bytes.to_vec())
.map_err(|_| JsonApiError::invalid(ctx, "the request body is not valid UTF-8", "").into())
}
pub const MAX_BODY: usize = 2 * 1024 * 1024;
#[cfg(feature = "validation")]
#[cfg_attr(docsrs, doc(cfg(feature = "validation")))]
pub async fn validated(
request: Request,
ctx: &Context,
validator: &crate::validation::DocumentValidator,
) -> Result<serde_json::Value, Errors> {
let body = body_text(request, ctx).await?;
validator.parse(&body, ctx).map_err(Errors)
}
pub fn path_id(request: &Request) -> Option<&str> {
request
.extensions()
.get::<axum::extract::Path<String>>()
.map(|axum::extract::Path(id)| id.as_str())
}
#[derive(Debug, Clone)]
pub struct Upload {
pub bytes: Vec<u8>,
pub content_type: String,
}
pub const MAX_UPLOAD: usize = 10 * 1024 * 1024;
const DEFAULT_CONTENT_TYPE: &str = "application/octet-stream";
impl Upload {
pub async fn limited(request: Request, ctx: &Context, limit: usize) -> Result<Self, Errors> {
let content_type = request
.headers()
.get(axum::http::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.unwrap_or(DEFAULT_CONTENT_TYPE)
.to_string();
let bytes = axum::body::to_bytes(request.into_body(), limit)
.await
.map_err(|_| {
JsonApiError::in_request(ErrorCode::InvalidAttribute, ctx).detail(format!(
"the uploaded body could not be read, or exceeds the {limit}-byte limit"
))
})?;
Ok(Self {
bytes: bytes.to_vec(),
content_type,
})
}
pub async fn accepting(
request: Request,
ctx: &Context,
limit: usize,
accepted: &[&str],
) -> Result<Self, Errors> {
let upload = Self::limited(request, ctx, limit).await?;
let kind = upload
.content_type
.split(';')
.next()
.unwrap_or_default()
.trim();
if !accepted
.iter()
.any(|allowed| allowed.eq_ignore_ascii_case(kind))
{
return Err(
JsonApiError::in_request(ErrorCode::UnsupportedMediaType, ctx)
.detail(format!(
"`{kind}` is not accepted here; send one of {}",
accepted
.iter()
.map(|allowed| format!("`{allowed}`"))
.collect::<Vec<_>>()
.join(", ")
))
.into(),
);
}
Ok(upload)
}
pub fn len(&self) -> usize {
self.bytes.len()
}
pub fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
}
impl<S: Sync> FromRequest<S> for Upload {
async fn from_request(request: Request, _state: &S, ctx: &Context) -> Result<Self, Errors> {
Self::limited(request, ctx, MAX_UPLOAD).await
}
}
#[cfg(feature = "streaming")]
pub const MAX_LINE: usize = 1024 * 1024;
#[cfg(feature = "streaming")]
#[cfg_attr(docsrs, doc(cfg(feature = "streaming")))]
pub struct JsonlLines {
body: axum::body::BodyDataStream,
buffer: Vec<u8>,
line: usize,
limit: usize,
ctx: Context,
done: bool,
}
#[cfg(feature = "streaming")]
impl JsonlLines {
pub fn new(request: Request, ctx: &Context) -> Self {
Self::limited(request, ctx, MAX_LINE)
}
pub fn limited(request: Request, ctx: &Context, limit: usize) -> Self {
Self {
body: request.into_body().into_data_stream(),
buffer: Vec::new(),
line: 0,
limit,
ctx: ctx.clone(),
done: false,
}
}
fn take_line(&mut self) -> Option<Vec<u8>> {
let newline = self.buffer.iter().position(|byte| *byte == b'\n')?;
let mut line: Vec<u8> = self.buffer.drain(..=newline).collect();
line.pop();
if line.last() == Some(&b'\r') {
line.pop();
}
Some(line)
}
fn too_long(&self, line: usize) -> JsonApiError {
JsonApiError::in_request(ErrorCode::InvalidAttribute, &self.ctx)
.detail(format!(
"line {line} exceeds the {} -byte limit",
self.limit
))
.pointer("")
}
}
#[cfg(feature = "streaming")]
impl futures_core::Stream for JsonlLines {
type Item = (usize, Result<Vec<u8>, JsonApiError>);
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
use std::task::Poll;
loop {
if self.done {
return Poll::Ready(None);
}
if let Some(line) = self.take_line() {
self.line += 1;
let number = self.line;
if line.iter().all(u8::is_ascii_whitespace) {
continue;
}
return Poll::Ready(Some((number, Ok(line))));
}
if self.buffer.len() > self.limit {
self.done = true;
let number = self.line + 1;
let error = self.too_long(number);
return Poll::Ready(Some((number, Err(error))));
}
match std::pin::Pin::new(&mut self.body).poll_next(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Some(Ok(frame))) => self.buffer.extend_from_slice(&frame),
Poll::Ready(Some(Err(_))) => {
self.done = true;
self.line += 1;
let number = self.line;
let error = JsonApiError::in_request(ErrorCode::InvalidAttribute, &self.ctx)
.detail("the request body could not be read to the end")
.pointer("");
return Poll::Ready(Some((number, Err(error))));
}
Poll::Ready(None) => {
self.done = true;
let rest = std::mem::take(&mut self.buffer);
if rest.iter().all(u8::is_ascii_whitespace) {
return Poll::Ready(None);
}
self.line += 1;
return Poll::Ready(Some((self.line, Ok(rest))));
}
}
}
}
}