mirror of
https://github.com/actix/actix-extras.git
synced 2025-06-26 10:27:42 +02:00
Add protobuf support
This commit is contained in:
44
src/error.rs
44
src/error.rs
@ -15,6 +15,8 @@ use http::{header, StatusCode, Error as HttpError};
|
||||
use http::uri::InvalidUriBytes;
|
||||
use http_range::HttpRangeParseError;
|
||||
use serde_json::error::Error as JsonError;
|
||||
use prost::EncodeError as ProtoBufEncodeError;
|
||||
use prost::DecodeError as ProtoBufDecodeError;
|
||||
pub use url::ParseError as UrlParseError;
|
||||
|
||||
// re-exports
|
||||
@ -107,6 +109,10 @@ impl From<failure::Error> for Error {
|
||||
/// `InternalServerError` for `JsonError`
|
||||
impl ResponseError for JsonError {}
|
||||
|
||||
/// `InternalServerError` for `ProtoBufEncodeError` `ProtoBufDecodeError`
|
||||
impl ResponseError for ProtoBufEncodeError {}
|
||||
impl ResponseError for ProtoBufDecodeError {}
|
||||
|
||||
/// `InternalServerError` for `UrlParseError`
|
||||
impl ResponseError for UrlParseError {}
|
||||
|
||||
@ -450,6 +456,44 @@ impl From<JsonError> for JsonPayloadError {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Fail, Debug)]
|
||||
pub enum ProtoBufPayloadError {
|
||||
/// Payload size is bigger than 256k
|
||||
#[fail(display="Payload size is bigger than 256k")]
|
||||
Overflow,
|
||||
/// Content type error
|
||||
#[fail(display="Content type error")]
|
||||
ContentType,
|
||||
/// Deserialize error
|
||||
#[fail(display="Json deserialize error: {}", _0)]
|
||||
Deserialize(#[cause] ProtoBufDecodeError),
|
||||
/// Payload error
|
||||
#[fail(display="Error that occur during reading payload: {}", _0)]
|
||||
Payload(#[cause] PayloadError),
|
||||
}
|
||||
|
||||
impl ResponseError for ProtoBufPayloadError {
|
||||
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
match *self {
|
||||
ProtoBufPayloadError::Overflow => httpcodes::HttpPayloadTooLarge.into(),
|
||||
_ => httpcodes::HttpBadRequest.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PayloadError> for ProtoBufPayloadError {
|
||||
fn from(err: PayloadError) -> ProtoBufPayloadError {
|
||||
ProtoBufPayloadError::Payload(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ProtoBufDecodeError> for ProtoBufPayloadError {
|
||||
fn from(err: ProtoBufDecodeError) -> ProtoBufPayloadError {
|
||||
ProtoBufPayloadError::Deserialize(err)
|
||||
}
|
||||
}
|
||||
|
||||
/// Errors which can occur when attempting to interpret a segment string as a
|
||||
/// valid path segment.
|
||||
#[derive(Fail, Debug, PartialEq)]
|
||||
|
@ -4,6 +4,7 @@ use bytes::{Bytes, BytesMut};
|
||||
use futures::{Future, Stream, Poll};
|
||||
use http_range::HttpRange;
|
||||
use serde::de::DeserializeOwned;
|
||||
use prost::Message;
|
||||
use mime::Mime;
|
||||
use url::form_urlencoded;
|
||||
use encoding::all::UTF_8;
|
||||
@ -12,6 +13,7 @@ use encoding::label::encoding_from_whatwg_label;
|
||||
use http::{header, HeaderMap};
|
||||
|
||||
use json::JsonBody;
|
||||
use protobuf::ProtoBufBody;
|
||||
use header::Header;
|
||||
use multipart::Multipart;
|
||||
use error::{ParseError, ContentTypeError,
|
||||
@ -209,6 +211,12 @@ pub trait HttpMessage {
|
||||
JsonBody::new(self)
|
||||
}
|
||||
|
||||
fn protobuf<T: Message + Default>(self) -> ProtoBufBody<Self, T>
|
||||
where Self: Stream<Item=Bytes, Error=PayloadError> + Sized
|
||||
{
|
||||
ProtoBufBody::new(self)
|
||||
}
|
||||
|
||||
/// Return stream to http payload processes as multipart.
|
||||
///
|
||||
/// Content-type: multipart/form-data;
|
||||
|
@ -11,6 +11,7 @@ use http::{StatusCode, Version, HeaderMap, HttpTryFrom, Error as HttpError};
|
||||
use http::header::{self, HeaderName, HeaderValue};
|
||||
use serde_json;
|
||||
use serde::Serialize;
|
||||
use prost::Message;
|
||||
|
||||
use body::Body;
|
||||
use error::Error;
|
||||
@ -508,6 +509,22 @@ impl HttpResponseBuilder {
|
||||
Ok(self.body(body)?)
|
||||
}
|
||||
|
||||
pub fn protobuf<T: Message>(&mut self, value: T) -> Result<HttpResponse, Error> {
|
||||
let mut body = Vec::new();
|
||||
value.encode(&mut body)?;
|
||||
|
||||
let contains = if let Some(parts) = parts(&mut self.response, &self.err) {
|
||||
parts.headers.contains_key(header::CONTENT_TYPE)
|
||||
} else {
|
||||
true
|
||||
};
|
||||
if !contains {
|
||||
self.header(header::CONTENT_TYPE, "application/protobuf");
|
||||
}
|
||||
|
||||
Ok(self.body(body)?)
|
||||
}
|
||||
|
||||
/// Set an empty body and generate `HttpResponse`
|
||||
///
|
||||
/// `HttpResponseBuilder` can not be used after this call.
|
||||
|
@ -78,6 +78,7 @@ extern crate url;
|
||||
extern crate libc;
|
||||
extern crate serde;
|
||||
extern crate serde_json;
|
||||
extern crate prost;
|
||||
extern crate flate2;
|
||||
extern crate brotli2;
|
||||
extern crate encoding;
|
||||
@ -111,6 +112,7 @@ mod httprequest;
|
||||
mod httpresponse;
|
||||
mod info;
|
||||
mod json;
|
||||
mod protobuf;
|
||||
mod route;
|
||||
mod router;
|
||||
mod resource;
|
||||
@ -132,6 +134,7 @@ pub mod server;
|
||||
pub use error::{Error, Result, ResponseError};
|
||||
pub use body::{Body, Binary};
|
||||
pub use json::Json;
|
||||
pub use protobuf::ProtoBuf;
|
||||
pub use application::Application;
|
||||
pub use httpmessage::HttpMessage;
|
||||
pub use httprequest::HttpRequest;
|
||||
|
113
src/protobuf.rs
Normal file
113
src/protobuf.rs
Normal file
@ -0,0 +1,113 @@
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures::{Poll, Future, Stream};
|
||||
use http::header::CONTENT_LENGTH;
|
||||
|
||||
use bytes::IntoBuf;
|
||||
use prost::Message;
|
||||
|
||||
use error::{Error, ProtoBufPayloadError, PayloadError};
|
||||
use handler::Responder;
|
||||
use httpmessage::HttpMessage;
|
||||
use httprequest::HttpRequest;
|
||||
use httpresponse::HttpResponse;
|
||||
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ProtoBuf<T: Message>(pub T);
|
||||
|
||||
impl<T: Message> Responder for ProtoBuf<T> {
|
||||
type Item = HttpResponse;
|
||||
type Error = Error;
|
||||
|
||||
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, Error> {
|
||||
let mut buf = Vec::new();
|
||||
self.0.encode(&mut buf)
|
||||
.map_err(Error::from)
|
||||
.and_then(|()| {
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type("application/protobuf")
|
||||
.body(buf)
|
||||
.into())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
pub struct ProtoBufBody<T, U: Message + Default>{
|
||||
limit: usize,
|
||||
ct: &'static str,
|
||||
req: Option<T>,
|
||||
fut: Option<Box<Future<Item=U, Error=ProtoBufPayloadError>>>,
|
||||
}
|
||||
|
||||
impl<T, U: Message + Default> ProtoBufBody<T, U> {
|
||||
|
||||
/// Create `ProtoBufBody` for request.
|
||||
pub fn new(req: T) -> Self {
|
||||
ProtoBufBody{
|
||||
limit: 262_144,
|
||||
req: Some(req),
|
||||
fut: None,
|
||||
ct: "application/protobuf",
|
||||
}
|
||||
}
|
||||
|
||||
/// Change max size of payload. By default max size is 256Kb
|
||||
pub fn limit(mut self, limit: usize) -> Self {
|
||||
self.limit = limit;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set allowed content type.
|
||||
///
|
||||
/// By default *application/protobuf* content type is used. Set content type
|
||||
/// to empty string if you want to disable content type check.
|
||||
pub fn content_type(mut self, ct: &'static str) -> Self {
|
||||
self.ct = ct;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U: Message + Default + 'static> Future for ProtoBufBody<T, U>
|
||||
where T: HttpMessage + Stream<Item=Bytes, Error=PayloadError> + 'static
|
||||
{
|
||||
type Item = U;
|
||||
type Error = ProtoBufPayloadError;
|
||||
|
||||
fn poll(&mut self) -> Poll<U, ProtoBufPayloadError> {
|
||||
if let Some(req) = self.req.take() {
|
||||
if let Some(len) = req.headers().get(CONTENT_LENGTH) {
|
||||
if let Ok(s) = len.to_str() {
|
||||
if let Ok(len) = s.parse::<usize>() {
|
||||
if len > self.limit {
|
||||
return Err(ProtoBufPayloadError::Overflow);
|
||||
}
|
||||
} else {
|
||||
return Err(ProtoBufPayloadError::Overflow);
|
||||
}
|
||||
}
|
||||
}
|
||||
// check content-type
|
||||
if !self.ct.is_empty() && req.content_type() != self.ct {
|
||||
return Err(ProtoBufPayloadError::ContentType)
|
||||
}
|
||||
|
||||
let limit = self.limit;
|
||||
let fut = req.from_err()
|
||||
.fold(BytesMut::new(), move |mut body, chunk| {
|
||||
if (body.len() + chunk.len()) > limit {
|
||||
Err(ProtoBufPayloadError::Overflow)
|
||||
} else {
|
||||
body.extend_from_slice(&chunk);
|
||||
Ok(body)
|
||||
}
|
||||
})
|
||||
.and_then(|body| Ok(<U>::decode(&mut body.into_buf())?));
|
||||
self.fut = Some(Box::new(fut));
|
||||
}
|
||||
|
||||
self.fut.as_mut().expect("ProtoBufBody could not be used second time").poll()
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user