use crate::server::rpc_module::MethodSink;
use futures_channel::mpsc;
use futures_util::stream::StreamExt;
use jsonrpsee_types::v2::{ErrorCode, ErrorObject, Id, InvalidRequest, Response, RpcError, TwoPointZero};
use serde::Serialize;
pub fn send_response(id: Id, tx: &MethodSink, result: impl Serialize) {
let json = match serde_json::to_string(&Response { jsonrpc: TwoPointZero, id: id.clone(), result }) {
Ok(json) => json,
Err(err) => {
log::error!("Error serializing response: {:?}", err);
return send_error(id, tx, ErrorCode::InternalError.into());
}
};
if let Err(err) = tx.unbounded_send(json) {
log::error!("Error sending response to the client: {:?}", err)
}
}
pub fn send_error(id: Id, tx: &MethodSink, error: ErrorObject) {
let json = match serde_json::to_string(&RpcError { jsonrpc: TwoPointZero, error, id }) {
Ok(json) => json,
Err(err) => {
log::error!("Error serializing error message: {:?}", err);
return;
}
};
if let Err(err) = tx.unbounded_send(json) {
log::error!("Could not send error response to the client: {:?}", err)
}
}
pub fn prepare_error(data: &[u8]) -> (Id<'_>, ErrorCode) {
match serde_json::from_slice::<InvalidRequest>(data) {
Ok(InvalidRequest { id }) => (id, ErrorCode::InvalidRequest),
Err(_) => (Id::Null, ErrorCode::ParseError),
}
}
pub async fn collect_batch_response(rx: mpsc::UnboundedReceiver<String>) -> String {
let mut buf = String::with_capacity(2048);
buf.push('[');
let mut buf = rx
.fold(buf, |mut acc, response| async move {
acc.push_str(&response);
acc.push(',');
acc
})
.await;
buf.pop();
buf.push(']');
buf
}