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

feat: Switch to color_eyre and remove unneeded .unwrap()s #426

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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
104 changes: 97 additions & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ harness = false
dhat-profiling = ["dhat"]

[dependencies]
anyhow = "1.0.75"
async-stream = "0.3.5"
async-trait = "0.1.74"
chrono = { version = "0.4.31", features = ["serde"] }
Expand Down Expand Up @@ -58,6 +57,7 @@ tokio = { version = "1.29.1", features = [
tokio-rustls = "0.23.4"
toml = "0.7.6"
humansize = "2.1.3"
color-eyre = "0.6.2"

[dev-dependencies]
criterion = { version = "0.5.1", features = ["async_tokio", "html_reports"] }
Expand Down
22 changes: 12 additions & 10 deletions src/addon/compression/gzip.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use anyhow::{Error, Result};
use color_eyre::eyre::eyre;
use flate2::write::GzEncoder;
use http::{HeaderValue, Request, Response};
use hyper::body::aggregate;
Expand All @@ -18,7 +18,7 @@ const IGNORED_CONTENT_TYPE: [&str; 6] = [
"video",
];

pub async fn is_encoding_accepted(request: Arc<Mutex<Request<Body>>>) -> Result<bool> {
pub async fn is_encoding_accepted(request: Arc<Mutex<Request<Body>>>) -> color_eyre::Result<bool> {
if let Some(accept_encoding) = request
.lock()
.await
Expand All @@ -36,7 +36,9 @@ pub async fn is_encoding_accepted(request: Arc<Mutex<Request<Body>>>) -> Result<
Ok(false)
}

pub async fn is_compressable_content_type(response: Arc<Mutex<Response<Body>>>) -> Result<bool> {
pub async fn is_compressible_content_type(
response: Arc<Mutex<Response<Body>>>,
) -> color_eyre::Result<bool> {
if let Some(content_type) = response
.lock()
.await
Expand All @@ -58,26 +60,26 @@ pub async fn is_compressable_content_type(response: Arc<Mutex<Response<Body>>>)
pub async fn should_compress(
request: Arc<Mutex<Request<Body>>>,
response: Arc<Mutex<Response<Body>>>,
) -> Result<bool> {
) -> color_eyre::Result<bool> {
Ok(is_encoding_accepted(request).await?
&& is_compressable_content_type(Arc::clone(&response)).await?)
&& is_compressible_content_type(Arc::clone(&response)).await?)
}

pub fn compress(bytes: &[u8]) -> Result<Vec<u8>> {
pub fn compress(bytes: &[u8]) -> color_eyre::Result<Vec<u8>> {
let buffer: Vec<u8> = Vec::with_capacity(bytes.len());
let mut compressor: GzEncoder<Vec<u8>> = GzEncoder::new(buffer, flate2::Compression::default());

compressor.write_all(bytes)?;

compressor.finish().map_err(Error::from)
compressor.finish().map_err(|err| eyre!(err))
}

pub async fn compress_http_response(
request: Arc<Mutex<Request<Body>>>,
response: Arc<Mutex<Response<Body>>>,
) -> Result<()> {
if let Ok(compressable) = should_compress(Arc::clone(&request), Arc::clone(&response)).await {
if compressable {
) -> color_eyre::Result<()> {
if let Ok(compressible) = should_compress(Arc::clone(&request), Arc::clone(&response)).await {
if compressible {
let mut buffer: Vec<u8> = Vec::new();

{
Expand Down
18 changes: 7 additions & 11 deletions src/addon/cors.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use anyhow::{Error, Result};
use hyper::header::{self, HeaderName, HeaderValue};
use std::convert::TryFrom;

use crate::config::cors::CorsConfig;

Expand Down Expand Up @@ -211,10 +209,8 @@ impl CorsBuilder {
}
}

impl TryFrom<CorsConfig> for Cors {
type Error = Error;

fn try_from(value: CorsConfig) -> Result<Self> {
impl From<CorsConfig> for Cors {
fn from(value: CorsConfig) -> Self {
let mut builder = Cors::builder();

if value.allow_credentials {
Expand Down Expand Up @@ -249,7 +245,7 @@ impl TryFrom<CorsConfig> for Cors {
builder = builder.request_method(request_method);
}

Ok(builder.build())
builder.build()
}
}

Expand Down Expand Up @@ -341,7 +337,7 @@ mod tests {
"content-length".to_string(),
"request-id".to_string(),
];
let allow_mehtods = vec!["GET".to_string(), "POST".to_string(), "PUT".to_string()];
let allow_methods = vec!["GET".to_string(), "POST".to_string(), "PUT".to_string()];
let allow_origin = String::from("github.com");
let expose_headers = vec!["content-type".to_string(), "request-id".to_string()];
let max_age = 5400;
Expand All @@ -354,7 +350,7 @@ mod tests {
let config = CorsConfig {
allow_credentials: true,
allow_headers: Some(allow_headers.clone()),
allow_methods: Some(allow_mehtods.clone()),
allow_methods: Some(allow_methods.clone()),
allow_origin: Some(allow_origin.clone()),
expose_headers: Some(expose_headers.clone()),
max_age: Some(max_age),
Expand All @@ -364,14 +360,14 @@ mod tests {
let cors = Cors {
allow_credentials: true,
allow_headers: Some(allow_headers),
allow_methods: Some(allow_mehtods),
allow_methods: Some(allow_methods),
allow_origin: Some(allow_origin),
expose_headers: Some(expose_headers),
max_age: Some(max_age),
request_headers: Some(request_headers),
request_method: Some(request_method),
};

assert_eq!(cors, Cors::try_from(config).unwrap());
assert_eq!(cors, Cors::from(config));
}
}
6 changes: 3 additions & 3 deletions src/addon/file_server/file.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use anyhow::{Context, Result};
use chrono::{DateTime, Local};
use color_eyre::eyre::Context;
use futures::Stream;
use hyper::body::Bytes;
use mime_guess::{from_path, Mime};
Expand Down Expand Up @@ -40,7 +40,7 @@ impl File {
self.metadata.len()
}

pub fn last_modified(&self) -> Result<DateTime<Local>> {
pub fn last_modified(&self) -> color_eyre::Result<DateTime<Local>> {
let modified = self
.metadata
.modified()
Expand Down Expand Up @@ -80,7 +80,7 @@ impl From<File> for ByteStream {
}

impl Stream for ByteStream {
type Item = Result<Bytes>;
type Item = color_eyre::Result<Bytes>;

fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
let ByteStream {
Expand Down
15 changes: 9 additions & 6 deletions src/addon/file_server/http_utils.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use anyhow::{Context, Result};
use chrono::{DateTime, Local, Utc};
use color_eyre::eyre::Context;
use futures::Stream;
use http::response::Builder as HttpResponseBuilder;
use hyper::body::Body;
Expand Down Expand Up @@ -69,8 +69,10 @@ impl ResponseHeaders {
pub fn new(
file: &File,
cache_control_directive: CacheControlDirective,
) -> Result<ResponseHeaders> {
let last_modified = file.last_modified()?;
) -> color_eyre::Result<ResponseHeaders> {
let last_modified = file
.last_modified()
.context("Unable to get file's last modified date")?;

Ok(ResponseHeaders {
cache_control: cache_control_directive.to_string(),
Expand Down Expand Up @@ -111,8 +113,9 @@ impl ResponseHeaders {
pub async fn make_http_file_response(
file: File,
cache_control_directive: CacheControlDirective,
) -> Result<hyper::http::Response<Body>> {
let headers = ResponseHeaders::new(&file, cache_control_directive)?;
) -> color_eyre::Result<hyper::http::Response<Body>> {
let headers = ResponseHeaders::new(&file, cache_control_directive)
.context("Failed to construct response headers")?;
let builder = HttpResponseBuilder::new()
.header(http::header::CONTENT_LENGTH, headers.content_length)
.header(http::header::CACHE_CONTROL, headers.cache_control)
Expand Down Expand Up @@ -143,7 +146,7 @@ pub struct ByteStream {
}

impl Stream for ByteStream {
type Item = Result<Bytes>;
type Item = color_eyre::Result<Bytes>;

fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
let ByteStream {
Expand Down
Loading
Loading