Skip to main content

miden_node_store/state/
disk_monitor.rs

1use std::path::{Path, PathBuf};
2use std::time::Duration;
3
4use miden_node_tracing::spawn::spawn_blocking_in_current_span;
5use miden_node_tracing::{instrument, miden_span_record};
6use miden_node_utils::shutdown::CancellationToken;
7
8use crate::state::State;
9
10impl State {
11    /// Spawns a background task that periodically records the on-disk size of every store data path
12    /// as `OTel` span attributes.
13    pub fn spawn_disk_monitor(&self, shutdown: CancellationToken) -> tokio::task::JoinHandle<()> {
14        let data_directory = self.data_directory.clone();
15
16        tokio::spawn(async move {
17            let mut interval = tokio::time::interval(Duration::from_mins(5));
18            loop {
19                tokio::select! {
20                    () = shutdown.cancelled() => return,
21                    _ = interval.tick() => {},
22                }
23                let _ = measure_disk_space_usage(data_directory.clone()).await;
24            }
25        })
26    }
27}
28
29#[instrument(name = "measure_disk_space_usage", err)]
30async fn measure_disk_space_usage(data_dir: PathBuf) -> Result<(), tokio::task::JoinError> {
31    let usage = spawn_blocking_in_current_span(move || measure_disk_usage_bytes(&data_dir)).await?;
32    miden_span_record!(
33        db.sqlite.size = usage.sqlite_db,
34        db.sqlite.wal.size = usage.sqlite_wal,
35        db.block_store.size = usage.block_store,
36        db.account_tree.size = usage.account_tree,
37        db.nullifier_tree.size = usage.nullifier_tree,
38        db.account_state_forest.size = usage.account_state_forest
39    );
40
41    Ok(())
42}
43
44/// Byte counts for each on-disk storage component.
45struct DiskUsage {
46    sqlite_db: u64,
47    sqlite_wal: u64,
48    block_store: u64,
49    account_tree: u64,
50    nullifier_tree: u64,
51    account_state_forest: u64,
52}
53
54/// Collects on-disk byte sizes for every store data path under `data_dir`.
55fn measure_disk_usage_bytes(data_dir: &Path) -> DiskUsage {
56    DiskUsage {
57        sqlite_db: path_size_bytes(&data_dir.join("miden-store.sqlite3")),
58        sqlite_wal: path_size_bytes(&data_dir.join("miden-store.sqlite3-wal")),
59        block_store: dir_size_bytes(&data_dir.join("blocks")),
60        account_tree: dir_size_bytes(&data_dir.join("accounttree")),
61        nullifier_tree: dir_size_bytes(&data_dir.join("nullifiertree")),
62        account_state_forest: dir_size_bytes(&data_dir.join("accountstateforest")),
63    }
64}
65
66/// Returns the byte length of the file at `path`, or `0` if it does not exist.
67fn path_size_bytes(path: &Path) -> u64 {
68    fs_err::metadata(path).map_or(0, |m| m.len())
69}
70
71/// Returns the total byte length of all files in `path` iteratively, or `0` on any error.
72fn dir_size_bytes(path: &Path) -> u64 {
73    let mut to_process = vec![path.to_path_buf()];
74    let mut total = 0u64;
75    while let Some(dir) = to_process.pop() {
76        let Ok(entries) = fs_err::read_dir(&dir) else {
77            continue;
78        };
79        for entry in entries.flatten() {
80            if let Ok(meta) = entry.metadata() {
81                if meta.is_dir() {
82                    to_process.push(entry.path());
83                } else {
84                    total += meta.len();
85                }
86            }
87        }
88    }
89    total
90}