Skip to content

Commit

Permalink
big clean up and docs improvmenet of types mod (#1894)
Browse files Browse the repository at this point in the history
  • Loading branch information
robjtede authored Jan 9, 2021
1 parent 530d037 commit 6575ee9
Show file tree
Hide file tree
Showing 22 changed files with 677 additions and 746 deletions.
12 changes: 11 additions & 1 deletion CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
# Changes

## Unreleased - 2021-xx-xx
### Added
* The method `Either<web::Json<T>, web::Form<T>>::into_inner()` which returns the inner type for
whichever variant was created. Also works for `Either<web::Form<T>, web::Json<T>>`. [#1894]

### Changed
* Rework `Responder` trait to be sync and returns `Response`/`HttpResponse` directly.
Making it more simple and performant. [#1891]

* Our `Either` type now uses `Left`/`Right` variants (instead of `A`/`B`) [#1894]

### Removed
* Public field of `web::Path` has been made private. [#1894]
* Public field of `web::Query` has been made private. [#1894]

[#1891]: https://github.com/actix/actix-web/pull/1891
[#1894]: https://github.com/actix/actix-web/pull/1894

## 4.0.0-beta.1 - 2021-01-07
### Added
Expand Down
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ awc = { version = "3.0.0-beta.1", default-features = false }
ahash = "0.6"
bytes = "1"
derive_more = "0.99.5"
either = "1.5.3"
encoding_rs = "0.8"
futures-core = { version = "0.3.7", default-features = false }
futures-util = { version = "0.3.7", default-features = false }
Expand Down Expand Up @@ -142,4 +143,4 @@ harness = false

[[bench]]
name = "responder"
harness = false
harness = false
3 changes: 3 additions & 0 deletions actix-http/CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# Changes

## Unreleased - 2021-xx-xx
* `Response::content_type` now takes an `impl IntoHeaderValue` to support `mime` types. [#1894]

[#1894]: https://github.com/actix/actix-web/pull/1894


## 3.0.0-beta.1 - 2021-01-07
Expand Down
53 changes: 33 additions & 20 deletions actix-http/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,6 @@ impl fmt::Debug for Error {
}

impl std::error::Error for Error {
fn cause(&self) -> Option<&dyn std::error::Error> {
None
}

fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
Expand Down Expand Up @@ -309,28 +305,45 @@ impl From<httparse::Error> for ParseError {
pub enum PayloadError {
/// A payload reached EOF, but is not complete.
#[display(
fmt = "A payload reached EOF, but is not complete. With error: {:?}",
fmt = "A payload reached EOF, but is not complete. Inner error: {:?}",
_0
)]
Incomplete(Option<io::Error>),
/// Content encoding stream corruption

/// Content encoding stream corruption.
#[display(fmt = "Can not decode content-encoding.")]
EncodingCorrupted,
/// A payload reached size limit.
#[display(fmt = "A payload reached size limit.")]

/// Payload reached size limit.
#[display(fmt = "Payload reached size limit.")]
Overflow,
/// A payload length is unknown.
#[display(fmt = "A payload length is unknown.")]

/// Payload length is unknown.
#[display(fmt = "Payload length is unknown.")]
UnknownLength,
/// Http2 payload error

/// HTTP/2 payload error.
#[display(fmt = "{}", _0)]
Http2Payload(h2::Error),
/// Io error

/// Generic I/O error.
#[display(fmt = "{}", _0)]
Io(io::Error),
}

impl std::error::Error for PayloadError {}
impl std::error::Error for PayloadError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
PayloadError::Incomplete(None) => None,
PayloadError::Incomplete(Some(err)) => Some(err as &dyn std::error::Error),
PayloadError::EncodingCorrupted => None,
PayloadError::Overflow => None,
PayloadError::UnknownLength => None,
PayloadError::Http2Payload(err) => Some(err as &dyn std::error::Error),
PayloadError::Io(err) => Some(err as &dyn std::error::Error),
}
}
}

impl From<h2::Error> for PayloadError {
fn from(err: h2::Error) -> Self {
Expand Down Expand Up @@ -1009,22 +1022,22 @@ mod tests {
fn test_payload_error() {
let err: PayloadError =
io::Error::new(io::ErrorKind::Other, "ParseError").into();
assert!(format!("{}", err).contains("ParseError"));
assert!(err.to_string().contains("ParseError"));

let err = PayloadError::Incomplete(None);
assert_eq!(
format!("{}", err),
"A payload reached EOF, but is not complete. With error: None"
err.to_string(),
"A payload reached EOF, but is not complete. Inner error: None"
);
}

macro_rules! from {
($from:expr => $error:pat) => {
match ParseError::from($from) {
e @ $error => {
assert!(format!("{}", e).len() >= 5);
err @ $error => {
assert!(err.to_string().len() >= 5);
}
e => unreachable!("{:?}", e),
err => unreachable!("{:?}", err),
}
};
}
Expand Down Expand Up @@ -1067,7 +1080,7 @@ mod tests {
let err = PayloadError::Overflow;
let resp_err: &dyn ResponseError = &err;
let err = resp_err.downcast_ref::<PayloadError>().unwrap();
assert_eq!(err.to_string(), "A payload reached size limit.");
assert_eq!(err.to_string(), "Payload reached size limit.");
let not_err = resp_err.downcast_ref::<ContentTypeError>();
assert!(not_err.is_none());
}
Expand Down
19 changes: 9 additions & 10 deletions actix-http/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -481,15 +481,14 @@ impl ResponseBuilder {
self
}

/// Set response content type
/// Set response content type.
#[inline]
pub fn content_type<V>(&mut self, value: V) -> &mut Self
where
HeaderValue: TryFrom<V>,
<HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
V: IntoHeaderValue,
{
if let Some(parts) = parts(&mut self.head, &self.err) {
match HeaderValue::try_from(value) {
match value.try_into() {
Ok(value) => {
parts.headers.insert(header::CONTENT_TYPE, value);
}
Expand Down Expand Up @@ -802,47 +801,47 @@ impl From<ResponseBuilder> for Response {
impl From<&'static str> for Response {
fn from(val: &'static str) -> Self {
Response::Ok()
.content_type("text/plain; charset=utf-8")
.content_type(mime::TEXT_PLAIN_UTF_8)
.body(val)
}
}

impl From<&'static [u8]> for Response {
fn from(val: &'static [u8]) -> Self {
Response::Ok()
.content_type("application/octet-stream")
.content_type(mime::APPLICATION_OCTET_STREAM)
.body(val)
}
}

impl From<String> for Response {
fn from(val: String) -> Self {
Response::Ok()
.content_type("text/plain; charset=utf-8")
.content_type(mime::TEXT_PLAIN_UTF_8)
.body(val)
}
}

impl<'a> From<&'a String> for Response {
fn from(val: &'a String) -> Self {
Response::Ok()
.content_type("text/plain; charset=utf-8")
.content_type(mime::TEXT_PLAIN_UTF_8)
.body(val)
}
}

impl From<Bytes> for Response {
fn from(val: Bytes) -> Self {
Response::Ok()
.content_type("application/octet-stream")
.content_type(mime::APPLICATION_OCTET_STREAM)
.body(val)
}
}

impl From<BytesMut> for Response {
fn from(val: BytesMut) -> Self {
Response::Ok()
.content_type("application/octet-stream")
.content_type(mime::APPLICATION_OCTET_STREAM)
.body(val)
}
}
Expand Down
2 changes: 1 addition & 1 deletion actix-http/src/ws/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ impl Codec {

/// Set max frame size.
///
/// By default max size is set to 64kb.
/// By default max size is set to 64kB.
pub fn max_size(mut self, size: usize) -> Self {
self.max_size = size;
self
Expand Down
4 changes: 2 additions & 2 deletions awc/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ where
}
}

/// Change max size of payload. By default max size is 256Kb
/// Change max size of payload. By default max size is 256kB
pub fn limit(mut self, limit: usize) -> Self {
if let Some(ref mut fut) = self.fut {
fut.limit = limit;
Expand Down Expand Up @@ -276,7 +276,7 @@ where
}
}

/// Change max size of payload. By default max size is 64Kb
/// Change max size of payload. By default max size is 64kB
pub fn limit(mut self, limit: usize) -> Self {
if let Some(ref mut fut) = self.fut {
fut.limit = limit;
Expand Down
2 changes: 1 addition & 1 deletion awc/src/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ impl WebsocketsRequest {

/// Set max frame size
///
/// By default max size is set to 64kb
/// By default max size is set to 64kB
pub fn max_frame_size(mut self, size: usize) -> Self {
self.max_size = size;
self
Expand Down
46 changes: 23 additions & 23 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
//! Error and Result module
pub use actix_http::error::*;
use derive_more::{Display, From};
use derive_more::{Display, Error, From};
use serde_json::error::Error as JsonError;
use url::ParseError as UrlParseError;

use crate::http::StatusCode;
use crate::HttpResponse;
use crate::{http::StatusCode, HttpResponse};

/// Errors which can occur when attempting to generate resource uri.
#[derive(Debug, PartialEq, Display, From)]
Expand All @@ -28,34 +27,37 @@ impl std::error::Error for UrlGenerationError {}
impl ResponseError for UrlGenerationError {}

/// A set of errors that can occur during parsing urlencoded payloads
#[derive(Debug, Display, From)]
#[derive(Debug, Display, Error, From)]
pub enum UrlencodedError {
/// Can not decode chunked transfer encoding
#[display(fmt = "Can not decode chunked transfer encoding")]
/// Can not decode chunked transfer encoding.
#[display(fmt = "Can not decode chunked transfer encoding.")]
Chunked,
/// Payload size is bigger than allowed. (default: 256kB)

/// Payload size is larger than allowed. (default limit: 256kB).
#[display(
fmt = "Urlencoded payload size is bigger ({} bytes) than allowed (default: {} bytes)",
fmt = "URL encoded payload is larger ({} bytes) than allowed (limit: {} bytes).",
size,
limit
)]
Overflow { size: usize, limit: usize },
/// Payload size is now known
#[display(fmt = "Payload size is now known")]

/// Payload size is now known.
#[display(fmt = "Payload size is now known.")]
UnknownLength,
/// Content type error
#[display(fmt = "Content type error")]

/// Content type error.
#[display(fmt = "Content type error.")]
ContentType,
/// Parse error
#[display(fmt = "Parse error")]

/// Parse error.
#[display(fmt = "Parse error.")]
Parse,
/// Payload error
#[display(fmt = "Error that occur during reading payload: {}", _0)]

/// Payload error.
#[display(fmt = "Error that occur during reading payload: {}.", _0)]
Payload(PayloadError),
}

impl std::error::Error for UrlencodedError {}

/// Return `BadRequest` for `UrlencodedError`
impl ResponseError for UrlencodedError {
fn status_code(&self) -> StatusCode {
Expand Down Expand Up @@ -115,16 +117,14 @@ impl ResponseError for PathError {
}
}

/// A set of errors that can occur during parsing query strings
#[derive(Debug, Display, From)]
/// A set of errors that can occur during parsing query strings.
#[derive(Debug, Display, Error, From)]
pub enum QueryPayloadError {
/// Deserialize error
/// Query deserialize error.
#[display(fmt = "Query deserialize error: {}", _0)]
Deserialize(serde::de::value::Error),
}

impl std::error::Error for QueryPayloadError {}

/// Return `BadRequest` for `QueryPayloadError`
impl ResponseError for QueryPayloadError {
fn status_code(&self) -> StatusCode {
Expand Down
Loading

0 comments on commit 6575ee9

Please sign in to comment.