Skip to content

Commit

Permalink
Merge branch 'main' into release
Browse files Browse the repository at this point in the history
  • Loading branch information
chrislearn committed Feb 15, 2024
2 parents 58a37b5 + 46ebfc1 commit bc4a1df
Show file tree
Hide file tree
Showing 103 changed files with 1,207 additions and 740 deletions.
50 changes: 31 additions & 19 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ members = ["crates/*"]
resolver = "2"

[workspace.package]
version = "0.65.2"
version = "0.66.0"
authors = ["Chrislearn Young <[email protected]>"]
edition = "2021"
rust-version = "1.75"
Expand All @@ -19,24 +19,24 @@ license = "MIT OR Apache-2.0"
categories = ["web-programming::http-server", "web-programming::websocket", "network-programming", "asynchronous"]

[workspace.dependencies]
salvo_macros = { version = "0.65.2", path = "crates/macros", default-features = false }
salvo_core = { version = "0.65.2", path = "crates/core", default-features = false }
salvo_extra = { version = "0.65.2", path = "crates/extra", default-features = false }
salvo-compression = { version = "0.65.2", path = "crates/compression", default-features = false }
salvo-cache = { version = "0.65.2", path = "crates/cache", default-features = false }
salvo-cors = { version = "0.65.2", path = "crates/cors", default-features = false }
salvo-csrf = { version = "0.65.2", path = "crates/csrf", default-features = false }
salvo-flash = { version = "0.65.2", path = "crates/flash", default-features = false }
salvo_macros = { version = "0.66.0", path = "crates/macros", default-features = false }
salvo_core = { version = "0.66.0", path = "crates/core", default-features = false }
salvo_extra = { version = "0.66.0", path = "crates/extra", default-features = false }
salvo-compression = { version = "0.66.0", path = "crates/compression", default-features = false }
salvo-cache = { version = "0.66.0", path = "crates/cache", default-features = false }
salvo-cors = { version = "0.66.0", path = "crates/cors", default-features = false }
salvo-csrf = { version = "0.66.0", path = "crates/csrf", default-features = false }
salvo-flash = { version = "0.66.0", path = "crates/flash", default-features = false }
salvo-http3 = { version = "0.0.9", default-features = false }
salvo-jwt-auth = { version = "0.65.2", path = "crates/jwt-auth", default-features = false }
salvo-oapi = { version = "0.65.2", path = "./crates/oapi", default-features = false }
salvo-oapi-macros = { version = "0.65.2", path = "crates/oapi-macros", default-features = false }
salvo-otel = { version = "0.65.2", path = "crates/otel", default-features = false }
salvo-proxy = { version = "0.65.2", path = "crates/proxy", default-features = false }
salvo-rate-limiter = { version = "0.65.2", path = "crates/rate-limiter", default-features = false }
salvo-serde-util = { version = "0.65.2", path = "crates/serde-util", default-features = true }
salvo-serve-static = { version = "0.65.2", path = "crates/serve-static", default-features = false }
salvo-session = { version = "0.65.2", path = "crates/session", default-features = false }
salvo-jwt-auth = { version = "0.66.0", path = "crates/jwt-auth", default-features = false }
salvo-oapi = { version = "0.66.0", path = "./crates/oapi", default-features = false }
salvo-oapi-macros = { version = "0.66.0", path = "crates/oapi-macros", default-features = false }
salvo-otel = { version = "0.66.0", path = "crates/otel", default-features = false }
salvo-proxy = { version = "0.66.0", path = "crates/proxy", default-features = false }
salvo-rate-limiter = { version = "0.66.0", path = "crates/rate-limiter", default-features = false }
salvo-serde-util = { version = "0.66.0", path = "crates/serde-util", default-features = true }
salvo-serve-static = { version = "0.66.0", path = "crates/serve-static", default-features = false }
salvo-session = { version = "0.66.0", path = "crates/session", default-features = false }

aead = "0.5"
aes-gcm = "0.10"
Expand Down Expand Up @@ -133,4 +133,16 @@ x509-parser = "0.15"
# Compress
brotli = { version = "3.3", default-features = false }
flate2 = { version = "1.0", default-features = false }
zstd = { version = "0.13", default-features = false }
zstd = { version = "0.13", default-features = false }

[workspace.lints.rust]
unsafe_code = "forbid"
unreachable_pub = "deny"
missing_docs = "warn"

[workspace.lints.clippy]
future_not_send = "warn"
unwrap_used = "warn"

[workspace.lints.rustdoc]
broken_intra_doc_links = "warn"
9 changes: 6 additions & 3 deletions crates/cache/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,13 @@ moka-store = ["dep:moka"]
[dependencies]
bytes = { workspace = true }
moka = { workspace = true, optional = true, features = ["future"] }
salvo_core = { workspace = true, features = ["http1"]}
salvo_core = { workspace = true, features = ["http1"] }
tracing = { workspace = true }

[dev-dependencies]
salvo_core = { workspace = true, features = ["test"] }
salvo_core = { workspace = true, features = ["test"] }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
time = { workspace = true }
time = { workspace = true }

[lints]
workspace = true
3 changes: 0 additions & 3 deletions crates/cache/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,6 @@
#![doc(html_favicon_url = "https://salvo.rs/favicon-32x32.png")]
#![doc(html_logo_url = "https://salvo.rs/images/logo.svg")]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(unreachable_pub)]
#![forbid(unsafe_code)]
#![warn(missing_docs)]

use std::borrow::Borrow;
use std::collections::VecDeque;
Expand Down
3 changes: 3 additions & 0 deletions crates/compression/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,6 @@ zstd = { workspace = true, optional = true, features = ["default"] }

[dev-dependencies]
salvo_core = { workspace = true, features = ["http1", "test"] }

[lints]
workspace = true
2 changes: 1 addition & 1 deletion crates/compression/src/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ impl CompressionLevel {
Self::Precise(quality) => quality.min(21) as i32,
Self::Default => 1,
};
ZstdEncoder::new(Writer::new(), quality).unwrap()
ZstdEncoder::new(Writer::new(), quality).expect("`ZstdEncoder::new` returned an error")
}
}

Expand Down
23 changes: 15 additions & 8 deletions crates/compression/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
#![cfg_attr(docsrs, feature(doc_cfg))]

//! Compression middleware for for Savlo web server framework.
//!
//! Read more: <https://salvo.rs>
use std::fmt::{self, Display};
use std::str::FromStr;

use indexmap::IndexMap;

use salvo_core::http::body::ResBody;
use salvo_core::http::header::{HeaderValue, ACCEPT_ENCODING, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE};
use salvo_core::http::{self, Mime, StatusCode};
use salvo_core::http::{self, mime, Mime, StatusCode};
use salvo_core::{async_trait, Depot, FlowCtrl, Handler, Request, Response};

mod encoder;
Expand Down Expand Up @@ -38,18 +41,22 @@ pub enum CompressionLevel {
#[derive(Eq, PartialEq, Clone, Copy, Debug, Hash)]
#[non_exhaustive]
pub enum CompressionAlgo {
/// Compress use Brotli algo.
#[cfg(feature = "brotli")]
#[cfg_attr(docsrs, doc(cfg(feature = "brotli")))]
Brotli,

/// Compress use Deflate algo.
#[cfg(feature = "deflate")]
#[cfg_attr(docsrs, doc(cfg(feature = "deflate")))]
Deflate,

/// Compress use Gzip algo.
#[cfg(feature = "gzip")]
#[cfg_attr(docsrs, doc(cfg(feature = "gzip")))]
Gzip,

/// Compress use Zstd algo.
#[cfg(feature = "zstd")]
#[cfg_attr(docsrs, doc(cfg(feature = "zstd")))]
Zstd,
Expand Down Expand Up @@ -141,13 +148,13 @@ impl Default for Compression {
Self {
algos,
content_types: vec![
"text/*".parse().unwrap(),
"application/javascript".parse().unwrap(),
"application/json".parse().unwrap(),
"application/xml".parse().unwrap(),
"application/rss+xml".parse().unwrap(),
"application/wasm".parse().unwrap(),
"image/svg+xml".parse().unwrap(),
mime::TEXT_STAR,
mime::APPLICATION_JAVASCRIPT,
mime::APPLICATION_JSON,
mime::IMAGE_SVG,
"application/wasm".parse().expect("invalid mime type"),
"application/xml".parse().expect("invalid mime type"),
"application/rss+xml".parse().expect("invalid mime type"),
],
min_length: 0,
force_priority: false,
Expand Down
5 changes: 4 additions & 1 deletion crates/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ native-tls = ["http1", "http2", "dep:tokio-native-tls", "dep:native-tls"]
openssl = ["http2", "dep:openssl", "dep:tokio-openssl"]
unix = ["http1"]
test = ["dep:brotli", "dep:flate2", "dep:zstd", "dep:encoding_rs", "dep:serde_urlencoded", "dep:url", "tokio/macros"]
acme = ["http1", "http2", "hyper-util/http1", "hyper-util/http2","hyper-util/client-legacy", "dep:hyper-rustls", "dep:rcgen", "dep:ring", "dep:x509-parser", "dep:tokio-rustls", "dep:rustls-pemfile"]
acme = ["http1", "http2", "hyper-util/http1", "hyper-util/http2", "hyper-util/client-legacy", "dep:hyper-rustls", "dep:rcgen", "dep:ring", "dep:x509-parser", "dep:tokio-rustls", "dep:rustls-pemfile"]
tower-compat = ["dep:tower"]

[dependencies]
Expand Down Expand Up @@ -98,3 +98,6 @@ nix = { workspace = true, features = ["fs", "user"] }

[dev-dependencies]
fastrand = { workspace = true }

[lints]
workspace = true
18 changes: 12 additions & 6 deletions crates/core/src/catcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ fn status_error_json(code: StatusCode, name: &str, brief: &str, cause: Option<&s
cause: cause.unwrap_or(EMPTY_CAUSE_MSG),
},
};
serde_json::to_string(&data).unwrap()
serde_json::to_string(&data).unwrap_or_default()
}

fn status_error_plain(code: StatusCode, name: &str, brief: &str, cause: Option<&str>) -> String {
Expand Down Expand Up @@ -255,15 +255,15 @@ fn status_error_xml(code: StatusCode, name: &str, brief: &str, cause: Option<&st
brief,
cause: cause.unwrap_or(EMPTY_CAUSE_MSG),
};
serde_xml_rs::to_string(&data).unwrap()
serde_xml_rs::to_string(&data).unwrap_or_default()
}

/// Create bytes from `StatusError`.
#[doc(hidden)]
#[inline]
pub fn status_error_bytes(err: &StatusError, prefer_format: &Mime, footer: Option<&str>) -> (Mime, Bytes) {
let format = if !SUPPORTED_FORMATS.contains(&prefer_format.subtype()) {
"text/html".parse().unwrap()
mime::TEXT_HTML
} else {
prefer_format.clone()
};
Expand All @@ -287,10 +287,16 @@ pub fn write_error_default(req: &Request, res: &mut Response, footer: Option<&st
status_error_bytes(body, &format, footer)
} else {
let status = res.status_code.unwrap_or(StatusCode::NOT_FOUND);
status_error_bytes(&StatusError::from_code(status).unwrap(), &format, footer)
status_error_bytes(
&StatusError::from_code(status).unwrap_or_else(StatusError::internal_server_error),
&format,
footer,
)
};
res.headers_mut()
.insert(header::CONTENT_TYPE, format.to_string().parse().unwrap());
res.headers_mut().insert(
header::CONTENT_TYPE,
format.to_string().parse().expect("invalid `Content-Type`"),
);
res.write_body(data).ok();
}

Expand Down
13 changes: 4 additions & 9 deletions crates/core/src/conn/acme/jose.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,14 @@ pub(crate) async fn request(
payload,
signature,
})
.unwrap();
.map_err(|e| IoError::new(ErrorKind::Other, e.to_string()))?;

let req = hyper::Request::builder()
.header("content-type", "application/jose+json")
.method(Method::POST)
.uri(uri)
.body(Full::from(body))
.unwrap();
.map_err(|e| IoError::new(ErrorKind::Other, format!("failed to build http request: {}", e)))?;

let res = client
.request(req)
Expand Down Expand Up @@ -156,13 +156,8 @@ where
{
let res = request(cli, key_pair, kid, nonce, url, payload).await?;

let data = res
.into_body()
.collect()
.await?
.to_bytes();
serde_json::from_slice(&data)
.map_err(|e| Error::other(format!("response is not a valid json: {}", e)))
let data = res.into_body().collect().await?.to_bytes();
serde_json::from_slice(&data).map_err(|e| Error::other(format!("response is not a valid json: {}", e)))
}

#[inline]
Expand Down
13 changes: 8 additions & 5 deletions crates/core/src/conn/acme/listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ use tokio_rustls::rustls::sign::CertifiedKey;
use tokio_rustls::server::TlsStream;
use tokio_rustls::TlsAcceptor;

use crate::conn::{Accepted, Acceptor, HandshakeStream, Holding, Listener};
use crate::conn::{Accepted, Acceptor, Holding, Listener};

use crate::conn::HandshakeStream;
use crate::fuse::ArcFuseFactory;
use crate::http::uri::Scheme;
use crate::http::Version;
use crate::http::{HttpConnection, Version};
use crate::Router;

use super::config::{AcmeConfig, AcmeConfigBuilder};
Expand Down Expand Up @@ -431,16 +433,17 @@ where
}

#[inline]
async fn accept(&mut self) -> IoResult<Accepted<Self::Conn>> {
async fn accept(&mut self, fuse_factory: ArcFuseFactory) -> IoResult<Accepted<Self::Conn>> {
let Accepted {
conn,
local_addr,
remote_addr,
http_version,
http_scheme,
} = self.inner.accept().await?;
} = self.inner.accept(fuse_factory).await?;
let fusewire = conn.fusewire();
Ok(Accepted {
conn: HandshakeStream::new(self.tls_acceptor.accept(conn)),
conn: HandshakeStream::new(self.tls_acceptor.accept(conn), fusewire),
local_addr,
remote_addr,
http_version,
Expand Down
25 changes: 16 additions & 9 deletions crates/core/src/conn/joined.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ use std::io::Result as IoResult;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Duration;

use pin_project::pin_project;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio_util::sync::CancellationToken;

use crate::conn::{Holding, HttpBuilder};
use crate::fuse::{ArcFuseFactory, ArcFusewire, SteadyFusewire};
use crate::http::HttpConnection;
use crate::service::HyperHandler;

Expand Down Expand Up @@ -120,13 +121,16 @@ where
self,
handler: HyperHandler,
builder: Arc<HttpBuilder>,
idle_timeout: Option<Duration>,
graceful_stop_token: CancellationToken,
) -> IoResult<()> {
match self {
JoinedStream::A(a) => a.serve(handler, builder, idle_timeout).await,
JoinedStream::B(b) => b.serve(handler, builder, idle_timeout).await,
JoinedStream::A(a) => a.serve(handler, builder, graceful_stop_token).await,
JoinedStream::B(b) => b.serve(handler, builder, graceful_stop_token).await,
}
}
fn fusewire(&self) -> ArcFusewire {
Arc::new(SteadyFusewire)
}
}

impl<A, B> Acceptor for JoinedAcceptor<A, B>
Expand All @@ -144,12 +148,12 @@ where
}

#[inline]
async fn accept(&mut self) -> IoResult<Accepted<Self::Conn>> {
async fn accept(&mut self, fuse_factory: ArcFuseFactory) -> IoResult<Accepted<Self::Conn>> {
tokio::select! {
accepted = self.a.accept() => {
accepted = self.a.accept(fuse_factory.clone()) => {
Ok(accepted?.map_conn(JoinedStream::A))
}
accepted = self.b.accept() => {
accepted = self.b.accept(fuse_factory) => {
Ok(accepted?.map_conn(JoinedStream::B))
}
}
Expand All @@ -158,11 +162,14 @@ where

#[cfg(test)]
mod tests {
use std::sync::Arc;

use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;

use super::*;
use crate::conn::TcpListener;
use crate::fuse::SteadyFusewire;

#[tokio::test]
async fn test_joined_listener() {
Expand All @@ -177,9 +184,9 @@ mod tests {
let mut stream = TcpStream::connect(addr2).await.unwrap();
stream.write_i32(100).await.unwrap();
});
let Accepted { mut conn, .. } = acceptor.accept().await.unwrap();
let Accepted { mut conn, .. } = acceptor.accept(Arc::new(SteadyFusewire)).await.unwrap();
let first = conn.read_i32().await.unwrap();
let Accepted { mut conn, .. } = acceptor.accept().await.unwrap();
let Accepted { mut conn, .. } = acceptor.accept(Arc::new(SteadyFusewire)).await.unwrap();
let second = conn.read_i32().await.unwrap();
assert_eq!(first + second, 150);
}
Expand Down
Loading

0 comments on commit bc4a1df

Please sign in to comment.