Skip to content

Commit

Permalink
fmt: sync with core
Browse files Browse the repository at this point in the history
  • Loading branch information
DaniPopes committed Nov 13, 2023
1 parent d83f79a commit 89c7d95
Show file tree
Hide file tree
Showing 38 changed files with 219 additions and 573 deletions.
7 changes: 1 addition & 6 deletions crates/json-rpc/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,12 +159,7 @@ mod test {
fn it_serializes_and_deserializes() {
let cases = [
(TestCase { id: Id::Number(1) }, r#"{"id":1}"#),
(
TestCase {
id: Id::String("foo".to_string()),
},
r#"{"id":"foo"}"#,
),
(TestCase { id: Id::String("foo".to_string()) }, r#"{"id":"foo"}"#),
(TestCase { id: Id::None }, r#"{"id":null}"#),
];
for (case, expected) in cases {
Expand Down
15 changes: 7 additions & 8 deletions crates/json-rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,13 @@
//! actual data being passed to and from the RPC. We can achieve partial
//! (de)serialization by making them generic over a `serde_json::RawValue`.
//!
//! - For [`Request`] - [`PartiallySerializedRequest`] is a
//! `Request<Box<RawValue>`. It represents a `Request` whose parameters have
//! been serialized. [`SerializedRequest`], on the other hand is a request
//! that has been totally serialized. For client-development purposes, its
//! [`Id`] and method have been preserved.
//! - For [`Response`] - [`BorrowedResponse`] is a `Response<&RawValue>`. It
//! represents a Response whose [`Id`] and return status (success or failure)
//! have been deserialized, but whose payload has not.
//! - For [`Request`] - [`PartiallySerializedRequest`] is a `Request<Box<RawValue>`. It represents a
//! `Request` whose parameters have been serialized. [`SerializedRequest`], on the other hand is a
//! request that has been totally serialized. For client-development purposes, its [`Id`] and
//! method have been preserved.
//! - For [`Response`] - [`BorrowedResponse`] is a `Response<&RawValue>`. It represents a Response
//! whose [`Id`] and return status (success or failure) have been deserialized, but whose payload
//! has not.
//!
//! Allowing partial serialization lets us include many unlike [`Request`]
//! objects in collections (e.g. in a batch request). This is useful for
Expand Down
15 changes: 7 additions & 8 deletions crates/json-rpc/src/packet.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use crate::{Id, Response, SerializedRequest};
use serde::de::{self, Deserializer, MapAccess, SeqAccess, Visitor};
use serde::{ser::SerializeSeq, Deserialize, Serialize};
use serde::{
de::{self, Deserializer, MapAccess, SeqAccess, Visitor},
ser::SerializeSeq,
Deserialize, Serialize,
};
use serde_json::value::RawValue;
use std::collections::HashSet;
use std::fmt;
use std::marker::PhantomData;
use std::{collections::HashSet, fmt, marker::PhantomData};

/// A [`RequestPacket`] is a [`SerializedRequest`] or a batch of serialized
/// request.
Expand Down Expand Up @@ -193,9 +194,7 @@ where
}
}

deserializer.deserialize_any(ResponsePacketVisitor {
marker: PhantomData,
})
deserializer.deserialize_any(ResponsePacketVisitor { marker: PhantomData })
}
}

Expand Down
5 changes: 1 addition & 4 deletions crates/json-rpc/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,7 @@ where
/// Serialize the request, including the request parameters.
pub fn serialize(self) -> serde_json::Result<SerializedRequest> {
let request = serde_json::to_string(&self)?;
Ok(SerializedRequest {
meta: self.meta,
request: RawValue::from_string(request)?,
})
Ok(SerializedRequest { meta: self.meta, request: RawValue::from_string(request)? })
}
}

Expand Down
21 changes: 7 additions & 14 deletions crates/json-rpc/src/response/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,30 +151,23 @@ where
/// # Returns
///
/// - `None` if the error has no `data` field.
/// - `Some(Ok(data))` if the error has a `data` field that can be
/// deserialized.
/// - `Some(Err(err))` if the error has a `data` field that can't be
/// deserialized.
/// - `Some(Ok(data))` if the error has a `data` field that can be deserialized.
/// - `Some(Err(err))` if the error has a `data` field that can't be deserialized.
pub fn try_data_as<T: Deserialize<'a>>(&'a self) -> Option<serde_json::Result<T>> {
self.data
.as_ref()
.map(|data| serde_json::from_str(data.borrow().get()))
self.data.as_ref().map(|data| serde_json::from_str(data.borrow().get()))
}

/// Attempt to deserialize the data field.
///
/// # Returns
///
/// - `Ok(ErrorPayload<T>)` if the data field can be deserialized
/// - `Err(self)` if the data field can't be deserialized, or if there
/// is no data field.
/// - `Err(self)` if the data field can't be deserialized, or if there is no data field.
pub fn deser_data<T: DeserializeOwned>(self) -> Result<ErrorPayload<T>, Self> {
match self.try_data_as::<T>() {
Some(Ok(data)) => Ok(ErrorPayload {
code: self.code,
message: self.message,
data: Some(data),
}),
Some(Ok(data)) => {
Ok(ErrorPayload { code: self.code, message: self.message, data: Some(data) })
}
_ => Err(self),
}
}
Expand Down
68 changes: 21 additions & 47 deletions crates/json-rpc/src/response/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,7 @@ impl BorrowedResponse<'_> {
/// Convert this borrowed response to an owned response by copying the data
/// from the deserializer (if necessary).
pub fn into_owned(self) -> Response {
Response {
id: self.id.clone(),
payload: self.payload.into_owned(),
}
Response { id: self.id.clone(), payload: self.payload.into_owned() }
}
}

Expand Down Expand Up @@ -74,19 +71,13 @@ where
///
/// # Returns
///
/// - `Ok(Response<T, ErrData>)` if the payload is a success and can be
/// deserialized as T, or if the payload is an error.
/// - `Ok(Response<T, ErrData>)` if the payload is a success and can be deserialized as T, or if
/// the payload is an error.
/// - `Err(self)` if the payload is a success and can't be deserialized.
pub fn deser_success<T: DeserializeOwned>(self) -> Result<Response<T, ErrData>, Self> {
match self.payload.deserialize_success() {
Ok(payload) => Ok(Response {
id: self.id,
payload,
}),
Err(payload) => Err(Response {
id: self.id,
payload,
}),
Ok(payload) => Ok(Response { id: self.id, payload }),
Err(payload) => Err(Response { id: self.id, payload }),
}
}
}
Expand All @@ -107,19 +98,13 @@ where
///
/// # Returns
///
/// - `Ok(Response<Payload, T>)` if the payload is an error and can be
/// deserialized as `T`, or if the payload is a success.
/// - `Ok(Response<Payload, T>)` if the payload is an error and can be deserialized as `T`, or
/// if the payload is a success.
/// - `Err(self)` if the payload is an error and can't be deserialized.
pub fn deser_err<T: DeserializeOwned>(self) -> Result<Response<Payload, T>, Self> {
match self.payload.deserialize_error() {
Ok(payload) => Ok(Response {
id: self.id,
payload,
}),
Err(payload) => Err(Response {
id: self.id,
payload,
}),
Ok(payload) => Ok(Response { id: self.id, payload }),
Err(payload) => Err(Response { id: self.id, payload }),
}
}
}
Expand Down Expand Up @@ -221,18 +206,16 @@ where
let id = id.unwrap_or(Id::None);

match (result, error) {
(Some(result), None) => Ok(Response {
id,
payload: ResponsePayload::Success(result),
}),
(None, Some(error)) => Ok(Response {
id,
payload: ResponsePayload::Failure(error),
}),
(Some(result), None) => {
Ok(Response { id, payload: ResponsePayload::Success(result) })
}
(None, Some(error)) => {
Ok(Response { id, payload: ResponsePayload::Failure(error) })
}
(None, None) => Err(serde::de::Error::missing_field("result or error")),
(Some(_), Some(_)) => Err(serde::de::Error::custom(
"result and error are mutually exclusive",
)),
(Some(_), Some(_)) => {
Err(serde::de::Error::custom("result and error are mutually exclusive"))
}
}
}
}
Expand All @@ -252,10 +235,7 @@ mod test {
}"#;
let response: super::Response = serde_json::from_str(response).unwrap();
assert_eq!(response.id, super::Id::Number(1));
assert!(matches!(
response.payload,
super::ResponsePayload::Success(_)
));
assert!(matches!(response.payload, super::ResponsePayload::Success(_)));
}

#[test]
Expand All @@ -270,10 +250,7 @@ mod test {
}"#;
let response: super::Response = serde_json::from_str(response).unwrap();
assert_eq!(response.id, super::Id::None);
assert!(matches!(
response.payload,
super::ResponsePayload::Failure(_)
));
assert!(matches!(response.payload, super::ResponsePayload::Failure(_)));
}

#[test]
Expand All @@ -290,10 +267,7 @@ mod test {
}"#;
let response: super::Response = serde_json::from_str(response).unwrap();
assert_eq!(response.id, super::Id::None);
assert!(matches!(
response.payload,
super::ResponsePayload::Success(_)
));
assert!(matches!(response.payload, super::ResponsePayload::Success(_)));
}
}

Expand Down
18 changes: 8 additions & 10 deletions crates/json-rpc/src/response/payload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,19 +81,18 @@ where
/// # Returns
/// - `None` if the payload is an error
/// - `Some(Ok(T))` if the payload is a success and can be deserialized
/// - `Some(Err(serde_json::Error))` if the payload is a success and can't
/// be deserialized as `T`
/// - `Some(Err(serde_json::Error))` if the payload is a success and can't be deserialized as
/// `T`
pub fn try_success_as<T: Deserialize<'a>>(&'a self) -> Option<serde_json::Result<T>> {
self.as_success()
.map(|payload| serde_json::from_str(payload.as_ref().get()))
self.as_success().map(|payload| serde_json::from_str(payload.as_ref().get()))
}

/// Deserialize a Success payload, if possible, transforming this type.
///
/// # Returns
///
/// - `Ok(ResponsePayload<T>)` if the payload is an error, or if the
/// payload is a success and can be deserialized as `T`
/// - `Ok(ResponsePayload<T>)` if the payload is an error, or if the payload is a success and
/// can be deserialized as `T`
/// - `Err(self)` if the payload is a success and can't be deserialized
pub fn deserialize_success<T: DeserializeOwned>(
self,
Expand All @@ -120,8 +119,7 @@ where
/// # Returns
/// - `None` if the payload is a success
/// - `Some(Ok(T))` if the payload is an error and can be deserialized
/// - `Some(Err(serde_json::Error))` if the payload is an error and can't
/// be deserialized as `T`
/// - `Some(Err(serde_json::Error))` if the payload is an error and can't be deserialized as `T`
pub fn try_error_as<T: Deserialize<'a>>(&'a self) -> Option<serde_json::Result<T>> {
self.as_error().and_then(|error| error.try_data_as::<T>())
}
Expand All @@ -130,8 +128,8 @@ where
///
/// # Returns
///
/// - `Ok(ResponsePayload<Payload, T>)` if the payload is an error, or if
/// the payload is an error and can be deserialized as `T`.
/// - `Ok(ResponsePayload<Payload, T>)` if the payload is an error, or if the payload is an
/// error and can be deserialized as `T`.
/// - `Err(self)` if the payload is an error and can't be deserialized.
pub fn deserialize_error<T: DeserializeOwned>(
self,
Expand Down
27 changes: 10 additions & 17 deletions crates/json-rpc/src/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,10 +192,9 @@ where
///
/// # Returns
/// - `None` if the response is not `Success`.
/// - `Some(Ok(Resp))` if the response is `Success` and the
/// `result` field can be deserialized.
/// - `Some(Err(err))` if the response is `Success` and the `result` field
/// can't be deserialized.
/// - `Some(Ok(Resp))` if the response is `Success` and the `result` field can be deserialized.
/// - `Some(Err(err))` if the response is `Success` and the `result` field can't be
/// deserialized.
pub fn try_success_as<'a, Resp: Deserialize<'a>>(&'a self) -> Option<serde_json::Result<Resp>> {
match self {
Self::Success(val) => Some(serde_json::from_str(val.borrow().get())),
Expand Down Expand Up @@ -245,10 +244,9 @@ where
///
/// # Returns
/// - `None` if the response is not `Failure`
/// - `Some(Ok(ErrorPayload))` if the response is `Failure` and the
/// `data` field can be deserialized.
/// - `Some(Err(err))` if the response is `Failure` and the `data` field
/// can't be deserialized.
/// - `Some(Ok(ErrorPayload))` if the response is `Failure` and the `data` field can be
/// deserialized.
/// - `Some(Err(err))` if the response is `Failure` and the `data` field can't be deserialized.
pub fn try_failure_as<'a, ErrData: Deserialize<'a>>(
&'a self,
) -> Option<serde_json::Result<ErrData>> {
Expand All @@ -263,10 +261,9 @@ where
pub fn deserialize_failure<ErrData: RpcReturn>(self) -> Result<RpcResult<T, ErrData, E>, Self> {
match self {
RpcResult::Success(ok) => Ok(RpcResult::Success(ok)),
RpcResult::Failure(err_resp) => err_resp
.deser_data::<ErrData>()
.map(RpcResult::Failure)
.map_err(RpcResult::Failure),
RpcResult::Failure(err_resp) => {
err_resp.deser_data::<ErrData>().map(RpcResult::Failure).map_err(RpcResult::Failure)
}
RpcResult::Err(err) => Ok(RpcResult::Err(err)),
}
}
Expand Down Expand Up @@ -296,11 +293,7 @@ where
data: Some(data),
})),
Some(Err(e)) => {
let text = err_resp
.data
.as_ref()
.map(|d| d.borrow().get())
.unwrap_or("");
let text = err_resp.data.as_ref().map(|d| d.borrow().get()).unwrap_or("");
Err(f(e, text))
}
},
Expand Down
12 changes: 2 additions & 10 deletions crates/providers/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,7 @@ pub struct Stack<T, Inner, Outer> {
impl<T, Inner, Outer> Stack<T, Inner, Outer> {
/// Create a new `Stack`.
pub fn new(inner: Inner, outer: Outer) -> Self {
Stack {
inner,
outer,
_pd: std::marker::PhantomData,
}
Stack { inner, outer, _pd: std::marker::PhantomData }
}
}

Expand Down Expand Up @@ -92,11 +88,7 @@ impl<L, N, T> ProviderBuilder<L, N, T> {
/// builder.network::<Arbitrum>()
/// ```
pub fn network<Net: Network>(self) -> ProviderBuilder<L, Net, T> {
ProviderBuilder {
layer: self.layer,
transport: self.transport,
network: PhantomData,
}
ProviderBuilder { layer: self.layer, transport: self.transport, network: PhantomData }
}

/// Finish the layer stack by providing a root [`RpcClient`], outputting
Expand Down
5 changes: 1 addition & 4 deletions crates/providers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,7 @@ where
T: Transport,
{
fn from(client: RpcClient<T>) -> Self {
Self {
network: PhantomData,
client,
}
Self { network: PhantomData, client }
}
}

Expand Down
Loading

0 comments on commit 89c7d95

Please sign in to comment.