Skip to content

Commit

Permalink
temp
Browse files Browse the repository at this point in the history
  • Loading branch information
Misieq01 committed Apr 18, 2024
1 parent 5151d9c commit b964454
Show file tree
Hide file tree
Showing 9 changed files with 8,092 additions and 645 deletions.
84 changes: 59 additions & 25 deletions crates/edr_eth/src/remote/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ use reqwest_tracing::TracingMiddleware;
use revm_primitives::{Bytecode, KECCAK_EMPTY};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use tokio::sync::{OnceCell, RwLock};
use tokio::time::sleep;
use tracing::{info, info_span};
use uuid::Uuid;

use super::{
Expand Down Expand Up @@ -79,6 +81,10 @@ pub enum RpcClientError {
#[error(transparent)]
InvalidJsonRequest(serde_json::Error),

/// The request was rate limited.
#[error("The request was rate limited")]
TooManyRetries(),

/// The server returned an invalid JSON-RPC response.
#[error("Response '{response}' failed to parse with expected type '{expected_type}', due to error: '{error}'")]
InvalidResponse {
Expand Down Expand Up @@ -603,17 +609,28 @@ impl RpcClient {
self.batch_call_with_resolver(methods, |_| None).await
}

#[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))]
async fn batch_call_with_resolver(
&self,
methods: &[RequestMethod],
resolve_block_number: impl Fn(&serde_json::Value) -> Option<u64>,
) -> Result<VecDeque<ResponseValue>, RpcClientError> {
let ids = self.get_ids(methods.len() as u64);

let cache_keys = methods.iter().map(try_read_cache_key).collect::<Vec<_>>();

let mut results: Vec<Option<ResponseValue>> = Vec::with_capacity(cache_keys.len());
#[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))]
async fn batch_call_with_resolver(
&self,
methods: &[RequestMethod],
resolve_block_number: impl Fn(&serde_json::Value) -> Option<u64>,
) -> Result<VecDeque<ResponseValue>, RpcClientError> {
let ids = self.get_ids(methods.len() as u64);
let cache_keys = methods.iter().map(try_read_cache_key).collect::<Vec<_>>();
let mut results: Vec<Option<ResponseValue>> = Vec::with_capacity(cache_keys.len());
let mut retry_number = 0;
let seconds = Duration::from_secs(1);
let mut needs_to_retry;

info!("Rust Batch Call");
info_span!(
"Rust Batch Call",
methods = ?methods,
cache_keys = ?cache_keys,
);

loop {
needs_to_retry = false;

for cache_key in &cache_keys {
results.push(self.try_from_cache(cache_key.as_ref()).await?);
Expand All @@ -637,13 +654,13 @@ impl RpcClient {

// Don't send empty request
if requests.is_empty() {
Ok(results
return Ok(results
.into_iter()
.enumerate()
.map(|(_index, result)| {
result.expect("If there are no requests to send, there must be a cached response for each method invocation")
})
.collect())
.collect());
} else {
let request_body = SerializedRequest(
serde_json::to_value(&requests).map_err(RpcClientError::InvalidJsonRequest)?,
Expand All @@ -661,22 +678,38 @@ impl RpcClient {
id: response.id,
})?;

let result =
response
.data
.into_result()
.map_err(|error| RpcClientError::JsonRpcError {
let result = match response.data.into_result() {
Ok(data) => data,
Err(error) => {
if error.code == 429 {
needs_to_retry = true;
break;
} else {
return Err(RpcClientError::JsonRpcError {
error,
request: request_body.to_json_string(),
})?;

self.try_write_response_to_cache(&methods[index], &result, &resolve_block_number)
.await?;
});
}
}
};

self.try_write_response_to_cache(&methods[index], &result, &resolve_block_number)
.await?;

results[index] = Some(ResponseValue::Remote(result));
}

results[index] = Some(ResponseValue::Remote(result));
if needs_to_retry {
if retry_number < MAX_RETRIES {
sleep(seconds).await;
retry_number += 1;
continue;
} else {
return Err(RpcClientError::TooManyRetries());
}
}

results
return results
.into_iter()
.enumerate()
.map(|(index, result)| {
Expand All @@ -686,7 +719,8 @@ impl RpcClient {
response: remote_response.clone(),
})
})
.collect()
.collect();
}
}
}

Expand Down
35 changes: 25 additions & 10 deletions crates/edr_napi/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -224,17 +224,32 @@ switch (platform) {
}
break
case 'arm':
localFileExisted = existsSync(
join(__dirname, 'edr.linux-arm-gnueabihf.node')
)
try {
if (localFileExisted) {
nativeBinding = require('./edr.linux-arm-gnueabihf.node')
} else {
nativeBinding = require('@nomicfoundation/edr-linux-arm-gnueabihf')
if (isMusl()) {
localFileExisted = existsSync(
join(__dirname, 'edr.linux-arm-musleabihf.node')
)
try {
if (localFileExisted) {
nativeBinding = require('./edr.linux-arm-musleabihf.node')
} else {
nativeBinding = require('@nomicfoundation/edr-linux-arm-musleabihf')
}
} catch (e) {
loadError = e
}
} else {
localFileExisted = existsSync(
join(__dirname, 'edr.linux-arm-gnueabihf.node')
)
try {
if (localFileExisted) {
nativeBinding = require('./edr.linux-arm-gnueabihf.node')
} else {
nativeBinding = require('@nomicfoundation/edr-linux-arm-gnueabihf')
}
} catch (e) {
loadError = e
}
} catch (e) {
loadError = e
}
break
case 'riscv64':
Expand Down
2 changes: 2 additions & 0 deletions crates/edr_provider/src/requests/eth/transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use edr_eth::{
Bytes, SpecId, B256, U256,
};
use edr_evm::{blockchain::BlockchainError, trace::Trace, ExecutableTransaction, SyncBlock};
use log::info;

use crate::{
data::{BlockDataForTransaction, ProviderData, SendTransactionResult, TransactionAndBlock},
Expand Down Expand Up @@ -453,6 +454,7 @@ fn validate_send_transaction_request<LoggerErrorT: Debug>(
) -> Result<(), ProviderError<LoggerErrorT>> {
if let Some(chain_id) = request.chain_id {
let expected = data.chain_id();
info!("Validating chain id: expected={}, actual={}", expected, chain_id);
if chain_id != expected {
return Err(ProviderError::InvalidChainId {
expected,
Expand Down
Loading

0 comments on commit b964454

Please sign in to comment.