Skip to main content

reth_engine_tree/tree/
instrumented_state.rs

1//! Implements a state provider that tracks latency metrics.
2use alloy_primitives::{Address, StorageKey, StorageValue, B256};
3use metrics::{Gauge, Histogram};
4use reth_concurrency::sync::{
5    atomic::{AtomicU64, AtomicUsize, Ordering},
6    time::FastInstant as Instant,
7};
8use reth_errors::ProviderResult;
9use reth_metrics::Metrics;
10use reth_primitives_traits::{Account, Bytecode};
11use reth_provider::EvmStateProvider;
12use std::{sync::Arc, time::Duration};
13
14/// Nanoseconds per second
15const NANOS_PER_SEC: u32 = 1_000_000_000;
16
17/// An atomic version of [`Duration`], using an [`AtomicU64`] to store the total nanoseconds in the
18/// duration.
19#[derive(Debug, Default)]
20pub(crate) struct AtomicDuration {
21    /// The nanoseconds part of the duration
22    ///
23    /// We would have to accumulate 584 years of nanoseconds to overflow a u64, so this is
24    /// sufficiently large for our use case. We don't expect to be adding arbitrary durations to
25    /// this value.
26    nanos: AtomicU64,
27}
28
29impl AtomicDuration {
30    /// Returns the duration as a [`Duration`]
31    pub(crate) fn duration(&self) -> Duration {
32        let nanos = self.nanos.load(Ordering::Relaxed);
33        let seconds = nanos / NANOS_PER_SEC as u64;
34        let nanos = nanos % NANOS_PER_SEC as u64;
35        // `as u32` is ok because we did a mod by u32 const
36        Duration::new(seconds, nanos as u32)
37    }
38
39    /// Adds a [`Duration`] to the atomic duration.
40    pub(crate) fn add_duration(&self, duration: Duration) {
41        // this is `as_nanos` but without the `as u128` - we do not expect durations over 584 years
42        // as input here
43        let total_nanos =
44            duration.as_secs() * NANOS_PER_SEC as u64 + duration.subsec_nanos() as u64;
45        // add the nanoseconds part of the duration
46        self.nanos.fetch_add(total_nanos, Ordering::Relaxed);
47    }
48}
49
50/// A wrapper of a state provider and latency metrics.
51#[derive(Debug)]
52pub struct InstrumentedStateProvider<S> {
53    /// The state provider
54    state_provider: S,
55    /// Prometheus metrics for the instrumented state provider
56    metrics: StateProviderMetrics,
57    /// Shared fetch statistics, readable after the provider is consumed.
58    stats: Arc<StateProviderStats>,
59}
60
61impl<S> InstrumentedStateProvider<S>
62where
63    S: EvmStateProvider,
64{
65    /// Creates a new [`InstrumentedStateProvider`] from a state provider with the provided label
66    /// for metrics.
67    pub fn new(state_provider: S, source: &'static str) -> Self {
68        Self::with_stats(
69            state_provider,
70            StateProviderMetrics::with_source(source),
71            Arc::new(StateProviderStats::default()),
72        )
73    }
74
75    /// Creates a new [`InstrumentedStateProvider`] that writes into shared statistics.
76    pub(crate) const fn with_stats(
77        state_provider: S,
78        metrics: StateProviderMetrics,
79        stats: Arc<StateProviderStats>,
80    ) -> Self {
81        Self { state_provider, metrics, stats }
82    }
83
84    /// Returns a shared reference to the accumulated fetch statistics.
85    pub fn stats(&self) -> Arc<StateProviderStats> {
86        Arc::clone(&self.stats)
87    }
88}
89
90/// Metrics for the instrumented state provider
91#[derive(Metrics, Clone)]
92#[metrics(scope = "sync.state_provider")]
93pub(crate) struct StateProviderMetrics {
94    /// A histogram of the time it takes to get a storage value
95    storage_fetch_latency: Histogram,
96
97    /// A histogram of the time it takes to get a code value
98    code_fetch_latency: Histogram,
99
100    /// A histogram of the time it takes to get an account value
101    account_fetch_latency: Histogram,
102
103    /// A histogram of the total time we spend fetching storage over the lifetime of this state
104    /// provider
105    total_storage_fetch_latency: Histogram,
106
107    /// A gauge of the total time we spend fetching storage over the lifetime of this state
108    /// provider
109    total_storage_fetch_latency_gauge: Gauge,
110
111    /// A histogram of the total time we spend fetching code over the lifetime of this state
112    /// provider
113    total_code_fetch_latency: Histogram,
114
115    /// A gauge of the total time we spend fetching code over the lifetime of this state provider
116    total_code_fetch_latency_gauge: Gauge,
117
118    /// A histogram of the total time we spend fetching accounts over the lifetime of this state
119    /// provider
120    total_account_fetch_latency: Histogram,
121
122    /// A gauge of the total time we spend fetching accounts over the lifetime of this state
123    /// provider
124    total_account_fetch_latency_gauge: Gauge,
125}
126
127impl StateProviderMetrics {
128    /// Creates state-provider metrics with the given source label.
129    pub(crate) fn with_source(source: &'static str) -> Self {
130        Self::new_with_labels(&[("source", source)])
131    }
132
133    /// Records accumulated fetch latency totals.
134    pub(crate) fn record_totals(&self, stats: &StateProviderStats) {
135        let total_storage_fetch_latency = stats.total_storage_fetch_latency.duration();
136        self.total_storage_fetch_latency.record(total_storage_fetch_latency);
137        self.total_storage_fetch_latency_gauge.set(total_storage_fetch_latency.as_secs_f64());
138
139        let total_code_fetch_latency = stats.total_code_fetch_latency.duration();
140        self.total_code_fetch_latency.record(total_code_fetch_latency);
141        self.total_code_fetch_latency_gauge.set(total_code_fetch_latency.as_secs_f64());
142
143        let total_account_fetch_latency = stats.total_account_fetch_latency.duration();
144        self.total_account_fetch_latency.record(total_account_fetch_latency);
145        self.total_account_fetch_latency_gauge.set(total_account_fetch_latency.as_secs_f64());
146    }
147}
148
149impl<S: EvmStateProvider> EvmStateProvider for InstrumentedStateProvider<S> {
150    fn basic_account(&self, address: &Address) -> ProviderResult<Option<Account>> {
151        let start = Instant::now();
152        let res = self.state_provider.basic_account(address);
153        let elapsed = start.elapsed();
154        self.metrics.account_fetch_latency.record(elapsed);
155        self.stats.total_account_fetches.fetch_add(1, Ordering::Relaxed);
156        self.stats.total_account_fetch_latency.add_duration(elapsed);
157        res
158    }
159
160    fn storage(
161        &self,
162        account: Address,
163        storage_key: StorageKey,
164    ) -> ProviderResult<Option<StorageValue>> {
165        let start = Instant::now();
166        let res = self.state_provider.storage(account, storage_key);
167        let elapsed = start.elapsed();
168        self.metrics.storage_fetch_latency.record(elapsed);
169        self.stats.total_storage_fetches.fetch_add(1, Ordering::Relaxed);
170        self.stats.total_storage_fetch_latency.add_duration(elapsed);
171        res
172    }
173
174    fn bytecode_by_hash(&self, code_hash: &B256) -> ProviderResult<Option<Bytecode>> {
175        let start = Instant::now();
176        let res = self.state_provider.bytecode_by_hash(code_hash);
177        let elapsed = start.elapsed();
178        self.metrics.code_fetch_latency.record(elapsed);
179        self.stats.total_code_fetches.fetch_add(1, Ordering::Relaxed);
180        self.stats.total_code_fetch_latency.add_duration(elapsed);
181        self.stats.total_code_fetched_bytes.fetch_add(
182            res.as_ref()
183                .ok()
184                .and_then(|code| code.as_ref().map(|code| code.len()))
185                .unwrap_or_default(),
186            Ordering::Relaxed,
187        );
188        res
189    }
190
191    fn block_hash(&self, number: alloy_primitives::BlockNumber) -> ProviderResult<Option<B256>> {
192        self.state_provider.block_hash(number)
193    }
194}
195
196/// Accumulated fetch statistics from an [`InstrumentedStateProvider`].
197///
198/// Shared via `Arc` so statistics can be read after the provider is consumed.
199#[derive(Debug, Default)]
200pub struct StateProviderStats {
201    total_storage_fetches: AtomicUsize,
202    total_storage_fetch_latency: AtomicDuration,
203
204    total_code_fetches: AtomicUsize,
205    total_code_fetch_latency: AtomicDuration,
206    total_code_fetched_bytes: AtomicUsize,
207
208    total_account_fetches: AtomicUsize,
209    total_account_fetch_latency: AtomicDuration,
210}
211
212impl StateProviderStats {
213    /// Returns total number of storage fetches.
214    pub fn total_storage_fetches(&self) -> usize {
215        self.total_storage_fetches.load(Ordering::Relaxed)
216    }
217
218    /// Returns total time spent on storage fetches.
219    pub fn total_storage_fetch_latency(&self) -> Duration {
220        self.total_storage_fetch_latency.duration()
221    }
222
223    /// Returns total number of code fetches.
224    pub fn total_code_fetches(&self) -> usize {
225        self.total_code_fetches.load(Ordering::Relaxed)
226    }
227
228    /// Returns total time spent on code fetches.
229    pub fn total_code_fetch_latency(&self) -> Duration {
230        self.total_code_fetch_latency.duration()
231    }
232
233    /// Returns total amount of code fetched, in bytes.
234    pub fn total_code_fetched_bytes(&self) -> usize {
235        self.total_code_fetched_bytes.load(Ordering::Relaxed)
236    }
237
238    /// Returns total number of account fetches.
239    pub fn total_account_fetches(&self) -> usize {
240        self.total_account_fetches.load(Ordering::Relaxed)
241    }
242
243    /// Returns total time spent on account fetches.
244    pub fn total_account_fetch_latency(&self) -> Duration {
245        self.total_account_fetch_latency.duration()
246    }
247}