2023-01-16 23:32:42 -08:00
|
|
|
use std::sync::{
|
|
|
|
atomic::{AtomicU32, Ordering},
|
|
|
|
Arc,
|
|
|
|
};
|
2023-01-16 23:05:24 -08:00
|
|
|
|
2023-01-16 23:32:42 -08:00
|
|
|
use log::info;
|
|
|
|
use solana_client::{
|
|
|
|
nonblocking::{rpc_client::RpcClient, tpu_client::TpuClient},
|
|
|
|
tpu_client::TpuClientConfig,
|
|
|
|
};
|
|
|
|
use tokio::sync::RwLock;
|
2023-01-16 23:05:24 -08:00
|
|
|
|
2023-01-16 23:32:42 -08:00
|
|
|
#[derive(Clone)]
|
2023-01-16 23:05:24 -08:00
|
|
|
pub struct TpuManager {
|
2023-01-16 23:32:42 -08:00
|
|
|
error_count: Arc<AtomicU32>,
|
|
|
|
rpc_client: Arc<RpcClient>,
|
|
|
|
tpu_client: Arc<RwLock<TpuClient>>,
|
2023-01-16 23:05:24 -08:00
|
|
|
ws_addr: String,
|
|
|
|
fanout_slots: u64,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TpuManager {
|
|
|
|
pub async fn new(
|
|
|
|
rpc_client: Arc<RpcClient>,
|
|
|
|
ws_addr: String,
|
|
|
|
fanout_slots: u64,
|
|
|
|
) -> anyhow::Result<Self> {
|
2023-01-16 23:32:42 -08:00
|
|
|
let tpu_client = Self::new_tpu_client(rpc_client.clone(), &ws_addr, fanout_slots).await?;
|
|
|
|
let tpu_client = Arc::new(RwLock::new(tpu_client));
|
2023-01-16 23:05:24 -08:00
|
|
|
|
|
|
|
Ok(Self {
|
2023-01-16 23:32:42 -08:00
|
|
|
rpc_client,
|
2023-01-16 23:05:24 -08:00
|
|
|
tpu_client,
|
|
|
|
ws_addr,
|
|
|
|
fanout_slots,
|
2023-01-16 23:32:42 -08:00
|
|
|
error_count: Default::default(),
|
2023-01-16 23:05:24 -08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-01-16 23:32:42 -08:00
|
|
|
pub async fn new_tpu_client(
|
|
|
|
rpc_client: Arc<RpcClient>,
|
|
|
|
ws_addr: &str,
|
|
|
|
fanout_slots: u64,
|
|
|
|
) -> anyhow::Result<TpuClient> {
|
|
|
|
Ok(TpuClient::new(
|
|
|
|
rpc_client.clone(),
|
|
|
|
ws_addr,
|
|
|
|
TpuClientConfig { fanout_slots },
|
|
|
|
)
|
|
|
|
.await?)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn reset(&self) -> anyhow::Result<()> {
|
|
|
|
self.error_count.fetch_add(1, Ordering::Relaxed);
|
|
|
|
|
|
|
|
if self.error_count.load(Ordering::Relaxed) > 5 {
|
|
|
|
let tpu_client =
|
|
|
|
Self::new_tpu_client(self.rpc_client.clone(), &self.ws_addr, self.fanout_slots)
|
|
|
|
.await?;
|
|
|
|
self.error_count.store(0, Ordering::Relaxed);
|
|
|
|
*self.tpu_client.write().await = tpu_client;
|
|
|
|
info!("TPU Reset after 5 errors");
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2023-01-16 23:05:24 -08:00
|
|
|
pub async fn try_send_wire_transaction_batch(
|
|
|
|
&self,
|
|
|
|
wire_transactions: Vec<Vec<u8>>,
|
|
|
|
) -> anyhow::Result<()> {
|
|
|
|
match self
|
|
|
|
.tpu_client
|
2023-01-16 23:32:42 -08:00
|
|
|
.read()
|
|
|
|
.await
|
2023-01-16 23:05:24 -08:00
|
|
|
.try_send_wire_transaction_batch(wire_transactions)
|
|
|
|
.await
|
|
|
|
{
|
2023-01-16 23:32:42 -08:00
|
|
|
Ok(_) => Ok(()),
|
2023-01-16 23:05:24 -08:00
|
|
|
Err(err) => {
|
2023-01-16 23:32:42 -08:00
|
|
|
self.reset().await?;
|
2023-01-16 23:05:24 -08:00
|
|
|
Err(err.into())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|