|
| 1 | +use crate::{RpcHostError, RpcHostNotifier}; |
| 2 | +use alloy::providers::Provider; |
| 3 | +use std::collections::VecDeque; |
| 4 | + |
| 5 | +/// Default block buffer capacity. |
| 6 | +const DEFAULT_BUFFER_CAPACITY: usize = 64; |
| 7 | +/// Default backfill batch size. |
| 8 | +const DEFAULT_BACKFILL_BATCH_SIZE: u64 = 32; |
| 9 | + |
| 10 | +/// Builder for [`RpcHostNotifier`]. |
| 11 | +/// |
| 12 | +/// # Example |
| 13 | +/// |
| 14 | +/// ```ignore |
| 15 | +/// let notifier = RpcHostNotifierBuilder::new(provider) |
| 16 | +/// .with_buffer_capacity(128) |
| 17 | +/// .with_backfill_batch_size(64) |
| 18 | +/// .build() |
| 19 | +/// .await?; |
| 20 | +/// ``` |
| 21 | +#[derive(Debug)] |
| 22 | +pub struct RpcHostNotifierBuilder<P> { |
| 23 | + provider: P, |
| 24 | + buffer_capacity: usize, |
| 25 | + backfill_batch_size: u64, |
| 26 | + genesis_timestamp: u64, |
| 27 | +} |
| 28 | + |
| 29 | +impl<P> RpcHostNotifierBuilder<P> |
| 30 | +where |
| 31 | + P: Provider + Clone, |
| 32 | +{ |
| 33 | + /// Create a new builder with the given provider. |
| 34 | + pub const fn new(provider: P) -> Self { |
| 35 | + Self { |
| 36 | + provider, |
| 37 | + buffer_capacity: DEFAULT_BUFFER_CAPACITY, |
| 38 | + backfill_batch_size: DEFAULT_BACKFILL_BATCH_SIZE, |
| 39 | + genesis_timestamp: 0, |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + /// Set the block buffer capacity (default: 64). |
| 44 | + pub const fn with_buffer_capacity(mut self, capacity: usize) -> Self { |
| 45 | + self.buffer_capacity = capacity; |
| 46 | + self |
| 47 | + } |
| 48 | + |
| 49 | + /// Set the backfill batch size (default: 32). |
| 50 | + pub const fn with_backfill_batch_size(mut self, batch_size: u64) -> Self { |
| 51 | + self.backfill_batch_size = batch_size; |
| 52 | + self |
| 53 | + } |
| 54 | + |
| 55 | + /// Set the genesis timestamp for epoch calculation. |
| 56 | + pub const fn with_genesis_timestamp(mut self, timestamp: u64) -> Self { |
| 57 | + self.genesis_timestamp = timestamp; |
| 58 | + self |
| 59 | + } |
| 60 | + |
| 61 | + /// Build the notifier, establishing the `newHeads` WebSocket subscription. |
| 62 | + pub async fn build(self) -> Result<RpcHostNotifier<P>, RpcHostError> { |
| 63 | + let sub = self.provider.subscribe_blocks().await?; |
| 64 | + let header_sub = sub.into_stream(); |
| 65 | + |
| 66 | + Ok(RpcHostNotifier { |
| 67 | + provider: self.provider, |
| 68 | + header_sub, |
| 69 | + block_buffer: VecDeque::with_capacity(self.buffer_capacity), |
| 70 | + buffer_capacity: self.buffer_capacity, |
| 71 | + cached_safe: None, |
| 72 | + cached_finalized: None, |
| 73 | + last_tag_epoch: None, |
| 74 | + backfill_from: None, |
| 75 | + backfill_batch_size: self.backfill_batch_size, |
| 76 | + genesis_timestamp: self.genesis_timestamp, |
| 77 | + }) |
| 78 | + } |
| 79 | +} |
0 commit comments