diff --git a/crates/cache/src/lib.rs b/crates/cache/src/lib.rs index 4c59e5fa6..559efca28 100644 --- a/crates/cache/src/lib.rs +++ b/crates/cache/src/lib.rs @@ -21,6 +21,7 @@ use std::borrow::Borrow; use std::collections::VecDeque; use std::error::Error as StdError; +use std::future::Future; use std::hash::Hash; use bytes::Bytes; @@ -42,14 +43,12 @@ cfg_feature! { } /// Issuer -#[async_trait] pub trait CacheIssuer: Send + Sync + 'static { /// The key is used to identify the rate limit. type Key: Hash + Eq + Send + Sync + 'static; /// Issue a new key for the request. If it returns `None`, the request will not be cached. - async fn issue(&self, req: &mut Request, depot: &Depot) -> Option; + fn issue(&self, req: &mut Request, depot: &Depot) -> impl Future> + Send; } -#[async_trait] impl CacheIssuer for F where F: Fn(&mut Request, &Depot) -> Option + Send + Sync + 'static, @@ -113,7 +112,6 @@ impl RequestIssuer { } } -#[async_trait] impl CacheIssuer for RequestIssuer { type Key = String; async fn issue(&self, req: &mut Request, _depot: &Depot) -> Option { @@ -147,19 +145,18 @@ impl CacheIssuer for RequestIssuer { } /// Store cache. -#[async_trait] pub trait CacheStore: Send + Sync + 'static { /// Error type for CacheStore. type Error: StdError + Sync + Send + 'static; /// Key type Key: Hash + Eq + Send + Clone + 'static; /// Get the cache item from the store. - async fn load_entry(&self, key: &Q) -> Option + fn load_entry(&self, key: &Q) -> impl Future> + Send where Self::Key: Borrow, Q: Hash + Eq + Sync; /// Save the cache item from the store. - async fn save_entry(&self, key: Self::Key, data: CachedEntry) -> Result<(), Self::Error>; + fn save_entry(&self, key: Self::Key, data: CachedEntry) -> impl Future> + Send; } /// `CachedBody` is used to save response body to `CachedStore`. diff --git a/crates/cache/src/moka_store.rs b/crates/cache/src/moka_store.rs index eeb78d63d..6bda1eeeb 100644 --- a/crates/cache/src/moka_store.rs +++ b/crates/cache/src/moka_store.rs @@ -8,7 +8,6 @@ use std::time::Duration; use moka::future::Cache as MokaCache; use moka::future::CacheBuilder as MokaCacheBuilder; use moka::notification::RemovalCause; -use salvo_core::async_trait; use super::{CacheStore, CachedEntry}; @@ -114,7 +113,6 @@ where } } -#[async_trait] impl CacheStore for MokaStore where K: Hash + Eq + Send + Sync + Clone + 'static, diff --git a/crates/core/src/conn/acme/cache.rs b/crates/core/src/conn/acme/cache.rs index 19b46c0c2..700bee2fe 100644 --- a/crates/core/src/conn/acme/cache.rs +++ b/crates/core/src/conn/acme/cache.rs @@ -5,10 +5,10 @@ Note that the files contain private keys. */ use std::error::Error as StdError; +use std::future::Future; use std::io::{Error as IoError, ErrorKind, Result as IoResult}; use std::path::Path; -use async_trait::async_trait; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::engine::Engine; use ring::digest::{Context, SHA256}; @@ -19,8 +19,8 @@ use tokio::io::AsyncWriteExt; pub trait CacheError: StdError + Send + Sync + 'static {} impl CacheError for T where T: StdError + Send + Sync + 'static {} + /// Trait to define a custom location/mechanism to cache account data and certificates. -#[async_trait] pub trait AcmeCache { /// The error type returned from the functions on this trait. type Error: CacheError; @@ -36,7 +36,11 @@ pub trait AcmeCache { /// /// Returns an error when the private key was unable to be written /// successfully. - async fn read_key(&self, directory_name: &str, domains: &[String]) -> Result>, Self::Error>; + fn read_key( + &self, + directory_name: &str, + domains: &[String], + ) -> impl Future>, Self::Error>> + Send; /// Writes a certificate retrieved from `Acme`. The parameters are: /// @@ -50,7 +54,12 @@ pub trait AcmeCache { /// /// Returns an error when the certificate was unable to be written /// successfully. - async fn write_key(&self, directory_name: &str, domains: &[String], data: &[u8]) -> Result<(), Self::Error>; + fn write_key( + &self, + directory_name: &str, + domains: &[String], + data: &[u8], + ) -> impl Future> + Send; /// Returns the previously written certificate retrieved from `Acme`. The parameters are: /// @@ -63,7 +72,11 @@ pub trait AcmeCache { /// /// Returns an error when the certificate was unable to be written /// successfully. - async fn read_cert(&self, directory_name: &str, domains: &[String]) -> Result>, Self::Error>; + fn read_cert( + &self, + directory_name: &str, + domains: &[String], + ) -> impl Future>, Self::Error>> + Send; /// Writes a certificate retrieved from `Acme`. The parameters are: /// @@ -77,12 +90,17 @@ pub trait AcmeCache { /// /// Returns an error when the certificate was unable to be written /// successfully. - async fn write_cert(&self, directory_name: &str, domains: &[String], data: &[u8]) -> Result<(), Self::Error>; + fn write_cert( + &self, + directory_name: &str, + domains: &[String], + data: &[u8], + ) -> impl Future> + Send; } static KEY_PEM_PREFIX: &str = "key-"; static CERT_PEM_PREFIX: &str = "cert-"; -#[async_trait] + impl

AcmeCache for P where P: AsRef + Send + Sync, diff --git a/crates/core/src/conn/acme/listener.rs b/crates/core/src/conn/acme/listener.rs index c7a45e957..0bb39266c 100644 --- a/crates/core/src/conn/acme/listener.rs +++ b/crates/core/src/conn/acme/listener.rs @@ -15,7 +15,7 @@ use crate::conn::{Accepted, Acceptor, HandshakeStream, Holding, Listener}; use crate::http::uri::Scheme; use crate::http::Version; -use crate::{async_trait, Router}; +use crate::Router; use super::config::{AcmeConfig, AcmeConfigBuilder}; use super::resolver::{ResolveServerCert, ACME_TLS_ALPN_NAME}; @@ -265,7 +265,6 @@ impl AcmeListener { } } -#[async_trait] impl Listener for AcmeListener where T: Listener + Send, @@ -273,7 +272,7 @@ where { type Acceptor = AcmeAcceptor; - async fn try_bind(mut self) -> crate::Result { + async fn try_bind(self) -> crate::Result { let Self { inner, config_builder, @@ -320,7 +319,6 @@ cfg_feature! { } } - #[async_trait] impl Listener for AcmeQuinnListener where T: Listener + Send, @@ -420,7 +418,7 @@ where self.server_config.clone() } } -#[async_trait] + impl Acceptor for AcmeAcceptor where T: Acceptor + Send + 'static, diff --git a/crates/core/src/conn/joined.rs b/crates/core/src/conn/joined.rs index 249a29304..297742d95 100644 --- a/crates/core/src/conn/joined.rs +++ b/crates/core/src/conn/joined.rs @@ -8,7 +8,6 @@ use std::time::Duration; use pin_project::pin_project; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; -use crate::async_trait; use crate::conn::{Holding, HttpBuilder}; use crate::http::HttpConnection; use crate::service::HyperHandler; @@ -83,7 +82,6 @@ impl JoinedListener { JoinedListener { a, b } } } -#[async_trait] impl Listener for JoinedListener where A: Listener + Send + Unpin + 'static, @@ -131,7 +129,6 @@ where } } -#[async_trait] impl Acceptor for JoinedAcceptor where A: Acceptor + Send + Unpin + 'static, diff --git a/crates/core/src/conn/mod.rs b/crates/core/src/conn/mod.rs index 59c0fd0b3..a02d8be1f 100644 --- a/crates/core/src/conn/mod.rs +++ b/crates/core/src/conn/mod.rs @@ -4,19 +4,19 @@ //! The module also provides support for HTTP versions 1 and 2, as well as the QUIC protocol. //! Additionally, it includes implementations for Unix domain sockets. use std::fmt::{self, Display, Formatter}; +use std::future::Future; use std::io::Result as IoResult; use http::uri::Scheme; use tokio::io::{AsyncRead, AsyncWrite}; -use crate::async_trait; use crate::http::{HttpConnection, Version}; mod proto; pub use proto::HttpBuilder; cfg_feature! { - #![any(feature = "native-tls", feature = "rustls", feature = "openssl-tls", feature = "acme")] + #![any(feature = "native-tls", feature = "rustls", feature = "openssl", feature = "acme")] mod handshake_stream; pub use handshake_stream::HandshakeStream; } @@ -155,7 +155,6 @@ where } /// `Acceptor` represents an acceptor that can accept incoming connections. -#[async_trait] pub trait Acceptor { /// Conn type type Conn: HttpConnection + AsyncRead + AsyncWrite + Send + Unpin + 'static; @@ -164,7 +163,7 @@ pub trait Acceptor { fn holdings(&self) -> &[Holding]; /// Accepts a new incoming connection from this listener. - async fn accept(&mut self) -> IoResult>; + fn accept(&mut self) -> impl Future>> + Send; } /// Holding information. @@ -191,27 +190,27 @@ impl Display for Holding { } /// `Listener` represents a listener that can bind to a specific address and port and return an acceptor. -#[async_trait] + pub trait Listener { /// Acceptor type. type Acceptor: Acceptor; /// Bind and returns acceptor. - async fn bind(self) -> Self::Acceptor + fn bind(self) -> impl Future + Send where - Self: Sized, + Self: Sized + Send, { - self.try_bind().await.unwrap() + async move { self.try_bind().await.unwrap() } } /// Bind and returns acceptor. - async fn try_bind(self) -> crate::Result; + fn try_bind(self) -> impl Future> + Send; /// Join current Listener with the other. #[inline] fn join(self, other: T) -> JoinedListener where - Self: Sized, + Self: Sized + Send, { JoinedListener::new(self, other) } diff --git a/crates/core/src/conn/native_tls/listener.rs b/crates/core/src/conn/native_tls/listener.rs index 66b8637fd..b3fefd0a1 100644 --- a/crates/core/src/conn/native_tls/listener.rs +++ b/crates/core/src/conn/native_tls/listener.rs @@ -12,7 +12,6 @@ use http::uri::Scheme; use tokio::io::{AsyncRead, AsyncWrite}; use tokio_native_tls::TlsStream; -use crate::async_trait; use crate::conn::{Accepted, Acceptor, HandshakeStream, Holding, HttpBuilder, IntoConfigStream, Listener}; use crate::http::{HttpConnection, Version}; use crate::service::HyperHandler; @@ -43,7 +42,6 @@ where } } -#[async_trait] impl Listener for NativeTlsListener where S: IntoConfigStream + Send + 'static, @@ -124,7 +122,6 @@ where } } -#[async_trait] impl Acceptor for NativeTlsAcceptor where S: Stream + Send + Unpin + 'static, diff --git a/crates/core/src/conn/openssl/listener.rs b/crates/core/src/conn/openssl/listener.rs index 967155785..5af709e29 100644 --- a/crates/core/src/conn/openssl/listener.rs +++ b/crates/core/src/conn/openssl/listener.rs @@ -16,7 +16,6 @@ use tokio_openssl::SslStream; use super::SslAcceptorBuilder; -use crate::async_trait; use crate::conn::{Accepted, Acceptor, HandshakeStream, Holding, HttpBuilder, IntoConfigStream, Listener}; use crate::http::{HttpConnection, Version}; use crate::service::HyperHandler; @@ -46,7 +45,6 @@ where } } -#[async_trait] impl Listener for OpensslListener where S: IntoConfigStream + Send + 'static, @@ -129,7 +127,6 @@ where } } -#[async_trait] impl Acceptor for OpensslAcceptor where S: Stream + Send + Unpin + 'static, diff --git a/crates/core/src/conn/quinn/listener.rs b/crates/core/src/conn/quinn/listener.rs index d58413973..8c1974398 100644 --- a/crates/core/src/conn/quinn/listener.rs +++ b/crates/core/src/conn/quinn/listener.rs @@ -13,7 +13,6 @@ use futures_util::task::noop_waker_ref; use http::uri::Scheme; use salvo_http3::http3_quinn::{self, Endpoint}; -use crate::async_trait; use crate::conn::quinn::ServerConfig; use crate::conn::{Holding, IntoConfigStream}; use crate::http::Version; @@ -44,7 +43,6 @@ where } } } -#[async_trait] impl Listener for QuinnListener where S: IntoConfigStream + Send + 'static, @@ -100,7 +98,6 @@ where } } -#[async_trait] impl Acceptor for QuinnAcceptor where S: Stream + Send + Unpin + 'static, diff --git a/crates/core/src/conn/rustls/listener.rs b/crates/core/src/conn/rustls/listener.rs index bdb45a73f..10078e05c 100644 --- a/crates/core/src/conn/rustls/listener.rs +++ b/crates/core/src/conn/rustls/listener.rs @@ -11,7 +11,6 @@ use futures_util::task::noop_waker_ref; use tokio::io::{AsyncRead, AsyncWrite}; use tokio_rustls::server::TlsStream; -use crate::async_trait; use crate::conn::Holding; use crate::conn::{Accepted, HandshakeStream, Acceptor, IntoConfigStream, Listener}; use crate::http::uri::Scheme; @@ -44,7 +43,6 @@ where } } -#[async_trait] impl Listener for RustlsListener where S: IntoConfigStream + Send + 'static, @@ -110,7 +108,6 @@ where } } -#[async_trait] impl Acceptor for RustlsAcceptor where S: Stream + Send + Unpin + 'static, diff --git a/crates/core/src/conn/tcp.rs b/crates/core/src/conn/tcp.rs index 0d2dfa16f..ec43a5f84 100644 --- a/crates/core/src/conn/tcp.rs +++ b/crates/core/src/conn/tcp.rs @@ -7,7 +7,6 @@ use std::vec; use tokio::net::{TcpListener as TokioTcpListener, TcpStream, ToSocketAddrs}; -use crate::async_trait; use crate::conn::{Holding, HttpBuilder}; use crate::http::uri::Scheme; use crate::http::{HttpConnection, Version}; @@ -96,7 +95,6 @@ impl TcpListener { } } } -#[async_trait] impl Listener for TcpListener where T: ToSocketAddrs + Send, @@ -166,7 +164,6 @@ impl HttpConnection for TcpStream { } } -#[async_trait] impl Acceptor for TcpAcceptor { type Conn = TcpStream; diff --git a/crates/core/src/conn/unix.rs b/crates/core/src/conn/unix.rs index a9f34af24..a87d91eff 100644 --- a/crates/core/src/conn/unix.rs +++ b/crates/core/src/conn/unix.rs @@ -6,13 +6,13 @@ use std::sync::Arc; use std::time::Duration; use http::uri::Scheme; +use nix::unistd::{chown, Gid, Uid}; use tokio::net::{UnixListener as TokioUnixListener, UnixStream}; -use nix::unistd::{Gid, chown, Uid}; -use crate::{Error, async_trait}; use crate::conn::{Holding, HttpBuilder}; use crate::http::{HttpConnection, Version}; use crate::service::HyperHandler; +use crate::Error; use super::{Accepted, Acceptor, Listener}; @@ -28,9 +28,11 @@ impl UnixListener { /// Creates a new `UnixListener` bind to the specified path. #[inline] pub fn new(path: T) -> UnixListener { - UnixListener { path, + UnixListener { + path, permissions: None, - owner: None, } + owner: None, + } } /// Provides permissions to be set on actual bind. @@ -43,12 +45,11 @@ impl UnixListener { #[inline] /// Provides owner to be set on actual bind. pub fn owner(mut self, uid: Option, gid: Option) -> Self { - self.owner = Some((uid.map(|v| Uid::from_raw(v)), gid.map(|v| Gid::from_raw(v)))); + self.owner = Some((uid.map(Uid::from_raw), gid.map(Gid::from_raw))); self } } -#[async_trait] impl Listener for UnixListener where T: AsRef + Send + Clone, @@ -60,7 +61,7 @@ where (Some(permissions), Some((uid, gid))) => { let inner = TokioUnixListener::bind(self.path.clone())?; set_permissions(self.path.clone(), permissions)?; - chown(self.path.as_ref().as_os_str().into(), uid, gid).map_err(Error::other)?; + chown(self.path.as_ref().as_os_str(), uid, gid).map_err(Error::other)?; inner } (Some(permissions), None) => { @@ -70,7 +71,7 @@ where } (None, Some((uid, gid))) => { let inner = TokioUnixListener::bind(self.path.clone())?; - chown(self.path.as_ref().as_os_str().into(), uid, gid).map_err(Error::other)?; + chown(self.path.as_ref().as_os_str(), uid, gid).map_err(Error::other)?; inner } (None, None) => TokioUnixListener::bind(self.path)?, @@ -95,7 +96,6 @@ pub struct UnixAcceptor { } #[cfg(unix)] -#[async_trait] impl Acceptor for UnixAcceptor { type Conn = UnixStream; diff --git a/crates/core/src/test/request/builder.rs b/crates/core/src/test/request/builder.rs index 955d085e5..044e16855 100644 --- a/crates/core/src/test/request/builder.rs +++ b/crates/core/src/test/request/builder.rs @@ -1,5 +1,6 @@ use std::borrow::Borrow; use std::convert::TryInto; +use std::future::Future; use std::str; use std::sync::Arc; @@ -11,7 +12,7 @@ use url::Url; use crate::http::body::ReqBody; use crate::http::Method; use crate::routing::{FlowCtrl, Router}; -use crate::{async_trait, Depot, Error, Handler, Request, Response, Service}; +use crate::{ Depot, Error, Handler, Request, Response, Service}; /// `RequestBuilder` is the main way of building requests. /// @@ -249,34 +250,28 @@ impl RequestBuilder { } /// Trait for sending request to target, such as [`Router`], [`Service`], [`Handler`]. for test usage. -#[async_trait] pub trait SendTarget { /// Send request to target, such as [`Router`], [`Service`], [`Handler`]. #[must_use = "future must be used"] - async fn call(self, req: Request) -> Response; + fn call(self, req: Request) -> impl Future + Send; } -#[async_trait] impl SendTarget for &Service { async fn call(self, req: Request) -> Response { self.handle(req).await } } -#[async_trait] impl SendTarget for Router { async fn call(self, req: Request) -> Response { let router = Arc::new(self); SendTarget::call(router, req).await } } -#[async_trait] impl SendTarget for Arc { async fn call(self, req: Request) -> Response { let srv = Service::new(self); srv.handle(req).await } } - -#[async_trait] impl SendTarget for Arc where T: Handler + Send, @@ -293,7 +288,6 @@ where res } } -#[async_trait] impl SendTarget for T where T: Handler + Send, diff --git a/crates/core/src/test/response.rs b/crates/core/src/test/response.rs index 9c9a2b6ae..9dca44ec3 100644 --- a/crates/core/src/test/response.rs +++ b/crates/core/src/test/response.rs @@ -1,4 +1,5 @@ use std::borrow::Cow; +use std::future::Future; use std::io::{self, Result as IoResult, Write}; use bytes::{Bytes, BytesMut}; @@ -13,7 +14,7 @@ use zstd::stream::write::Decoder as ZstdDecoder; use crate::catcher::status_error_bytes; use crate::http::header::{self, CONTENT_ENCODING}; use crate::http::response::{ResBody, Response}; -use crate::{async_trait, Error}; +use crate::Error; struct Writer { buf: BytesMut, @@ -43,24 +44,22 @@ impl io::Write for Writer { } /// More utils functions for response. -#[async_trait] pub trait ResponseExt { /// Take body as `String` from response. - async fn take_string(&mut self) -> crate::Result; + fn take_string(&mut self) -> impl Future> + Send; /// Take body as deserialize it to type `T` instance. - async fn take_json(&mut self) -> crate::Result; + fn take_json(&mut self) -> impl Future> + Send; /// Take body as `String` from response with charset. - async fn take_string_with_charset( + fn take_string_with_charset( &mut self, content_type: Option<&Mime>, charset: &str, compress: Option<&str>, - ) -> crate::Result; + ) -> impl Future>; /// Take all body bytes. If body is none, it will creates and returns a new [`Bytes`]. - async fn take_bytes(&mut self, content_type: Option<&Mime>) -> crate::Result; + fn take_bytes(&mut self, content_type: Option<&Mime>) -> impl Future> + Send; } -#[async_trait] impl ResponseExt for Response { async fn take_string(&mut self) -> crate::Result { let content_type = self diff --git a/crates/csrf/src/cookie_store.rs b/crates/csrf/src/cookie_store.rs index b1bbca150..7fe0e99ea 100644 --- a/crates/csrf/src/cookie_store.rs +++ b/crates/csrf/src/cookie_store.rs @@ -1,7 +1,7 @@ use cookie::time::Duration; use cookie::{Cookie, Expiration, SameSite}; use salvo_core::http::uri::Scheme; -use salvo_core::{async_trait, Depot, Error, Request, Response}; +use salvo_core::{Depot, Error, Request, Response}; use crate::CsrfCipher; @@ -61,7 +61,6 @@ impl CookieStore { self } } -#[async_trait] impl CsrfStore for CookieStore { type Error = Error; async fn load(&self, req: &mut Request, _depot: &mut Depot, cipher: &C) -> Option<(String, String)> { diff --git a/crates/csrf/src/lib.rs b/crates/csrf/src/lib.rs index 3383dbf09..9d01d442a 100644 --- a/crates/csrf/src/lib.rs +++ b/crates/csrf/src/lib.rs @@ -16,6 +16,7 @@ #![warn(rustdoc::broken_intra_doc_links)] use std::error::Error as StdError; +use std::future::Future; mod finder; @@ -164,21 +165,25 @@ fn default_skipper(req: &mut Request, _depot: &Depot) -> bool { } /// Store proof. -#[async_trait] pub trait CsrfStore: Send + Sync + 'static { /// Error type for CsrfStore. type Error: StdError + Send + Sync + 'static; /// Get the proof from the store. - async fn load(&self, req: &mut Request, depot: &mut Depot, cipher: &C) -> Option<(String, String)>; + fn load( + &self, + req: &mut Request, + depot: &mut Depot, + cipher: &C, + ) -> impl Future> + Send; /// Save the proof from the store. - async fn save( + fn save( &self, req: &mut Request, depot: &mut Depot, res: &mut Response, token: &str, proof: &str, - ) -> Result<(), Self::Error>; + ) -> impl Future> + Send; } /// Generate token and proof and valid token. diff --git a/crates/csrf/src/session_store.rs b/crates/csrf/src/session_store.rs index 6963dadf0..ab96a4bd7 100644 --- a/crates/csrf/src/session_store.rs +++ b/crates/csrf/src/session_store.rs @@ -1,4 +1,4 @@ -use salvo_core::{async_trait, Depot, Error, Request, Response}; +use salvo_core::{Depot, Error, Request, Response}; use salvo_session::SessionDepotExt; use super::{CsrfCipher, CsrfStore}; @@ -23,7 +23,6 @@ impl SessionStore { } } -#[async_trait] impl CsrfStore for SessionStore { type Error = Error; async fn load(&self, _req: &mut Request, depot: &mut Depot, _cipher: &C) -> Option<(String, String)> { diff --git a/crates/extra/src/basic_auth.rs b/crates/extra/src/basic_auth.rs index 0b9180a3b..a20147653 100644 --- a/crates/extra/src/basic_auth.rs +++ b/crates/extra/src/basic_auth.rs @@ -1,6 +1,8 @@ //! basic auth middleware. //! //! Read more: +use std::future::Future; + use salvo_core::http::header::{HeaderName, PROXY_AUTHORIZATION, AUTHORIZATION}; use salvo_core::http::{Request, Response, StatusCode}; use salvo_core::{async_trait, Depot, Error, FlowCtrl, Handler}; @@ -10,10 +12,9 @@ use base64::engine::{general_purpose, Engine}; pub const USERNAME_KEY: &str = "::salvo::basic_auth::username"; /// BasicAuthValidator -#[async_trait] pub trait BasicAuthValidator: Send + Sync { /// Validate is that username and password is right. - async fn validate(&self, username: &str, password: &str, depot: &mut Depot) -> bool; + fn validate(&self, username: &str, password: &str, depot: &mut Depot) -> impl Future + Send; } /// BasicAuthDepotExt pub trait BasicAuthDepotExt { @@ -147,7 +148,6 @@ mod tests { } struct Validator; - #[async_trait] impl BasicAuthValidator for Validator { async fn validate(&self, username: &str, password: &str, _depot: &mut Depot) -> bool { username == "root" && password == "pwd" diff --git a/crates/flash/src/cookie_store.rs b/crates/flash/src/cookie_store.rs index 818c4da76..8fada7e75 100644 --- a/crates/flash/src/cookie_store.rs +++ b/crates/flash/src/cookie_store.rs @@ -1,6 +1,6 @@ use salvo_core::http::cookie::time::Duration; use salvo_core::http::cookie::{Cookie, SameSite}; -use salvo_core::{async_trait, Depot, Request, Response}; +use salvo_core::{Depot, Request, Response}; use super::{Flash, FlashHandler, FlashStore}; @@ -72,7 +72,6 @@ impl CookieStore { FlashHandler::new(self) } } -#[async_trait] impl FlashStore for CookieStore { async fn load_flash(&self, req: &mut Request, _depot: &mut Depot) -> Option { match req.cookie(&self.name) { diff --git a/crates/flash/src/lib.rs b/crates/flash/src/lib.rs index f303993cc..84b00acf4 100644 --- a/crates/flash/src/lib.rs +++ b/crates/flash/src/lib.rs @@ -11,6 +11,7 @@ #![warn(rustdoc::broken_intra_doc_links)] use std::fmt::{self, Debug, Display, Formatter}; +use std::future::Future; use std::ops::Deref; use salvo_core::{async_trait, Depot, FlowCtrl, Handler, Request, Response}; @@ -184,14 +185,19 @@ impl Display for FlashLevel { } /// `FlashStore` is for stores flash messages. -#[async_trait] pub trait FlashStore: Debug + Send + Sync + 'static { /// Get the flash messages from the store. - async fn load_flash(&self, req: &mut Request, depot: &mut Depot) -> Option; + fn load_flash(&self, req: &mut Request, depot: &mut Depot) -> impl Future> + Send; /// Save the flash messages to the store. - async fn save_flash(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, flash: Flash); + fn save_flash( + &self, + req: &mut Request, + depot: &mut Depot, + res: &mut Response, + flash: Flash, + ) -> impl Future + Send; /// Clear the flash store. - async fn clear_flash(&self, depot: &mut Depot, res: &mut Response); + fn clear_flash(&self, depot: &mut Depot, res: &mut Response) -> impl Future + Send; } /// A trait for `Depot` to get flash messages. diff --git a/crates/flash/src/session_store.rs b/crates/flash/src/session_store.rs index 2d16f6beb..412bddd53 100644 --- a/crates/flash/src/session_store.rs +++ b/crates/flash/src/session_store.rs @@ -1,4 +1,4 @@ -use salvo_core::{async_trait, Depot, Request, Response}; +use salvo_core::{Depot, Request, Response}; use salvo_session::SessionDepotExt; use super::{Flash, FlashHandler, FlashStore}; @@ -35,7 +35,7 @@ impl SessionStore { FlashHandler::new(self) } } -#[async_trait] + impl FlashStore for SessionStore { async fn load_flash(&self, _req: &mut Request, depot: &mut Depot) -> Option { depot.session().and_then(|s| s.get::(&self.name)) diff --git a/crates/jwt-auth/src/decoder.rs b/crates/jwt-auth/src/decoder.rs index 9b05dc630..f0b15a9fa 100644 --- a/crates/jwt-auth/src/decoder.rs +++ b/crates/jwt-auth/src/decoder.rs @@ -1,17 +1,21 @@ use jsonwebtoken::errors::Error as JwtError; use jsonwebtoken::{decode, Algorithm, DecodingKey, TokenData, Validation}; use serde::Deserialize; +use std::future::Future; -use salvo_core::{async_trait, Depot}; +use salvo_core::Depot; /// JwtAuthDecoder is used to decode token to claims. -#[async_trait] pub trait JwtAuthDecoder { /// Error type. type Error: std::error::Error + Send + Sync + 'static; ///Decode token. - async fn decode(&self, token: &str, depot: &mut Depot) -> Result, Self::Error> + fn decode( + &self, + token: &str, + depot: &mut Depot, + ) -> impl Future, Self::Error>> + Send where C: for<'de> Deserialize<'de>; } @@ -106,7 +110,6 @@ impl ConstDecoder { } } -#[async_trait] impl JwtAuthDecoder for ConstDecoder { type Error = JwtError; diff --git a/crates/jwt-auth/src/oidc/mod.rs b/crates/jwt-auth/src/oidc/mod.rs index 5e4ad37d9..a103d2523 100644 --- a/crates/jwt-auth/src/oidc/mod.rs +++ b/crates/jwt-auth/src/oidc/mod.rs @@ -16,7 +16,7 @@ use hyper_util::rt::TokioExecutor; use jsonwebtoken::jwk::{Jwk, JwkSet}; use jsonwebtoken::{Algorithm, DecodingKey, TokenData, Validation}; use salvo_core::http::{header::CACHE_CONTROL, uri::Uri}; -use salvo_core::{async_trait, Depot}; +use salvo_core::Depot; use serde::de::DeserializeOwned; use serde::Deserialize; use tokio::sync::{Notify, RwLock}; @@ -39,7 +39,6 @@ pub struct OidcDecoder { notifier: Arc, } -#[async_trait] impl JwtAuthDecoder for OidcDecoder { type Error = JwtAuthError; diff --git a/crates/macros/src/shared.rs b/crates/macros/src/shared.rs index 286e67a2a..703c570a7 100644 --- a/crates/macros/src/shared.rs +++ b/crates/macros/src/shared.rs @@ -4,6 +4,7 @@ use quote::ToTokens; use regex::Regex; use syn::{FnArg, Ident, PatType, Receiver, Type, TypePath}; +#[allow(dead_code)] pub(crate) enum InputType<'a> { Request(&'a PatType), Depot(&'a PatType), diff --git a/crates/oapi-macros/src/feature/items.rs b/crates/oapi-macros/src/feature/items.rs index 0b3e0bee6..0e055b10e 100644 --- a/crates/oapi-macros/src/feature/items.rs +++ b/crates/oapi-macros/src/feature/items.rs @@ -768,6 +768,7 @@ impl From for Feature { impl_name!(MinItems = "min_items"); #[derive(Clone, Debug)] +#[allow(dead_code)] pub(crate) struct MaxProperties(pub(crate) usize, pub(crate) Ident); impl Parse for MaxProperties { fn parse(input: ParseStream, ident: Ident) -> syn::Result @@ -790,6 +791,7 @@ impl From for Feature { impl_name!(MaxProperties = "max_properties"); #[derive(Clone, Debug)] +#[allow(dead_code)] pub(crate) struct MinProperties(pub(crate) usize, pub(crate) Ident); impl Parse for MinProperties { fn parse(input: ParseStream, ident: Ident) -> syn::Result diff --git a/crates/oapi-macros/src/shared.rs b/crates/oapi-macros/src/shared.rs index bb43a2d31..a12013b4f 100644 --- a/crates/oapi-macros/src/shared.rs +++ b/crates/oapi-macros/src/shared.rs @@ -4,6 +4,7 @@ use quote::ToTokens; use regex::Regex; use syn::{FnArg, Ident, PatType, Receiver, Type, TypePath}; +#[allow(dead_code)] pub(crate) enum InputType<'a> { Request(&'a PatType), Depot(&'a PatType), diff --git a/crates/oapi/src/extract/parameter/path.rs b/crates/oapi/src/extract/parameter/path.rs index 9e9cb2381..f921b14cb 100644 --- a/crates/oapi/src/extract/parameter/path.rs +++ b/crates/oapi/src/extract/parameter/path.rs @@ -155,7 +155,7 @@ mod tests { #[tokio::test] async fn test_path_prarm_extract_with_value() { - let mut req = TestClient::get("http://127.0.0.1:5801").build_hyper(); + let req = TestClient::get("http://127.0.0.1:5801").build_hyper(); let schema = req.uri().scheme().cloned().unwrap(); let mut req = Request::from_hyper(req, schema); req.params_mut().insert("param".to_string(), "param".to_string()); diff --git a/crates/oapi/src/extract/parameter/query.rs b/crates/oapi/src/extract/parameter/query.rs index de1fe0633..a67350a3c 100644 --- a/crates/oapi/src/extract/parameter/query.rs +++ b/crates/oapi/src/extract/parameter/query.rs @@ -209,7 +209,7 @@ mod tests { #[tokio::test] async fn test_required_query_prarm_extract_with_value() { - let mut req = TestClient::get("http://127.0.0.1:5801").build_hyper(); + let req = TestClient::get("http://127.0.0.1:5801").build_hyper(); let schema = req.uri().scheme().cloned().unwrap(); let mut req = Request::from_hyper(req, schema); req.queries_mut().insert("param".to_string(), "param".to_string()); @@ -242,7 +242,7 @@ mod tests { #[tokio::test] async fn test_query_prarm_extract_with_value() { - let mut req = TestClient::get("http://127.0.0.1:5801").build_hyper(); + let req = TestClient::get("http://127.0.0.1:5801").build_hyper(); let schema = req.uri().scheme().cloned().unwrap(); let mut req = Request::from_hyper(req, schema); req.queries_mut().insert("param".to_string(), "param".to_string()); diff --git a/crates/proxy/src/clients.rs b/crates/proxy/src/clients.rs index 55e13ac99..3db368b45 100644 --- a/crates/proxy/src/clients.rs +++ b/crates/proxy/src/clients.rs @@ -4,7 +4,7 @@ use hyper_util::client::legacy::{connect::HttpConnector, Client as HyperUtilClie use hyper_util::rt::TokioExecutor; use salvo_core::http::{ReqBody, ResBody, StatusCode}; use salvo_core::rt::tokio::TokioIo; -use salvo_core::{async_trait, Error}; +use salvo_core::Error; use tokio::io::copy_bidirectional; use super::{HyperRequest, HyperResponse}; @@ -33,7 +33,6 @@ impl HyperClient { } } -#[async_trait] impl super::Client for HyperClient { type Error = salvo_core::Error; diff --git a/crates/proxy/src/lib.rs b/crates/proxy/src/lib.rs index b31dd66fc..25ff9489b 100644 --- a/crates/proxy/src/lib.rs +++ b/crates/proxy/src/lib.rs @@ -12,6 +12,7 @@ use std::convert::{Infallible, TryFrom}; use std::error::Error as StdError; +use std::future::Future; use hyper::upgrade::OnUpgrade; use percent_encoding::{utf8_percent_encode, CONTROLS}; @@ -36,23 +37,24 @@ pub(crate) fn encode_url_path(path: &str) -> String { } /// Client trait. -#[async_trait] pub trait Client: Send + Sync + 'static { /// Error type. type Error: StdError + Send + Sync + 'static; /// Elect a upstream to process current request. - async fn execute(&self, req: HyperRequest, upgraded: Option) -> Result; + fn execute( + &self, + req: HyperRequest, + upgraded: Option, + ) -> impl Future> + Send; } /// Upstreams trait. -#[async_trait] pub trait Upstreams: Send + Sync + 'static { /// Error type. type Error: StdError + Send + Sync + 'static; /// Elect a upstream to process current request. - async fn elect(&self) -> Result<&str, Self::Error>; + fn elect(&self) -> impl Future> + Send; } -#[async_trait] impl Upstreams for &'static str { type Error = Infallible; @@ -60,7 +62,6 @@ impl Upstreams for &'static str { Ok(*self) } } -#[async_trait] impl Upstreams for String { type Error = Infallible; async fn elect(&self) -> Result<&str, Self::Error> { @@ -68,7 +69,6 @@ impl Upstreams for String { } } -#[async_trait] impl Upstreams for [&'static str; N] { type Error = Error; async fn elect(&self) -> Result<&str, Self::Error> { @@ -80,7 +80,6 @@ impl Upstreams for [&'static str; N] { } } -#[async_trait] impl Upstreams for Vec where T: AsRef + Send + Sync + 'static, diff --git a/crates/rate-limiter/src/fixed_guard.rs b/crates/rate-limiter/src/fixed_guard.rs index 2bac90e82..6784bc0b6 100644 --- a/crates/rate-limiter/src/fixed_guard.rs +++ b/crates/rate-limiter/src/fixed_guard.rs @@ -1,4 +1,3 @@ -use salvo_core::async_trait; use serde::{Deserialize, Serialize}; use time::OffsetDateTime; @@ -29,7 +28,6 @@ impl FixedGuard { } } -#[async_trait] impl RateGuard for FixedGuard { type Quota = BasicQuota; async fn verify(&mut self, quota: &Self::Quota) -> bool { diff --git a/crates/rate-limiter/src/lib.rs b/crates/rate-limiter/src/lib.rs index 2ec43a10b..461b6ba42 100644 --- a/crates/rate-limiter/src/lib.rs +++ b/crates/rate-limiter/src/lib.rs @@ -22,6 +22,7 @@ use std::borrow::Borrow; use std::error::Error as StdError; +use std::future::Future; use std::hash::Hash; use salvo_core::conn::SocketAddr; @@ -56,14 +57,12 @@ cfg_feature! { } /// Issuer is used to identify every request. -#[async_trait] pub trait RateIssuer: Send + Sync + 'static { /// The key is used to identify the rate limit. type Key: Hash + Eq + Send + Sync + 'static; /// Issue a new key for the request. - async fn issue(&self, req: &mut Request, depot: &Depot) -> Option; + fn issue(&self, req: &mut Request, depot: &Depot) -> impl Future> + Send; } -#[async_trait] impl RateIssuer for F where F: Fn(&mut Request, &Depot) -> Option + Send + Sync + 'static, @@ -77,7 +76,6 @@ where /// Identify user by IP address. pub struct RemoteIpIssuer; -#[async_trait] impl RateIssuer for RemoteIpIssuer { type Key = String; async fn issue(&self, req: &mut Request, _depot: &Depot) -> Option { @@ -90,25 +88,23 @@ impl RateIssuer for RemoteIpIssuer { } /// `RateGuard` is strategy to verify is the request exceeded quota -#[async_trait] pub trait RateGuard: Clone + Send + Sync + 'static { /// The quota for the rate limit. type Quota: Clone + Send + Sync + 'static; /// Verify is current request exceed the quota. - async fn verify(&mut self, quota: &Self::Quota) -> bool; + fn verify(&mut self, quota: &Self::Quota) -> impl Future + Send; /// Returns the remaining quota. - async fn remaining(&self, quota: &Self::Quota) -> usize; + fn remaining(&self, quota: &Self::Quota) -> impl Future + Send; /// Returns the reset time. - async fn reset(&self, quota: &Self::Quota) -> i64; + fn reset(&self, quota: &Self::Quota) -> impl Future + Send; /// Returns the limit. - async fn limit(&self, quota: &Self::Quota) -> usize; + fn limit(&self, quota: &Self::Quota) -> impl Future + Send; } /// `RateStore` is used to store rate limit data. -#[async_trait] pub trait RateStore: Send + Sync + 'static { /// Error type for RateStore. type Error: StdError; @@ -117,12 +113,16 @@ pub trait RateStore: Send + Sync + 'static { /// Saved guard. type Guard; /// Get the guard from the store. - async fn load_guard(&self, key: &Q, refer: &Self::Guard) -> Result + fn load_guard( + &self, + key: &Q, + refer: &Self::Guard, + ) -> impl Future> + Send where Self::Key: Borrow, Q: Hash + Eq + Sync; /// Save the guard from the store. - async fn save_guard(&self, key: Self::Key, guard: Self::Guard) -> Result<(), Self::Error>; + fn save_guard(&self, key: Self::Key, guard: Self::Guard) -> impl Future> + Send; } /// `RateLimiter` is the main struct to used limit user request. @@ -241,7 +241,6 @@ mod tests { use super::*; struct UserIssuer; - #[async_trait] impl RateIssuer for UserIssuer { type Key = String; async fn issue(&self, req: &mut Request, _depot: &Depot) -> Option { @@ -264,7 +263,6 @@ mod tests { }); struct CustomQuotaGetter; - #[async_trait] impl QuotaGetter for CustomQuotaGetter { type Quota = BasicQuota; type Error = Error; @@ -345,7 +343,6 @@ mod tests { }); struct CustomQuotaGetter; - #[async_trait] impl QuotaGetter for CustomQuotaGetter { type Quota = CelledQuota; type Error = Error; diff --git a/crates/rate-limiter/src/moka_store.rs b/crates/rate-limiter/src/moka_store.rs index a62ee641a..4858c4223 100644 --- a/crates/rate-limiter/src/moka_store.rs +++ b/crates/rate-limiter/src/moka_store.rs @@ -3,7 +3,6 @@ use std::convert::Infallible; use std::hash::Hash; use moka::future::Cache as MokaCache; -use salvo_core::async_trait; use super::{RateGuard, RateStore}; @@ -38,7 +37,6 @@ where } } -#[async_trait] impl RateStore for MokaStore where K: Hash + Eq + Send + Sync + Clone + 'static, diff --git a/crates/rate-limiter/src/quota.rs b/crates/rate-limiter/src/quota.rs index 98db9cd48..d342a8ed5 100644 --- a/crates/rate-limiter/src/quota.rs +++ b/crates/rate-limiter/src/quota.rs @@ -1,14 +1,13 @@ use std::borrow::Borrow; use std::convert::Infallible; use std::error::Error as StdError; +use std::future::Future; use std::hash::Hash; -use salvo_core::async_trait; use serde::{Deserialize, Serialize}; use time::Duration; /// Used to get quota and you can config users' quota config in database. -#[async_trait] pub trait QuotaGetter: Send + Sync + 'static { /// Quota type. type Quota: Clone + Send + Sync + 'static; @@ -16,7 +15,7 @@ pub trait QuotaGetter: Send + Sync + 'static { type Error: StdError; /// Get quota. - async fn get(&self, key: &Q) -> Result + fn get(&self, key: &Q) -> impl Future> + Send where Key: Borrow, Q: Hash + Eq + Sync; @@ -110,7 +109,6 @@ impl CelledQuota { } } -#[async_trait] impl QuotaGetter for T where Key: Hash + Eq + Send + Sync + 'static, diff --git a/crates/rate-limiter/src/sliding_guard.rs b/crates/rate-limiter/src/sliding_guard.rs index 5ba84ad45..0100e172d 100644 --- a/crates/rate-limiter/src/sliding_guard.rs +++ b/crates/rate-limiter/src/sliding_guard.rs @@ -1,4 +1,3 @@ -use salvo_core::async_trait; use time::{Duration, OffsetDateTime}; use super::{CelledQuota, RateGuard}; @@ -32,7 +31,6 @@ impl SlidingGuard { } } -#[async_trait] impl RateGuard for SlidingGuard { type Quota = CelledQuota; async fn verify(&mut self, quota: &Self::Quota) -> bool { diff --git a/examples/basic-auth/src/main.rs b/examples/basic-auth/src/main.rs index 6bd57b6b3..46249b7b5 100644 --- a/examples/basic-auth/src/main.rs +++ b/examples/basic-auth/src/main.rs @@ -18,7 +18,6 @@ async fn hello() -> &'static str { } struct Validator; -#[async_trait] impl BasicAuthValidator for Validator { async fn validate(&self, username: &str, password: &str, _depot: &mut Depot) -> bool { username == "root" && password == "pwd" diff --git a/examples/cors/src/main.rs b/examples/cors/src/main.rs index f00427537..42fa41958 100644 --- a/examples/cors/src/main.rs +++ b/examples/cors/src/main.rs @@ -1,4 +1,3 @@ -use salvo::catcher::Catcher; use salvo::cors::Cors; use salvo::http::Method; use salvo::prelude::*; diff --git a/examples/rate-limiter-dynamic/src/main.rs b/examples/rate-limiter-dynamic/src/main.rs index 9d9fed507..6029aae44 100644 --- a/examples/rate-limiter-dynamic/src/main.rs +++ b/examples/rate-limiter-dynamic/src/main.rs @@ -16,7 +16,6 @@ static USER_QUOTAS: Lazy> = Lazy::new(|| { }); struct UserIssuer; -#[async_trait] impl RateIssuer for UserIssuer { type Key = String; async fn issue(&self, req: &mut Request, _depot: &Depot) -> Option { @@ -25,7 +24,6 @@ impl RateIssuer for UserIssuer { } struct CustomQuotaGetter; -#[async_trait] impl QuotaGetter for CustomQuotaGetter { type Quota = CelledQuota; type Error = Error;