Skip to main content

alloy_json_rpc/
result.rs

1use crate::{Response, ResponsePayload, RpcError, RpcRecv};
2use serde_json::value::RawValue;
3use std::{any::TypeId, borrow::Borrow};
4
5/// The result of a JSON-RPC request.
6///
7/// Either a success response, an error response, or a non-response error. The
8/// non-response error is intended to be used for errors returned by a
9/// transport, or serde errors.
10///
11/// The common cases are:
12/// - `Ok(T)` - The server returned a successful response.
13/// - `Err(RpcError::ErrorResponse(ErrResp))` - The server returned an error response.
14/// - `Err(RpcError::SerError(E))` - A serialization error occurred.
15/// - `Err(RpcError::DeserError { err: E, text: String })` - A deserialization error occurred.
16/// - `Err(RpcError::TransportError(E))` - Some client-side or communication error occurred.
17pub type RpcResult<T, E, ErrResp = Box<RawValue>> = Result<T, RpcError<E, ErrResp>>;
18
19/// A partially deserialized [`RpcResult`], borrowing from the deserializer.
20pub type BorrowedRpcResult<'a, E> = RpcResult<&'a RawValue, E, &'a RawValue>;
21
22/// Transform a transport response into an [`RpcResult`], discarding the [`Id`].
23///
24/// [`Id`]: crate::Id
25pub fn transform_response<T, E, ErrResp>(response: Response<T, ErrResp>) -> RpcResult<T, E, ErrResp>
26where
27    ErrResp: RpcRecv,
28{
29    match response {
30        Response { payload: ResponsePayload::Failure(err_resp), .. } => {
31            Err(RpcError::err_resp(err_resp))
32        }
33        Response { payload: ResponsePayload::Success(result), .. } => Ok(result),
34    }
35}
36
37/// Transform a transport outcome into an [`RpcResult`], discarding the [`Id`].
38///
39/// [`Id`]: crate::Id
40pub fn transform_result<T, E, ErrResp>(
41    response: Result<Response<T, ErrResp>, E>,
42) -> Result<T, RpcError<E, ErrResp>>
43where
44    ErrResp: RpcRecv,
45{
46    match response {
47        Ok(resp) => transform_response(resp),
48        Err(e) => Err(RpcError::Transport(e)),
49    }
50}
51
52/// Attempt to deserialize the `Ok(_)` variant of an [`RpcResult`].
53pub fn try_deserialize_ok<J, T, E, ErrResp>(
54    result: RpcResult<J, E, ErrResp>,
55) -> RpcResult<T, E, ErrResp>
56where
57    J: Borrow<RawValue> + 'static,
58    T: RpcRecv,
59    ErrResp: RpcRecv,
60{
61    let json = result?;
62
63    // Fast path: the caller wants the already-owned `Box<RawValue>` back unchanged. Hand it
64    // over directly, skipping the byte copy and full JSON validation scan that
65    // `from_str::<Box<RawValue>>` would repeat over an already-validated value.
66    if TypeId::of::<J>() == TypeId::of::<Box<RawValue>>()
67        && TypeId::of::<T>() == TypeId::of::<Box<RawValue>>()
68    {
69        // SAFETY: `J` and `T` are both `Box<RawValue>`, so this is a no-op reinterpretation.
70        // `transmute_copy` stands in for the unstable `transmute_unchecked` (sizes are equal).
71        let json = std::mem::ManuallyDrop::new(json);
72        return Ok(unsafe { std::mem::transmute_copy::<J, T>(&json) });
73    }
74
75    let _guard = debug_span!("deserialize_response", ty=%std::any::type_name::<T>()).entered();
76    let json = json.borrow().get();
77    trace!(%json, "deserializing");
78    serde_json::from_str(json)
79        .inspect(|response| trace!(?response, "deserialized"))
80        .inspect_err(|err| trace!(?err, "failed to deserialize"))
81        .map_err(|err| RpcError::deser_err(err, json))
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87    use serde_json::value::to_raw_value;
88
89    #[test]
90    fn raw_value_success_returns_payload_without_reencoding() {
91        // Deliberately non-canonical spacing: a byte-identical result proves the payload
92        // was not re-parsed and re-encoded.
93        let src = "{  \"a\" :1,\"b\": [ 2 ,3 ] }";
94        let raw = RawValue::from_string(src.to_owned()).unwrap();
95        let ptr = raw.get().as_ptr();
96        let input: RpcResult<Box<RawValue>, (), Box<RawValue>> = Ok(raw);
97
98        let out = try_deserialize_ok::<_, Box<RawValue>, (), Box<RawValue>>(input).unwrap();
99
100        assert_eq!(out.get(), src);
101        // Same allocation: the owned payload was handed back, not rebuilt.
102        assert_eq!(out.get().as_ptr(), ptr);
103    }
104
105    #[test]
106    fn generic_deserialize_path_unchanged() {
107        let raw = to_raw_value(&42u64).unwrap();
108        let input: RpcResult<Box<RawValue>, (), Box<RawValue>> = Ok(raw);
109        let out = try_deserialize_ok::<_, u64, (), Box<RawValue>>(input).unwrap();
110        assert_eq!(out, 42);
111    }
112}