reth_db_api/
database_metrics.rs

1use metrics::{counter, gauge, histogram, Label};
2use std::sync::Arc;
3
4/// Represents a type that can report metrics, used mainly with the database. The `report_metrics`
5/// method can be used as a prometheus hook.
6pub trait DatabaseMetrics {
7    /// Reports metrics for the database.
8    fn report_metrics(&self) {
9        for (name, value, labels) in self.gauge_metrics() {
10            gauge!(name, labels).set(value);
11        }
12
13        for (name, value, labels) in self.counter_metrics() {
14            counter!(name, labels).increment(value);
15        }
16
17        for (name, value, labels) in self.histogram_metrics() {
18            histogram!(name, labels).record(value);
19        }
20    }
21
22    /// Returns a list of [Gauge](metrics::Gauge) metrics for the database.
23    fn gauge_metrics(&self) -> Vec<(&'static str, f64, Vec<Label>)> {
24        vec![]
25    }
26
27    /// Returns a list of [Counter](metrics::Counter) metrics for the database.
28    fn counter_metrics(&self) -> Vec<(&'static str, u64, Vec<Label>)> {
29        vec![]
30    }
31
32    /// Returns a list of [Histogram](metrics::Histogram) metrics for the database.
33    fn histogram_metrics(&self) -> Vec<(&'static str, f64, Vec<Label>)> {
34        vec![]
35    }
36}
37
38impl<DB: DatabaseMetrics> DatabaseMetrics for Arc<DB> {
39    fn report_metrics(&self) {
40        <DB as DatabaseMetrics>::report_metrics(self)
41    }
42}
43
44/// The type used to store metadata about the database.
45#[derive(Debug, Default)]
46pub struct DatabaseMetadataValue {
47    /// The freelist size
48    freelist_size: Option<usize>,
49}
50
51impl DatabaseMetadataValue {
52    /// Creates a new [`DatabaseMetadataValue`] with the given freelist size.
53    pub const fn new(freelist_size: Option<usize>) -> Self {
54        Self { freelist_size }
55    }
56
57    /// Returns the freelist size, if available.
58    pub const fn freelist_size(&self) -> Option<usize> {
59        self.freelist_size
60    }
61}
62
63/// Includes a method to return a [`DatabaseMetadataValue`] type, which can be used to dynamically
64/// retrieve information about the database.
65pub trait DatabaseMetadata {
66    /// Returns a metadata type, [`DatabaseMetadataValue`] for the database.
67    fn metadata(&self) -> DatabaseMetadataValue;
68}
69
70impl<DB: DatabaseMetadata> DatabaseMetadata for Arc<DB> {
71    fn metadata(&self) -> DatabaseMetadataValue {
72        <DB as DatabaseMetadata>::metadata(self)
73    }
74}