1
0
mirror of https://github.com/actix/actix-extras.git synced 2025-02-13 07:02:20 +01:00

331 lines
9.2 KiB
Rust
Raw Normal View History

2021-06-27 07:02:38 +01:00
#![forbid(unsafe_code)]
#![deny(rust_2018_idioms, nonstandard_style)]
2021-12-08 06:11:13 +00:00
#![warn(future_incompatible)]
2021-06-27 07:02:38 +01:00
use std::{
fmt,
future::Future,
ops::{Deref, DerefMut},
pin::Pin,
task::{self, Poll},
};
2018-03-21 15:43:32 -07:00
2021-06-27 07:02:38 +01:00
use actix_web::{
2021-12-11 16:05:21 +00:00
body::BoxBody,
2021-06-27 07:02:38 +01:00
dev::Payload,
error::PayloadError,
http::header::{CONTENT_LENGTH, CONTENT_TYPE},
web::BytesMut,
2021-08-30 23:27:44 +01:00
Error, FromRequest, HttpMessage, HttpRequest, HttpResponse, HttpResponseBuilder, Responder,
ResponseError,
2021-06-27 07:02:38 +01:00
};
use derive_more::Display;
use futures_util::{
future::{FutureExt as _, LocalBoxFuture},
stream::StreamExt as _,
};
2021-08-30 23:27:44 +01:00
use prost::{DecodeError as ProtoBufDecodeError, EncodeError as ProtoBufEncodeError, Message};
2018-03-21 15:43:32 -07:00
#[derive(Debug, Display)]
2018-03-21 15:43:32 -07:00
pub enum ProtoBufPayloadError {
/// Payload size is bigger than 256k
#[display(fmt = "Payload size is bigger than 256k")]
2018-03-21 15:43:32 -07:00
Overflow,
2021-06-27 07:02:38 +01:00
2018-03-21 15:43:32 -07:00
/// Content type error
#[display(fmt = "Content type error")]
2018-03-21 15:43:32 -07:00
ContentType,
2021-06-27 07:02:38 +01:00
2018-03-21 15:43:32 -07:00
/// Serialize error
#[display(fmt = "ProtoBuf serialize error: {}", _0)]
Serialize(ProtoBufEncodeError),
2021-06-27 07:02:38 +01:00
2018-03-21 15:43:32 -07:00
/// Deserialize error
#[display(fmt = "ProtoBuf deserialize error: {}", _0)]
Deserialize(ProtoBufDecodeError),
2021-06-27 07:02:38 +01:00
2018-03-21 15:43:32 -07:00
/// Payload error
#[display(fmt = "Error that occur during reading payload: {}", _0)]
Payload(PayloadError),
2018-03-21 15:43:32 -07:00
}
impl ResponseError for ProtoBufPayloadError {
fn error_response(&self) -> HttpResponse {
match *self {
2018-04-10 12:40:11 -07:00
ProtoBufPayloadError::Overflow => HttpResponse::PayloadTooLarge().into(),
_ => HttpResponse::BadRequest().into(),
2018-03-21 15:43:32 -07:00
}
}
}
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)
}
}
pub struct ProtoBuf<T: Message>(pub T);
2018-04-10 12:40:11 -07:00
impl<T: Message> Deref for ProtoBuf<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T: Message> DerefMut for ProtoBuf<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
impl<T: Message> fmt::Debug for ProtoBuf<T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2018-04-10 12:40:11 -07:00
write!(f, "ProtoBuf: {:?}", self.0)
}
}
impl<T: Message> fmt::Display for ProtoBuf<T>
where
T: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2018-04-10 12:40:11 -07:00
fmt::Display::fmt(&self.0, f)
}
}
pub struct ProtoBufConfig {
limit: usize,
}
impl ProtoBufConfig {
/// Change max size of payload. By default max size is 256Kb
pub fn limit(&mut self, limit: usize) -> &mut Self {
self.limit = limit;
self
}
}
impl Default for ProtoBufConfig {
fn default() -> Self {
ProtoBufConfig { limit: 262_144 }
2018-04-10 12:40:11 -07:00
}
}
impl<T> FromRequest for ProtoBuf<T>
where
T: Message + Default + 'static,
2018-04-10 12:40:11 -07:00
{
type Error = Error;
2020-01-02 03:40:29 +09:00
type Future = LocalBoxFuture<'static, Result<Self, Error>>;
2018-04-10 12:40:11 -07:00
#[inline]
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
let limit = req
.app_data::<ProtoBufConfig>()
.map(|c| c.limit)
.unwrap_or(262_144);
2020-01-02 03:40:29 +09:00
ProtoBufMessage::new(req, payload)
.limit(limit)
.map(move |res| match res {
Err(e) => Err(e.into()),
Ok(item) => Ok(ProtoBuf(item)),
})
.boxed_local()
2018-04-10 12:40:11 -07:00
}
}
impl<T: Message + Default> Responder for ProtoBuf<T> {
2021-12-11 16:05:21 +00:00
type Body = BoxBody;
2021-03-21 23:50:26 +01:00
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
2018-03-21 15:43:32 -07:00
let mut buf = Vec::new();
2021-03-21 23:50:26 +01:00
match self.0.encode(&mut buf) {
Ok(()) => HttpResponse::Ok()
.content_type("application/protobuf")
.body(buf),
2021-08-30 23:27:44 +01:00
Err(err) => HttpResponse::from_error(Error::from(ProtoBufPayloadError::Serialize(err))),
2021-03-21 23:50:26 +01:00
}
2018-03-21 15:43:32 -07:00
}
}
pub struct ProtoBufMessage<T: Message + Default> {
2018-03-21 15:43:32 -07:00
limit: usize,
2019-03-07 14:19:57 +08:00
length: Option<usize>,
stream: Option<Payload>,
2019-03-07 14:19:57 +08:00
err: Option<ProtoBufPayloadError>,
2020-01-02 03:40:29 +09:00
fut: Option<LocalBoxFuture<'static, Result<T, ProtoBufPayloadError>>>,
2018-03-21 15:43:32 -07:00
}
impl<T: Message + Default> ProtoBufMessage<T> {
2018-03-21 15:43:32 -07:00
/// Create `ProtoBufMessage` for request.
pub fn new(req: &HttpRequest, payload: &mut Payload) -> Self {
2019-03-07 14:19:57 +08:00
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 {
2018-03-21 15:43:32 -07:00
limit: 262_144,
2019-03-07 14:19:57 +08:00
length: len,
stream: Some(payload.take()),
2018-03-21 15:43:32 -07:00
fut: None,
2019-03-07 14:19:57 +08:00
err: None,
2018-03-21 15:43:32 -07:00
}
}
/// Change max size of payload. By default max size is 256Kb
pub fn limit(mut self, limit: usize) -> Self {
self.limit = limit;
self
}
}
impl<T: Message + Default + 'static> Future for ProtoBufMessage<T> {
2020-01-02 03:40:29 +09:00
type Output = Result<T, ProtoBufPayloadError>;
2018-03-21 15:43:32 -07:00
2021-08-30 23:27:44 +01:00
fn poll(mut self: Pin<&mut Self>, task: &mut task::Context<'_>) -> Poll<Self::Output> {
2019-03-07 14:19:57 +08:00
if let Some(ref mut fut) = self.fut {
2020-01-02 03:40:29 +09:00
return Pin::new(fut).poll(task);
2019-03-07 14:19:57 +08:00
}
2018-03-21 15:43:32 -07:00
2019-03-07 14:19:57 +08:00
if let Some(err) = self.err.take() {
2020-01-02 03:40:29 +09:00
return Poll::Ready(Err(err));
2018-03-21 15:43:32 -07:00
}
2019-03-07 14:19:57 +08:00
let limit = self.limit;
if let Some(len) = self.length.take() {
if len > limit {
2020-01-02 03:40:29 +09:00
return Poll::Ready(Err(ProtoBufPayloadError::Overflow));
2019-03-07 14:19:57 +08:00
}
}
2020-01-02 04:22:52 +09:00
let mut stream = self
.stream
.take()
.expect("ProtoBufMessage could not be used second time");
2020-01-02 03:40:29 +09:00
self.fut = Some(
async move {
let mut body = BytesMut::with_capacity(8192);
while let Some(item) = stream.next().await {
let chunk = item?;
if (body.len() + chunk.len()) > limit {
return Err(ProtoBufPayloadError::Overflow);
} else {
body.extend_from_slice(&chunk);
}
2019-03-07 14:19:57 +08:00
}
2020-01-02 03:40:29 +09:00
2020-09-12 00:52:55 +01:00
Ok(<T>::decode(&mut body)?)
2020-01-02 03:40:29 +09:00
}
.boxed_local(),
);
self.poll(task)
2018-03-21 15:43:32 -07:00
}
}
pub trait ProtoBufResponseBuilder {
fn protobuf<T: Message>(&mut self, value: T) -> Result<HttpResponse, Error>;
}
impl ProtoBufResponseBuilder for HttpResponseBuilder {
fn protobuf<T: Message>(&mut self, value: T) -> Result<HttpResponse, Error> {
self.insert_header((CONTENT_TYPE, "application/protobuf"));
2018-03-21 15:43:32 -07:00
let mut body = Vec::new();
value
.encode(&mut body)
.map_err(ProtoBufPayloadError::Serialize)?;
2018-04-10 12:40:11 -07:00
Ok(self.body(body))
2018-03-21 15:43:32 -07:00
}
}
#[cfg(test)]
mod tests {
use super::*;
2020-01-02 03:40:29 +09:00
use actix_web::http::header;
2020-01-02 04:22:52 +09:00
use actix_web::test::TestRequest;
2018-03-21 15:43:32 -07:00
impl PartialEq for ProtoBufPayloadError {
fn eq(&self, other: &ProtoBufPayloadError) -> bool {
match *self {
ProtoBufPayloadError::Overflow => {
matches!(*other, ProtoBufPayloadError::Overflow)
}
ProtoBufPayloadError::ContentType => {
matches!(*other, ProtoBufPayloadError::ContentType)
}
2018-03-21 15:43:32 -07:00
_ => false,
}
}
}
2019-03-07 14:19:57 +08:00
#[derive(Clone, PartialEq, Message)]
2018-03-21 15:43:32 -07:00
pub struct MyObject {
#[prost(int32, tag = "1")]
2018-03-21 15:43:32 -07:00
pub number: i32,
#[prost(string, tag = "2")]
2018-03-21 15:43:32 -07:00
pub name: String,
}
2020-01-02 03:40:29 +09:00
#[actix_rt::test]
async fn test_protobuf() {
let protobuf = ProtoBuf(MyObject {
number: 9,
name: "test".to_owned(),
});
let req = TestRequest::default().to_http_request();
2020-01-02 03:40:29 +09:00
let resp = protobuf.respond_to(&req).await.unwrap();
let ct = resp.headers().get(header::CONTENT_TYPE).unwrap();
assert_eq!(ct, "application/protobuf");
2018-03-21 15:43:32 -07:00
}
2020-01-02 03:40:29 +09:00
#[actix_rt::test]
async fn test_protobuf_message() {
let (req, mut pl) = TestRequest::default().to_http_parts();
2020-01-02 03:40:29 +09:00
let protobuf = ProtoBufMessage::<MyObject>::new(&req, &mut pl).await;
assert_eq!(protobuf.err().unwrap(), ProtoBufPayloadError::ContentType);
2018-03-21 15:43:32 -07:00
2021-03-21 23:50:26 +01:00
let (req, mut pl) = TestRequest::get()
.insert_header((header::CONTENT_TYPE, "application/text"))
2021-03-21 23:50:26 +01:00
.to_http_parts();
2020-01-02 03:40:29 +09:00
let protobuf = ProtoBufMessage::<MyObject>::new(&req, &mut pl).await;
assert_eq!(protobuf.err().unwrap(), ProtoBufPayloadError::ContentType);
2018-03-21 15:43:32 -07:00
2021-03-21 23:50:26 +01:00
let (req, mut pl) = TestRequest::get()
.insert_header((header::CONTENT_TYPE, "application/protobuf"))
.insert_header((header::CONTENT_LENGTH, "10000"))
2021-03-21 23:50:26 +01:00
.to_http_parts();
2020-01-02 04:22:52 +09:00
let protobuf = ProtoBufMessage::<MyObject>::new(&req, &mut pl)
.limit(100)
.await;
assert_eq!(protobuf.err().unwrap(), ProtoBufPayloadError::Overflow);
2018-03-21 15:43:32 -07:00
}
}