-
Notifications
You must be signed in to change notification settings - Fork 16
Feat/monitor event stream #78
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
ferranbt
wants to merge
3
commits into
main
Choose a base branch
from
feat/monitor-event-stream
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,68 +1,198 @@ | ||
use crate::tx::FBPooledTransaction; | ||
use alloy_primitives::TxHash; | ||
use futures_util::StreamExt; | ||
use reth_transaction_pool::{AllTransactionsEvents, FullTransactionEvent}; | ||
use jsonrpsee::{ | ||
core::{async_trait, SubscriptionResult}, | ||
proc_macros::rpc, | ||
PendingSubscriptionSink, SubscriptionMessage, | ||
}; | ||
use reth_transaction_pool::{FullTransactionEvent, TransactionEvent, TransactionPool}; | ||
use serde::Serialize; | ||
use tokio::sync::broadcast; | ||
use tracing::info; | ||
|
||
pub async fn monitor_tx_pool(mut new_transactions: AllTransactionsEvents<FBPooledTransaction>) { | ||
while let Some(event) = new_transactions.next().await { | ||
transaction_event_log(event); | ||
#[rpc(server, namespace = "txpool")] | ||
pub trait TxpoolExtApi { | ||
/// Creates a subscription that returns the txpool events. | ||
#[subscription(name = "subscribeEvents", item = usize)] | ||
fn subscribe_events(&self) -> SubscriptionResult; | ||
} | ||
|
||
pub struct TransactionPoolMonitor<Pool> { | ||
pool: Pool, | ||
log_events: bool, | ||
txpool_monitor: bool, | ||
event_sender: broadcast::Sender<TransactionEventData>, | ||
// Keep a receiver to prevent channel from closing | ||
_event_receiver: broadcast::Receiver<TransactionEventData>, | ||
} | ||
|
||
impl<Pool> TransactionPoolMonitor<Pool> { | ||
pub fn new(pool: Pool, log_events: bool, txpool_monitor: bool, buffer_size: usize) -> Self { | ||
let (event_sender, _event_receiver) = broadcast::channel(buffer_size); | ||
|
||
if log_events { | ||
info!("Logging pool transactions"); | ||
} | ||
if txpool_monitor { | ||
info!("Monitoring txpool enabled"); | ||
} | ||
|
||
Self { | ||
pool, | ||
log_events, | ||
txpool_monitor, | ||
event_sender, | ||
_event_receiver, | ||
} | ||
} | ||
} | ||
|
||
fn transaction_event_log(event: FullTransactionEvent<FBPooledTransaction>) { | ||
match event { | ||
FullTransactionEvent::Pending(hash) => { | ||
info!( | ||
target = "monitoring", | ||
tx_hash = hash.to_string(), | ||
kind = "pending", | ||
"Transaction event received" | ||
) | ||
impl<Pool> TransactionPoolMonitor<Pool> | ||
where | ||
Pool: TransactionPool<Transaction = FBPooledTransaction> + Clone + 'static, | ||
{ | ||
pub fn rpc(&self) -> TransactionPoolMonitorRpc { | ||
TransactionPoolMonitorRpc { | ||
event_sender: self.event_sender.clone(), | ||
} | ||
FullTransactionEvent::Queued(hash) => { | ||
info!( | ||
target = "monitoring", | ||
tx_hash = hash.to_string(), | ||
kind = "queued", | ||
"Transaction event received" | ||
) | ||
} | ||
|
||
pub async fn run(self) { | ||
let mut new_transactions = self.pool.all_transactions_event_listener(); | ||
|
||
while let Some(event) = new_transactions.next().await { | ||
// Push the event to the buffer | ||
let event_data = TransactionEventData::from(event); | ||
if self.log_events { | ||
info!( | ||
target = "monitoring", | ||
tx_hash = event_data.hash.to_string(), | ||
kind = event_data.kind(), | ||
"Transaction event received" | ||
) | ||
} | ||
|
||
if self.txpool_monitor { | ||
println!("Sending event: {:?}", event_data); | ||
let _ = self.event_sender.send(event_data); | ||
} | ||
} | ||
FullTransactionEvent::Mined { | ||
tx_hash, | ||
block_hash, | ||
} => info!( | ||
target = "monitoring", | ||
tx_hash = tx_hash.to_string(), | ||
kind = "mined", | ||
block_hash = block_hash.to_string(), | ||
"Transaction event received" | ||
), | ||
FullTransactionEvent::Replaced { | ||
transaction, | ||
replaced_by, | ||
} => info!( | ||
target = "monitoring", | ||
tx_hash = transaction.hash().to_string(), | ||
kind = "replaced", | ||
replaced_by = replaced_by.to_string(), | ||
"Transaction event received" | ||
), | ||
FullTransactionEvent::Discarded(hash) => { | ||
info!( | ||
target = "monitoring", | ||
tx_hash = hash.to_string(), | ||
kind = "discarded", | ||
"Transaction event received" | ||
) | ||
} | ||
} | ||
|
||
pub struct TransactionPoolMonitorRpc { | ||
event_sender: broadcast::Sender<TransactionEventData>, | ||
} | ||
|
||
#[async_trait] | ||
impl TxpoolExtApiServer for TransactionPoolMonitorRpc { | ||
fn subscribe_events( | ||
&self, | ||
pending_subscription_sink: PendingSubscriptionSink, | ||
) -> SubscriptionResult { | ||
println!("Subscribing to txpool events"); | ||
let mut event_receiver = self.event_sender.subscribe(); | ||
|
||
tokio::spawn(async move { | ||
let sink = match pending_subscription_sink.accept().await { | ||
Ok(sink) => sink, | ||
Err(e) => { | ||
tracing::warn!("failed to accept subscription: {e}"); | ||
return; | ||
} | ||
}; | ||
|
||
println!("Subscribed to txpool events"); | ||
|
||
loop { | ||
match event_receiver.recv().await { | ||
Ok(event) => { | ||
println!("Received event: {:?}", event); | ||
|
||
let msg = SubscriptionMessage::from( | ||
serde_json::value::to_raw_value(&event) | ||
.expect("Failed to serialize event"), | ||
); | ||
|
||
if sink.send(msg).await.is_err() { | ||
tracing::debug!("Subscription closed"); | ||
break; | ||
} | ||
} | ||
Err(broadcast::error::RecvError::Lagged(_)) => { | ||
tracing::warn!("Subscription lagged, some events were dropped"); | ||
continue; | ||
} | ||
Err(broadcast::error::RecvError::Closed) => { | ||
tracing::debug!("Event channel closed"); | ||
break; | ||
} | ||
} | ||
} | ||
}); | ||
|
||
Ok(()) | ||
} | ||
} | ||
|
||
#[derive(Clone, Debug, Serialize)] | ||
struct TransactionEventData { | ||
hash: TxHash, | ||
transaction_event: TransactionEvent, | ||
} | ||
|
||
impl TransactionEventData { | ||
pub fn kind(&self) -> &str { | ||
match self.transaction_event { | ||
TransactionEvent::Pending => "pending", | ||
TransactionEvent::Queued => "queued", | ||
TransactionEvent::Mined(_) => "mined", | ||
TransactionEvent::Replaced(_) => "replaced", | ||
TransactionEvent::Discarded => "discarded", | ||
TransactionEvent::Invalid => "invalid", | ||
TransactionEvent::Propagated(_) => "propagated", | ||
} | ||
FullTransactionEvent::Invalid(hash) => { | ||
info!( | ||
target = "monitoring", | ||
tx_hash = hash.to_string(), | ||
kind = "invalid", | ||
"Transaction event received" | ||
) | ||
} | ||
} | ||
|
||
impl From<FullTransactionEvent<FBPooledTransaction>> for TransactionEventData { | ||
fn from(event: FullTransactionEvent<FBPooledTransaction>) -> Self { | ||
match event { | ||
FullTransactionEvent::Pending(hash) => Self { | ||
hash, | ||
transaction_event: TransactionEvent::Pending, | ||
}, | ||
FullTransactionEvent::Queued(hash) => Self { | ||
hash, | ||
transaction_event: TransactionEvent::Queued, | ||
}, | ||
FullTransactionEvent::Mined { | ||
tx_hash, | ||
block_hash, | ||
} => Self { | ||
hash: tx_hash, | ||
transaction_event: TransactionEvent::Mined(block_hash), | ||
}, | ||
FullTransactionEvent::Replaced { | ||
transaction, | ||
replaced_by, | ||
} => Self { | ||
hash: *transaction.hash(), | ||
transaction_event: TransactionEvent::Replaced(replaced_by), | ||
}, | ||
FullTransactionEvent::Discarded(hash) => Self { | ||
hash, | ||
transaction_event: TransactionEvent::Discarded, | ||
}, | ||
FullTransactionEvent::Invalid(hash) => Self { | ||
hash, | ||
transaction_event: TransactionEvent::Invalid, | ||
}, | ||
FullTransactionEvent::Propagated(kind) => Self { | ||
hash: TxHash::default(), | ||
transaction_event: TransactionEvent::Propagated(kind), | ||
}, | ||
} | ||
FullTransactionEvent::Propagated(_propagated) => {} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If the buffer has elements, does this subscribe tries to read those elements first? or if will start at the beginning of the stream?