Skip to content

Commit

Permalink
add rpc streaming from ironfish node
Browse files Browse the repository at this point in the history
  • Loading branch information
jowparks committed Oct 24, 2024
1 parent f3ce30c commit dfa76f8
Show file tree
Hide file tree
Showing 5 changed files with 93 additions and 28 deletions.
2 changes: 1 addition & 1 deletion crates/networking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ pub mod rpc_abi;
pub mod rpc_handler;
pub mod server_handler;
pub mod socket_message;
pub mod web_abi;
pub mod stream;
pub mod web_abi;

use db_handler::{DBTransaction, InnerBlock, Json};
use rpc_abi::RpcBlock;
Expand Down
3 changes: 0 additions & 3 deletions crates/networking/src/rpc_abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,6 @@ pub struct RpcResponseStream<T> {
pub data: T
}




impl<T: Serialize> IntoResponse for RpcResponse<T> {
fn into_response(self) -> axum::response::Response {
Json(json!({"code": 200, "data": self.data})).into_response()
Expand Down
10 changes: 7 additions & 3 deletions crates/networking/src/rpc_handler/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use ureq::{Agent, AgentBuilder, Error, Response};

use crate::{
rpc_abi::{
RpcBroadcastTxRequest, RpcBroadcastTxResponse, RpcCreateTxRequest, RpcCreateTxResponse, RpcExportAccountResponse, RpcGetAccountStatusRequest, RpcGetAccountStatusResponse, RpcGetAccountTransactionRequest, RpcGetAccountTransactionResponse, RpcGetBalancesRequest, RpcGetBalancesResponse, RpcGetBlockRequest, RpcGetBlockResponse, RpcGetBlocksRequest, RpcGetBlocksResponse, RpcGetLatestBlockResponse, RpcGetTransactionsRequest, RpcGetTransactionsResponse, RpcImportAccountRequest, RpcImportAccountResponse, RpcRemoveAccountRequest, RpcRemoveAccountResponse, RpcResetAccountRequest, RpcResponse, RpcSetAccountHeadRequest, RpcSetScanningRequest, SendTransactionRequest, SendTransactionResponse
RpcBroadcastTxRequest, RpcBroadcastTxResponse, RpcCreateTxRequest, RpcCreateTxResponse, RpcExportAccountResponse, RpcGetAccountStatusRequest, RpcGetAccountStatusResponse, RpcGetAccountTransactionRequest, RpcGetAccountTransactionResponse, RpcGetBalancesRequest, RpcGetBalancesResponse, RpcGetBlockRequest, RpcGetBlockResponse, RpcGetBlocksRequest, RpcGetBlocksResponse, RpcGetLatestBlockResponse, RpcGetTransactionsRequest, RpcGetTransactionsResponse, RpcImportAccountRequest, RpcImportAccountResponse, RpcRemoveAccountRequest, RpcRemoveAccountResponse, RpcResetAccountRequest, RpcResponse, RpcSetAccountHeadRequest, RpcSetScanningRequest, SendTransactionRequest, SendTransactionResponse, TransactionStatus
},
rpc_handler::RpcError, stream::RequestExt,
};
Expand Down Expand Up @@ -136,16 +136,20 @@ impl RpcHandler {
) -> Result<RpcResponse<RpcGetTransactionsResponse>, OreoError> {
let path = format!("http://{}/wallet/getAccountTransactions", self.endpoint);
let resp = self.agent.clone().post(&path).send_json(&request);

match resp {
Ok(response) => {
let transactions = response.collect_stream();
let transactions: Result<Vec<_>, OreoError> = response
.into_stream::<TransactionStatus>()
.collect();

Ok(RpcResponse {
status: 200,
data: RpcGetTransactionsResponse {
transactions: transactions?,
},
})
},
}
Err(e) => Err(OreoError::InternalRpcError(e.to_string())),
}
}
Expand Down
103 changes: 82 additions & 21 deletions crates/networking/src/stream.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,94 @@
use std::io::Read;
use std::io::{BufRead, BufReader, Read};
use std::marker::PhantomData;

use oreo_errors::OreoError;
use serde::de::DeserializeOwned;
use serde::Deserialize;
use ureq::Response;

use crate::rpc_abi::RpcResponseStream;

pub trait RequestExt {
fn collect_stream<T: DeserializeOwned>(self) -> Result<Vec<T>, OreoError>;
pub struct StreamReader<T, R> {
reader: BufReader<R>,
_marker: PhantomData<T>,
}

impl RequestExt for Response {
fn collect_stream<T: DeserializeOwned>(self) -> Result<Vec<T>, OreoError> {
let reader = self.into_reader();
let mut buffered = std::io::BufReader::new(reader);
let mut items = Vec::new();
let mut response_str = String::new();
buffered.read_to_string(&mut response_str).map_err(|e| OreoError::InternalRpcError(e.to_string()))?;
let lines = response_str.split('\x0c').collect::<Vec<&str>>();

// Get rid of status code
for line in lines[0..lines.len()-1].into_iter() {
let line = *line; // Dereference to get &str
if !line.trim().is_empty() {
let item: RpcResponseStream<T> = serde_json::from_str(line)
.map_err(|e| OreoError::InternalRpcError(e.to_string()))?;
items.push(item.data);
#[derive(Deserialize)]
#[serde(untagged)]
enum ResponseItem<T> {
Data(RpcResponseStream<T>),
Status { status: u16 },
}

impl<T, R> StreamReader<T, R> where T: DeserializeOwned, R: Read {
pub fn new(reader: R) -> Self {
Self {
reader: BufReader::new(reader),
_marker: PhantomData,
}
}

fn read_item(&mut self) -> Result<Option<Vec<u8>>, OreoError> {
let mut item = Vec::new();
loop {
let bytes_read = self.reader.read_until(b'\x0c', &mut item)
.map_err(|e| OreoError::RpcStreamError(e.to_string()))?;
if bytes_read == 0 {
break;
}
if item.last() == Some(&b'\x0c') {
item.pop();
break;
}
}
match item.len() {
0 => Ok(None),
_ => Ok(Some(item))
}
}


/// Parses a chunk of data into a `ResponseItem<T>`.
fn parse_item(&self, chunk: &[u8]) -> Result<Option<T>, OreoError> {
match serde_json::from_slice::<ResponseItem<T>>(chunk) {
Ok(ResponseItem::Data(item)) => Ok(Some(item.data)),
Ok(ResponseItem::Status { status: 200 }) => Ok(None),
Ok(ResponseItem::Status { status }) => Err(OreoError::RpcStreamError(format!("Received error status: {}", status))),
Err(e) => {
let err_str = format!("Failed to parse JSON object: {:?}", e);
Err(OreoError::RpcStreamError(err_str))
}
}
Ok(items)
}
}
}

impl<T, R> Iterator for StreamReader<T, R>
where
T: DeserializeOwned,
R: Read,
{
type Item = Result<T, OreoError>;

fn next(&mut self) -> Option<Self::Item> {
match self.read_item() {
Ok(Some(chunk)) => match self.parse_item(&chunk) {
Ok(Some(data)) => Some(Ok(data)),
Ok(None) => None, // End of stream
Err(e) => Some(Err(e)),
},
Ok(None) => None, // EOF reached
Err(e) => Some(Err(e)),
}
}
}

pub trait RequestExt {
fn into_stream<T: DeserializeOwned>(self) -> StreamReader<T, Box<dyn Read + Send + Sync + 'static>>;
}

impl RequestExt for Response {
fn into_stream<T: DeserializeOwned>(self) -> StreamReader<T, Box<dyn Read + Send + Sync + 'static>> {
let reader = self.into_reader();
StreamReader::new(Box::new(reader))
}
}
3 changes: 3 additions & 0 deletions crates/oreo_errors/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ pub enum OreoError {
AccountStatusError(String),
#[error("Unauthorized")]
Unauthorized,
#[error("RPC stream error")]
RpcStreamError(String),
}

impl IntoResponse for OreoError {
Expand Down Expand Up @@ -73,6 +75,7 @@ impl IntoResponse for OreoError {
OreoError::DServerError(_) => (StatusCode::from_u16(614).unwrap(), self.to_string()),
OreoError::AccountStatusError(_) => (StatusCode::from_u16(615).unwrap(), self.to_string()),
OreoError::Unauthorized => (StatusCode::UNAUTHORIZED, self.to_string()),
OreoError::RpcStreamError(_) => (StatusCode::from_u16(615).unwrap(), self.to_string()),
};
Json(json!({"code": status_code.as_u16(), "error": err_msg})).into_response()
}
Expand Down

0 comments on commit dfa76f8

Please sign in to comment.