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

chore(jsonrpc): extract request parser #6849

Closed
wants to merge 1 commit into from
Closed
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
14 changes: 5 additions & 9 deletions chain/jsonrpc-adversarial-primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,15 @@ rust-version = "1.60.0"
edition = "2021"

[dependencies]
serde = { version = "1", features = ["derive"], optional = true }
serde_json = { version = "1", optional = true }
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1" }
near-primitives = { path = "../../core/primitives" }

near-jsonrpc-primitives = { path = "../jsonrpc-primitives", optional = true }
near-network-primitives = { path = "../network-primitives" }
deepsize = { version = "0.2.0", optional = true }

[features]
ser_de = [
"serde_json",
"serde",
"near-jsonrpc-primitives",
"near-network-primitives/test_features"
]
deepsize_feature = ["deepsize", "near-primitives/deepsize_feature"]
server = ["near-jsonrpc-primitives/server"]
test_features = ["near-network-primitives/test_features"]
deepsize_feature = ["deepsize", "near-primitives/deepsize_feature"]
26 changes: 9 additions & 17 deletions chain/jsonrpc-adversarial-primitives/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,40 +1,32 @@
#[cfg(feature = "ser_de")]
use near_jsonrpc_primitives::errors::RpcError;
use near_network_primitives::types::{Edge, SimpleEdge};
use near_primitives::network::PeerId;
#[cfg(feature = "ser_de")]
use serde::Deserialize;
#[cfg(feature = "ser_de")]
use serde_json::Value;

#[cfg_attr(feature = "ser_de", derive(Deserialize))]
#[cfg_attr(feature = "test_features", derive(Deserialize))]
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
pub struct SetRoutingTableRequest {
pub add_edges: Option<Vec<Edge>>,
pub remove_edges: Option<Vec<SimpleEdge>>,
pub prune_edges: Option<bool>,
}

#[cfg(feature = "ser_de")]
impl SetRoutingTableRequest {
pub fn parse(value: Option<Value>) -> Result<Self, RpcError> {
if let Some(value) = value {
serde_json::from_value(value)
.map_err(|err| RpcError::parse_error(format!("Error {:?}", err)))
} else {
Err(RpcError::parse_error("Require at least one parameter".to_owned()))
}
#[cfg(feature = "server")]
impl near_jsonrpc_primitives::RpcRequest for SetRoutingTableRequest {
fn parse(
value: Option<serde_json::Value>,
) -> Result<Self, near_jsonrpc_primitives::errors::RpcParseError> {
near_jsonrpc_primitives::utils::parse_params::<Self>(value)
}
}

#[cfg_attr(feature = "ser_de", derive(Deserialize))]
#[derive(Deserialize)]
pub struct SetAdvOptionsRequest {
pub disable_edge_signature_verification: Option<bool>,
pub disable_edge_propagation: Option<bool>,
pub disable_edge_pruning: Option<bool>,
}

#[cfg_attr(feature = "ser_de", derive(Deserialize))]
#[derive(Deserialize)]
pub struct StartRoutingTableSyncRequest {
pub peer_id: PeerId,
}
1 change: 1 addition & 0 deletions chain/jsonrpc-primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,5 @@ near-primitives-core = { path = "../../core/primitives-core" }
near-rpc-error-macro = { path = "../../tools/rpctypegen/macro" }

[features]
server = []
test_features = []
8 changes: 7 additions & 1 deletion chain/jsonrpc-primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,10 @@ pub mod errors;
pub mod message;
pub(crate) mod metrics;
pub mod types;
pub(crate) mod utils;
#[cfg(feature = "server")]
pub mod utils;

#[cfg(feature = "server")]
pub trait RpcRequest: Sized {
fn parse(value: Option<serde_json::Value>) -> Result<Self, errors::RpcParseError>;
}
5 changes: 3 additions & 2 deletions chain/jsonrpc-primitives/src/types/blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,9 @@ impl From<RpcBlockError> for crate::errors::RpcError {
}
}

impl RpcBlockRequest {
pub fn parse(value: Option<Value>) -> Result<RpcBlockRequest, crate::errors::RpcParseError> {
#[cfg(feature = "server")]
impl crate::RpcRequest for RpcBlockRequest {
fn parse(value: Option<Value>) -> Result<RpcBlockRequest, crate::errors::RpcParseError> {
let block_reference = if let Ok((block_id,)) =
crate::utils::parse_params::<(near_primitives::types::BlockId,)>(value.clone())
{
Expand Down
14 changes: 8 additions & 6 deletions chain/jsonrpc-primitives/src/types/changes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,17 @@ pub enum RpcStateChangesError {
InternalError { error_message: String },
}

impl RpcStateChangesInBlockRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
Ok(crate::utils::parse_params::<Self>(value)?)
#[cfg(feature = "server")]
impl crate::RpcRequest for RpcStateChangesInBlockRequest {
fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
crate::utils::parse_params::<Self>(value)
}
}

impl RpcStateChangesInBlockByTypeRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
Ok(crate::utils::parse_params::<Self>(value)?)
#[cfg(feature = "server")]
impl crate::RpcRequest for RpcStateChangesInBlockByTypeRequest {
fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
crate::utils::parse_params::<Self>(value)
}
}

Expand Down
5 changes: 3 additions & 2 deletions chain/jsonrpc-primitives/src/types/chunks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,9 @@ impl From<ChunkReference> for near_client_primitives::types::GetChunk {
}
}

impl RpcChunkRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
#[cfg(feature = "server")]
impl crate::RpcRequest for RpcChunkRequest {
fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
// Try to parse legacy positioned args and if it fails parse newer named args
let chunk_reference = if let Ok((chunk_id,)) =
crate::utils::parse_params::<(near_primitives::hash::CryptoHash,)>(value.clone())
Expand Down
5 changes: 3 additions & 2 deletions chain/jsonrpc-primitives/src/types/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ pub struct RpcProtocolConfigRequest {
pub block_reference: near_primitives::types::BlockReference,
}

impl RpcProtocolConfigRequest {
pub fn parse(
#[cfg(feature = "server")]
impl crate::RpcRequest for RpcProtocolConfigRequest {
fn parse(
value: Option<Value>,
) -> Result<RpcProtocolConfigRequest, crate::errors::RpcParseError> {
crate::utils::parse_params::<near_primitives::types::BlockReference>(value)
Expand Down
5 changes: 3 additions & 2 deletions chain/jsonrpc-primitives/src/types/gas_price.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,9 @@ impl From<RpcGasPriceError> for crate::errors::RpcError {
}
}

impl RpcGasPriceRequest {
pub fn parse(value: Option<Value>) -> Result<RpcGasPriceRequest, crate::errors::RpcParseError> {
#[cfg(feature = "server")]
impl crate::RpcRequest for RpcGasPriceRequest {
fn parse(value: Option<Value>) -> Result<RpcGasPriceRequest, crate::errors::RpcParseError> {
crate::utils::parse_params::<(MaybeBlockId,)>(value)
.map(|(block_id,)| RpcGasPriceRequest { block_id })
}
Expand Down
14 changes: 8 additions & 6 deletions chain/jsonrpc-primitives/src/types/light_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,20 +67,22 @@ pub enum RpcLightClientNextBlockError {
EpochOutOfBounds { epoch_id: near_primitives::types::EpochId },
}

impl RpcLightClientExecutionProofRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
Ok(crate::utils::parse_params::<Self>(value)?)
#[cfg(feature = "server")]
impl crate::RpcRequest for RpcLightClientExecutionProofRequest {
fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
crate::utils::parse_params::<Self>(value)
}
}

impl RpcLightClientNextBlockRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
#[cfg(feature = "server")]
impl crate::RpcRequest for RpcLightClientNextBlockRequest {
fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
if let Ok((last_block_hash,)) =
crate::utils::parse_params::<(near_primitives::hash::CryptoHash,)>(value.clone())
{
Ok(Self { last_block_hash })
} else {
Ok(crate::utils::parse_params::<Self>(value)?)
crate::utils::parse_params::<Self>(value)
}
}
}
Expand Down
19 changes: 8 additions & 11 deletions chain/jsonrpc-primitives/src/types/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,10 @@ pub enum QueryResponseKind {
AccessKeyList(near_primitives::views::AccessKeyList),
}

impl RpcQueryRequest {
pub fn parse(value: Option<Value>) -> Result<RpcQueryRequest, crate::errors::RpcParseError> {
let query_request = if let Ok((path, data)) =
crate::utils::parse_params::<(String, String)>(value.clone())
{
#[cfg(feature = "server")]
impl crate::RpcRequest for RpcQueryRequest {
fn parse(value: Option<Value>) -> Result<RpcQueryRequest, crate::errors::RpcParseError> {
if let Ok((path, data)) = crate::utils::parse_params::<(String, String)>(value.clone()) {
// Handle a soft-deprecated version of the query API, which is based on
// positional arguments with a "path"-style first argument.
//
Expand Down Expand Up @@ -155,14 +154,12 @@ impl RpcQueryRequest {
}
};
// Use Finality::None here to make backward compatibility tests work
RpcQueryRequest {
return Ok(RpcQueryRequest {
request,
block_reference: near_primitives::types::BlockReference::latest(),
}
} else {
crate::utils::parse_params::<RpcQueryRequest>(value)?
};
Ok(query_request)
});
}
crate::utils::parse_params::<Self>(value)
}
}

Expand Down
5 changes: 3 additions & 2 deletions chain/jsonrpc-primitives/src/types/receipts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@ impl From<ReceiptReference> for near_client_primitives::types::GetReceipt {
}
}

impl RpcReceiptRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
#[cfg(feature = "server")]
impl crate::RpcRequest for RpcReceiptRequest {
fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
let receipt_reference = crate::utils::parse_params::<ReceiptReference>(value)?;
Ok(Self { receipt_reference })
}
Expand Down
14 changes: 8 additions & 6 deletions chain/jsonrpc-primitives/src/types/sandbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ pub struct RpcSandboxPatchStateRequest {
pub records: Vec<StateRecord>,
}

impl RpcSandboxPatchStateRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
Ok(crate::utils::parse_params::<RpcSandboxPatchStateRequest>(value)?)
#[cfg(feature = "server")]
impl crate::RpcRequest for RpcSandboxPatchStateRequest {
fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
crate::utils::parse_params::<Self>(value)
}
}

Expand Down Expand Up @@ -50,9 +51,10 @@ pub struct RpcSandboxFastForwardRequest {
pub delta_height: BlockHeightDelta,
}

impl RpcSandboxFastForwardRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
Ok(crate::utils::parse_params::<RpcSandboxFastForwardRequest>(value)?)
#[cfg(feature = "server")]
impl crate::RpcRequest for RpcSandboxFastForwardRequest {
fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
crate::utils::parse_params::<Self>(value)
}
}

Expand Down
10 changes: 6 additions & 4 deletions chain/jsonrpc-primitives/src/types/transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,17 @@ pub struct RpcBroadcastTxSyncResponse {
pub transaction_hash: near_primitives::hash::CryptoHash,
}

impl RpcBroadcastTransactionRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
#[cfg(feature = "server")]
impl crate::RpcRequest for RpcBroadcastTransactionRequest {
fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
let signed_transaction = crate::utils::parse_signed_transaction(value)?;
Ok(Self { signed_transaction })
}
}

impl RpcTransactionStatusCommonRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
#[cfg(feature = "server")]
impl crate::RpcRequest for RpcTransactionStatusCommonRequest {
fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
if let Ok((hash, account_id)) = crate::utils::parse_params::<(
near_primitives::hash::CryptoHash,
AccountId,
Expand Down
12 changes: 7 additions & 5 deletions chain/jsonrpc-primitives/src/types/validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,9 @@ impl From<actix::MailboxError> for RpcValidatorError {
}
}

impl RpcValidatorRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
#[cfg(feature = "server")]
impl crate::RpcRequest for RpcValidatorRequest {
fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
let epoch_reference = if let Ok((block_id,)) =
crate::utils::parse_params::<(near_primitives::types::MaybeBlockId,)>(value.clone())
{
Expand All @@ -79,9 +80,10 @@ impl RpcValidatorRequest {
}
}

impl RpcValidatorsOrderedRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
Ok(crate::utils::parse_params::<RpcValidatorsOrderedRequest>(value)?)
#[cfg(feature = "server")]
impl crate::RpcRequest for RpcValidatorsOrderedRequest {
fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
crate::utils::parse_params::<Self>(value)
}
}

Expand Down
4 changes: 2 additions & 2 deletions chain/jsonrpc-primitives/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use serde_json::Value;

use near_primitives::borsh::BorshDeserialize;

pub(crate) fn parse_params<T: DeserializeOwned>(
pub fn parse_params<T: DeserializeOwned>(
value: Option<Value>,
) -> Result<T, crate::errors::RpcParseError> {
if let Some(value) = value {
Expand All @@ -14,7 +14,7 @@ pub(crate) fn parse_params<T: DeserializeOwned>(
}
}

pub(crate) fn parse_signed_transaction(
pub fn parse_signed_transaction(
value: Option<Value>,
) -> Result<near_primitives::transaction::SignedTransaction, crate::errors::RpcParseError> {
let (encoded,) = crate::utils::parse_params::<(String,)>(value.clone())?;
Expand Down
6 changes: 3 additions & 3 deletions chain/jsonrpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ near-client = { path = "../client" }
near-network = { path = "../network" }
near-o11y = { path = "../../core/o11y" }
near-jsonrpc-client = { path = "client" }
near-jsonrpc-primitives = { path = "../jsonrpc-primitives" }
near-jsonrpc-adversarial-primitives = { path = "../jsonrpc-adversarial-primitives", optional = true }
near-jsonrpc-primitives = { path = "../jsonrpc-primitives", features = ["server"] }
near-jsonrpc-adversarial-primitives = { path = "../jsonrpc-adversarial-primitives", features = ["server"], optional = true }
near-rpc-error-macro = { path = "../../tools/rpctypegen/macro" }
near-network-primitives = { path = "../network-primitives" }

Expand All @@ -40,7 +40,7 @@ test_features = [
"near-client/test_features",
"near-network/test_features",
"near-jsonrpc-primitives/test_features",
"near-jsonrpc-adversarial-primitives/ser_de",
"near-jsonrpc-adversarial-primitives/test_features",
]
nightly = ["nightly_protocol"]
nightly_protocol = ["near-primitives/nightly_protocol"]
Expand Down
4 changes: 2 additions & 2 deletions chain/jsonrpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use near_client::{
pub use near_jsonrpc_client as client;
use near_jsonrpc_primitives::errors::RpcError;
use near_jsonrpc_primitives::message::{Message, Request};
use near_jsonrpc_primitives::types::config::RpcProtocolConfigResponse;
use near_jsonrpc_primitives::RpcRequest;
use near_metrics::{Encoder, TextEncoder};
use near_network::types::{NetworkClientMessages, NetworkClientResponses};
use near_primitives::hash::CryptoHash;
Expand Down Expand Up @@ -923,7 +923,7 @@ impl JsonRpcHandler {
.view_client_addr
.send(GetProtocolConfig(request_data.block_reference.into()))
.await??;
Ok(RpcProtocolConfigResponse { config_view })
Ok(near_jsonrpc_primitives::types::config::RpcProtocolConfigResponse { config_view })
}

async fn query(
Expand Down