use crate::{Response, ResponsePayload, RpcError, RpcRecv};
use serde_json::value::RawValue;
use std::{any::TypeId, borrow::Borrow};
pub type RpcResult<T, E, ErrResp = Box<RawValue>> = Result<T, RpcError<E, ErrResp>>;
pub type BorrowedRpcResult<'a, E> = RpcResult<&'a RawValue, E, &'a RawValue>;
pub fn transform_response<T, E, ErrResp>(response: Response<T, ErrResp>) -> RpcResult<T, E, ErrResp>
where
ErrResp: RpcRecv,
{
match response {
Response { payload: ResponsePayload::Failure(err_resp), .. } => {
Err(RpcError::err_resp(err_resp))
}
Response { payload: ResponsePayload::Success(result), .. } => Ok(result),
}
}
pub fn transform_result<T, E, ErrResp>(
response: Result<Response<T, ErrResp>, E>,
) -> Result<T, RpcError<E, ErrResp>>
where
ErrResp: RpcRecv,
{
match response {
Ok(resp) => transform_response(resp),
Err(e) => Err(RpcError::Transport(e)),
}
}
pub fn try_deserialize_ok<J, T, E, ErrResp>(
result: RpcResult<J, E, ErrResp>,
) -> RpcResult<T, E, ErrResp>
where
J: Borrow<RawValue> + 'static,
T: RpcRecv,
ErrResp: RpcRecv,
{
let json = result?;
if TypeId::of::<J>() == TypeId::of::<Box<RawValue>>()
&& TypeId::of::<T>() == TypeId::of::<Box<RawValue>>()
{
let json = std::mem::ManuallyDrop::new(json);
return Ok(unsafe { std::mem::transmute_copy::<J, T>(&json) });
}
let _guard = debug_span!("deserialize_response", ty=%std::any::type_name::<T>()).entered();
let json = json.borrow().get();
trace!(%json, "deserializing");
serde_json::from_str(json)
.inspect(|response| trace!(?response, "deserialized"))
.inspect_err(|err| trace!(?err, "failed to deserialize"))
.map_err(|err| RpcError::deser_err(err, json))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::value::to_raw_value;
#[test]
fn raw_value_success_returns_payload_without_reencoding() {
let src = "{ \"a\" :1,\"b\": [ 2 ,3 ] }";
let raw = RawValue::from_string(src.to_owned()).unwrap();
let ptr = raw.get().as_ptr();
let input: RpcResult<Box<RawValue>, (), Box<RawValue>> = Ok(raw);
let out = try_deserialize_ok::<_, Box<RawValue>, (), Box<RawValue>>(input).unwrap();
assert_eq!(out.get(), src);
assert_eq!(out.get().as_ptr(), ptr);
}
#[test]
fn generic_deserialize_path_unchanged() {
let raw = to_raw_value(&42u64).unwrap();
let input: RpcResult<Box<RawValue>, (), Box<RawValue>> = Ok(raw);
let out = try_deserialize_ok::<_, u64, (), Box<RawValue>>(input).unwrap();
assert_eq!(out, 42);
}
}