Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

surface errors in RPC methods #5

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
73 changes: 51 additions & 22 deletions crates/networking/src/stream.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,62 @@
use std::io::Read;
use std::io::{BufRead, BufReader, Read};
use std::marker::PhantomData;

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

use crate::rpc_abi::RpcResponseStream;

pub struct StreamReader<T> {
reader: BufReader<Box<dyn Read>>,
_marker: PhantomData<T>,
}

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

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

fn next(&mut self) -> Option<Self::Item> {
let mut chunk = Vec::new();
match self.reader.read_until(b'\x0c', &mut chunk) {
Ok(0) => None, // EOF reached
Ok(_) => {
if chunk.ends_with(&[b'\x0c']) {
chunk.pop();
}

if chunk.is_empty() {
self.next()
} else {
let item_result = serde_json::from_slice::<RpcResponseStream<T>>(&chunk)
.map(|item| item.data)
.map_err(|e| OreoError::InternalRpcError(e.to_string()));
Some(item_result)
}
}
Err(e) => Some(Err(OreoError::InternalRpcError(e.to_string()))),
}
}
}

pub trait RequestExt {
fn collect_stream<T: DeserializeOwned>(self) -> Result<Vec<T>, OreoError>;
fn into_stream<T: DeserializeOwned>(self) -> StreamReader<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);
}
}
Ok(items)
}
}
fn into_stream<T: DeserializeOwned>(self) -> StreamReader<T> {
let reader = self.into_reader();
StreamReader::new(Box::new(reader))
}
}
66 changes: 39 additions & 27 deletions crates/oreo_errors/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,33 +47,45 @@ pub enum OreoError {

impl IntoResponse for OreoError {
fn into_response(self) -> Response {
let (status_code, err_msg) = match self {
OreoError::DBError => (StatusCode::from_u16(600).unwrap(), self.to_string()),
OreoError::Duplicate(_) => (StatusCode::from_u16(601).unwrap(), self.to_string()),
OreoError::NoImported(_) => (StatusCode::from_u16(602).unwrap(), self.to_string()),
OreoError::Scanning(_) => (StatusCode::from_u16(603).unwrap(), self.to_string()),
OreoError::Syncing => (StatusCode::from_u16(604).unwrap(), self.to_string()),
OreoError::InternalRpcError(_) => (StatusCode::from_u16(605).unwrap(), self.to_string()),
OreoError::GenerateSpendProofFailed(_) => {
(StatusCode::from_u16(606).unwrap(), self.to_string())
}
OreoError::GenerateOutputProofFailed(_) => {
(StatusCode::from_u16(607).unwrap(), self.to_string())
}
OreoError::GenerateMintAssetProofFailed(_) => {
(StatusCode::from_u16(608).unwrap(), self.to_string())
}
OreoError::BalanceNotEnough => (StatusCode::from_u16(609).unwrap(), self.to_string()),
OreoError::BadMintRequest => (StatusCode::from_u16(610).unwrap(), self.to_string()),
OreoError::TransactionNotFound => {
(StatusCode::from_u16(611).unwrap(), self.to_string())
}
OreoError::SeralizeError(_) => (StatusCode::from_u16(612).unwrap(), self.to_string()),
OreoError::ParseError(_) => (StatusCode::from_u16(613).unwrap(), self.to_string()),
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()),
};
let (status_code, err_msg) = get_status_code(self);
Json(json!({"code": status_code.as_u16(), "error": err_msg})).into_response()
}
}

impl From<OreoError> for Response {
fn from(err: OreoError) -> Response {
let (status_code, err_msg) = get_status_code(err);
Json(json!({"code": status_code.as_u16(), "error": err_msg})).into_response()
}
}

pub fn get_status_code(err: OreoError) -> (StatusCode, String) {
let (status_code, err_msg) = match err {
OreoError::DBError => (StatusCode::from_u16(600).unwrap(), err.to_string()),
OreoError::Duplicate(_) => (StatusCode::from_u16(601).unwrap(), err.to_string()),
OreoError::NoImported(_) => (StatusCode::from_u16(602).unwrap(), err.to_string()),
OreoError::Scanning(_) => (StatusCode::from_u16(603).unwrap(), err.to_string()),
OreoError::Syncing => (StatusCode::from_u16(604).unwrap(), err.to_string()),
OreoError::InternalRpcError(_) => (StatusCode::from_u16(605).unwrap(), err.to_string()),
OreoError::GenerateSpendProofFailed(_) => {
(StatusCode::from_u16(606).unwrap(), err.to_string())
}
OreoError::GenerateOutputProofFailed(_) => {
(StatusCode::from_u16(607).unwrap(), err.to_string())
}
OreoError::GenerateMintAssetProofFailed(_) => {
(StatusCode::from_u16(608).unwrap(), err.to_string())
}
OreoError::BalanceNotEnough => (StatusCode::from_u16(609).unwrap(), err.to_string()),
OreoError::BadMintRequest => (StatusCode::from_u16(610).unwrap(), err.to_string()),
OreoError::TransactionNotFound => {
(StatusCode::from_u16(611).unwrap(), err.to_string())
}
OreoError::SeralizeError(_) => (StatusCode::from_u16(612).unwrap(), err.to_string()),
OreoError::ParseError(_) => (StatusCode::from_u16(613).unwrap(), err.to_string()),
OreoError::DServerError(_) => (StatusCode::from_u16(614).unwrap(), err.to_string()),
OreoError::AccountStatusError(_) => (StatusCode::from_u16(615).unwrap(), err.to_string()),
OreoError::Unauthorized => (StatusCode::from_u16(401).unwrap(), err.to_string()),
};
(status_code, err_msg)
}
Loading