web3-proxy/web3_proxy/src/frontend/http_proxy.rs

81 lines
2.6 KiB
Rust
Raw Normal View History

2022-08-21 12:39:38 +03:00
use super::errors::{anyhow_error_into_response, FrontendResult};
use super::rate_limit::{rate_limit_by_ip, rate_limit_by_user_key, RateLimitResult};
2022-08-16 22:29:00 +03:00
use crate::stats::{Protocol, ProxyRequestLabels};
use crate::{app::Web3ProxyApp, jsonrpc::JsonRpcRequestEnum};
2022-08-06 04:17:25 +03:00
use axum::extract::Path;
2022-08-11 03:16:13 +03:00
use axum::response::Response;
2022-06-05 22:58:47 +03:00
use axum::{http::StatusCode, response::IntoResponse, Extension, Json};
2022-07-07 06:22:09 +03:00
use axum_client_ip::ClientIp;
2022-08-21 12:39:38 +03:00
use std::net::IpAddr;
2022-06-05 22:58:47 +03:00
use std::sync::Arc;
2022-08-16 03:33:26 +03:00
use tracing::{error_span, Instrument};
2022-08-06 04:17:25 +03:00
use uuid::Uuid;
2022-06-05 22:58:47 +03:00
2022-08-05 22:22:23 +03:00
pub async fn public_proxy_web3_rpc(
2022-07-07 06:22:09 +03:00
Json(payload): Json<JsonRpcRequestEnum>,
Extension(app): Extension<Arc<Web3ProxyApp>>,
ClientIp(ip): ClientIp,
2022-08-21 12:39:38 +03:00
) -> FrontendResult {
let _ip: IpAddr = rate_limit_by_ip(&app, ip).await?.try_into()?;
2022-08-04 04:10:27 +03:00
let protocol = Protocol::HTTP;
2022-08-16 03:33:26 +03:00
let user_id = 0;
let user_span = error_span!("user", user_id, ?protocol);
/*
// TODO: move this to a helper function (or two). have it fetch method, protocol, etc. from tracing?
match &payload {
JsonRpcRequestEnum::Batch(batch) => {
2022-08-16 03:33:26 +03:00
// TODO: use inc_by if possible? need to group them by rpc_method
for single in batch {
let rpc_method = single.method.clone();
let _count = app
.stats
.proxy_requests
.get_or_create(&ProxyRequestLabels {
rpc_method,
2022-08-16 03:33:26 +03:00
protocol: protocol.clone(),
user_id,
})
.inc();
}
}
JsonRpcRequestEnum::Single(single) => {
let rpc_method = single.method.clone();
let _count = app
.stats
.proxy_requests
.get_or_create(&ProxyRequestLabels {
protocol,
rpc_method,
user_id,
})
.inc();
}
};
*/
2022-08-16 03:33:26 +03:00
2022-08-21 12:39:38 +03:00
let response = app.proxy_web3_rpc(payload).instrument(user_span).await?;
Ok((StatusCode::OK, Json(&response)).into_response())
2022-08-04 04:10:27 +03:00
}
2022-07-07 06:22:09 +03:00
2022-08-04 04:10:27 +03:00
pub async fn user_proxy_web3_rpc(
Json(payload): Json<JsonRpcRequestEnum>,
Extension(app): Extension<Arc<Web3ProxyApp>>,
2022-08-06 04:17:25 +03:00
Path(user_key): Path<Uuid>,
2022-08-21 12:39:38 +03:00
) -> FrontendResult {
let user_id: u64 = rate_limit_by_user_key(&app, user_key).await?.try_into()?;
2022-07-07 06:22:09 +03:00
let protocol = Protocol::HTTP;
let user_span = error_span!("user", user_id, ?protocol);
2022-08-21 12:39:38 +03:00
let response = app.proxy_web3_rpc(payload).instrument(user_span).await?;
Ok((StatusCode::OK, Json(&response)).into_response())
2022-06-05 22:58:47 +03:00
}