Skip to main content

reth_exex/wal/
mod.rs

1#![allow(dead_code)]
2
3mod cache;
4pub use cache::BlockCache;
5mod storage;
6use reth_ethereum_primitives::EthPrimitives;
7use reth_node_api::NodePrimitives;
8pub use storage::Storage;
9mod metrics;
10use metrics::Metrics;
11mod error;
12pub use error::{WalError, WalResult};
13
14use std::{
15    path::Path,
16    sync::{
17        atomic::{AtomicU32, Ordering},
18        Arc,
19    },
20};
21
22use alloy_eips::BlockNumHash;
23use alloy_primitives::B256;
24use parking_lot::{RwLock, RwLockReadGuard};
25use reth_exex_types::ExExNotification;
26use tracing::{debug, instrument};
27
28/// WAL is a write-ahead log (WAL) that stores the notifications sent to ExExes.
29///
30/// WAL is backed by a directory of binary files represented by [`Storage`] and a block cache
31/// represented by [`BlockCache`]. The role of the block cache is to avoid walking the WAL directory
32/// and decoding notifications every time we want to iterate or finalize the WAL.
33///
34/// The expected mode of operation is as follows:
35/// 1. On every new canonical chain notification, call [`Wal::commit`].
36/// 2. When the chain is finalized, call [`Wal::finalize`] to prevent the infinite growth of the
37///    WAL.
38#[derive(Debug, Clone)]
39pub struct Wal<N: NodePrimitives = EthPrimitives> {
40    inner: Arc<WalInner<N>>,
41}
42
43impl<N> Wal<N>
44where
45    N: NodePrimitives,
46{
47    /// Creates a new instance of [`Wal`].
48    pub fn new(directory: impl AsRef<Path>) -> WalResult<Self> {
49        Ok(Self { inner: Arc::new(WalInner::new(directory)?) })
50    }
51
52    /// Returns a read-only handle to the WAL.
53    pub fn handle(&self) -> WalHandle<N> {
54        WalHandle { wal: self.inner.clone() }
55    }
56
57    /// Commits the notification to WAL.
58    ///
59    /// Returns the ID of the file the notification was written to.
60    pub fn commit(&self, notification: &ExExNotification<N>) -> WalResult<u32> {
61        self.inner.commit(notification)
62    }
63
64    /// Finalizes the WAL up to the given canonical block, inclusive.
65    ///
66    /// The caller should check that all ExExes are on the canonical chain and will not need any
67    /// blocks from the WAL below the provided block, inclusive.
68    pub fn finalize(&self, to_block: BlockNumHash) -> WalResult<()> {
69        self.inner.finalize(to_block, None)
70    }
71
72    /// Finalizes the WAL like [`Self::finalize`], but keeps notifications with file IDs of at
73    /// least `retain_from`, if any.
74    pub(crate) fn finalize_retaining(
75        &self,
76        to_block: BlockNumHash,
77        retain_from: Option<u32>,
78    ) -> WalResult<()> {
79        self.inner.finalize(to_block, retain_from)
80    }
81
82    /// Returns an iterator over all notifications in the WAL.
83    pub fn iter_notifications(
84        &self,
85    ) -> WalResult<Box<dyn Iterator<Item = WalResult<ExExNotification<N>>> + '_>> {
86        self.inner.iter_notifications()
87    }
88
89    /// Returns the number of blocks in the WAL.
90    pub fn num_blocks(&self) -> usize {
91        self.inner.block_cache().num_blocks()
92    }
93
94    /// Reads a notification retained for delivery by the manager.
95    pub(crate) fn read_notification(&self, file_id: u32) -> WalResult<ExExNotification<N>> {
96        self.inner
97            .storage
98            .read_notification(file_id)?
99            .map(|(notification, _)| notification)
100            .ok_or(WalError::FileNotFound(file_id))
101    }
102}
103
104/// Inner type for the WAL.
105#[derive(Debug)]
106struct WalInner<N: NodePrimitives> {
107    next_file_id: AtomicU32,
108    /// The underlying WAL storage backed by a file.
109    storage: Storage<N>,
110    /// WAL block cache. See [`cache::BlockCache`] docs for more details.
111    block_cache: RwLock<BlockCache>,
112    metrics: Metrics,
113}
114
115impl<N> WalInner<N>
116where
117    N: NodePrimitives,
118{
119    fn new(directory: impl AsRef<Path>) -> WalResult<Self> {
120        let wal = Self {
121            next_file_id: AtomicU32::new(0),
122            storage: Storage::new(directory)?,
123            block_cache: RwLock::new(BlockCache::default()),
124            metrics: Metrics::default(),
125        };
126        wal.fill_block_cache()?;
127        Ok(wal)
128    }
129
130    fn block_cache(&self) -> RwLockReadGuard<'_, BlockCache> {
131        self.block_cache.read()
132    }
133
134    /// Fills the block cache with the notifications from the storage.
135    #[instrument(skip(self))]
136    fn fill_block_cache(&self) -> WalResult<()> {
137        let file_ids = self.storage.file_ids()?;
138        let Some(last_file_id) = file_ids.last() else { return Ok(()) };
139        self.next_file_id.store(last_file_id + 1, Ordering::Relaxed);
140
141        let mut block_cache = self.block_cache.write();
142        let mut notifications_size = 0;
143
144        for entry in self.storage.iter_notifications(file_ids) {
145            let (file_id, size, notification) = entry?;
146
147            notifications_size += size;
148
149            let committed_chain = notification.committed_chain();
150            let reverted_chain = notification.reverted_chain();
151
152            debug!(
153                target: "exex::wal",
154                ?file_id,
155                reverted_block_range = ?reverted_chain.as_ref().map(|chain| chain.range()),
156                committed_block_range = ?committed_chain.as_ref().map(|chain| chain.range()),
157                "Inserting block cache entries"
158            );
159
160            block_cache.insert_notification_blocks_with_file_id(file_id, &notification);
161        }
162
163        self.update_metrics(&block_cache, notifications_size as i64);
164
165        Ok(())
166    }
167
168    #[instrument(skip_all, fields(
169        reverted_block_range = ?notification.reverted_chain().as_ref().map(|chain| chain.range()),
170        committed_block_range = ?notification.committed_chain().as_ref().map(|chain| chain.range())
171    ))]
172    fn commit(&self, notification: &ExExNotification<N>) -> WalResult<u32> {
173        let mut block_cache = self.block_cache.write();
174
175        let file_id = self.next_file_id.fetch_add(1, Ordering::Relaxed);
176        let size = self.storage.write_notification(file_id, notification)?;
177
178        debug!(target: "exex::wal", ?file_id, "Inserting notification blocks into the block cache");
179        block_cache.insert_notification_blocks_with_file_id(file_id, notification);
180
181        self.update_metrics(&block_cache, size as i64);
182
183        Ok(file_id)
184    }
185
186    #[instrument(skip(self))]
187    fn finalize(&self, to_block: BlockNumHash, retain_from: Option<u32>) -> WalResult<()> {
188        let mut block_cache = self.block_cache.write();
189        let file_ids = block_cache.remove_before(to_block.number, retain_from);
190
191        // Remove notifications from the storage.
192        if file_ids.is_empty() {
193            debug!(target: "exex::wal", "No notifications were finalized from the storage");
194            return Ok(())
195        }
196
197        let (removed_notifications, removed_size) = self.storage.remove_notifications(file_ids)?;
198        debug!(target: "exex::wal", ?removed_notifications, ?removed_size, "Storage was finalized");
199
200        self.update_metrics(&block_cache, -(removed_size as i64));
201
202        Ok(())
203    }
204
205    fn update_metrics(&self, block_cache: &BlockCache, size_delta: i64) {
206        self.metrics.size_bytes.increment(size_delta as f64);
207        self.metrics.notifications_count.set(block_cache.notification_max_blocks.len() as f64);
208        self.metrics.committed_blocks_count.set(block_cache.committed_blocks.len() as f64);
209
210        if let Some(lowest_committed_block_height) = block_cache.lowest_committed_block_height {
211            self.metrics.lowest_committed_block_height.set(lowest_committed_block_height as f64);
212        }
213
214        if let Some(highest_committed_block_height) = block_cache.highest_committed_block_height {
215            self.metrics.highest_committed_block_height.set(highest_committed_block_height as f64);
216        }
217    }
218
219    /// Returns an iterator over all notifications in the WAL.
220    fn iter_notifications(
221        &self,
222    ) -> WalResult<Box<dyn Iterator<Item = WalResult<ExExNotification<N>>> + '_>> {
223        Ok(Box::new(
224            self.storage.iter_notifications(self.storage.file_ids()?).map(|entry| Ok(entry?.2)),
225        ))
226    }
227}
228
229/// A read-only handle to the WAL that can be shared.
230#[derive(Debug)]
231pub struct WalHandle<N: NodePrimitives> {
232    wal: Arc<WalInner<N>>,
233}
234
235impl<N> WalHandle<N>
236where
237    N: NodePrimitives,
238{
239    /// Returns the notification for the given committed block hash if it exists.
240    pub fn get_committed_notification_by_block_hash(
241        &self,
242        block_hash: &B256,
243    ) -> WalResult<Option<ExExNotification<N>>> {
244        let Some(file_id) = self.wal.block_cache().get_file_id_by_committed_block_hash(block_hash)
245        else {
246            return Ok(None)
247        };
248
249        self.wal
250            .storage
251            .read_notification(file_id)
252            .map(|entry| entry.map(|(notification, _)| notification))
253    }
254}
255
256#[cfg(test)]
257mod tests {
258    use crate::wal::{cache::CachedBlock, error::WalResult, Wal};
259    use alloy_primitives::B256;
260    use itertools::Itertools;
261    use reth_ethereum_primitives::EthPrimitives;
262    use reth_exex_types::ExExNotification;
263    use reth_provider::Chain;
264    use reth_testing_utils::generators::{
265        self, random_block, random_block_range, BlockParams, BlockRangeParams,
266    };
267    use std::{collections::BTreeMap, sync::Arc};
268
269    fn read_notifications(wal: &Wal) -> WalResult<Vec<ExExNotification>> {
270        wal.inner
271            .storage
272            .iter_notifications(wal.inner.storage.file_ids()?)
273            .map(|entry| entry.map(|(_, _, n)| n))
274            .collect()
275    }
276
277    fn sort_committed_blocks(
278        committed_blocks: Vec<(B256, u32, CachedBlock)>,
279    ) -> Vec<(B256, u32, CachedBlock)> {
280        committed_blocks
281            .into_iter()
282            .sorted_by_key(|(_, _, block)| (block.block.number, block.block.hash))
283            .collect()
284    }
285
286    #[test]
287    fn test_wal() -> eyre::Result<()> {
288        reth_tracing::init_test_tracing();
289
290        let mut rng = generators::rng();
291
292        // Create an instance of the WAL in a temporary directory
293        let temp_dir = tempfile::tempdir()?;
294        let wal = Wal::new(&temp_dir)?;
295        assert!(wal.inner.block_cache().is_empty());
296
297        // Create 4 canonical blocks and one reorged block with number 2
298        let blocks = random_block_range(&mut rng, 0..=3, BlockRangeParams::default())
299            .into_iter()
300            .map(|block| block.try_recover())
301            .collect::<Result<Vec<_>, _>>()?;
302        let block_1_reorged = random_block(
303            &mut rng,
304            1,
305            BlockParams { parent: Some(blocks[0].hash()), ..Default::default() },
306        )
307        .try_recover()?;
308        let block_2_reorged = random_block(
309            &mut rng,
310            2,
311            BlockParams { parent: Some(blocks[1].hash()), ..Default::default() },
312        )
313        .try_recover()?;
314
315        // Create notifications for the above blocks.
316        // 1. Committed notification for blocks with number 0 and 1
317        // 2. Reverted notification for block with number 1
318        // 3. Committed notification for block with number 1 and 2
319        // 4. Reorged notification for block with number 2 that was reverted, and blocks with number
320        //    2 and 3 that were committed
321        let committed_notification_1 = ExExNotification::ChainCommitted {
322            new: Arc::new(Chain::new(
323                vec![blocks[0].clone(), blocks[1].clone()],
324                Default::default(),
325                BTreeMap::new(),
326            )),
327        };
328        let reverted_notification = ExExNotification::ChainReverted {
329            old: Arc::new(Chain::new(vec![blocks[1].clone()], Default::default(), BTreeMap::new())),
330        };
331        let committed_notification_2 = ExExNotification::ChainCommitted {
332            new: Arc::new(Chain::new(
333                vec![block_1_reorged.clone(), blocks[2].clone()],
334                Default::default(),
335                BTreeMap::new(),
336            )),
337        };
338        let reorged_notification = ExExNotification::ChainReorged {
339            old: Arc::new(Chain::new(vec![blocks[2].clone()], Default::default(), BTreeMap::new())),
340            new: Arc::new(Chain::new(
341                vec![block_2_reorged.clone(), blocks[3].clone()],
342                Default::default(),
343                BTreeMap::new(),
344            )),
345        };
346
347        // Commit notifications, verify that the block cache is updated and the notifications are
348        // written to WAL.
349
350        // First notification (commit block 0, 1)
351        let file_id = 0;
352        let committed_notification_1_cache_blocks = (blocks[1].number, file_id);
353        let committed_notification_1_cache_committed_blocks = vec![
354            (
355                blocks[0].hash(),
356                file_id,
357                CachedBlock {
358                    block: (blocks[0].number, blocks[0].hash()).into(),
359                    parent_hash: blocks[0].parent_hash,
360                },
361            ),
362            (
363                blocks[1].hash(),
364                file_id,
365                CachedBlock {
366                    block: (blocks[1].number, blocks[1].hash()).into(),
367                    parent_hash: blocks[1].parent_hash,
368                },
369            ),
370        ];
371        wal.commit(&committed_notification_1)?;
372        assert_eq!(
373            wal.inner.block_cache().blocks_sorted(),
374            [committed_notification_1_cache_blocks]
375        );
376        assert_eq!(
377            wal.inner.block_cache().committed_blocks_sorted(),
378            committed_notification_1_cache_committed_blocks
379        );
380        assert_eq!(read_notifications(&wal)?, vec![committed_notification_1.clone()]);
381
382        // Second notification (revert block 1)
383        wal.commit(&reverted_notification)?;
384        let file_id = 1;
385        let reverted_notification_cache_blocks = (blocks[1].number, file_id);
386        assert_eq!(
387            wal.inner.block_cache().blocks_sorted(),
388            [reverted_notification_cache_blocks, committed_notification_1_cache_blocks]
389        );
390        assert_eq!(
391            wal.inner.block_cache().committed_blocks_sorted(),
392            committed_notification_1_cache_committed_blocks
393        );
394        assert_eq!(
395            read_notifications(&wal)?,
396            vec![committed_notification_1.clone(), reverted_notification.clone()]
397        );
398
399        // Third notification (commit block 1, 2)
400        wal.commit(&committed_notification_2)?;
401        let file_id = 2;
402        let committed_notification_2_cache_blocks = (blocks[2].number, file_id);
403        let committed_notification_2_cache_committed_blocks = vec![
404            (
405                block_1_reorged.hash(),
406                file_id,
407                CachedBlock {
408                    block: (block_1_reorged.number, block_1_reorged.hash()).into(),
409                    parent_hash: block_1_reorged.parent_hash,
410                },
411            ),
412            (
413                blocks[2].hash(),
414                file_id,
415                CachedBlock {
416                    block: (blocks[2].number, blocks[2].hash()).into(),
417                    parent_hash: blocks[2].parent_hash,
418                },
419            ),
420        ];
421        assert_eq!(
422            wal.inner.block_cache().blocks_sorted(),
423            [
424                committed_notification_2_cache_blocks,
425                reverted_notification_cache_blocks,
426                committed_notification_1_cache_blocks,
427            ]
428        );
429        assert_eq!(
430            wal.inner.block_cache().committed_blocks_sorted(),
431            sort_committed_blocks(
432                [
433                    committed_notification_1_cache_committed_blocks.clone(),
434                    committed_notification_2_cache_committed_blocks.clone()
435                ]
436                .concat()
437            )
438        );
439        assert_eq!(
440            read_notifications(&wal)?,
441            vec![
442                committed_notification_1.clone(),
443                reverted_notification.clone(),
444                committed_notification_2.clone()
445            ]
446        );
447
448        // Fourth notification (revert block 2, commit block 2, 3)
449        wal.commit(&reorged_notification)?;
450        let file_id = 3;
451        let reorged_notification_cache_blocks = (blocks[3].number, file_id);
452        let reorged_notification_cache_committed_blocks = vec![
453            (
454                block_2_reorged.hash(),
455                file_id,
456                CachedBlock {
457                    block: (block_2_reorged.number, block_2_reorged.hash()).into(),
458                    parent_hash: block_2_reorged.parent_hash,
459                },
460            ),
461            (
462                blocks[3].hash(),
463                file_id,
464                CachedBlock {
465                    block: (blocks[3].number, blocks[3].hash()).into(),
466                    parent_hash: blocks[3].parent_hash,
467                },
468            ),
469        ];
470        assert_eq!(
471            wal.inner.block_cache().blocks_sorted(),
472            [
473                reorged_notification_cache_blocks,
474                committed_notification_2_cache_blocks,
475                reverted_notification_cache_blocks,
476                committed_notification_1_cache_blocks,
477            ]
478        );
479        assert_eq!(
480            wal.inner.block_cache().committed_blocks_sorted(),
481            sort_committed_blocks(
482                [
483                    committed_notification_1_cache_committed_blocks,
484                    committed_notification_2_cache_committed_blocks.clone(),
485                    reorged_notification_cache_committed_blocks.clone()
486                ]
487                .concat()
488            )
489        );
490        assert_eq!(
491            read_notifications(&wal)?,
492            vec![
493                committed_notification_1,
494                reverted_notification,
495                committed_notification_2.clone(),
496                reorged_notification.clone()
497            ]
498        );
499
500        // Now, finalize the WAL up to the block 1. Block 1 was in the third notification that also
501        // had block 2 committed. In this case, we can't split the notification into two parts, so
502        // we preserve the whole notification in both the block cache and the storage, and delete
503        // the notifications before it.
504        wal.finalize((block_1_reorged.number, block_1_reorged.hash()).into())?;
505        assert_eq!(
506            wal.inner.block_cache().blocks_sorted(),
507            [reorged_notification_cache_blocks, committed_notification_2_cache_blocks]
508        );
509        assert_eq!(
510            wal.inner.block_cache().committed_blocks_sorted(),
511            sort_committed_blocks(
512                [
513                    committed_notification_2_cache_committed_blocks.clone(),
514                    reorged_notification_cache_committed_blocks.clone()
515                ]
516                .concat()
517            )
518        );
519        assert_eq!(
520            read_notifications(&wal)?,
521            vec![committed_notification_2.clone(), reorged_notification.clone()]
522        );
523
524        // Re-open the WAL and verify that the cache population works correctly
525        let wal = Wal::new(&temp_dir)?;
526        assert_eq!(
527            wal.inner.block_cache().blocks_sorted(),
528            [reorged_notification_cache_blocks, committed_notification_2_cache_blocks]
529        );
530        assert_eq!(
531            wal.inner.block_cache().committed_blocks_sorted(),
532            sort_committed_blocks(
533                [
534                    committed_notification_2_cache_committed_blocks,
535                    reorged_notification_cache_committed_blocks
536                ]
537                .concat()
538            )
539        );
540        assert_eq!(read_notifications(&wal)?, vec![committed_notification_2, reorged_notification]);
541
542        Ok(())
543    }
544
545    #[test]
546    fn test_finalize_with_sparse_file_ids() -> eyre::Result<()> {
547        let mut rng = generators::rng();
548
549        let temp_dir = tempfile::tempdir()?;
550        let wal = Wal::<EthPrimitives>::new(&temp_dir)?;
551
552        let blocks = random_block_range(&mut rng, 0..=5, BlockRangeParams::default())
553            .into_iter()
554            .map(|block| block.try_recover())
555            .collect::<Result<Vec<_>, _>>()?;
556        let chain = |range: std::ops::RangeInclusive<usize>| {
557            Arc::new(Chain::new(blocks[range].to_vec(), Default::default(), BTreeMap::new()))
558        };
559
560        let commit_to_four = ExExNotification::ChainCommitted { new: chain(1..=4) };
561        let revert_to_two = ExExNotification::ChainReverted { old: chain(2..=4) };
562        let commit_two = ExExNotification::ChainCommitted { new: chain(2..=2) };
563        let commit_to_five = ExExNotification::ChainCommitted { new: chain(3..=5) };
564
565        wal.commit(&commit_to_four)?;
566        wal.commit(&revert_to_two)?;
567        wal.commit(&commit_two)?;
568        wal.commit(&commit_to_five)?;
569        assert_eq!(wal.inner.storage.file_ids()?, vec![0, 1, 2, 3]);
570
571        // File 2 has a lower maximum block than the surrounding notifications, so finalizing it
572        // leaves a gap in the file ID sequence.
573        wal.finalize((blocks[2].number, blocks[2].hash()).into())?;
574        assert_eq!(wal.inner.storage.file_ids()?, vec![0, 1, 3]);
575
576        let wal = Wal::<EthPrimitives>::new(&temp_dir)?;
577        assert_eq!(read_notifications(&wal)?, vec![commit_to_four, revert_to_two, commit_to_five]);
578
579        wal.commit(&commit_two)?;
580        assert_eq!(wal.inner.storage.file_ids()?, vec![0, 1, 3, 4]);
581
582        Ok(())
583    }
584}