2025-07-19 23:46:42 +08:00
|
|
|
use crate::common::AnyResult;
|
2025-08-11 01:04:16 +08:00
|
|
|
use crate::streaming::common::{
|
2026-05-19 00:27:06 +08:00
|
|
|
parse_grpc_transaction_events, process_grpc_transaction, transaction_metrics_callback,
|
|
|
|
|
MetricsManager, MicroBatchBuffer, PerformanceMetrics, SlotBuffer, StreamClientConfig,
|
2025-10-12 17:20:50 +08:00
|
|
|
SubscriptionHandle,
|
2025-08-11 01:04:16 +08:00
|
|
|
};
|
2025-08-16 14:48:51 +08:00
|
|
|
use crate::streaming::event_parser::common::filter::EventTypeFilter;
|
2026-05-15 05:09:29 +08:00
|
|
|
use crate::streaming::event_parser::{DexEvent, Protocol};
|
2025-09-02 17:27:27 +08:00
|
|
|
use crate::streaming::grpc::pool::factory;
|
2026-05-19 00:27:06 +08:00
|
|
|
use crate::streaming::grpc::{EventPretty, SubscriptionManager, TransactionPretty};
|
2025-08-29 16:45:22 +08:00
|
|
|
use anyhow::anyhow;
|
|
|
|
|
use futures::channel::mpsc;
|
|
|
|
|
use futures::{SinkExt, StreamExt};
|
|
|
|
|
use log::error;
|
2026-05-19 00:27:06 +08:00
|
|
|
use sol_parser_sdk::grpc::OrderMode;
|
2025-08-29 16:45:22 +08:00
|
|
|
use solana_sdk::pubkey::Pubkey;
|
|
|
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
2025-10-10 18:19:44 +08:00
|
|
|
use std::sync::Arc;
|
2026-05-15 05:09:29 +08:00
|
|
|
use std::time::{SystemTime, UNIX_EPOCH};
|
2025-08-29 16:45:22 +08:00
|
|
|
use tokio::sync::Mutex;
|
2026-05-19 00:27:06 +08:00
|
|
|
use tokio::time::{Duration, Instant};
|
2025-08-29 16:45:22 +08:00
|
|
|
use yellowstone_grpc_proto::geyser::subscribe_update::UpdateOneof;
|
2025-09-10 23:21:08 +08:00
|
|
|
use yellowstone_grpc_proto::geyser::{
|
|
|
|
|
CommitmentLevel, SubscribeRequest, SubscribeRequestFilterAccountsFilter, SubscribeRequestPing,
|
|
|
|
|
};
|
2025-07-19 23:46:42 +08:00
|
|
|
|
2025-08-13 23:30:59 +08:00
|
|
|
/// 交易过滤器
|
2025-08-25 17:09:14 -07:00
|
|
|
#[derive(Debug, Clone)]
|
2025-08-13 23:30:59 +08:00
|
|
|
pub struct TransactionFilter {
|
|
|
|
|
pub account_include: Vec<String>,
|
|
|
|
|
pub account_exclude: Vec<String>,
|
|
|
|
|
pub account_required: Vec<String>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// 账户过滤器
|
2025-08-25 17:09:14 -07:00
|
|
|
#[derive(Debug, Clone)]
|
2025-08-13 23:30:59 +08:00
|
|
|
pub struct AccountFilter {
|
|
|
|
|
pub account: Vec<String>,
|
|
|
|
|
pub owner: Vec<String>,
|
2025-09-10 23:21:08 +08:00
|
|
|
pub filters: Vec<SubscribeRequestFilterAccountsFilter>,
|
2025-08-13 23:30:59 +08:00
|
|
|
}
|
|
|
|
|
|
2025-07-19 23:46:42 +08:00
|
|
|
pub struct YellowstoneGrpc {
|
2025-08-11 01:04:16 +08:00
|
|
|
pub endpoint: String,
|
|
|
|
|
pub x_token: Option<String>,
|
|
|
|
|
pub config: StreamClientConfig,
|
|
|
|
|
pub subscription_manager: SubscriptionManager,
|
2025-08-21 15:47:31 +08:00
|
|
|
pub subscription_handle: Arc<Mutex<Option<SubscriptionHandle>>>,
|
2025-08-25 17:09:14 -07:00
|
|
|
// Dynamic subscription management fields
|
|
|
|
|
pub active_subscription: Arc<AtomicBool>,
|
2025-08-29 16:45:22 +08:00
|
|
|
pub control_tx: Arc<tokio::sync::Mutex<Option<mpsc::Sender<SubscribeRequest>>>>,
|
|
|
|
|
pub current_request: Arc<tokio::sync::RwLock<Option<SubscribeRequest>>>,
|
2025-09-10 23:21:08 +08:00
|
|
|
|
|
|
|
|
pub event_type_filter: Arc<tokio::sync::RwLock<Option<EventTypeFilter>>>,
|
2025-07-19 23:46:42 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl YellowstoneGrpc {
|
2025-08-04 21:30:55 +08:00
|
|
|
/// 创建客户端,使用默认配置
|
2025-07-19 23:46:42 +08:00
|
|
|
pub fn new(endpoint: String, x_token: Option<String>) -> AnyResult<Self> {
|
2025-08-11 01:04:16 +08:00
|
|
|
Self::new_with_config(endpoint, x_token, StreamClientConfig::default())
|
2025-08-03 05:37:04 +08:00
|
|
|
}
|
|
|
|
|
|
2025-08-04 21:30:55 +08:00
|
|
|
/// 创建客户端,使用自定义配置
|
2025-08-11 01:04:16 +08:00
|
|
|
pub fn new_with_config(
|
|
|
|
|
endpoint: String,
|
|
|
|
|
x_token: Option<String>,
|
|
|
|
|
config: StreamClientConfig,
|
|
|
|
|
) -> AnyResult<Self> {
|
2026-06-01 20:20:01 +08:00
|
|
|
sol_parser_sdk::warmup_parser();
|
2025-08-12 11:34:26 +08:00
|
|
|
let _ = rustls::crypto::ring::default_provider().install_default().ok();
|
2025-08-11 01:04:16 +08:00
|
|
|
let subscription_manager =
|
|
|
|
|
SubscriptionManager::new(endpoint.clone(), x_token.clone(), config.clone());
|
2025-10-10 18:19:44 +08:00
|
|
|
MetricsManager::init(config.enable_metrics);
|
2025-08-11 01:04:16 +08:00
|
|
|
|
|
|
|
|
Ok(Self {
|
|
|
|
|
endpoint,
|
2025-08-03 05:37:04 +08:00
|
|
|
x_token,
|
2025-08-04 21:30:55 +08:00
|
|
|
config,
|
2025-08-11 01:04:16 +08:00
|
|
|
subscription_manager,
|
2025-08-21 15:47:31 +08:00
|
|
|
subscription_handle: Arc::new(Mutex::new(None)),
|
2025-08-25 17:09:14 -07:00
|
|
|
active_subscription: Arc::new(AtomicBool::new(false)),
|
2025-08-29 16:45:22 +08:00
|
|
|
control_tx: Arc::new(tokio::sync::Mutex::new(None)),
|
|
|
|
|
current_request: Arc::new(tokio::sync::RwLock::new(None)),
|
2025-09-10 23:21:08 +08:00
|
|
|
event_type_filter: Arc::new(tokio::sync::RwLock::new(None)),
|
2025-08-03 05:37:04 +08:00
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-11 01:04:16 +08:00
|
|
|
/// 获取配置
|
|
|
|
|
pub fn get_config(&self) -> &StreamClientConfig {
|
2025-08-04 21:30:55 +08:00
|
|
|
&self.config
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// 更新配置
|
2025-08-11 01:04:16 +08:00
|
|
|
pub fn update_config(&mut self, config: StreamClientConfig) {
|
2025-08-04 21:30:55 +08:00
|
|
|
self.config = config;
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-03 05:37:04 +08:00
|
|
|
/// 获取性能指标
|
2025-08-26 17:57:39 +08:00
|
|
|
pub fn get_metrics(&self) -> PerformanceMetrics {
|
2025-10-10 18:19:44 +08:00
|
|
|
MetricsManager::global().get_metrics()
|
2025-08-11 01:04:16 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// 打印性能指标
|
2025-08-26 17:57:39 +08:00
|
|
|
pub fn print_metrics(&self) {
|
2025-10-10 18:19:44 +08:00
|
|
|
MetricsManager::global().print_metrics();
|
2025-08-03 05:37:04 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// 启用或禁用性能监控
|
|
|
|
|
pub fn set_enable_metrics(&mut self, enabled: bool) {
|
2025-08-04 21:30:55 +08:00
|
|
|
self.config.enable_metrics = enabled;
|
2025-08-03 05:37:04 +08:00
|
|
|
}
|
|
|
|
|
|
2025-08-21 15:47:31 +08:00
|
|
|
/// 停止当前订阅
|
|
|
|
|
pub async fn stop(&self) {
|
|
|
|
|
let mut handle_guard = self.subscription_handle.lock().await;
|
|
|
|
|
if let Some(handle) = handle_guard.take() {
|
|
|
|
|
handle.stop();
|
|
|
|
|
}
|
2025-08-25 17:09:14 -07:00
|
|
|
*self.control_tx.lock().await = None;
|
|
|
|
|
*self.current_request.write().await = None;
|
|
|
|
|
self.active_subscription.store(false, Ordering::Release);
|
2025-08-21 15:47:31 +08:00
|
|
|
}
|
|
|
|
|
|
2025-08-16 14:48:51 +08:00
|
|
|
/// Simplified immediate event subscription (recommended for simple scenarios)
|
|
|
|
|
///
|
|
|
|
|
/// # Parameters
|
|
|
|
|
/// * `protocols` - List of protocols to monitor
|
|
|
|
|
/// * `bot_wallet` - Optional bot wallet address for filtering related transactions
|
|
|
|
|
/// * `transaction_filter` - Transaction filter specifying accounts to include/exclude
|
|
|
|
|
/// * `account_filter` - Account filter specifying accounts and owners to monitor
|
|
|
|
|
/// * `event_filter` - Optional event filter for further event filtering, no filtering if None
|
|
|
|
|
/// * `commitment` - Optional commitment level, defaults to Confirmed
|
|
|
|
|
/// * `callback` - Event callback function that receives parsed unified events
|
|
|
|
|
///
|
|
|
|
|
/// # Returns
|
|
|
|
|
/// Returns `AnyResult<()>`, `Ok(())` on success, error information on failure
|
2026-06-01 20:20:01 +08:00
|
|
|
#[allow(clippy::too_many_arguments)]
|
2025-08-04 21:30:55 +08:00
|
|
|
pub async fn subscribe_events_immediate<F>(
|
|
|
|
|
&self,
|
|
|
|
|
protocols: Vec<Protocol>,
|
|
|
|
|
bot_wallet: Option<Pubkey>,
|
2025-09-10 23:21:08 +08:00
|
|
|
transaction_filter: Vec<TransactionFilter>,
|
|
|
|
|
account_filter: Vec<AccountFilter>,
|
2025-08-16 14:48:51 +08:00
|
|
|
event_type_filter: Option<EventTypeFilter>,
|
2025-08-04 21:30:55 +08:00
|
|
|
commitment: Option<CommitmentLevel>,
|
|
|
|
|
callback: F,
|
|
|
|
|
) -> AnyResult<()>
|
|
|
|
|
where
|
2025-10-12 22:00:15 +08:00
|
|
|
F: Fn(DexEvent) + Send + Sync + 'static,
|
2025-08-04 21:30:55 +08:00
|
|
|
{
|
2025-09-10 23:21:08 +08:00
|
|
|
*self.event_type_filter.write().await = event_type_filter.clone();
|
2025-08-29 16:45:22 +08:00
|
|
|
if self
|
|
|
|
|
.active_subscription
|
|
|
|
|
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
|
|
|
|
|
.is_err()
|
|
|
|
|
{
|
2025-08-25 17:09:14 -07:00
|
|
|
return Err(anyhow!("Already subscribed. Use update_subscription() to modify filters"));
|
|
|
|
|
}
|
2025-08-21 15:47:31 +08:00
|
|
|
|
2026-05-25 00:41:25 +08:00
|
|
|
let mut start_guard = SubscriptionStartGuard::new(self.active_subscription.clone());
|
2025-08-04 21:30:55 +08:00
|
|
|
// 启动自动性能监控(如果启用)
|
|
|
|
|
if self.config.enable_metrics {
|
2026-05-25 00:41:25 +08:00
|
|
|
start_guard.set_metrics_handle(MetricsManager::global().start_auto_monitoring().await);
|
2025-08-04 21:30:55 +08:00
|
|
|
}
|
|
|
|
|
|
2025-09-10 23:21:08 +08:00
|
|
|
let transactions = self
|
|
|
|
|
.subscription_manager
|
|
|
|
|
.get_subscribe_request_filter(transaction_filter, event_type_filter.as_ref());
|
|
|
|
|
let accounts = self
|
|
|
|
|
.subscription_manager
|
|
|
|
|
.subscribe_with_account_request(account_filter, event_type_filter.as_ref());
|
2025-08-11 01:04:16 +08:00
|
|
|
|
2025-08-04 21:30:55 +08:00
|
|
|
// 订阅事件
|
2025-10-04 08:44:07 +08:00
|
|
|
let (subscribe_tx, mut stream, subscribe_request) = self
|
2025-08-13 23:30:59 +08:00
|
|
|
.subscription_manager
|
2025-08-31 22:18:18 +08:00
|
|
|
.subscribe_with_request(transactions, accounts, commitment, event_type_filter.as_ref())
|
2025-08-13 23:30:59 +08:00
|
|
|
.await?;
|
2025-08-04 21:30:55 +08:00
|
|
|
|
2025-08-29 14:59:16 +08:00
|
|
|
// 用 Arc<Mutex<>> 包装 subscribe_tx 以支持多线程共享
|
|
|
|
|
let subscribe_tx = Arc::new(Mutex::new(subscribe_tx));
|
2025-08-25 17:09:14 -07:00
|
|
|
*self.current_request.write().await = Some(subscribe_request);
|
|
|
|
|
let (control_tx, mut control_rx) = mpsc::channel(100);
|
|
|
|
|
*self.control_tx.lock().await = Some(control_tx);
|
2025-08-29 14:59:16 +08:00
|
|
|
|
2025-10-12 17:20:50 +08:00
|
|
|
// Wrap callback once before the async block
|
|
|
|
|
let callback = Arc::new(callback);
|
2026-05-19 00:27:06 +08:00
|
|
|
let transaction_callback = transaction_metrics_callback(callback.clone());
|
|
|
|
|
let order_mode = self.config.order_mode;
|
|
|
|
|
let order_timeout_ms = self.config.order_timeout_ms;
|
|
|
|
|
let micro_batch_us = self.config.micro_batch_us;
|
2025-10-12 17:20:50 +08:00
|
|
|
|
2026-05-19 04:26:51 -07:00
|
|
|
let active_subscription = self.active_subscription.clone();
|
2026-05-25 00:41:25 +08:00
|
|
|
let control_tx_cleanup = self.control_tx.clone();
|
|
|
|
|
let current_request_cleanup = self.current_request.clone();
|
|
|
|
|
let metrics_handle = start_guard.disarm();
|
2025-08-21 15:47:31 +08:00
|
|
|
let stream_handle = tokio::spawn(async move {
|
2026-05-25 00:41:25 +08:00
|
|
|
let cleanup = SubscriptionCleanupGuard::new(
|
|
|
|
|
active_subscription,
|
|
|
|
|
control_tx_cleanup,
|
|
|
|
|
current_request_cleanup,
|
|
|
|
|
metrics_handle,
|
|
|
|
|
);
|
2026-05-19 00:27:06 +08:00
|
|
|
let mut slot_buffer = SlotBuffer::new();
|
|
|
|
|
let mut micro_batch = MicroBatchBuffer::new();
|
|
|
|
|
let mut last_slot = 0u64;
|
|
|
|
|
let check_interval = match order_mode {
|
|
|
|
|
OrderMode::MicroBatch => Duration::from_micros(micro_batch_us.max(1)),
|
|
|
|
|
_ => Duration::from_millis((order_timeout_ms / 2).max(1)),
|
|
|
|
|
};
|
|
|
|
|
let mut next_check = Instant::now() + check_interval;
|
|
|
|
|
|
2025-08-25 17:09:14 -07:00
|
|
|
loop {
|
2026-05-19 00:27:06 +08:00
|
|
|
if has_buffered_events(order_mode, &slot_buffer, µ_batch) {
|
|
|
|
|
flush_ordered_timeouts(
|
|
|
|
|
order_mode,
|
|
|
|
|
&mut slot_buffer,
|
|
|
|
|
&mut micro_batch,
|
|
|
|
|
transaction_callback.clone(),
|
|
|
|
|
order_timeout_ms,
|
|
|
|
|
micro_batch_us,
|
|
|
|
|
&mut next_check,
|
|
|
|
|
check_interval,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-25 17:09:14 -07:00
|
|
|
tokio::select! {
|
|
|
|
|
message = stream.next() => {
|
|
|
|
|
match message {
|
|
|
|
|
Some(Ok(msg)) => {
|
2025-08-31 22:18:18 +08:00
|
|
|
let created_at = msg.created_at;
|
|
|
|
|
match msg.update_oneof {
|
|
|
|
|
Some(UpdateOneof::Account(account)) => {
|
2026-05-19 04:26:51 -07:00
|
|
|
let Some(account_pretty) =
|
2026-05-25 00:41:25 +08:00
|
|
|
factory::try_create_account_pretty_pooled(account)
|
2026-05-19 04:26:51 -07:00
|
|
|
else {
|
|
|
|
|
continue;
|
|
|
|
|
};
|
2025-08-31 22:18:18 +08:00
|
|
|
log::debug!("Received account: {:?}", account_pretty);
|
2025-10-12 17:20:50 +08:00
|
|
|
if let Err(e) = process_grpc_transaction(
|
|
|
|
|
EventPretty::Account(account_pretty),
|
|
|
|
|
&protocols,
|
|
|
|
|
event_type_filter.as_ref(),
|
|
|
|
|
callback.clone(),
|
|
|
|
|
bot_wallet,
|
|
|
|
|
)
|
|
|
|
|
.await
|
2025-08-31 22:18:18 +08:00
|
|
|
{
|
|
|
|
|
error!("Error processing account event: {e:?}");
|
2025-08-29 16:45:22 +08:00
|
|
|
}
|
2025-08-29 14:59:16 +08:00
|
|
|
}
|
2025-08-31 22:18:18 +08:00
|
|
|
Some(UpdateOneof::BlockMeta(sut)) => {
|
2025-09-02 17:27:27 +08:00
|
|
|
let block_meta_pretty = factory::create_block_meta_pretty_pooled(sut, created_at);
|
2025-08-31 22:18:18 +08:00
|
|
|
log::debug!("Received block meta: {:?}", block_meta_pretty);
|
2025-10-12 17:20:50 +08:00
|
|
|
if let Err(e) = process_grpc_transaction(
|
|
|
|
|
EventPretty::BlockMeta(block_meta_pretty),
|
|
|
|
|
&protocols,
|
|
|
|
|
event_type_filter.as_ref(),
|
|
|
|
|
callback.clone(),
|
|
|
|
|
bot_wallet,
|
|
|
|
|
)
|
|
|
|
|
.await
|
2025-08-31 22:18:18 +08:00
|
|
|
{
|
|
|
|
|
error!("Error processing block meta event: {e:?}");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Some(UpdateOneof::Transaction(sut)) => {
|
2026-05-19 04:26:51 -07:00
|
|
|
let Some(transaction_pretty) =
|
2026-05-25 00:41:25 +08:00
|
|
|
factory::try_create_transaction_pretty_pooled(sut, created_at)
|
2026-05-19 04:26:51 -07:00
|
|
|
else {
|
|
|
|
|
continue;
|
|
|
|
|
};
|
2025-08-31 22:18:18 +08:00
|
|
|
log::debug!(
|
|
|
|
|
"Received transaction: {} at slot {}",
|
|
|
|
|
transaction_pretty.signature,
|
|
|
|
|
transaction_pretty.slot
|
|
|
|
|
);
|
2026-05-19 00:27:06 +08:00
|
|
|
handle_ordered_transaction(
|
|
|
|
|
transaction_pretty,
|
2025-10-12 17:20:50 +08:00
|
|
|
&protocols,
|
|
|
|
|
event_type_filter.as_ref(),
|
2026-05-19 00:27:06 +08:00
|
|
|
transaction_callback.clone(),
|
2025-10-12 17:20:50 +08:00
|
|
|
bot_wallet,
|
2026-05-19 00:27:06 +08:00
|
|
|
order_mode,
|
|
|
|
|
&mut slot_buffer,
|
|
|
|
|
&mut micro_batch,
|
|
|
|
|
&mut last_slot,
|
|
|
|
|
micro_batch_us,
|
|
|
|
|
);
|
2025-08-31 22:18:18 +08:00
|
|
|
}
|
|
|
|
|
Some(UpdateOneof::Ping(_)) => {
|
|
|
|
|
// 只在需要时获取锁,并立即释放
|
|
|
|
|
if let Ok(mut tx_guard) = subscribe_tx.try_lock() {
|
|
|
|
|
let _ = tx_guard
|
|
|
|
|
.send(SubscribeRequest {
|
|
|
|
|
ping: Some(SubscribeRequestPing { id: 1 }),
|
|
|
|
|
..Default::default()
|
|
|
|
|
})
|
|
|
|
|
.await;
|
|
|
|
|
}
|
2026-03-07 06:44:42 +00:00
|
|
|
let ts = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
|
|
|
|
|
log::debug!("service is ping: {}", ts);
|
2025-08-31 22:18:18 +08:00
|
|
|
}
|
|
|
|
|
Some(UpdateOneof::Pong(_)) => {
|
2026-03-07 06:44:42 +00:00
|
|
|
let ts = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
|
|
|
|
|
log::debug!("service is pong: {}", ts);
|
2025-08-31 22:18:18 +08:00
|
|
|
}
|
|
|
|
|
_ => {
|
|
|
|
|
log::debug!("Received other message type");
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-08-29 14:59:16 +08:00
|
|
|
}
|
2025-08-25 17:09:14 -07:00
|
|
|
Some(Err(error)) => {
|
|
|
|
|
error!("Stream error: {error:?}");
|
2026-05-19 00:27:06 +08:00
|
|
|
flush_ordered_on_disconnect(
|
|
|
|
|
order_mode,
|
|
|
|
|
&mut slot_buffer,
|
|
|
|
|
&mut micro_batch,
|
|
|
|
|
transaction_callback.clone(),
|
|
|
|
|
);
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
None => {
|
|
|
|
|
flush_ordered_on_disconnect(
|
|
|
|
|
order_mode,
|
|
|
|
|
&mut slot_buffer,
|
|
|
|
|
&mut micro_batch,
|
|
|
|
|
transaction_callback.clone(),
|
|
|
|
|
);
|
2025-08-25 17:09:14 -07:00
|
|
|
break;
|
|
|
|
|
}
|
2025-08-04 21:30:55 +08:00
|
|
|
}
|
|
|
|
|
}
|
2025-08-25 17:09:14 -07:00
|
|
|
Some(update) = control_rx.next() => {
|
2025-08-29 16:45:22 +08:00
|
|
|
if let Err(e) = subscribe_tx.lock().await.send(update).await {
|
2025-08-25 17:09:14 -07:00
|
|
|
error!("Failed to send subscription update: {}", e);
|
2026-05-19 00:27:06 +08:00
|
|
|
flush_ordered_on_disconnect(
|
|
|
|
|
order_mode,
|
|
|
|
|
&mut slot_buffer,
|
|
|
|
|
&mut micro_batch,
|
|
|
|
|
transaction_callback.clone(),
|
|
|
|
|
);
|
2025-08-25 17:09:14 -07:00
|
|
|
break;
|
|
|
|
|
}
|
2025-08-04 21:30:55 +08:00
|
|
|
}
|
2026-05-19 00:27:06 +08:00
|
|
|
_ = tokio::time::sleep_until(next_check), if has_buffered_events(order_mode, &slot_buffer, µ_batch) => {
|
|
|
|
|
flush_ordered_timeouts(
|
|
|
|
|
order_mode,
|
|
|
|
|
&mut slot_buffer,
|
|
|
|
|
&mut micro_batch,
|
|
|
|
|
transaction_callback.clone(),
|
|
|
|
|
order_timeout_ms,
|
|
|
|
|
micro_batch_us,
|
|
|
|
|
&mut next_check,
|
|
|
|
|
check_interval,
|
|
|
|
|
);
|
|
|
|
|
}
|
2025-08-04 21:30:55 +08:00
|
|
|
}
|
|
|
|
|
}
|
2026-05-25 00:41:25 +08:00
|
|
|
cleanup.finish().await;
|
2025-08-04 21:30:55 +08:00
|
|
|
});
|
|
|
|
|
|
2025-08-21 15:47:31 +08:00
|
|
|
// 保存订阅句柄
|
2026-05-25 00:41:25 +08:00
|
|
|
let subscription_handle = SubscriptionHandle::new(stream_handle, None, None);
|
2025-08-21 15:47:31 +08:00
|
|
|
let mut handle_guard = self.subscription_handle.lock().await;
|
|
|
|
|
*handle_guard = Some(subscription_handle);
|
|
|
|
|
|
2025-07-26 17:11:28 +08:00
|
|
|
Ok(())
|
|
|
|
|
}
|
2025-08-25 17:09:14 -07:00
|
|
|
|
|
|
|
|
/// Update subscription filters at runtime without reconnection
|
|
|
|
|
///
|
|
|
|
|
/// # Parameters
|
|
|
|
|
/// * `transaction_filter` - New transaction filter to apply
|
|
|
|
|
/// * `account_filter` - New account filter to apply
|
|
|
|
|
///
|
|
|
|
|
/// # Returns
|
|
|
|
|
/// Returns `AnyResult<()>` on success, error on failure
|
|
|
|
|
pub async fn update_subscription(
|
|
|
|
|
&self,
|
2025-09-10 23:21:08 +08:00
|
|
|
transaction_filter: Vec<TransactionFilter>,
|
|
|
|
|
account_filter: Vec<AccountFilter>,
|
2025-08-25 17:09:14 -07:00
|
|
|
) -> AnyResult<()> {
|
|
|
|
|
let mut control_sender = {
|
|
|
|
|
let control_guard = self.control_tx.lock().await;
|
2025-08-29 16:45:22 +08:00
|
|
|
|
2025-08-25 17:09:14 -07:00
|
|
|
if !self.active_subscription.load(Ordering::Acquire) {
|
|
|
|
|
return Err(anyhow!("No active subscription to update"));
|
|
|
|
|
}
|
2025-08-29 16:45:22 +08:00
|
|
|
|
|
|
|
|
control_guard
|
|
|
|
|
.as_ref()
|
2025-08-25 17:09:14 -07:00
|
|
|
.ok_or_else(|| anyhow!("No active subscription to update"))?
|
|
|
|
|
.clone()
|
|
|
|
|
};
|
2025-08-29 16:45:22 +08:00
|
|
|
|
|
|
|
|
let mut request = self
|
|
|
|
|
.current_request
|
|
|
|
|
.read()
|
|
|
|
|
.await
|
2025-08-25 17:09:14 -07:00
|
|
|
.as_ref()
|
|
|
|
|
.ok_or_else(|| anyhow!("No active subscription"))?
|
|
|
|
|
.clone();
|
2025-08-29 16:45:22 +08:00
|
|
|
|
|
|
|
|
request.transactions = self
|
|
|
|
|
.subscription_manager
|
2025-08-25 17:09:14 -07:00
|
|
|
.get_subscribe_request_filter(
|
2025-09-10 23:21:08 +08:00
|
|
|
transaction_filter,
|
|
|
|
|
self.event_type_filter.read().await.as_ref(),
|
2025-08-25 17:09:14 -07:00
|
|
|
)
|
|
|
|
|
.unwrap_or_default();
|
2025-08-29 16:45:22 +08:00
|
|
|
|
|
|
|
|
request.accounts = self
|
|
|
|
|
.subscription_manager
|
2025-09-10 23:21:08 +08:00
|
|
|
.subscribe_with_account_request(
|
|
|
|
|
account_filter,
|
|
|
|
|
self.event_type_filter.read().await.as_ref(),
|
|
|
|
|
)
|
2025-08-25 17:09:14 -07:00
|
|
|
.unwrap_or_default();
|
2025-08-29 16:45:22 +08:00
|
|
|
|
|
|
|
|
control_sender
|
|
|
|
|
.send(request.clone())
|
|
|
|
|
.await
|
2025-08-25 17:09:14 -07:00
|
|
|
.map_err(|e| anyhow!("Failed to send update: {}", e))?;
|
2025-08-29 16:45:22 +08:00
|
|
|
|
2025-08-25 17:09:14 -07:00
|
|
|
*self.current_request.write().await = Some(request);
|
2025-08-29 16:45:22 +08:00
|
|
|
|
2025-08-25 17:09:14 -07:00
|
|
|
Ok(())
|
|
|
|
|
}
|
2025-07-19 23:46:42 +08:00
|
|
|
}
|
2025-08-03 05:37:04 +08:00
|
|
|
|
2026-05-19 00:27:06 +08:00
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
|
|
|
fn handle_ordered_transaction(
|
|
|
|
|
transaction_pretty: TransactionPretty,
|
|
|
|
|
protocols: &[Protocol],
|
|
|
|
|
event_type_filter: Option<&EventTypeFilter>,
|
|
|
|
|
callback: Arc<dyn Fn(DexEvent) + Send + Sync>,
|
|
|
|
|
bot_wallet: Option<Pubkey>,
|
|
|
|
|
order_mode: OrderMode,
|
|
|
|
|
slot_buffer: &mut SlotBuffer,
|
|
|
|
|
micro_batch: &mut MicroBatchBuffer,
|
|
|
|
|
last_slot: &mut u64,
|
|
|
|
|
micro_batch_us: u64,
|
|
|
|
|
) {
|
|
|
|
|
let fallback_slot = transaction_pretty.slot;
|
|
|
|
|
let fallback_tx_index = transaction_pretty.tx_index.unwrap_or(0);
|
|
|
|
|
let recv_us = transaction_pretty.recv_us;
|
|
|
|
|
let events =
|
|
|
|
|
parse_grpc_transaction_events(transaction_pretty, protocols, event_type_filter, bot_wallet);
|
|
|
|
|
|
|
|
|
|
match order_mode {
|
|
|
|
|
OrderMode::Unordered => {
|
|
|
|
|
for event in events {
|
|
|
|
|
callback(event);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
OrderMode::Ordered => {
|
|
|
|
|
if fallback_slot > *last_slot && *last_slot > 0 {
|
|
|
|
|
deliver_events(callback.clone(), slot_buffer.flush_before(fallback_slot));
|
|
|
|
|
}
|
|
|
|
|
*last_slot = fallback_slot;
|
|
|
|
|
for event in events {
|
|
|
|
|
let (slot, tx_index) = event_order_key(&event, fallback_slot, fallback_tx_index);
|
|
|
|
|
slot_buffer.push(slot, tx_index, event);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
OrderMode::StreamingOrdered => {
|
2026-06-16 00:28:15 +09:00
|
|
|
// Events parsed from one transaction share its (slot, tx_index); push them as a
|
|
|
|
|
// single group so the streaming watermark advances per transaction and no event of
|
|
|
|
|
// a multi-event transaction is dropped.
|
|
|
|
|
for ((slot, tx_index), group) in
|
|
|
|
|
group_events_by_order_key(events, fallback_slot, fallback_tx_index)
|
|
|
|
|
{
|
|
|
|
|
deliver_events(callback.clone(), slot_buffer.push_streaming(slot, tx_index, group));
|
2026-05-19 00:27:06 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
OrderMode::MicroBatch => {
|
|
|
|
|
for event in events {
|
|
|
|
|
let (slot, tx_index) = event_order_key(&event, fallback_slot, fallback_tx_index);
|
|
|
|
|
if micro_batch.push(slot, tx_index, event, recv_us, micro_batch_us) {
|
|
|
|
|
deliver_events(callback.clone(), micro_batch.flush());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
|
|
|
fn flush_ordered_timeouts(
|
|
|
|
|
order_mode: OrderMode,
|
|
|
|
|
slot_buffer: &mut SlotBuffer,
|
|
|
|
|
micro_batch: &mut MicroBatchBuffer,
|
|
|
|
|
callback: Arc<dyn Fn(DexEvent) + Send + Sync>,
|
|
|
|
|
order_timeout_ms: u64,
|
|
|
|
|
micro_batch_us: u64,
|
|
|
|
|
next_check: &mut Instant,
|
|
|
|
|
check_interval: Duration,
|
|
|
|
|
) {
|
|
|
|
|
if Instant::now() < *next_check {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
*next_check = Instant::now() + check_interval;
|
|
|
|
|
|
|
|
|
|
match order_mode {
|
|
|
|
|
OrderMode::Ordered => {
|
|
|
|
|
if slot_buffer.should_timeout(order_timeout_ms) {
|
|
|
|
|
deliver_events(callback, slot_buffer.flush_all());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
OrderMode::StreamingOrdered => {
|
|
|
|
|
if slot_buffer.should_timeout(order_timeout_ms) {
|
|
|
|
|
deliver_events(callback, slot_buffer.flush_streaming_timeout());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
OrderMode::MicroBatch => {
|
|
|
|
|
let now_us =
|
|
|
|
|
crate::streaming::event_parser::common::high_performance_clock::get_high_perf_clock(
|
|
|
|
|
);
|
|
|
|
|
if micro_batch.should_flush(now_us, micro_batch_us) {
|
|
|
|
|
deliver_events(callback, micro_batch.flush());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
OrderMode::Unordered => {}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn flush_ordered_on_disconnect(
|
|
|
|
|
order_mode: OrderMode,
|
|
|
|
|
slot_buffer: &mut SlotBuffer,
|
|
|
|
|
micro_batch: &mut MicroBatchBuffer,
|
|
|
|
|
callback: Arc<dyn Fn(DexEvent) + Send + Sync>,
|
|
|
|
|
) {
|
|
|
|
|
match order_mode {
|
|
|
|
|
OrderMode::Ordered => deliver_events(callback, slot_buffer.flush_all()),
|
|
|
|
|
OrderMode::StreamingOrdered => {
|
|
|
|
|
deliver_events(callback, slot_buffer.flush_streaming_timeout())
|
|
|
|
|
}
|
|
|
|
|
OrderMode::MicroBatch => deliver_events(callback, micro_batch.flush()),
|
|
|
|
|
OrderMode::Unordered => {}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
|
fn event_order_key(event: &DexEvent, fallback_slot: u64, fallback_tx_index: u64) -> (u64, u64) {
|
|
|
|
|
let metadata = event.metadata();
|
|
|
|
|
(metadata.slot.max(fallback_slot), metadata.tx_index.unwrap_or(fallback_tx_index))
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-16 00:28:15 +09:00
|
|
|
/// Group consecutive events that share the same `(slot, tx_index)` order key, preserving order.
|
|
|
|
|
/// Events of a single transaction carry the same key, so this normally yields one group, but it
|
|
|
|
|
/// stays correct if a transaction ever spans multiple keys.
|
|
|
|
|
fn group_events_by_order_key(
|
|
|
|
|
events: Vec<DexEvent>,
|
|
|
|
|
fallback_slot: u64,
|
|
|
|
|
fallback_tx_index: u64,
|
|
|
|
|
) -> Vec<((u64, u64), Vec<DexEvent>)> {
|
|
|
|
|
let mut groups: Vec<((u64, u64), Vec<DexEvent>)> = Vec::new();
|
|
|
|
|
for event in events {
|
|
|
|
|
let key = event_order_key(&event, fallback_slot, fallback_tx_index);
|
|
|
|
|
match groups.last_mut() {
|
|
|
|
|
Some((last_key, group)) if *last_key == key => group.push(event),
|
|
|
|
|
_ => groups.push((key, vec![event])),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
groups
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-19 00:27:06 +08:00
|
|
|
#[inline]
|
|
|
|
|
fn deliver_events(callback: Arc<dyn Fn(DexEvent) + Send + Sync>, events: Vec<DexEvent>) {
|
|
|
|
|
for event in events {
|
|
|
|
|
callback(event);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
|
fn has_buffered_events(
|
|
|
|
|
order_mode: OrderMode,
|
|
|
|
|
slot_buffer: &SlotBuffer,
|
|
|
|
|
micro_batch: &MicroBatchBuffer,
|
|
|
|
|
) -> bool {
|
|
|
|
|
match order_mode {
|
|
|
|
|
OrderMode::Ordered | OrderMode::StreamingOrdered => !slot_buffer.is_empty(),
|
|
|
|
|
OrderMode::MicroBatch => !micro_batch.is_empty(),
|
|
|
|
|
OrderMode::Unordered => false,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-25 00:41:25 +08:00
|
|
|
struct SubscriptionStartGuard {
|
|
|
|
|
active_subscription: Arc<AtomicBool>,
|
|
|
|
|
metrics_handle: Option<tokio::task::JoinHandle<()>>,
|
|
|
|
|
disarmed: bool,
|
|
|
|
|
}
|
2026-05-19 04:26:51 -07:00
|
|
|
|
2026-05-25 00:41:25 +08:00
|
|
|
impl SubscriptionStartGuard {
|
|
|
|
|
fn new(active_subscription: Arc<AtomicBool>) -> Self {
|
|
|
|
|
Self { active_subscription, metrics_handle: None, disarmed: false }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn set_metrics_handle(&mut self, metrics_handle: Option<tokio::task::JoinHandle<()>>) {
|
|
|
|
|
self.metrics_handle = metrics_handle;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn disarm(&mut self) -> Option<tokio::task::JoinHandle<()>> {
|
|
|
|
|
self.disarmed = true;
|
|
|
|
|
self.metrics_handle.take()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Drop for SubscriptionStartGuard {
|
2026-05-19 04:26:51 -07:00
|
|
|
fn drop(&mut self) {
|
2026-05-25 00:41:25 +08:00
|
|
|
if !self.disarmed {
|
|
|
|
|
self.active_subscription.store(false, Ordering::Release);
|
|
|
|
|
if let Some(handle) = self.metrics_handle.take() {
|
|
|
|
|
handle.abort();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct SubscriptionCleanupGuard {
|
|
|
|
|
active_subscription: Arc<AtomicBool>,
|
|
|
|
|
control_tx: Arc<tokio::sync::Mutex<Option<mpsc::Sender<SubscribeRequest>>>>,
|
|
|
|
|
current_request: Arc<tokio::sync::RwLock<Option<SubscribeRequest>>>,
|
|
|
|
|
metrics_handle: Option<tokio::task::JoinHandle<()>>,
|
|
|
|
|
finished: bool,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl SubscriptionCleanupGuard {
|
|
|
|
|
fn new(
|
|
|
|
|
active_subscription: Arc<AtomicBool>,
|
|
|
|
|
control_tx: Arc<tokio::sync::Mutex<Option<mpsc::Sender<SubscribeRequest>>>>,
|
|
|
|
|
current_request: Arc<tokio::sync::RwLock<Option<SubscribeRequest>>>,
|
|
|
|
|
metrics_handle: Option<tokio::task::JoinHandle<()>>,
|
|
|
|
|
) -> Self {
|
|
|
|
|
Self { active_subscription, control_tx, current_request, metrics_handle, finished: false }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn finish(mut self) {
|
|
|
|
|
*self.control_tx.lock().await = None;
|
|
|
|
|
*self.current_request.write().await = None;
|
|
|
|
|
self.active_subscription.store(false, Ordering::Release);
|
|
|
|
|
if let Some(handle) = self.metrics_handle.take() {
|
|
|
|
|
handle.abort();
|
|
|
|
|
}
|
|
|
|
|
self.finished = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Drop for SubscriptionCleanupGuard {
|
|
|
|
|
fn drop(&mut self) {
|
|
|
|
|
if !self.finished {
|
|
|
|
|
self.active_subscription.store(false, Ordering::Release);
|
|
|
|
|
if let Some(handle) = self.metrics_handle.take() {
|
|
|
|
|
handle.abort();
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-05-19 04:26:51 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-21 15:47:31 +08:00
|
|
|
// 实现 Clone trait 以支持模块间共享
|
|
|
|
|
impl Clone for YellowstoneGrpc {
|
|
|
|
|
fn clone(&self) -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
endpoint: self.endpoint.clone(),
|
|
|
|
|
x_token: self.x_token.clone(),
|
|
|
|
|
config: self.config.clone(),
|
|
|
|
|
subscription_manager: self.subscription_manager.clone(),
|
|
|
|
|
subscription_handle: self.subscription_handle.clone(), // 共享同一个 Arc<Mutex<>>
|
2025-08-25 17:09:14 -07:00
|
|
|
active_subscription: self.active_subscription.clone(),
|
|
|
|
|
control_tx: self.control_tx.clone(),
|
2025-09-10 23:21:08 +08:00
|
|
|
event_type_filter: self.event_type_filter.clone(),
|
2025-08-25 17:09:14 -07:00
|
|
|
current_request: self.current_request.clone(),
|
2025-08-21 15:47:31 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|