Skip to content

Commit

Permalink
[refactor]: remove Value enum
Browse files Browse the repository at this point in the history
Signed-off-by: Marin Veršić <[email protected]>
  • Loading branch information
mversic committed Mar 7, 2024
1 parent 108084d commit 579f68c
Show file tree
Hide file tree
Showing 53 changed files with 1,796 additions and 2,805 deletions.
54 changes: 26 additions & 28 deletions client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use eyre::{eyre, Result, WrapErr};
use futures_util::StreamExt;
use http_default::{AsyncWebSocketStream, WebSocketStream};
pub use iroha_config::client_api::ConfigDTO;
use iroha_data_model::query::QueryOutputBox;
use iroha_logger::prelude::*;
use iroha_telemetry::metrics::Status;
use iroha_torii_const::uri as torii_uri;
Expand All @@ -29,9 +30,8 @@ use crate::{
data_model::{
block::SignedBlock,
isi::Instruction,
predicate::PredicateBox,
prelude::*,
query::{Pagination, Query, Sorting},
query::{predicate::PredicateBox, Pagination, Query, Sorting},
BatchedResponse, ChainId, ValidationFail,
},
http::{Method as HttpMethod, RequestBuilder, Response, StatusCode},
Expand Down Expand Up @@ -81,13 +81,13 @@ impl Sign for SignedTransaction {

impl<R: QueryOutput> QueryResponseHandler<R>
where
<R as TryFrom<Value>>::Error: Into<eyre::Error>,
<R as TryFrom<QueryOutputBox>>::Error: Into<eyre::Error>,
{
fn handle(&mut self, resp: &Response<Vec<u8>>) -> QueryResult<R> {
// Separate-compilation friendly response handling
fn _handle_query_response_base(
resp: &Response<Vec<u8>>,
) -> QueryResult<BatchedResponse<Value>> {
) -> QueryResult<BatchedResponse<QueryOutputBox>> {
match resp.status() {
StatusCode::OK => {
let res = BatchedResponse::decode_all_versioned(resp.body());
Expand Down Expand Up @@ -127,12 +127,12 @@ where

let (batch, cursor) = _handle_query_response_base(resp)?.into();

let value = R::try_from(batch)
let output = R::try_from(batch)
.map_err(Into::into)
.wrap_err("Unexpected type")?;

self.query_request.request = crate::data_model::query::QueryRequest::Cursor(cursor);
Ok(value)
Ok(output)
}
}

Expand Down Expand Up @@ -215,12 +215,12 @@ impl From<ResponseReport> for eyre::Report {
}

/// Output of a query
pub trait QueryOutput: Into<Value> + TryFrom<Value> {
pub trait QueryOutput: Into<QueryOutputBox> + TryFrom<QueryOutputBox> {
/// Type of the query output
type Target: Clone;

/// Construct query output from query response
fn new(value: Self, query_request: QueryResponseHandler<Self>) -> Self::Target;
fn new(output: Self, query_request: QueryResponseHandler<Self>) -> Self::Target;
}

/// Iterable query output
Expand All @@ -244,7 +244,7 @@ impl<T> ResultSet<T> {
impl<T: Clone> Iterator for ResultSet<T>
where
Vec<T>: QueryOutput,
<Vec<T> as TryFrom<Value>>::Error: Into<eyre::Error>,
<Vec<T> as TryFrom<QueryOutputBox>>::Error: Into<eyre::Error>,
{
type Item = QueryResult<T>;

Expand All @@ -268,11 +268,11 @@ where
Err(err) => return Some(Err(ClientQueryError::Other(err))),
Ok(ok) => ok,
};
let value = match self.query_handler.handle(&response) {
let output = match self.query_handler.handle(&response) {
Err(err) => return Some(Err(err)),
Ok(ok) => ok,
};
self.iter = value;
self.iter = output;
self.client_cursor = 0;
}

Expand All @@ -284,14 +284,14 @@ where

impl<T: Debug + Clone> QueryOutput for Vec<T>
where
Self: Into<Value> + TryFrom<Value>,
Self: Into<QueryOutputBox> + TryFrom<QueryOutputBox>,
{
type Target = ResultSet<T>;

fn new(value: Self, query_handler: QueryResponseHandler<Self>) -> Self::Target {
fn new(output: Self, query_handler: QueryResponseHandler<Self>) -> Self::Target {
ResultSet {
query_handler,
iter: value,
iter: output,
client_cursor: 0,
}
}
Expand All @@ -302,22 +302,20 @@ macro_rules! impl_query_output {
impl QueryOutput for $ident {
type Target = Self;

fn new(value: Self, _query_handler: QueryResponseHandler<Self>) -> Self::Target {
value
fn new(output: Self, _query_handler: QueryResponseHandler<Self>) -> Self::Target {
output
}
} )+
};
}
impl_query_output! {
bool,
crate::data_model::Value,
crate::data_model::role::Role,
crate::data_model::asset::Asset,
crate::data_model::asset::AssetDefinition,
crate::data_model::account::Account,
crate::data_model::domain::Domain,
crate::data_model::block::BlockHeader,
crate::data_model::query::MetadataValue,
crate::data_model::metadata::MetadataValueBox,
crate::data_model::query::TransactionQueryOutput,
crate::data_model::permission::PermissionTokenSchema,
crate::data_model::trigger::Trigger<crate::data_model::events::TriggeringFilterBox>,
Expand Down Expand Up @@ -791,7 +789,7 @@ impl Client {
fetch_size: FetchSize,
) -> (DefaultRequestBuilder, QueryResponseHandler<R::Output>)
where
<R::Output as TryFrom<Value>>::Error: Into<eyre::Error>,
<R::Output as TryFrom<QueryOutputBox>>::Error: Into<eyre::Error>,
{
let query_builder = QueryBuilder::new(request, self.account_id.clone()).with_filter(filter);
let request = self.sign_query(query_builder).encode_versioned();
Expand Down Expand Up @@ -826,15 +824,15 @@ impl Client {
) -> QueryResult<<R::Output as QueryOutput>::Target>
where
R::Output: QueryOutput,
<R::Output as TryFrom<Value>>::Error: Into<eyre::Error>,
<R::Output as TryFrom<QueryOutputBox>>::Error: Into<eyre::Error>,
{
iroha_logger::trace!(?request, %pagination, ?sorting, ?filter);
let (req, mut resp_handler) =
self.prepare_query_request::<R>(request, filter, pagination, sorting, fetch_size);

let response = req.build()?.send()?;
let value = resp_handler.handle(&response)?;
let output = QueryOutput::new(value, resp_handler);
let output = resp_handler.handle(&response)?;
let output = QueryOutput::new(output, resp_handler);

Ok(output)
}
Expand All @@ -847,7 +845,7 @@ impl Client {
where
R: Query + Debug,
R::Output: QueryOutput,
<R::Output as TryFrom<Value>>::Error: Into<eyre::Error>,
<R::Output as TryFrom<QueryOutputBox>>::Error: Into<eyre::Error>,
{
self.build_query(request).execute()
}
Expand All @@ -865,7 +863,7 @@ impl Client {
) -> QueryResult<O::Target>
where
O: QueryOutput,
<O as TryFrom<Value>>::Error: Into<eyre::Error>,
<O as TryFrom<QueryOutputBox>>::Error: Into<eyre::Error>,
{
let request = QueryRequest {
torii_url: self.torii_url.clone(),
Expand All @@ -875,8 +873,8 @@ impl Client {
let response = request.clone().assemble().build()?.send()?;

let mut resp_handler = QueryResponseHandler::<O>::new(request);
let value = resp_handler.handle(&response)?;
let output = O::new(value, resp_handler);
let output = resp_handler.handle(&response)?;
let output = O::new(output, resp_handler);

Ok(output)
}
Expand All @@ -890,7 +888,7 @@ impl Client {
where
R: Query + Debug,
R::Output: QueryOutput,
<R::Output as TryFrom<Value>>::Error: Into<eyre::Error>,
<R::Output as TryFrom<QueryOutputBox>>::Error: Into<eyre::Error>,
{
QueryRequestBuilder::new(self, request)
}
Expand Down
10 changes: 4 additions & 6 deletions client/src/query_builder.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
use std::fmt::Debug;

use iroha_data_model::query::QueryOutputBox;

use crate::{
client::{Client, QueryOutput, QueryResult},
data_model::{
predicate::PredicateBox,
query::{sorting::Sorting, FetchSize, Pagination, Query},
Value,
},
data_model::query::{predicate::PredicateBox, sorting::Sorting, FetchSize, Pagination, Query},
};

pub struct QueryRequestBuilder<'a, R> {
Expand All @@ -22,7 +20,7 @@ impl<'a, R> QueryRequestBuilder<'a, R>
where
R: Query + Debug,
R::Output: QueryOutput,
<R::Output as TryFrom<Value>>::Error: Into<eyre::Error>,
<R::Output as TryFrom<QueryOutputBox>>::Error: Into<eyre::Error>,
{
pub(crate) fn new(client: &'a Client, request: R) -> Self {
Self {
Expand Down
12 changes: 5 additions & 7 deletions client/tests/integration/burn_public_keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use iroha_client::{
crypto::{HashOf, KeyPair, PublicKey},
data_model::{isi::Instruction, prelude::*},
};
use iroha_data_model::query::TransactionQueryOutput;
use test_network::*;

fn submit(
Expand All @@ -27,11 +28,8 @@ fn submit(
(tx.hash(), client.submit_transaction_blocking(&tx))
}

fn get(client: &Client, hash: HashOf<SignedTransaction>) -> TransactionValue {
*client
.request(transaction::by_hash(hash))
.unwrap()
.transaction
fn get(client: &Client, hash: HashOf<SignedTransaction>) -> TransactionQueryOutput {
client.request(transaction::by_hash(hash)).unwrap()
}

fn account_keys_count(client: &Client, account_id: AccountId) -> usize {
Expand Down Expand Up @@ -95,7 +93,7 @@ fn public_keys_cannot_be_burned_to_nothing() {
let committed_txn = get(&client, tx_hash);
keys_count = charlie_keys_count(&client);
assert_eq!(keys_count, 1);
assert!(committed_txn.error.is_none());
assert!(committed_txn.as_ref().error.is_none());

let burn_the_last_key = burn(charlie_initial_keypair.public_key().clone());

Expand All @@ -108,5 +106,5 @@ fn public_keys_cannot_be_burned_to_nothing() {
let committed_txn = get(&client, tx_hash);
keys_count = charlie_keys_count(&client);
assert_eq!(keys_count, 1);
assert!(committed_txn.error.is_some());
assert!(committed_txn.as_ref().error.is_some());
}
1 change: 0 additions & 1 deletion client/tests/integration/queries/asset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,6 @@ fn test_total_quantity<T>(
) -> Result<()>
where
T: Copy + Into<AssetValue>,
Value: From<T>,
Mint<T, Asset>: Instruction,
Burn<T, Asset>: Instruction,
{
Expand Down
6 changes: 2 additions & 4 deletions client/tests/integration/queries/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::str::FromStr as _;

use eyre::{bail, Result};
use eyre::Result;
use iroha_client::{
client::{self, ClientQueryError},
data_model::{
Expand Down Expand Up @@ -57,9 +57,7 @@ fn live_query_is_dropped_after_smart_contract_end() -> Result<()> {
client.account_id.clone(),
Name::from_str("cursor").unwrap(),
))?;
let Value::String(cursor) = metadata_value.0 else {
bail!("Expected `Value::String`, got {:?}", metadata_value.0);
};
let cursor: String = metadata_value.try_into()?;
let asset_cursor = serde_json::from_str::<ForwardCursor>(&cursor)?;

let err = client
Expand Down
2 changes: 1 addition & 1 deletion client/tests/integration/roles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ fn register_and_grant_role_for_metadata_access() -> Result<()> {
let set_key_value = SetKeyValue::account(
mouse_id,
Name::from_str("key").expect("Valid"),
Value::String("value".to_owned()),
"value".to_owned(),
);
test_client.submit_blocking(set_key_value)?;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ extern crate alloc;
use alloc::string::ToString as _;
use core::num::NonZeroU32;

use iroha_smart_contract::{parse, prelude::*};
use iroha_smart_contract::{data_model::metadata::MetadataValue, parse, prelude::*};
use lol_alloc::{FreeListAllocator, LockedAllocator};

#[global_allocator]
Expand All @@ -31,7 +31,7 @@ fn main(owner: AccountId) {
SetKeyValue::account(
owner,
parse!("cursor" as Name),
Value::String(
MetadataValue::String(
serde_json::to_value(cursor)
.dbg_expect("Failed to convert cursor to JSON")
.to_string(),
Expand Down
Loading

0 comments on commit 579f68c

Please sign in to comment.