Skip to main content

reth_node_events/
cl.rs

1//! Events related to Consensus Layer health.
2
3use futures::Stream;
4use reth_storage_api::CanonChainTracker;
5use std::{
6    fmt,
7    pin::Pin,
8    task::{ready, Context, Poll},
9    time::Duration,
10};
11use tokio::time::{Instant, Interval};
12
13/// Interval of checking Consensus Layer client health.
14const CHECK_INTERVAL: Duration = Duration::from_secs(300);
15
16/// Period of not receiving fork choice updates from Consensus Layer client,
17/// after which the warning is issued.
18const NO_FORKCHOICE_UPDATE_RECEIVED_PERIOD: Duration = Duration::from_secs(120);
19
20/// A Stream of [`ConsensusLayerHealthEvent`].
21pub struct ConsensusLayerHealthEvents {
22    interval: Interval,
23    canon_chain: Box<dyn CanonChainTracker>,
24}
25
26impl fmt::Debug for ConsensusLayerHealthEvents {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        f.debug_struct("ConsensusLayerHealthEvents").field("interval", &self.interval).finish()
29    }
30}
31
32impl ConsensusLayerHealthEvents {
33    /// Creates a new [`ConsensusLayerHealthEvents`] with the given canonical chain tracker.
34    pub fn new(canon_chain: Box<dyn CanonChainTracker>) -> Self {
35        // Skip the first tick to prevent the false `ConsensusLayerHealthEvent::NeverSeen` event.
36        let interval = tokio::time::interval_at(Instant::now() + CHECK_INTERVAL, CHECK_INTERVAL);
37        Self { interval, canon_chain }
38    }
39}
40
41impl Stream for ConsensusLayerHealthEvents {
42    type Item = ConsensusLayerHealthEvent;
43
44    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
45        let this = self.get_mut();
46
47        loop {
48            ready!(this.interval.poll_tick(cx));
49
50            if let Some(fork_choice) = this.canon_chain.last_received_update_timestamp() {
51                if fork_choice.elapsed() <= NO_FORKCHOICE_UPDATE_RECEIVED_PERIOD {
52                    // We had an FCU, and it's recent. CL is healthy.
53                    continue
54                }
55                // We had an FCU, but it's too old.
56                return Poll::Ready(Some(
57                    ConsensusLayerHealthEvent::HaveNotReceivedUpdatesForAWhile(
58                        fork_choice.elapsed(),
59                    ),
60                ))
61            }
62
63            // We never received any forkchoice updates.
64            return Poll::Ready(Some(ConsensusLayerHealthEvent::NeverSeen))
65        }
66    }
67}
68
69/// Event that is triggered when Consensus Layer health is degraded from the
70/// Execution Layer point of view.
71#[derive(Clone, Copy, Debug)]
72pub enum ConsensusLayerHealthEvent {
73    /// Consensus Layer client was never seen (no forkchoice updates received).
74    NeverSeen,
75    /// Forkchoice updates from the Consensus Layer client have not been received for a while.
76    HaveNotReceivedUpdatesForAWhile(Duration),
77}