Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for cbor #619

Merged
merged 9 commits into from
Sep 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,13 @@ pin-project-lite = "0.2.6"
regex = "1.4.5"
serde = { version = "1.0.125", features = ["derive"] }
serde_json = "1.0.64"
serde_cbor = "0.11.1"
thiserror = "1.0.24"
static_assertions = "1.1.0"
http = "0.2.3"
multer = "2.0.0"
tempfile = "3.2.0"
bytes = { version = "1.0.1", features = ["serde"] }

# Feature optional dependencies
bson = { version = "2.0.0-beta.1", optional = true, features = ["chrono-0_4"] }
chrono = { version = "0.4.19", optional = true }
Expand All @@ -56,7 +56,7 @@ opentelemetry = { version = "0.13.0", optional = true }
url = { version = "2.2.1", optional = true }
uuid = { version = "0.8.2", optional = true, features = ["v4", "serde"] }
rust_decimal = { version = "1.14.3", optional = true }

mime = "0.3.15"
# Non-feature optional dependencies
blocking = { version = "1.0.2", optional = true }
lru = { version = "0.6.5", optional = true }
Expand Down
10 changes: 8 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,11 +212,11 @@ pub enum ParseRequestError {

/// The request's syntax was invalid.
#[error("Invalid request: {0}")]
InvalidRequest(serde_json::Error),
InvalidRequest(Box<dyn std::error::Error + Send + Sync>),

/// The request's files map was invalid.
#[error("Invalid files map: {0}")]
InvalidFilesMap(serde_json::Error),
InvalidFilesMap(Box<dyn std::error::Error + Send + Sync>),

/// The request's multipart data was invalid.
#[error("Invalid multipart data")]
Expand Down Expand Up @@ -258,6 +258,12 @@ impl From<multer::Error> for ParseRequestError {
}
}

impl From<mime::FromStrError> for ParseRequestError {
fn from(e: mime::FromStrError) -> Self {
Self::InvalidRequest(Box::new(e))
}
}

/// An error which can be extended into a `Error`.
pub trait ErrorExtensions: Sized {
/// Convert the error to a `Error`.
Expand Down
48 changes: 41 additions & 7 deletions src/http/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ mod graphiql_source;
mod multipart;
mod playground_source;
mod websocket;

use futures_util::io::{AsyncRead, AsyncReadExt};
use mime;

use crate::{BatchRequest, ParseRequestError, Request};

Expand All @@ -31,12 +31,34 @@ pub async fn receive_batch_body(
body: impl AsyncRead + Send,
opts: MultipartOptions,
) -> Result<BatchRequest, ParseRequestError> {
let content_type = content_type.as_ref().map(AsRef::as_ref);
// if no content-type header is set, we default to json
let content_type = content_type
.as_ref()
.map(AsRef::as_ref)
.unwrap_or("application/json");

let content_type: mime::Mime = content_type.parse()?;
match (content_type.type_(), content_type.subtype()) {
// application/json -> try json
(mime::APPLICATION, mime::JSON) => receive_batch_json(body).await,
// cbor is in application/octet-stream.
// TODO: wait for mime to add application/cbor and match against that too
(mime::OCTET_STREAM, _) | (mime::APPLICATION, mime::OCTET_STREAM) => {
receive_batch_cbor(body).await
}
// try to use multipart
(mime::MULTIPART, _) => {
if let Some(boundary) = content_type.get_param("boundary") {
multipart::receive_batch_multipart(body, boundary.to_string(), opts).await
} else {
Err(ParseRequestError::InvalidMultipart(
multer::Error::NoBoundary,
))
}
}

if let Some(Ok(boundary)) = content_type.map(multer::parse_boundary) {
multipart::receive_batch_multipart(body, boundary, opts).await
} else {
receive_batch_json(body).await
// default to json and try that
_ => receive_batch_json(body).await,
}
}

Expand All @@ -52,5 +74,17 @@ pub async fn receive_batch_json(body: impl AsyncRead) -> Result<BatchRequest, Pa
body.read_to_end(&mut data)
.await
.map_err(ParseRequestError::Io)?;
Ok(serde_json::from_slice::<BatchRequest>(&data).map_err(ParseRequestError::InvalidRequest)?)
Ok(serde_json::from_slice::<BatchRequest>(&data)
.map_err(|e| ParseRequestError::InvalidRequest(Box::new(e)))?)
}

/// Receive a GraphQL request from a body as CBOR
pub async fn receive_batch_cbor(body: impl AsyncRead) -> Result<BatchRequest, ParseRequestError> {
let mut data = Vec::new();
futures_util::pin_mut!(body);
body.read_to_end(&mut data)
.await
.map_err(ParseRequestError::Io)?;
Ok(serde_cbor::from_slice::<BatchRequest>(&data)
.map_err(|e| ParseRequestError::InvalidRequest(Box::new(e)))?)
}
4 changes: 2 additions & 2 deletions src/http/multipart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,14 @@ pub(super) async fn receive_batch_multipart(
let request_str = field.text().await?;
request = Some(
serde_json::from_str::<BatchRequest>(&request_str)
.map_err(ParseRequestError::InvalidRequest)?,
.map_err(|e| ParseRequestError::InvalidRequest(Box::new(e)))?,
);
}
Some("map") => {
let map_str = field.text().await?;
map = Some(
serde_json::from_str::<HashMap<String, Vec<String>>>(&map_str)
.map_err(ParseRequestError::InvalidFilesMap)?,
.map_err(|e| ParseRequestError::InvalidFilesMap(Box::new(e)))?,
);
}
_ => {
Expand Down