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