Skip to content

Commit

Permalink
Move backward compatibility to jsonrpc-primitives from jsonrpc, move …
Browse files Browse the repository at this point in the history
…ServerError from jsonrpc to jsonrpc-primitives, fix dependencies
  • Loading branch information
khorolets committed Apr 8, 2021
1 parent e087c29 commit f003ac4
Show file tree
Hide file tree
Showing 10 changed files with 84 additions and 103 deletions.
21 changes: 6 additions & 15 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion chain/jsonrpc-primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@ serde_json = "1"
thiserror = "1.0"
tracing = "0.1.13"
uuid = { version = "~0.8", features = ["v4"] }
near-runtime-utils = "4.0.0-pre.1"

near-chain-configs = { path = "../../core/chain-configs" }
near-client-primitives = { path = "../client-primitives" }
near-crypto = { path = "../../core/crypto" }
near-metrics = { path = "../../core/metrics" }
near-primitives = { path = "../../core/primitives" }
near-primitives-core = { path = "../../core/primitives-core" }
near-rpc-error-macro = { path = "../../tools/rpctypegen/macro" }
near-runtime-utils = { path = "../../runtime/near-runtime-utils" }
45 changes: 45 additions & 0 deletions chain/jsonrpc-primitives/src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use std::fmt::Display;

use serde::{Deserialize, Serialize};
use serde_json::{to_value, Value};

use near_primitives::errors::{InvalidTxError, TxExecutionError};

#[derive(Serialize)]
pub struct RpcParseError(pub String);

Expand All @@ -16,6 +20,15 @@ pub struct RpcError {
pub data: Option<Value>,
}

/// A general Server Error
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, near_rpc_error_macro::RpcError)]
pub enum ServerError {
TxExecutionError(TxExecutionError),
Timeout,
Closed,
InternalError,
}

impl RpcError {
/// A generic constructor.
///
Expand Down Expand Up @@ -75,3 +88,35 @@ impl From<crate::errors::RpcParseError> for RpcError {
Self::invalid_params(parse_error.0)
}
}

impl Display for ServerError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
ServerError::TxExecutionError(e) => write!(f, "ServerError: {}", e),
ServerError::Timeout => write!(f, "ServerError: Timeout"),
ServerError::Closed => write!(f, "ServerError: Closed"),
ServerError::InternalError => write!(f, "ServerError: Internal Error"),
}
}
}

impl From<InvalidTxError> for ServerError {
fn from(e: InvalidTxError) -> ServerError {
ServerError::TxExecutionError(TxExecutionError::InvalidTxError(e))
}
}

impl From<actix::MailboxError> for ServerError {
fn from(e: actix::MailboxError) -> Self {
match e {
actix::MailboxError::Closed => ServerError::Closed,
actix::MailboxError::Timeout => ServerError::Timeout,
}
}
}

impl From<ServerError> for RpcError {
fn from(e: ServerError) -> RpcError {
RpcError::server_error(Some(e))
}
}
11 changes: 9 additions & 2 deletions chain/jsonrpc-primitives/src/types/transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,15 @@ impl From<near_primitives::views::FinalExecutionOutcomeViewEnum> for RpcTransact

impl From<RpcTransactionError> for crate::errors::RpcError {
fn from(error: RpcTransactionError) -> Self {
let error_data = Some(Value::String(error.to_string()));

let error_data = match error {
RpcTransactionError::InvalidTransaction { ref context } => Some(
serde_json::to_value(crate::errors::ServerError::TxExecutionError(
near_primitives::errors::TxExecutionError::InvalidTxError(context.clone()),
))
.unwrap_or(Value::String(error.to_string())),
),
_ => Some(Value::String(error.to_string())),
};
Self::new(-32_000, "Server error".to_string(), error_data)
}
}
Expand Down
97 changes: 17 additions & 80 deletions chain/jsonrpc/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::fmt::Display;
use std::string::FromUtf8Error;
use std::time::Duration;

Expand Down Expand Up @@ -34,7 +33,6 @@ use near_metrics::{Encoder, TextEncoder};
#[cfg(feature = "adversarial")]
use near_network::types::{NetworkAdversarialMessage, NetworkViewClientMessages};
use near_network::{NetworkClientMessages, NetworkClientResponses};
use near_primitives::errors::{InvalidTxError, TxExecutionError};
use near_primitives::hash::CryptoHash;
use near_primitives::serialize::BaseEncode;
use near_primitives::transaction::SignedTransaction;
Expand Down Expand Up @@ -116,47 +114,6 @@ fn jsonify<T: serde::Serialize>(
.map_err(|err| RpcError::server_error(Some(err)))
}

/// A general Server Error
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, near_rpc_error_macro::RpcError)]
pub enum ServerError {
TxExecutionError(TxExecutionError),
Timeout,
Closed,
InternalError,
}

impl Display for ServerError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
ServerError::TxExecutionError(e) => write!(f, "ServerError: {}", e),
ServerError::Timeout => write!(f, "ServerError: Timeout"),
ServerError::Closed => write!(f, "ServerError: Closed"),
ServerError::InternalError => write!(f, "ServerError: Internal Error"),
}
}
}

impl From<InvalidTxError> for ServerError {
fn from(e: InvalidTxError) -> ServerError {
ServerError::TxExecutionError(TxExecutionError::InvalidTxError(e))
}
}

impl From<MailboxError> for ServerError {
fn from(e: MailboxError) -> Self {
match e {
MailboxError::Closed => ServerError::Closed,
MailboxError::Timeout => ServerError::Timeout,
}
}
}

impl From<ServerError> for RpcError {
fn from(e: ServerError) -> RpcError {
RpcError::server_error(Some(e))
}
}

#[easy_ext::ext(FromNetworkClientResponses)]
impl near_jsonrpc_primitives::types::transactions::RpcTransactionError {
pub fn from_network_client_responses(responses: NetworkClientResponses) -> Self {
Expand Down Expand Up @@ -231,31 +188,6 @@ fn process_query_response(
}
}

/// This function processes response from tx related methods to introduce
/// backward compatible response in case of specific errors
fn process_tx_response<S>(
tx_response: Result<S, near_jsonrpc_primitives::types::transactions::RpcTransactionError>,
) -> Result<Value, RpcError>
where
S: Serialize,
{
// This match is used here to give backward compatible error message for specific
// error variants. Should be refactored once structured errors fully shipped
match tx_response {
Ok(response) => serde_json::to_value(response)
.map_err(|err| RpcError::parse_error(err.to_string())),
Err(err) => match err {
near_jsonrpc_primitives::types::transactions::RpcTransactionError::InvalidTransaction { context } => Err(RpcError::new(
-32_000,
"Server_error".to_string(),
Some(serde_json::to_value(ServerError::TxExecutionError(TxExecutionError::InvalidTxError(context)))
.map_err(|err| RpcError::parse_error(err.to_string()))?,
))),
_ => Err(err.into())
}
}
}

struct JsonRpcHandler {
client_addr: Addr<ClientActor>,
view_client_addr: Addr<ViewClientActor>,
Expand Down Expand Up @@ -324,8 +256,9 @@ impl JsonRpcHandler {
near_jsonrpc_primitives::types::transactions::RpcTransactionRequest::parse(
request.params,
)?;
let send_tx_response = self.send_tx_commit(rpc_transaction_request).await;
process_tx_response(send_tx_response)
let send_tx_response = self.send_tx_commit(rpc_transaction_request).await?;
serde_json::to_value(send_tx_response)
.map_err(|err| RpcError::parse_error(err.to_string()))
}
"chunk" => {
let rpc_chunk_request =
Expand All @@ -338,8 +271,9 @@ impl JsonRpcHandler {
near_jsonrpc_primitives::types::transactions::RpcTransactionRequest::parse(
request.params,
)?;
let broadcast_tx_sync_response = self.send_tx_sync(rpc_transaction_request).await;
process_tx_response(broadcast_tx_sync_response)
let broadcast_tx_sync_response = self.send_tx_sync(rpc_transaction_request).await?;
serde_json::to_value(broadcast_tx_sync_response)
.map_err(|err| RpcError::parse_error(err.to_string()))
}
"EXPERIMENTAL_changes" => self.changes_in_block_by_type(request.params).await,
"EXPERIMENTAL_changes_in_block" => self.changes_in_block(request.params).await,
Expand All @@ -348,8 +282,9 @@ impl JsonRpcHandler {
near_jsonrpc_primitives::types::transactions::RpcTransactionRequest::parse(
request.params,
)?;
let broadcast_tx_sync_response = self.check_tx(rpc_transaction_request).await;
process_tx_response(broadcast_tx_sync_response)
let broadcast_tx_sync_response = self.check_tx(rpc_transaction_request).await?;
serde_json::to_value(broadcast_tx_sync_response)
.map_err(|err| RpcError::parse_error(err.to_string()))
}
"EXPERIMENTAL_genesis_config" => self.genesis_config().await,
"EXPERIMENTAL_light_client_proof" => {
Expand All @@ -374,8 +309,9 @@ impl JsonRpcHandler {
"EXPERIMENTAL_tx_status" => {
let rpc_transaction_status_common_request = near_jsonrpc_primitives::types::transactions::RpcTransactionStatusCommonRequest::parse(request.params)?;
let rpc_transaction_response =
self.tx_status_common(rpc_transaction_status_common_request, true).await;
process_tx_response(rpc_transaction_response)
self.tx_status_common(rpc_transaction_status_common_request, true).await?;
serde_json::to_value(rpc_transaction_response)
.map_err(|err| RpcError::parse_error(err.to_string()))
}
"EXPERIMENTAL_validators_ordered" => self.validators_ordered(request.params).await,
"gas_price" => {
Expand All @@ -401,8 +337,9 @@ impl JsonRpcHandler {
"tx" => {
let rpc_transaction_status_common_request = near_jsonrpc_primitives::types::transactions::RpcTransactionStatusCommonRequest::parse(request.params)?;
let rpc_transaction_response =
self.tx_status_common(rpc_transaction_status_common_request, false).await;
process_tx_response(rpc_transaction_response)
self.tx_status_common(rpc_transaction_status_common_request, false).await?;
serde_json::to_value(rpc_transaction_response)
.map_err(|err| RpcError::parse_error(err.to_string()))
}
"validators" => {
let rpc_validator_request =
Expand Down Expand Up @@ -872,7 +809,7 @@ impl JsonRpcHandler {
.view_client_addr
.send(GetExecutionOutcome { id })
.await
.map_err(|e| RpcError::from(ServerError::from(e)))?
.map_err(|e| RpcError::from(near_jsonrpc_primitives::errors::ServerError::from(e)))?
.map_err(|e| RpcError::server_error(Some(e)))?;
let block_proof = self
.view_client_addr
Expand All @@ -881,7 +818,7 @@ impl JsonRpcHandler {
head_block_hash: light_client_head,
})
.await
.map_err(|e| RpcError::from(ServerError::from(e)))?;
.map_err(|e| RpcError::from(near_jsonrpc_primitives::errors::ServerError::from(e)))?;
let res = block_proof.map(|block_proof| RpcLightClientExecutionProofResponse {
outcome_proof: execution_outcome_proof.outcome_proof,
outcome_root_proof: execution_outcome_proof.outcome_root_proof,
Expand Down
2 changes: 1 addition & 1 deletion test-utils/testlib/src/node/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::sync::RwLock;

use near_chain_configs::Genesis;
use near_crypto::{InMemorySigner, Signer};
use near_jsonrpc::ServerError;
use near_jsonrpc_primitives::errors::ServerError;
use near_primitives::state_record::StateRecord;
use near_primitives::transaction::SignedTransaction;
use near_primitives::types::{AccountId, Balance, NumSeats};
Expand Down
2 changes: 1 addition & 1 deletion test-utils/testlib/src/standard_test_cases.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::sync::Arc;

use assert_matches::assert_matches;
use near_crypto::{InMemorySigner, KeyType};
use near_jsonrpc::ServerError;
use near_jsonrpc_primitives::errors::ServerError;
use near_primitives::account::{AccessKey, AccessKeyPermission, FunctionCallPermission};
use near_primitives::errors::{
ActionError, ActionErrorKind, InvalidAccessKeyError, InvalidTxError, TxExecutionError,
Expand Down
2 changes: 1 addition & 1 deletion test-utils/testlib/src/user/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::sync::Arc;
use futures::{future::LocalBoxFuture, FutureExt};

use near_crypto::{PublicKey, Signer};
use near_jsonrpc::ServerError;
use near_jsonrpc_primitives::errors::ServerError;
use near_primitives::account::AccessKey;
use near_primitives::hash::CryptoHash;
use near_primitives::receipt::Receipt;
Expand Down
2 changes: 1 addition & 1 deletion test-utils/testlib/src/user/rpc_user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use futures::{Future, TryFutureExt};
use near_client::StatusResponse;
use near_crypto::{PublicKey, Signer};
use near_jsonrpc::client::{new_client, JsonRpcClient};
use near_jsonrpc::ServerError;
use near_jsonrpc_client::ChunkId;
use near_jsonrpc_primitives::errors::ServerError;
use near_jsonrpc_primitives::types::query::RpcQueryResponse;
use near_primitives::hash::CryptoHash;
use near_primitives::receipt::Receipt;
Expand Down
2 changes: 1 addition & 1 deletion test-utils/testlib/src/user/runtime_user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet};
use std::sync::{Arc, RwLock};

use near_crypto::{PublicKey, Signer};
use near_jsonrpc::ServerError;
use near_jsonrpc_primitives::errors::ServerError;
use near_primitives::errors::{RuntimeError, TxExecutionError};
use near_primitives::hash::CryptoHash;
use near_primitives::receipt::Receipt;
Expand Down

0 comments on commit f003ac4

Please sign in to comment.