1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-27 17:22:57 +01:00

Upgrade to actix-web 0.7.18

This commit is contained in:
kingxsp 2019-03-07 14:19:57 +08:00
parent 99e4e1c3ec
commit def07f58c8
5 changed files with 100 additions and 81 deletions

View File

@ -1,5 +1,9 @@
# Changes
## 0.3.0 (2019-03-07)
* Upgrade to actix-web 0.7.18
## 0.2.0 (2018-04-10)
* Provide protobuf extractor

View File

@ -1,6 +1,6 @@
[package]
name = "actix-protobuf"
version = "0.2.0"
version = "0.3.0"
authors = ["kingxsp <jin.hb.zh@outlook.com>"]
description = "Protobuf support for actix-web framework."
readme = "README.md"
@ -23,14 +23,14 @@ bytes = "0.4"
futures = "0.1"
failure = "0.1"
actix = "0.5"
actix-web = "0.5"
actix = "0.7"
actix-web = "0.7"
prost = "0.2"
prost = "0.4"
[dev-dependencies]
http = "^0.1.5"
prost-derive = "^0.2"
http = "^0.1"
prost-derive = "^0.4"
[workspace]
members = [

View File

@ -1,15 +1,15 @@
[package]
name = "prost-example"
version = "0.2.0"
version = "0.3.0"
authors = ["kingxsp <jin.hb.zh@outlook.com>"]
[dependencies]
bytes = "0.4"
env_logger = "*"
prost = "0.2"
prost-derive = "0.2"
prost = "0.4"
prost-derive = "0.4"
actix = "0.5"
actix-web = "0.5"
actix = "0.7"
actix-web = "0.7"
actix-protobuf = { path="../../" }

View File

@ -10,7 +10,7 @@ extern crate prost_derive;
use actix_web::*;
use actix_protobuf::*;
#[derive(Clone, Debug, PartialEq, Message)]
#[derive(Clone, PartialEq, Message)]
pub struct MyObj {
#[prost(int32, tag="1")]
pub number: i32,

View File

@ -14,14 +14,13 @@ extern crate prost;
use std::fmt;
use std::ops::{Deref, DerefMut};
use bytes::{Bytes, BytesMut};
use futures::{Poll, Future, Stream};
use bytes::IntoBuf;
use bytes::{BytesMut, IntoBuf};
use prost::Message;
use prost::DecodeError as ProtoBufDecodeError;
use prost::EncodeError as ProtoBufEncodeError;
use futures::{Poll, Future, Stream};
use actix_web::http::header::{CONTENT_TYPE, CONTENT_LENGTH};
use actix_web::{Responder, HttpMessage, HttpRequest, HttpResponse, FromRequest};
use actix_web::dev::HttpResponseBuilder;
@ -125,7 +124,7 @@ impl<T, S> FromRequest<S> for ProtoBuf<T>
#[inline]
fn from_request(req: &HttpRequest<S>, cfg: &Self::Config) -> Self::Result {
Box::new(
ProtoBufMessage::new(req.clone())
ProtoBufMessage::new(req)
.limit(cfg.limit)
.from_err()
.map(ProtoBuf))
@ -136,7 +135,7 @@ impl<T: Message + Default> Responder for ProtoBuf<T> {
type Item = HttpResponse;
type Error = Error;
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, Error> {
fn respond_to<S>(self, _: &HttpRequest<S>) -> Result<HttpResponse, Error> {
let mut buf = Vec::new();
self.0.encode(&mut buf)
.map_err(|e| Error::from(ProtoBufPayloadError::Serialize(e)))
@ -148,22 +147,43 @@ impl<T: Message + Default> Responder for ProtoBuf<T> {
}
}
pub struct ProtoBufMessage<T, U: Message + Default>{
pub struct ProtoBufMessage<T: HttpMessage, U: Message + Default>{
limit: usize,
ct: &'static str,
req: Option<T>,
length: Option<usize>,
stream: Option<T::Stream>,
err: Option<ProtoBufPayloadError>,
fut: Option<Box<Future<Item=U, Error=ProtoBufPayloadError>>>,
}
impl<T, U: Message + Default> ProtoBufMessage<T, U> {
impl<T: HttpMessage, U: Message + Default> ProtoBufMessage<T, U> {
/// Create `ProtoBufMessage` for request.
pub fn new(req: T) -> Self {
ProtoBufMessage{
pub fn new(req: &T) -> Self {
if req.content_type() != "application/protobuf" {
return ProtoBufMessage {
limit: 262_144,
length: None,
stream: None,
fut: None,
err: Some(ProtoBufPayloadError::ContentType),
};
}
let mut len = None;
if let Some(l) = req.headers().get(CONTENT_LENGTH) {
if let Ok(s) = l.to_str() {
if let Ok(l) = s.parse::<usize>() {
len = Some(l)
}
}
}
ProtoBufMessage {
limit: 262_144,
req: Some(req),
length: len,
stream: Some(req.payload()),
fut: None,
ct: "application/protobuf",
err: None,
}
}
@ -172,56 +192,45 @@ impl<T, U: Message + Default> ProtoBufMessage<T, U> {
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 ProtoBufMessage<T, U>
where T: HttpMessage + Stream<Item=Bytes, Error=PayloadError> + 'static
where T: HttpMessage + '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));
if let Some(ref mut fut) = self.fut {
return fut.poll();
}
self.fut.as_mut().expect("ProtoBufBody could not be used second time").poll()
if let Some(err) = self.err.take() {
return Err(err);
}
let limit = self.limit;
if let Some(len) = self.length.take() {
if len > limit {
return Err(ProtoBufPayloadError::Overflow);
}
}
let fut = self
.stream
.take()
.expect("ProtoBufMessage could not be used second time")
.from_err()
.fold(BytesMut::with_capacity(8192), 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.poll()
}
}
@ -245,15 +254,15 @@ impl ProtoBufResponseBuilder for HttpResponseBuilder {
pub trait ProtoBufHttpMessage {
fn protobuf<T: Message + Default>(self) -> ProtoBufMessage<Self, T>
where Self: Stream<Item=Bytes, Error=PayloadError> + Sized;
fn protobuf<T: Message + Default>(&self) -> ProtoBufMessage<Self, T>
where Self: HttpMessage + 'static;
}
impl<S> ProtoBufHttpMessage for HttpRequest<S> {
#[inline]
fn protobuf<T: Message + Default>(self) -> ProtoBufMessage<Self, T>
where Self: Stream<Item=Bytes, Error=PayloadError> + Sized
fn protobuf<T: Message + Default>(&self) -> ProtoBufMessage<Self, T>
where Self: HttpMessage + 'static
{
ProtoBufMessage::new(self)
}
@ -265,6 +274,7 @@ impl<S> ProtoBufHttpMessage for HttpRequest<S> {
mod tests {
use super::*;
use http::header;
use actix_web::test::TestRequest;
impl PartialEq for ProtoBufPayloadError {
fn eq(&self, other: &ProtoBufPayloadError) -> bool {
@ -282,7 +292,7 @@ mod tests {
}
}
#[derive(Clone, Debug, PartialEq, Message)]
#[derive(Clone, PartialEq, Message)]
pub struct MyObject {
#[prost(int32, tag="1")]
pub number: i32,
@ -293,27 +303,32 @@ mod tests {
#[test]
fn test_protobuf() {
let protobuf = ProtoBuf(MyObject{number: 9 , name: "test".to_owned()});
let resp = protobuf.respond_to(HttpRequest::default()).unwrap();
let resp = protobuf.respond_to(&TestRequest::default().finish()).unwrap();
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(), "application/protobuf");
}
#[test]
fn test_protobuf_message() {
let req = HttpRequest::default();
let req = TestRequest::default().finish();
let mut protobuf = req.protobuf::<MyObject>();
assert_eq!(protobuf.poll().err().unwrap(), ProtoBufPayloadError::ContentType);
let mut req = HttpRequest::default();
req.headers_mut().insert(header::CONTENT_TYPE,
header::HeaderValue::from_static("application/protobuf"));
let mut protobuf = req.protobuf::<MyObject>().content_type("text/protobuf");
let req = TestRequest::default()
.header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/text"),
).finish();
let mut protobuf = req.protobuf::<MyObject>();
assert_eq!(protobuf.poll().err().unwrap(), ProtoBufPayloadError::ContentType);
let mut req = HttpRequest::default();
req.headers_mut().insert(header::CONTENT_TYPE,
header::HeaderValue::from_static("application/json"));
req.headers_mut().insert(header::CONTENT_LENGTH,
header::HeaderValue::from_static("10000"));
let req = TestRequest::default()
.header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/protobuf"),
).header(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("10000"),
).finish();
let mut protobuf = req.protobuf::<MyObject>().limit(100);
assert_eq!(protobuf.poll().err().unwrap(), ProtoBufPayloadError::Overflow);
}