Skip to content

Commit

Permalink
refactor(protocol): protocol lib should not use anyhow
Browse files Browse the repository at this point in the history
  • Loading branch information
Sherlock-Holo committed May 30, 2024
1 parent 8cf87e1 commit 274b2dc
Show file tree
Hide file tree
Showing 6 changed files with 25 additions and 22 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

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

1 change: 0 additions & 1 deletion protocol/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ version = "0.1.0"
edition = "2021"

[dependencies]
anyhow = { workspace = true }
bytes = { workspace = true }
event-listener = { workspace = true }
futures-util = { workspace = true, features = ["io", "sink"] }
Expand Down
5 changes: 1 addition & 4 deletions protocol/src/accept.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::{io, mem, slice};

use bytes::{Buf, Bytes};
use futures_channel::mpsc::{self, UnboundedReceiver, UnboundedSender};
use futures_rustls::rustls::ServerConfig;
pub use futures_rustls::rustls::ServerConfig;
use futures_rustls::server::TlsStream;
use futures_util::{AsyncRead, AsyncWrite, Stream, TryFutureExt, TryStreamExt};
use http::{Request, Response, StatusCode, Version};
Expand Down Expand Up @@ -389,9 +389,6 @@ pub enum Error {
#[error("address domain invalid")]
AddrDomainInvalid,

#[error("auth failed")]
AuthFailed,

#[error(transparent)]
Other(Box<dyn std::error::Error + Send + Sync + 'static>),

Expand Down
4 changes: 2 additions & 2 deletions protocol/src/auth.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::fmt::{Debug, Formatter};

use totp_rs::{Algorithm, TOTP};
use totp_rs::{Algorithm, TotpUrlError, TOTP};

pub struct Auth {
totp: TOTP,
Expand All @@ -18,7 +18,7 @@ impl Auth {
pub fn new(
token_secret: String,
account_name: impl Into<Option<String>>,
) -> anyhow::Result<Self> {
) -> Result<Self, TotpUrlError> {
Ok(Self {
totp: TOTP::new(
Algorithm::SHA512,
Expand Down
34 changes: 21 additions & 13 deletions protocol/src/connect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use std::pin::Pin;
use std::sync::Arc;
use std::task::{ready, Context, Poll};

use anyhow::Context as _;
use bytes::Bytes;
use futures_channel::mpsc;
use futures_rustls::client::TlsStream;
Expand Down Expand Up @@ -41,6 +40,18 @@ pub type ReadWrite = (
SinkWriter<SinkBodySender<Infallible>>,
);

#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
Http(#[from] http::Error),

#[error("hyper error: {0}")]
Hyper(#[from] hyper_util::client::legacy::Error),

#[error(transparent)]
Other(Box<dyn std::error::Error + Send + Sync + 'static>),
}

#[derive(Debug)]
pub struct HyperConnectorConfig<TC, DR, E, T> {
pub tls_client_config: ClientConfig,
Expand Down Expand Up @@ -68,7 +79,7 @@ struct HyperConnectorInner<TC, DR> {
}

impl<DR: DnsResolver + Sync + 'static, TC: TcpConnector + Sync + 'static> HyperConnector<TC, DR> {
pub fn new<E, T>(config: HyperConnectorConfig<TC, DR, E, T>) -> anyhow::Result<Self>
pub fn new<E, T>(config: HyperConnectorConfig<TC, DR, E, T>) -> Result<Self, Error>
where
E: hyper::rt::Executor<Pin<Box<dyn Future<Output = ()> + Send>>>
+ Send
Expand Down Expand Up @@ -99,15 +110,16 @@ impl<DR: DnsResolver + Sync + 'static, TC: TcpConnector + Sync + 'static> HyperC
remote_addr: Uri::try_from(format!(
"https://{}:{}",
config.remote_domain, config.remote_port
))?,
))
.map_err(|err| Error::Other(err.into()))?,
token_generator: config.auth,
token_header: config.token_header,
}),
})
}

#[instrument(skip(self), err(Debug))]
pub async fn connect(&self, remote_addr: DomainOrSocketAddr) -> anyhow::Result<ReadWrite> {
pub async fn connect(&self, remote_addr: DomainOrSocketAddr) -> Result<ReadWrite, Error> {
let token = self.inner.token_generator.generate_token();
let remote_addr_data = super::encode_addr(remote_addr);

Expand All @@ -120,23 +132,19 @@ impl<DR: DnsResolver + Sync + 'static, TC: TcpConnector + Sync + 'static> HyperC
.version(Version::HTTP_2)
.uri(self.inner.remote_addr.clone())
.header(&self.inner.token_header, token)
.body(BoxBody::new(StreamBody::new(req_body_rx)))
.with_context(|| "build h2 request failed")?;
.body(BoxBody::new(StreamBody::new(req_body_rx)))?;

let response = self
.inner
.client
.request(request)
.await
.with_context(|| "send h2 request failed")?;
let response = self.inner.client.request(request).await?;

info!("receive h2 response done");

if response.status() != StatusCode::OK {
let status_code = response.status();
error!(%status_code, "status code is not 200");

return Err(anyhow::anyhow!("status {status_code} is not 200"));
return Err(Error::Other(
format!("status {status_code} is not 200").into(),
));
}

info!("get h2 stream done");
Expand Down
2 changes: 1 addition & 1 deletion server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ pub async fn run() -> Result<(), Error> {

info!(listen_addr = %config.listen_addr, "start listen");

let auth = Auth::new(config.token_secret, None).expect("TODO");
let auth = Auth::new(config.token_secret, None).map_err(|err| Error::Other(err.into()))?;
let server = HyperServer::new(config.token_header, auth, tcp_listener, server_config)?;

server.start().await
Expand Down

0 comments on commit 274b2dc

Please sign in to comment.