1use crate::{Response, ResponsePayload, RpcError, RpcRecv};
2use serde_json::value::RawValue;
3use std::borrow::Borrow;
4
5pub type RpcResult<T, E, ErrResp = Box<RawValue>> = Result<T, RpcError<E, ErrResp>>;
18
19pub type BorrowedRpcResult<'a, E> = RpcResult<&'a RawValue, E, &'a RawValue>;
21
22pub 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
37pub 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
52pub fn try_deserialize_ok<J, T, E, ErrResp>(
54    result: RpcResult<J, E, ErrResp>,
55) -> RpcResult<T, E, ErrResp>
56where
57    J: Borrow<RawValue>,
58    T: RpcRecv,
59    ErrResp: RpcRecv,
60{
61    let json = result?;
62    let _guard = debug_span!("deserialize_response", ty=%std::any::type_name::<T>()).entered();
63    let json = json.borrow().get();
64    trace!(%json, "deserializing");
65    serde_json::from_str(json)
66        .inspect(|response| trace!(?response, "deserialized"))
67        .inspect_err(|err| trace!(?err, "failed to deserialize"))
68        .map_err(|err| RpcError::deser_err(err, json))
69}