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

chore: update Hyper to v1 #450

Open
wants to merge 4 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
666 changes: 583 additions & 83 deletions Cargo.lock

Large diffs are not rendered by default.

14 changes: 8 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ version = "0.8.9"
authors = ["Esteban Borai <[email protected]>"]
edition = "2021"
description = "Simple and configurable command-line HTTP server"
repository = "https://github.com/EstebanBorai/http-server"
repository = "https://github.com/http-server-rs/http-server"
categories = ["web-programming", "web-programming::http-server"]
keywords = ["configurable", "http", "server", "serve", "static"]
license = "MIT OR Apache-2.0"
Expand Down Expand Up @@ -37,9 +37,11 @@ futures = "0.3.30"
flate2 = "1.0.28"
http = "0.2.11"
http-auth-basic = "0.3.3"
http-body-util = "0.1"
handlebars = "4.3.7"
hyper = { version = "0.14.27", features = ["http1", "server", "stream", "tcp"] }
hyper-rustls = { version = "0.23.0", features = ["webpki-roots"] }
hyper = { version = "1" }
hyper-rustls = { version = "0.27", features = ["webpki-roots"] }
hyper-util = { version = "0.1", features = ["full"] }
local-ip-address = "0.6.1"
mime_guess = "2.0.4"
percent-encoding = "2.2.0"
Expand All @@ -49,7 +51,7 @@ serde = { version = "1.0.192", features = ["derive"] }
serde_json = "1.0.108"
structopt = { version = "0.3.26", default-features = false }
termcolor = "1.1.3"
tokio = { version = "1.29.1", features = [
tokio = { version = "1", features = [
"fs",
"rt-multi-thread",
"signal",
Expand All @@ -61,8 +63,8 @@ humansize = "2.1.3"

[dev-dependencies]
criterion = { version = "0.5.1", features = ["async_tokio", "html_reports"] }
hyper = { version = "0.14.27", features = ["client"] }
tokio = { version = "1.29.1", features = ["full"] }
hyper = { version = "1", features = ["client"] }
tokio = { version = "1", features = ["full"] }
lazy_static = "1.4.0"

[profile.release]
Expand Down
33 changes: 28 additions & 5 deletions src/bin/main.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,48 @@
use http_server_lib::make_server;
use std::process::exit;

use anyhow::{Context, Result};
use http_server_lib::server::Server;
use structopt::StructOpt;

#[cfg(feature = "dhat-profiling")]
use dhat::{Dhat, DhatAlloc};

use http_server_lib::cli::Cli;
use http_server_lib::config::Config;
use http_server_lib::config::file::ConfigFile;

#[cfg(feature = "dhat-profiling")]
#[global_allocator]
static ALLOCATOR: DhatAlloc = DhatAlloc;

#[tokio::main]
async fn main() {
async fn main() -> Result<()> {
#[cfg(feature = "dhat-profiling")]
let _dhat = Dhat::start_heap_profiling();
let args = Cli::from_args();
let config = resolve_config(args)?;

match make_server() {
Ok(server) => {
server.run().await;
match Server::run(config).await {
Ok(_) => {
println!("Server exited successfuly");
Ok(())
}
Err(error) => {
eprint!("{:?}", error);
exit(1);
}
}
}

fn resolve_config(args: Cli) -> Result<Config> {
if let Some(config_path) = args.config {
let config_file = ConfigFile::from_file(config_path)?;
let config = Config::try_from(config_file)?;

return Ok(config);
}

// Otherwise configuration is build from CLI arguments
Config::try_from(args)
.with_context(|| anyhow::Error::msg("Failed to parse arguments from stdin"))
}
13 changes: 0 additions & 13 deletions src/config/basic_auth.rs

This file was deleted.

3 changes: 2 additions & 1 deletion src/config/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ use std::net::IpAddr;
use std::path::PathBuf;
use std::str::FromStr;

use super::basic_auth::BasicAuthConfig;
use crate::middleware::basic_auth::BasicAuthConfig;

use super::compression::CompressionConfig;
use super::cors::CorsConfig;
use super::proxy::ProxyConfig;
Expand Down
4 changes: 2 additions & 2 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
pub mod basic_auth;
pub mod compression;
pub mod cors;
pub mod file;
Expand All @@ -14,7 +13,8 @@ use std::path::PathBuf;

use crate::cli::Cli;

use self::basic_auth::BasicAuthConfig;
use crate::middleware::basic_auth::BasicAuthConfig;

use self::compression::CompressionConfig;
use self::cors::CorsConfig;
use self::file::ConfigFile;
Expand Down
39 changes: 5 additions & 34 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,5 @@
mod addon;
mod cli;
mod config;
mod server;
mod utils;

use anyhow::{Context, Result};
use std::convert::TryFrom;
use structopt::StructOpt;

use crate::config::file::ConfigFile;
use crate::config::Config;
use crate::server::Server;

fn resolve_config(cli_arguments: cli::Cli) -> Result<Config> {
if let Some(config_path) = cli_arguments.config {
let config_file = ConfigFile::from_file(config_path)?;
let config = Config::try_from(config_file)?;

return Ok(config);
}

// Otherwise configuration is build from CLI arguments
Config::try_from(cli_arguments)
.with_context(|| anyhow::Error::msg("Failed to parse arguments from stdin"))
}

pub fn make_server() -> Result<Server> {
let cli_arguments = cli::Cli::from_args();
let config = resolve_config(cli_arguments)?;
let server = Server::new(config);

Ok(server)
}
pub mod cli;
pub mod config;
pub mod middleware;
pub mod server;
pub mod utils;
63 changes: 63 additions & 0 deletions src/middleware/basic_auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
use std::sync::Arc;

use http_auth_basic::Credentials;
use hyper::header::AUTHORIZATION;
use hyper::http::StatusCode;

use crate::server::{middleware::MiddlewareBefore, HttpErrorResponse, HttpRequest};

use serde::Deserialize;

#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct BasicAuthConfig {
pub username: String,
pub password: String,
}

impl BasicAuthConfig {
pub fn new(username: String, password: String) -> Self {
BasicAuthConfig { username, password }
}
}

pub fn make_basic_auth_middleware(basic_auth_config: &BasicAuthConfig) -> MiddlewareBefore {
let credentials = Arc::new(Credentials::new(
basic_auth_config.username.as_str(),
basic_auth_config.password.as_str(),
));

Box::new(move |request: HttpRequest| {
let secret = Arc::clone(&credentials);

Box::pin(async move {
let auth_header = request
.headers()
.get(AUTHORIZATION)
.ok_or(
HttpErrorResponse::new(StatusCode::UNAUTHORIZED)
.with_message("Missing Authorization header"),
)
.map_err(|err| err.into_response())?;

let auth_header = auth_header.to_str().map_err(|err| {

Check failure on line 42 in src/middleware/basic_auth.rs

View workflow job for this annotation

GitHub Actions / clippy

unused variable: `err`

Check warning on line 42 in src/middleware/basic_auth.rs

View workflow job for this annotation

GitHub Actions / test

unused variable: `err`

Check warning on line 42 in src/middleware/basic_auth.rs

View workflow job for this annotation

GitHub Actions / Builds for ubuntu-latest

unused variable: `err`

Check warning on line 42 in src/middleware/basic_auth.rs

View workflow job for this annotation

GitHub Actions / Builds for macos-latest

unused variable: `err`
HttpErrorResponse::new(StatusCode::BAD_REQUEST)
.with_message("Invalid Authorization Header value")
.into_response()
})?;

let credentials = Credentials::from_header(auth_header.to_string()).map_err(|err| {
HttpErrorResponse::new(StatusCode::UNAUTHORIZED)
.with_message(err.to_string().as_str())
.into_response()
})?;

if credentials == *secret {
return Ok(request);
}

Err(HttpErrorResponse::new(StatusCode::UNAUTHORIZED)
.with_message("Invalid credentials")
.into_response())
})
})
}
1 change: 1 addition & 0 deletions src/middleware/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod basic_auth;
53 changes: 26 additions & 27 deletions src/addon/compression/gzip.rs → src/old/addon/compression/gzip.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use anyhow::{Error, Result};
use flate2::write::GzEncoder;
use http::{HeaderValue, Request, Response};
use hyper::body::aggregate;
use hyper::body::Buf;
use hyper::Body;
use hyper::body::Bytes;
use std::io::Write;
use std::sync::Arc;
use tokio::sync::Mutex;
Expand All @@ -18,7 +16,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<Bytes>>>) -> Result<bool> {
if let Some(accept_encoding) = request
.lock()
.await
Expand All @@ -36,7 +34,7 @@ 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_compressable_content_type(response: Arc<Mutex<Response<Bytes>>>) -> Result<bool> {
if let Some(content_type) = response
.lock()
.await
Expand All @@ -56,8 +54,8 @@ 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>>>,
request: Arc<Mutex<Request<Bytes>>>,
response: Arc<Mutex<Response<Bytes>>>,
) -> Result<bool> {
Ok(is_encoding_accepted(request).await?
&& is_compressable_content_type(Arc::clone(&response)).await?)
Expand All @@ -73,8 +71,8 @@ pub fn compress(bytes: &[u8]) -> Result<Vec<u8>> {
}

pub async fn compress_http_response(
request: Arc<Mutex<Request<Body>>>,
response: Arc<Mutex<Response<Body>>>,
request: Arc<Mutex<Request<Bytes>>>,
response: Arc<Mutex<Response<Bytes>>>,
) -> Result<()> {
if let Ok(compressable) = should_compress(Arc::clone(&request), Arc::clone(&response)).await {
if compressable {
Expand All @@ -90,11 +88,11 @@ pub async fn compress_http_response(
}

let body = response.body_mut();
let mut buffer_cursor = aggregate(body).await.unwrap();
// let mut buffer_cursor = aggregate(body).await.unwrap();

while buffer_cursor.has_remaining() {
buffer.push(buffer_cursor.get_u8());
}
// while buffer_cursor.has_remaining() {
// buffer.push(buffer_cursor.get_u8());
// }
}

let compressed = compress(&buffer)?;
Expand All @@ -108,7 +106,7 @@ pub async fn compress_http_response(

response_headers.remove(http::header::CONTENT_LENGTH);

*response.body_mut() = Body::from(compressed);
*response.body_mut() = Bytes::from(compressed);
}
}

Expand All @@ -118,7 +116,8 @@ pub async fn compress_http_response(
#[cfg(test)]
mod tests {
use http::response::Builder as HttpResponseBuilder;
use hyper::{Body, Request};
use hyper::Request;
use hyper::body::Bytes;
use std::sync::Arc;
use tokio::sync::Mutex;

Expand All @@ -130,10 +129,10 @@ mod tests {
#[allow(dead_code)]
fn make_gzip_request_response(
accept_encoding_gzip: bool,
) -> (middleware::Request<Body>, middleware::Response<Body>) {
) -> (middleware::Request<Bytes>, middleware::Response<Bytes>) {
let file = std::include_bytes!("../../../assets/test_file.hbs");
let request = if accept_encoding_gzip {
let mut req = Request::new(Body::empty());
let mut req = Request::new(Bytes::empty());

req.headers_mut().append(
http::header::ACCEPT_ENCODING,
Expand All @@ -142,11 +141,11 @@ mod tests {

Arc::new(Mutex::new(req))
} else {
Arc::new(Mutex::new(Request::new(Body::empty())))
Arc::new(Mutex::new(Request::new(Bytes::empty())))
};
let response_builder =
HttpResponseBuilder::new().header(http::header::CONTENT_TYPE, "text/html");
let response_body = Body::from(file.to_vec());
let response_body = Bytes::from(file.to_vec());

let response = response_builder.body(response_body).unwrap();
let response = Arc::new(Mutex::new(response));
Expand Down Expand Up @@ -195,11 +194,11 @@ mod tests {
let mut response = response.lock().await;
let body = response.body_mut();

let mut buffer_cursor = aggregate(body).await.unwrap();
// let mut buffer_cursor = aggregate(body).await.unwrap();

while buffer_cursor.has_remaining() {
body_buffer.push(buffer_cursor.get_u8());
}
// while buffer_cursor.has_remaining() {
// body_buffer.push(buffer_cursor.get_u8());
// }
}

compress_http_response(request, Arc::clone(&response))
Expand All @@ -210,11 +209,11 @@ mod tests {
let mut compressed_response = response.lock().await;
let compressed_body = compressed_response.body_mut();

let mut buffer_cursor = aggregate(compressed_body).await.unwrap();
// let mut buffer_cursor = aggregate(compressed_body).await.unwrap();

while buffer_cursor.has_remaining() {
compressed_body_buffer.push(buffer_cursor.get_u8());
}
// while buffer_cursor.has_remaining() {
// compressed_body_buffer.push(buffer_cursor.get_u8());
// }
}

assert_eq!(body_buffer.len(), 6364);
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
Loading
Loading