|
| 1 | +use alloy::consensus::TxEnvelope; |
| 2 | +use init4_bin_base::deps::tracing::{debug, info}; |
| 3 | +use signet_sim::SimCache; |
| 4 | +use signet_tx_cache::types::TxCacheBundle; |
| 5 | +use tokio::{ |
| 6 | + sync::{mpsc, watch}, |
| 7 | + task::JoinHandle, |
| 8 | +}; |
| 9 | +use trevm::revm::context::BlockEnv; |
| 10 | + |
| 11 | +/// Cache task for the block builder. |
| 12 | +/// |
| 13 | +/// This tasks handles the ingestion of transactions and bundles into the cache. |
| 14 | +/// It keeps a receiver for the block environment and cleans the cache when |
| 15 | +/// the environment changes. |
| 16 | +#[derive(Debug)] |
| 17 | +pub struct CacheTask { |
| 18 | + /// The shared sim cache to populate. |
| 19 | + cache: SimCache, |
| 20 | + |
| 21 | + /// The channel to receive the block environment. |
| 22 | + env: watch::Receiver<Option<BlockEnv>>, |
| 23 | + |
| 24 | + /// The channel to receive the transaction bundles. |
| 25 | + bundles: mpsc::UnboundedReceiver<TxCacheBundle>, |
| 26 | + /// The channel to receive the transactions. |
| 27 | + txns: mpsc::UnboundedReceiver<TxEnvelope>, |
| 28 | +} |
| 29 | + |
| 30 | +impl CacheTask { |
| 31 | + async fn task_future(mut self) { |
| 32 | + loop { |
| 33 | + let mut basefee = 0; |
| 34 | + tokio::select! { |
| 35 | + biased; |
| 36 | + res = self.env.changed() => { |
| 37 | + if res.is_err() { |
| 38 | + debug!("Cache task: env channel closed, exiting"); |
| 39 | + break; |
| 40 | + } |
| 41 | + if let Some(env) = self.env.borrow_and_update().as_ref() { |
| 42 | + basefee = env.basefee; |
| 43 | + info!(basefee, number = env.number, timestamp = env.timestamp, "block env changed, clearing cache"); |
| 44 | + self.cache.clean( |
| 45 | + env.number, env.timestamp |
| 46 | + ); |
| 47 | + } |
| 48 | + } |
| 49 | + Some(bundle) = self.bundles.recv() => { |
| 50 | + self.cache.add_item(bundle.bundle, basefee); |
| 51 | + } |
| 52 | + Some(txn) = self.txns.recv() => { |
| 53 | + self.cache.add_item(txn, basefee); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + /// Spawn the cache task. |
| 60 | + pub fn spawn(self) -> JoinHandle<()> { |
| 61 | + let fut = self.task_future(); |
| 62 | + tokio::spawn(fut) |
| 63 | + } |
| 64 | +} |
0 commit comments