2022-05-20 08:30:54 +03:00
|
|
|
use axum::{
|
2022-05-29 20:28:41 +03:00
|
|
|
extract::ws::{Message, WebSocket, WebSocketUpgrade},
|
2022-08-06 04:17:25 +03:00
|
|
|
extract::Path,
|
2022-08-11 04:53:27 +03:00
|
|
|
response::{IntoResponse, Redirect, Response},
|
2022-06-05 22:58:47 +03:00
|
|
|
Extension,
|
2022-05-20 08:30:54 +03:00
|
|
|
};
|
2022-08-04 04:10:27 +03:00
|
|
|
use axum_client_ip::ClientIp;
|
2022-05-29 20:28:41 +03:00
|
|
|
use futures::SinkExt;
|
2022-05-31 04:55:04 +03:00
|
|
|
use futures::{
|
|
|
|
future::AbortHandle,
|
|
|
|
stream::{SplitSink, SplitStream, StreamExt},
|
|
|
|
};
|
2022-08-12 22:07:14 +03:00
|
|
|
use handlebars::Handlebars;
|
2022-05-29 22:33:10 +03:00
|
|
|
use hashbrown::HashMap;
|
2022-07-22 22:30:39 +03:00
|
|
|
use serde_json::{json, value::RawValue};
|
2022-05-20 08:30:54 +03:00
|
|
|
use std::sync::Arc;
|
2022-07-09 01:14:45 +03:00
|
|
|
use std::{str::from_utf8_mut, sync::atomic::AtomicUsize};
|
|
|
|
use tracing::{error, info, trace};
|
2022-08-06 04:17:25 +03:00
|
|
|
use uuid::Uuid;
|
2022-06-16 05:53:37 +03:00
|
|
|
|
|
|
|
use crate::{
|
|
|
|
app::Web3ProxyApp,
|
|
|
|
jsonrpc::{JsonRpcForwardedResponse, JsonRpcForwardedResponseEnum, JsonRpcRequest},
|
|
|
|
};
|
2022-05-20 08:30:54 +03:00
|
|
|
|
2022-08-11 04:53:27 +03:00
|
|
|
use super::{errors::anyhow_error_into_response, rate_limit::RateLimitResult};
|
2022-08-04 04:10:27 +03:00
|
|
|
|
2022-08-05 22:22:23 +03:00
|
|
|
pub async fn public_websocket_handler(
|
2022-07-07 06:22:09 +03:00
|
|
|
Extension(app): Extension<Arc<Web3ProxyApp>>,
|
2022-08-04 04:10:27 +03:00
|
|
|
ClientIp(ip): ClientIp,
|
2022-08-10 05:37:34 +03:00
|
|
|
ws_upgrade: Option<WebSocketUpgrade>,
|
2022-08-07 22:33:16 +03:00
|
|
|
) -> Response {
|
2022-08-12 22:07:14 +03:00
|
|
|
let _ip = match app.rate_limit_by_ip(ip).await {
|
2022-08-11 04:53:27 +03:00
|
|
|
Ok(x) => match x.try_into_response().await {
|
|
|
|
Ok(RateLimitResult::AllowedIp(x)) => x,
|
|
|
|
Err(err_response) => return err_response,
|
|
|
|
_ => unimplemented!(),
|
|
|
|
},
|
|
|
|
Err(err) => return anyhow_error_into_response(None, None, err).into_response(),
|
|
|
|
};
|
2022-08-04 04:10:27 +03:00
|
|
|
|
2022-08-11 03:16:13 +03:00
|
|
|
match ws_upgrade {
|
|
|
|
Some(ws) => ws
|
|
|
|
.on_upgrade(|socket| proxy_web3_socket(app, socket))
|
|
|
|
.into_response(),
|
2022-08-07 22:33:16 +03:00
|
|
|
None => {
|
2022-08-12 22:07:14 +03:00
|
|
|
// this is not a websocket. redirect to a friendly page
|
|
|
|
Redirect::to(&app.config.redirect_public_url).into_response()
|
2022-08-07 22:33:16 +03:00
|
|
|
}
|
|
|
|
}
|
2022-08-04 04:10:27 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn user_websocket_handler(
|
|
|
|
Extension(app): Extension<Arc<Web3ProxyApp>>,
|
2022-08-06 04:17:25 +03:00
|
|
|
Path(user_key): Path<Uuid>,
|
2022-08-11 03:16:13 +03:00
|
|
|
ws_upgrade: Option<WebSocketUpgrade>,
|
2022-08-07 22:33:16 +03:00
|
|
|
) -> Response {
|
2022-08-11 04:53:27 +03:00
|
|
|
// TODO: dry this up. maybe a rate_limit_by_key_response function?
|
|
|
|
let user_id = match app.rate_limit_by_key(user_key).await {
|
|
|
|
Ok(x) => match x.try_into_response().await {
|
|
|
|
Ok(RateLimitResult::AllowedUser(x)) => x,
|
|
|
|
Err(err_response) => return err_response,
|
|
|
|
_ => unimplemented!(),
|
|
|
|
},
|
|
|
|
Err(err) => return anyhow_error_into_response(None, None, err).into_response(),
|
|
|
|
};
|
2022-08-04 04:10:27 +03:00
|
|
|
|
2022-08-11 03:16:13 +03:00
|
|
|
match ws_upgrade {
|
|
|
|
Some(ws_upgrade) => ws_upgrade.on_upgrade(|socket| proxy_web3_socket(app, socket)),
|
|
|
|
None => {
|
2022-08-12 22:07:14 +03:00
|
|
|
// TODO: store this on the app and use register_template?
|
|
|
|
let reg = Handlebars::new();
|
|
|
|
|
|
|
|
// TODO: show the user's address, not their id (remember to update the checks for {{user_id}} in app.rs)
|
2022-08-12 04:48:32 +03:00
|
|
|
// TODO: query to get the user's address. expose that instead of user_id
|
2022-08-12 22:07:14 +03:00
|
|
|
let user_url = reg
|
|
|
|
.render_template(
|
|
|
|
&app.config.redirect_user_url,
|
|
|
|
&json!({ "user_id": user_id }),
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
// this is not a websocket. redirect to a page for this user
|
|
|
|
Redirect::to(&user_url).into_response()
|
2022-08-11 03:16:13 +03:00
|
|
|
}
|
|
|
|
}
|
2022-05-29 20:28:41 +03:00
|
|
|
}
|
|
|
|
|
2022-07-07 06:22:09 +03:00
|
|
|
async fn proxy_web3_socket(app: Arc<Web3ProxyApp>, socket: WebSocket) {
|
2022-05-29 20:28:41 +03:00
|
|
|
// split the websocket so we can read and write concurrently
|
|
|
|
let (ws_tx, ws_rx) = socket.split();
|
|
|
|
|
|
|
|
// create a channel for our reader and writer can communicate. todo: benchmark different channels
|
|
|
|
let (response_tx, response_rx) = flume::unbounded::<Message>();
|
|
|
|
|
|
|
|
tokio::spawn(write_web3_socket(response_rx, ws_tx));
|
|
|
|
tokio::spawn(read_web3_socket(app, ws_rx, response_tx));
|
|
|
|
}
|
|
|
|
|
2022-07-25 03:27:00 +03:00
|
|
|
/// websockets support a few more methods than http clients
|
2022-05-31 04:55:04 +03:00
|
|
|
async fn handle_socket_payload(
|
2022-06-14 10:13:42 +03:00
|
|
|
app: Arc<Web3ProxyApp>,
|
2022-05-31 04:55:04 +03:00
|
|
|
payload: &str,
|
2022-07-09 01:14:45 +03:00
|
|
|
response_sender: &flume::Sender<Message>,
|
|
|
|
subscription_count: &AtomicUsize,
|
2022-05-31 04:55:04 +03:00
|
|
|
subscriptions: &mut HashMap<String, AbortHandle>,
|
|
|
|
) -> Message {
|
2022-07-09 05:23:26 +03:00
|
|
|
// TODO: do any clients send batches over websockets?
|
2022-05-31 04:55:04 +03:00
|
|
|
let (id, response) = match serde_json::from_str::<JsonRpcRequest>(payload) {
|
|
|
|
Ok(payload) => {
|
|
|
|
let id = payload.id.clone();
|
|
|
|
|
2022-06-14 07:04:14 +03:00
|
|
|
let response: anyhow::Result<JsonRpcForwardedResponseEnum> = match &payload.method[..] {
|
|
|
|
"eth_subscribe" => {
|
2022-06-14 10:13:42 +03:00
|
|
|
let response = app
|
|
|
|
.clone()
|
2022-07-09 01:14:45 +03:00
|
|
|
.eth_subscribe(payload, subscription_count, response_sender.clone())
|
2022-06-14 10:13:42 +03:00
|
|
|
.await;
|
2022-05-31 04:55:04 +03:00
|
|
|
|
2022-06-14 07:04:14 +03:00
|
|
|
match response {
|
|
|
|
Ok((handle, response)) => {
|
|
|
|
// TODO: better key
|
|
|
|
subscriptions
|
|
|
|
.insert(response.result.as_ref().unwrap().to_string(), handle);
|
2022-05-31 04:55:04 +03:00
|
|
|
|
2022-06-14 07:04:14 +03:00
|
|
|
Ok(response.into())
|
|
|
|
}
|
|
|
|
Err(err) => Err(err),
|
2022-05-31 04:55:04 +03:00
|
|
|
}
|
|
|
|
}
|
2022-06-14 07:04:14 +03:00
|
|
|
"eth_unsubscribe" => {
|
|
|
|
let subscription_id = payload.params.unwrap().to_string();
|
2022-05-31 04:55:04 +03:00
|
|
|
|
2022-06-14 07:04:14 +03:00
|
|
|
let partial_response = match subscriptions.remove(&subscription_id) {
|
|
|
|
None => "false",
|
|
|
|
Some(handle) => {
|
|
|
|
handle.abort();
|
|
|
|
"true"
|
|
|
|
}
|
|
|
|
};
|
2022-05-31 04:55:04 +03:00
|
|
|
|
2022-07-22 22:30:39 +03:00
|
|
|
let response =
|
|
|
|
JsonRpcForwardedResponse::from_value(json!(partial_response), id.clone());
|
2022-05-31 04:55:04 +03:00
|
|
|
|
2022-06-14 07:04:14 +03:00
|
|
|
Ok(response.into())
|
|
|
|
}
|
|
|
|
_ => app.proxy_web3_rpc(payload.into()).await,
|
2022-05-31 04:55:04 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
(id, response)
|
|
|
|
}
|
|
|
|
Err(err) => {
|
2022-06-06 01:39:44 +03:00
|
|
|
let id = RawValue::from_string("null".to_string()).unwrap();
|
2022-05-31 04:55:04 +03:00
|
|
|
(id, Err(err.into()))
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
let response_str = match response {
|
|
|
|
Ok(x) => serde_json::to_string(&x),
|
|
|
|
Err(err) => {
|
|
|
|
// we have an anyhow error. turn it into
|
|
|
|
let response = JsonRpcForwardedResponse::from_anyhow_error(err, id);
|
|
|
|
serde_json::to_string(&response)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
Message::Text(response_str)
|
|
|
|
}
|
|
|
|
|
2022-05-29 20:28:41 +03:00
|
|
|
async fn read_web3_socket(
|
2022-07-07 06:22:09 +03:00
|
|
|
app: Arc<Web3ProxyApp>,
|
2022-05-29 20:28:41 +03:00
|
|
|
mut ws_rx: SplitStream<WebSocket>,
|
2022-07-09 01:14:45 +03:00
|
|
|
response_sender: flume::Sender<Message>,
|
2022-05-29 20:28:41 +03:00
|
|
|
) {
|
2022-05-29 22:33:10 +03:00
|
|
|
let mut subscriptions = HashMap::new();
|
2022-07-09 01:14:45 +03:00
|
|
|
let subscription_count = AtomicUsize::new(1);
|
2022-05-29 22:33:10 +03:00
|
|
|
|
2022-05-29 20:28:41 +03:00
|
|
|
while let Some(Ok(msg)) = ws_rx.next().await {
|
|
|
|
// new message from our client. forward to a backend and then send it through response_tx
|
|
|
|
let response_msg = match msg {
|
|
|
|
Message::Text(payload) => {
|
2022-07-09 01:14:45 +03:00
|
|
|
handle_socket_payload(
|
|
|
|
app.clone(),
|
|
|
|
&payload,
|
|
|
|
&response_sender,
|
|
|
|
&subscription_count,
|
|
|
|
&mut subscriptions,
|
|
|
|
)
|
|
|
|
.await
|
2022-05-29 20:28:41 +03:00
|
|
|
}
|
|
|
|
Message::Ping(x) => Message::Pong(x),
|
2022-05-31 04:55:04 +03:00
|
|
|
Message::Pong(x) => {
|
2022-07-07 06:22:09 +03:00
|
|
|
trace!("pong: {:?}", x);
|
2022-05-31 04:55:04 +03:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
Message::Close(_) => {
|
|
|
|
info!("closing websocket connection");
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
Message::Binary(mut payload) => {
|
2022-08-11 03:16:13 +03:00
|
|
|
// TODO: poke rate limit for the user/ip
|
2022-05-31 04:55:04 +03:00
|
|
|
let payload = from_utf8_mut(&mut payload).unwrap();
|
|
|
|
|
2022-07-09 01:14:45 +03:00
|
|
|
handle_socket_payload(
|
|
|
|
app.clone(),
|
|
|
|
payload,
|
|
|
|
&response_sender,
|
|
|
|
&subscription_count,
|
|
|
|
&mut subscriptions,
|
|
|
|
)
|
|
|
|
.await
|
2022-05-31 04:55:04 +03:00
|
|
|
}
|
2022-05-29 20:28:41 +03:00
|
|
|
};
|
|
|
|
|
2022-07-09 01:14:45 +03:00
|
|
|
match response_sender.send_async(response_msg).await {
|
2022-05-30 04:28:22 +03:00
|
|
|
Ok(_) => {}
|
|
|
|
Err(err) => {
|
|
|
|
error!("{}", err);
|
|
|
|
break;
|
|
|
|
}
|
2022-05-29 20:28:41 +03:00
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn write_web3_socket(
|
|
|
|
response_rx: flume::Receiver<Message>,
|
|
|
|
mut ws_tx: SplitSink<WebSocket, Message>,
|
|
|
|
) {
|
2022-07-09 01:14:45 +03:00
|
|
|
// TODO: increment counter for open websockets
|
|
|
|
|
2022-05-29 20:28:41 +03:00
|
|
|
while let Ok(msg) = response_rx.recv_async().await {
|
2022-08-11 03:16:13 +03:00
|
|
|
// a response is ready
|
|
|
|
|
|
|
|
// TODO: poke rate limits for this user?
|
|
|
|
|
|
|
|
// forward the response to through the websocket
|
2022-06-16 05:53:37 +03:00
|
|
|
if let Err(err) = ws_tx.send(msg).await {
|
2022-07-09 01:14:45 +03:00
|
|
|
// this isn't a problem. this is common and happens whenever a client disconnects
|
|
|
|
trace!(?err, "unable to write to websocket");
|
2022-05-29 20:28:41 +03:00
|
|
|
break;
|
|
|
|
};
|
|
|
|
}
|
2022-07-09 01:14:45 +03:00
|
|
|
|
|
|
|
// TODO: decrement counter for open websockets
|
2022-05-29 20:28:41 +03:00
|
|
|
}
|