Skip to content

Commit

Permalink
fix: update http client
Browse files Browse the repository at this point in the history
  • Loading branch information
heilhead committed Feb 15, 2024
1 parent 8fe1538 commit 803b7ca
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 51 deletions.
20 changes: 18 additions & 2 deletions relay_client/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,22 @@ pub enum ClientError {
InvalidRequestType,
}

impl From<rpc::ErrorData> for ClientError {
fn from(err: rpc::ErrorData) -> Self {
let rpc::ErrorData {
code,
message,
data,
} = err;

Self::Rpc {
code,
message,
data,
}
}
}

impl ClientError {
pub fn into_service_error<T: ServiceError>(self) -> Error<T> {
match self {
Expand All @@ -79,7 +95,7 @@ impl ClientError {
};

match rpc::Error::try_from(err) {
Ok(err) => Error::Request(err),
Ok(err) => Error::Response(err),

Err(_) => Error::Client(ClientError::InvalidErrorResponse),
}
Expand All @@ -96,5 +112,5 @@ pub enum Error<T: ServiceError> {
Client(#[from] ClientError),

#[error(transparent)]
Request(#[from] rpc::Error<T>),
Response(#[from] rpc::Error<T>),
}
71 changes: 41 additions & 30 deletions relay_client/src/http.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use {
crate::{
error::{BoxError, ClientError},
error::{BoxError, ClientError, Error},
ConnectionOptions,
MessageIdGenerator,
},
Expand All @@ -16,8 +16,8 @@ use {
};

pub type TransportError = reqwest::Error;
pub type Response<T> = Result<<T as ServiceRequest>::Response, ClientError>;
pub type EmptyResponse = Result<(), ClientError>;
pub type Response<T> = Result<<T as ServiceRequest>::Response, Error<<T as ServiceRequest>::Error>>;
pub type EmptyResponse<T> = Result<(), Error<<T as ServiceRequest>::Error>>;

#[derive(Debug, thiserror::Error)]
pub enum RequestParamsError {
Expand All @@ -41,9 +41,6 @@ pub enum HttpClientError {

#[error("JWT error: {0}")]
Jwt(#[from] JwtError),

#[error("RPC error: code={} message={}", .0.code, .0.message)]
RpcError(rpc::ErrorData),
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -111,11 +108,14 @@ impl Client {
tag: u32,
ttl: Duration,
prompt: bool,
) -> EmptyResponse {
) -> EmptyResponse<rpc::Publish> {
let ttl_secs = ttl
.as_secs()
.try_into()
.map_err(|_| HttpClientError::InvalidRequest(RequestParamsError::InvalidTtl.into()))?;
.map_err(|_| {
HttpClientError::InvalidRequest(RequestParamsError::InvalidTtl.into()).into()
})
.map_err(Error::Client)?;

self.request(rpc::Publish {
topic,
Expand Down Expand Up @@ -175,7 +175,8 @@ impl Client {
.ttl
.as_secs()
.try_into()
.map_err(|err| HttpClientError::InvalidRequest(Box::new(err)))?;
.map_err(|err| HttpClientError::InvalidRequest(Box::new(err)).into())
.map_err(Error::Client)?;
let exp = iat + ttl_sec;

let claims = rpc::WatchRegisterClaims {
Expand All @@ -194,7 +195,10 @@ impl Client {
};

let payload = rpc::WatchRegister {
register_auth: claims.encode(keypair).map_err(HttpClientError::Jwt)?,
register_auth: claims
.encode(keypair)
.map_err(|err| HttpClientError::Jwt(err).into())
.map_err(Error::Client)?,
};

self.request(payload).await
Expand Down Expand Up @@ -230,7 +234,10 @@ impl Client {
};

let payload = rpc::WatchUnregister {
unregister_auth: claims.encode(keypair).map_err(HttpClientError::Jwt)?,
unregister_auth: claims
.encode(keypair)
.map_err(|err| HttpClientError::Jwt(err).into())
.map_err(Error::Client)?,
};

self.request(payload).await
Expand Down Expand Up @@ -307,37 +314,41 @@ impl Client {
params: payload.into_params(),
});

let result = self
.client
.post(self.url.clone())
.json(&payload)
.send()
.await
.map_err(HttpClientError::Transport)?;
let response = async {
let result = self
.client
.post(self.url.clone())
.json(&payload)
.send()
.await
.map_err(HttpClientError::Transport)?;

let status = result.status();
let status = result.status();

if !status.is_success() {
let body = result.text().await;
return Err(HttpClientError::InvalidHttpCode(status, body).into());
}
if !status.is_success() {
let body = result.text().await;
return Err(HttpClientError::InvalidHttpCode(status, body));
}

let response = result
.json::<rpc::Payload>()
.await
.map_err(|_| HttpClientError::InvalidResponse)?;
result
.json::<rpc::Payload>()
.await
.map_err(|_| HttpClientError::InvalidResponse)
}
.await
.map_err(|err| Error::Client(err.into()))?;

match response {
rpc::Payload::Response(rpc::Response::Success(response)) => {
serde_json::from_value(response.result)
.map_err(|_| HttpClientError::InvalidResponse.into())
.map_err(|_| Error::Client(HttpClientError::InvalidResponse.into()))
}

rpc::Payload::Response(rpc::Response::Error(response)) => {
Err(HttpClientError::RpcError(response.error).into())
Err(ClientError::from(response.error).into_service_error())
}

_ => Err(HttpClientError::InvalidResponse.into()),
_ => Err(Error::Client(HttpClientError::InvalidResponse.into())),
}
}
}
2 changes: 1 addition & 1 deletion relay_client/src/websocket/inbound.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ where
serde_json::to_value(data).map_err(ClientError::Serialization)?,
)),

Err(err) => Response::Error(ErrorResponse::new(self.id, rpc::Error::Request(err))),
Err(err) => Response::Error(ErrorResponse::new(self.id, rpc::Error::Handler(err))),
};

let message = Message::Text(
Expand Down
18 changes: 6 additions & 12 deletions relay_client/src/websocket/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,13 +185,9 @@ impl ClientStream {

if id.is_zero() {
return match response {
Response::Error(response) => {
Some(StreamEvent::InboundError(ClientError::Rpc {
code: response.error.code,
message: response.error.message,
data: response.error.data,
}))
}
Response::Error(response) => Some(StreamEvent::InboundError(
ClientError::from(response.error),
)),

Response::Success(_) => Some(StreamEvent::InboundError(
ClientError::InvalidResponseId,
Expand All @@ -201,11 +197,9 @@ impl ClientStream {

if let Some(tx) = self.requests.remove(&id) {
let result = match response {
Response::Error(response) => Err(ClientError::Rpc {
code: response.error.code,
message: response.error.message,
data: response.error.data,
}),
Response::Error(response) => {
Err(ClientError::from(response.error))
}

Response::Success(response) => Ok(response.result),
};
Expand Down
12 changes: 6 additions & 6 deletions relay_rpc/src/rpc/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,8 @@ pub enum Error<T: ServiceError> {
#[error("Invalid payload: {0}")]
Payload(#[from] PayloadError),

#[error("Request error: {0}")]
Request(T),
#[error("Request handler error: {0}")]
Handler(T),

#[error("Internal error: {0}")]
Internal(#[from] InternalError),
Expand All @@ -125,7 +125,7 @@ impl<T: ServiceError> Error<T> {
Self::Auth(_) => ERROR_CODE_AUTH,
Self::TooManyRequests => ERROR_CODE_TOO_MANY_REQUESTS,
Self::Payload(_) => ERROR_CODE_PAYLOAD,
Self::Request(_) => ERROR_CODE_REQUEST,
Self::Handler(_) => ERROR_CODE_HANDLER,
Self::Internal(_) => ERROR_CODE_INTERNAL,
}
}
Expand All @@ -134,7 +134,7 @@ impl<T: ServiceError> Error<T> {
match &self {
Self::Auth(err) => err.tag(),
Self::Payload(err) => err.tag(),
Self::Request(err) => err.tag(),
Self::Handler(err) => err.tag(),
Self::Internal(err) => err.tag(),
Self::TooManyRequests => self.tag(),
}
Expand All @@ -144,7 +144,7 @@ impl<T: ServiceError> Error<T> {
pub const ERROR_CODE_AUTH: i32 = 3000;
pub const ERROR_CODE_TOO_MANY_REQUESTS: i32 = 3001;
pub const ERROR_CODE_PAYLOAD: i32 = -32600;
pub const ERROR_CODE_REQUEST: i32 = -32000;
pub const ERROR_CODE_HANDLER: i32 = -32000;
pub const ERROR_CODE_INTERNAL: i32 = -32603;

#[derive(Debug, thiserror::Error)]
Expand All @@ -161,7 +161,7 @@ impl<T: ServiceError> TryFrom<ErrorData> for Error<T> {
ERROR_CODE_AUTH => Error::Auth(try_parse_error(tag)?),
ERROR_CODE_TOO_MANY_REQUESTS => Error::TooManyRequests,
ERROR_CODE_PAYLOAD => Error::Payload(try_parse_error(tag)?),
ERROR_CODE_REQUEST => Error::Request(try_parse_error(tag)?),
ERROR_CODE_HANDLER => Error::Handler(try_parse_error(tag)?),
ERROR_CODE_INTERNAL => Error::Internal(try_parse_error(tag)?),
_ => return Err(InvalidErrorData),
};
Expand Down

0 comments on commit 803b7ca

Please sign in to comment.