web3-proxy/web3_proxy/src/rpcs/request.rs

409 lines
16 KiB
Rust
Raw Normal View History

use super::one::Web3Rpc;
2022-08-24 03:11:49 +03:00
use super::provider::Web3Provider;
use crate::frontend::authorization::Authorization;
use anyhow::Context;
use chrono::Utc;
2022-11-01 21:54:39 +03:00
use entities::revert_log;
use entities::sea_orm_active_enums::Method;
use ethers::providers::{HttpClientError, ProviderError, WsClientError};
use ethers::types::{Address, Bytes};
2022-12-08 09:54:38 +03:00
use log::{debug, error, trace, warn, Level};
2022-11-14 21:24:52 +03:00
use migration::sea_orm::{self, ActiveEnum, ActiveModelTrait};
use serde_json::json;
2022-08-24 03:11:49 +03:00
use std::fmt;
use std::sync::atomic;
2022-08-24 03:14:49 +03:00
use std::sync::Arc;
2022-11-12 09:11:58 +03:00
use thread_fast_rng::rand::Rng;
2022-08-30 23:01:42 +03:00
use tokio::time::{sleep, Duration, Instant};
2022-08-24 03:11:49 +03:00
2022-08-30 23:01:42 +03:00
#[derive(Debug)]
2022-08-24 03:14:49 +03:00
pub enum OpenRequestResult {
2022-08-24 03:59:05 +03:00
Handle(OpenRequestHandle),
/// Unable to start a request. Retry at the given time.
2022-08-24 03:11:49 +03:00
RetryAt(Instant),
2023-02-15 04:41:40 +03:00
/// Unable to start a request because no servers are synced
NotReady,
2022-08-24 03:11:49 +03:00
}
2022-08-24 03:59:05 +03:00
/// Make RPC requests through this handle and drop it when you are done.
/// Opening this handle checks rate limits. Developers, try to keep opening a handle and using it as close together as possible
2022-08-30 23:01:42 +03:00
#[derive(Debug)]
2022-09-09 06:53:16 +03:00
pub struct OpenRequestHandle {
authorization: Arc<Authorization>,
2023-02-12 21:22:20 +03:00
rpc: Arc<Web3Rpc>,
2022-09-09 06:53:16 +03:00
}
2022-08-24 03:11:49 +03:00
2022-09-23 01:34:43 +03:00
/// Depending on the context, RPC errors can require different handling.
2023-02-16 02:31:59 +03:00
#[derive(Copy, Clone)]
2023-04-04 15:40:22 +03:00
pub enum RequestRevertHandler {
/// Log at the trace level. Use when errors are expected.
TraceLevel,
2022-09-23 01:15:56 +03:00
/// Log at the debug level. Use when errors are expected.
DebugLevel,
2022-09-23 01:15:56 +03:00
/// Log at the error level. Use when errors are bad.
ErrorLevel,
2022-09-23 01:15:56 +03:00
/// Log at the warn level. Use when errors do not cause problems.
WarnLevel,
/// Potentially save the revert. Users can tune how often this happens
2023-04-04 15:40:22 +03:00
Save,
}
2022-09-24 10:04:11 +03:00
// TODO: second param could be skipped since we don't need it here
#[derive(serde::Deserialize, serde::Serialize)]
2022-09-24 10:04:11 +03:00
struct EthCallParams((EthCallFirstParams, Option<serde_json::Value>));
#[derive(serde::Deserialize, serde::Serialize)]
struct EthCallFirstParams {
to: Address,
data: Option<Bytes>,
}
2023-04-04 15:40:22 +03:00
impl From<Level> for RequestRevertHandler {
fn from(level: Level) -> Self {
match level {
2023-04-04 15:40:22 +03:00
Level::Trace => RequestRevertHandler::TraceLevel,
Level::Debug => RequestRevertHandler::DebugLevel,
Level::Error => RequestRevertHandler::ErrorLevel,
Level::Warn => RequestRevertHandler::WarnLevel,
2022-09-23 01:15:56 +03:00
_ => unimplemented!("unexpected tracing Level"),
}
}
}
impl Authorization {
2022-09-23 01:34:43 +03:00
/// Save a RPC call that return "execution reverted" to the database.
async fn save_revert(
self: Arc<Self>,
method: Method,
params: EthCallFirstParams,
) -> anyhow::Result<()> {
2023-01-19 03:17:43 +03:00
let rpc_key_id = match self.checks.rpc_secret_key_id {
Some(rpc_key_id) => rpc_key_id.into(),
None => {
2022-11-12 11:24:32 +03:00
// // trace!(?self, "cannot save revert without rpc_key_id");
return Ok(());
}
};
let db_conn = self.db_conn.as_ref().context("no database connection")?;
// TODO: should the database set the timestamp?
// we intentionally use "now" and not the time the request started
// why? because we aggregate stats and setting one in the past could cause confusion
let timestamp = Utc::now();
let to: Vec<u8> = params
.to
.as_bytes()
.try_into()
.expect("address should always convert to a Vec<u8>");
let call_data = params.data.map(|x| format!("{}", x));
let rl = revert_log::ActiveModel {
rpc_key_id: sea_orm::Set(rpc_key_id),
method: sea_orm::Set(method),
to: sea_orm::Set(to),
call_data: sea_orm::Set(call_data),
timestamp: sea_orm::Set(timestamp),
..Default::default()
};
let rl = rl
.save(db_conn)
.await
.context("Failed saving new revert log")?;
// TODO: what log level?
// TODO: better format
2022-11-16 10:19:56 +03:00
trace!("revert_log: {:?}", rl);
// TODO: return something useful
Ok(())
2022-09-23 00:51:52 +03:00
}
}
2022-08-24 03:14:49 +03:00
impl OpenRequestHandle {
pub async fn new(authorization: Arc<Authorization>, rpc: Arc<Web3Rpc>) -> Self {
// TODO: take request_id as an argument?
// TODO: attach a unique id to this? customer requests have one, but not internal queries
// TODO: what ordering?!
// TODO: should we be using metered, or not? i think not because we want stats for each handle
// TODO: these should maybe be sent to an influxdb instance?
rpc.active_requests.fetch_add(1, atomic::Ordering::Relaxed);
Self { authorization, rpc }
2022-08-24 03:11:49 +03:00
}
2022-12-20 02:59:01 +03:00
pub fn connection_name(&self) -> String {
2023-02-12 21:22:20 +03:00
self.rpc.name.clone()
2022-12-20 02:59:01 +03:00
}
2022-09-23 01:34:43 +03:00
#[inline]
pub fn clone_connection(&self) -> Arc<Web3Rpc> {
2023-02-12 21:22:20 +03:00
self.rpc.clone()
2022-08-24 03:11:49 +03:00
}
/// Send a web3 request
/// By having the request method here, we ensure that the rate limiter was called and connection counts were properly incremented
2023-02-16 11:26:58 +03:00
/// depending on how things are locked, you might need to pass the provider in
/// we take self to ensure this function only runs once
pub async fn request<P, R>(
self,
2022-08-24 03:11:49 +03:00
method: &str,
params: &P,
2023-04-04 15:40:22 +03:00
revert_handler: RequestRevertHandler,
unlocked_provider: Option<Arc<Web3Provider>>,
) -> Result<R, ProviderError>
2022-08-24 03:11:49 +03:00
where
2022-09-23 00:51:52 +03:00
// TODO: not sure about this type. would be better to not need clones, but measure and spawns combine to need it
P: Clone + fmt::Debug + serde::Serialize + Send + Sync + 'static,
2022-08-24 03:11:49 +03:00
R: serde::Serialize + serde::de::DeserializeOwned + fmt::Debug,
{
2022-09-23 00:51:52 +03:00
// TODO: use tracing spans
// TODO: including params in this log is way too verbose
// trace!(rpc=%self.rpc, %method, "request");
2023-02-12 21:22:20 +03:00
trace!("requesting from {}", self.rpc);
2023-02-16 11:26:58 +03:00
let mut provider = if unlocked_provider.is_some() {
unlocked_provider
} else {
self.rpc.provider.read().await.clone()
};
let mut logged = false;
while provider.is_none() || provider.as_ref().map(|x| !x.ready()).unwrap() {
// trace!("waiting on provider: locking...");
// TODO: i dont like this. subscribing to a channel could be better
2023-02-16 11:26:58 +03:00
sleep(Duration::from_millis(100)).await;
if !logged {
2023-02-12 21:22:20 +03:00
debug!("no provider for open handle on {}", self.rpc);
logged = true;
}
2023-02-16 11:26:58 +03:00
provider = self.rpc.provider.read().await.clone();
}
let provider = provider.expect("provider was checked already");
2022-08-24 03:11:49 +03:00
2023-02-15 23:33:43 +03:00
self.rpc
.total_requests
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2023-02-16 11:26:58 +03:00
self.rpc
.active_requests
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
// let latency = Instant::now();
2023-02-15 23:33:43 +03:00
// TODO: replace ethers-rs providers with our own that supports streaming the responses
let response = match provider.as_ref() {
#[cfg(test)]
2023-03-31 14:43:41 +03:00
Web3Provider::Mock => {
return Err(ProviderError::CustomError(
"mock provider can't respond".to_string(),
))
}
Web3Provider::Ws(p) => p.request(method, params).await,
Web3Provider::Http(p) | Web3Provider::Both(p, _) => {
// TODO: i keep hearing that http is faster. but ws has always been better for me. investigate more with actual benchmarks
p.request(method, params).await
}
2022-08-24 03:11:49 +03:00
};
2023-02-16 11:26:58 +03:00
// note. we intentionally do not record this latency now. we do NOT want to measure errors
// let latency = latency.elapsed();
self.rpc
.active_requests
.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
2023-01-19 03:17:43 +03:00
// // TODO: i think ethers already has trace logging (and does it much more fancy)
// trace!(
// "response from {} for {} {:?}: {:?}",
// self.rpc,
2023-01-19 03:17:43 +03:00
// method,
// params,
// response,
// );
2022-12-06 00:13:36 +03:00
if let Err(err) = &response {
2022-09-23 01:42:44 +03:00
// only save reverts for some types of calls
// TODO: do something special for eth_sendRawTransaction too
2023-04-04 15:40:22 +03:00
let error_handler = if let RequestRevertHandler::Save = revert_handler {
2022-11-26 07:57:25 +03:00
// TODO: should all these be Trace or Debug or a mix?
2022-09-24 10:04:11 +03:00
if !["eth_call", "eth_estimateGas"].contains(&method) {
2022-11-12 11:24:32 +03:00
// trace!(%method, "skipping save on revert");
2023-04-04 15:40:22 +03:00
RequestRevertHandler::TraceLevel
} else if self.authorization.db_conn.is_some() {
let log_revert_chance = self.authorization.checks.log_revert_chance;
if log_revert_chance == 0.0 {
2022-11-12 11:24:32 +03:00
// trace!(%method, "no chance. skipping save on revert");
2023-04-04 15:40:22 +03:00
RequestRevertHandler::TraceLevel
} else if log_revert_chance == 1.0 {
2022-11-12 11:24:32 +03:00
// trace!(%method, "gaurenteed chance. SAVING on revert");
2023-01-17 09:54:40 +03:00
revert_handler
2022-11-12 09:11:58 +03:00
} else if thread_fast_rng::thread_fast_rng().gen_range(0.0f64..=1.0)
< log_revert_chance
{
2022-11-12 11:24:32 +03:00
// trace!(%method, "missed chance. skipping save on revert");
2023-04-04 15:40:22 +03:00
RequestRevertHandler::TraceLevel
2022-09-24 10:04:11 +03:00
} else {
2022-11-12 11:24:32 +03:00
// trace!("Saving on revert");
// TODO: is always logging at debug level fine?
2023-01-17 09:54:40 +03:00
revert_handler
2022-09-24 10:04:11 +03:00
}
2022-09-23 01:42:44 +03:00
} else {
2022-11-12 11:24:32 +03:00
// trace!(%method, "no database. skipping save on revert");
2023-04-04 15:40:22 +03:00
RequestRevertHandler::TraceLevel
}
2022-09-23 01:42:44 +03:00
} else {
2023-01-17 09:54:40 +03:00
revert_handler
2022-09-23 01:42:44 +03:00
};
// TODO: simple enum -> string derive?
#[derive(Debug)]
2023-04-04 15:40:22 +03:00
enum ResponseTypes {
Revert,
RateLimit,
2023-04-04 15:40:22 +03:00
Ok,
}
2022-10-12 00:31:34 +03:00
// check for "execution reverted" here
// TODO: move this info a function on ResponseErrorType
let response_type = if let ProviderError::JsonRpcClientError(err) = err {
2022-10-12 00:31:34 +03:00
// Http and Ws errors are very similar, but different types
let msg = match &*provider {
#[cfg(test)]
Web3Provider::Mock => unimplemented!(),
Web3Provider::Both(_, _) => {
if let Some(HttpClientError::JsonRpcError(err)) =
err.downcast_ref::<HttpClientError>()
{
Some(&err.message)
} else if let Some(WsClientError::JsonRpcError(err)) =
err.downcast_ref::<WsClientError>()
{
Some(&err.message)
} else {
None
}
}
2022-10-12 00:31:34 +03:00
Web3Provider::Http(_) => {
if let Some(HttpClientError::JsonRpcError(err)) =
err.downcast_ref::<HttpClientError>()
{
Some(&err.message)
} else {
None
}
}
Web3Provider::Ws(_) => {
if let Some(WsClientError::JsonRpcError(err)) =
err.downcast_ref::<WsClientError>()
{
Some(&err.message)
} else {
None
}
}
};
if let Some(msg) = msg {
if msg.starts_with("execution reverted") {
2023-02-12 21:22:20 +03:00
trace!("revert from {}", self.rpc);
2023-04-04 15:40:22 +03:00
ResponseTypes::Revert
} else if msg.contains("limit") || msg.contains("request") {
2023-02-12 21:22:20 +03:00
trace!("rate limit from {}", self.rpc);
2023-04-04 15:40:22 +03:00
ResponseTypes::RateLimit
} else {
2023-04-04 15:40:22 +03:00
ResponseTypes::Ok
}
2022-10-12 00:31:34 +03:00
} else {
2023-04-04 15:40:22 +03:00
ResponseTypes::Ok
2022-10-12 00:31:34 +03:00
}
} else {
2023-04-04 15:40:22 +03:00
ResponseTypes::Ok
2022-10-12 00:31:34 +03:00
};
2022-10-10 07:15:07 +03:00
2023-04-04 15:40:22 +03:00
if matches!(response_type, ResponseTypes::RateLimit) {
if let Some(hard_limit_until) = self.rpc.hard_limit_until.as_ref() {
let retry_at = Instant::now() + Duration::from_secs(1);
2023-04-04 15:40:22 +03:00
trace!("retry {} at: {:?}", self.rpc, retry_at);
2023-04-04 15:40:22 +03:00
hard_limit_until.send_replace(retry_at);
}
2023-04-04 15:40:22 +03:00
}
// TODO: think more about the method and param logs. those can be sensitive information
match revert_handler {
RequestRevertHandler::DebugLevel => {
// TODO: think about this revert check more. sometimes we might want reverts logged so this needs a flag
if matches!(response_type, ResponseTypes::Revert) {
debug!(
"bad response from {}! method={} params={:?} err={:?}",
self.rpc, method, params, err
);
}
}
2023-04-04 15:40:22 +03:00
RequestRevertHandler::TraceLevel => {
trace!(
"bad response from {}! method={} params={:?} err={:?}",
self.rpc,
method,
params,
err
);
}
RequestRevertHandler::ErrorLevel => {
// TODO: include params if not running in release mode
error!(
"bad response from {}! method={} err={:?}",
self.rpc, method, err
);
}
RequestRevertHandler::WarnLevel => {
// TODO: include params if not running in release mode
warn!(
"bad response from {}! method={} err={:?}",
self.rpc, method, err
);
}
RequestRevertHandler::Save => {
trace!(
"bad response from {}! method={} params={:?} err={:?}",
self.rpc,
method,
params,
err
);
// TODO: do not unwrap! (doesn't matter much since we check method as a string above)
let method: Method = Method::try_from_value(&method.to_string()).unwrap();
// TODO: DO NOT UNWRAP! But also figure out the best way to keep returning ProviderErrors here
let params: EthCallParams = serde_json::from_value(json!(params))
.context("parsing params to EthCallParams")
.unwrap();
// spawn saving to the database so we don't slow down the request
let f = self.authorization.clone().save_revert(method, params.0 .0);
tokio::spawn(f);
}
}
2023-02-16 02:52:42 +03:00
} else {
// TODO: record request latency
// let latency_ms = start.elapsed().as_secs_f64() * 1000.0;
2023-02-16 02:52:42 +03:00
2023-02-16 08:09:39 +03:00
// TODO: is this lock here a problem? should this be done through a channel? i started to code it, but it didn't seem to matter
// let mut latency_recording = self.rpc.request_latency.write();
2023-02-16 02:52:42 +03:00
// latency_recording.record(latency_ms);
}
2022-08-24 03:11:49 +03:00
response
}
}