Skip to main content

snapshot_bench/
snapshot_bench.rs

1//! What an idle store writes: how often the five-minute compaction replaces
2//! the snapshot, and how many bytes that is.
3//!
4//! Starts a store at the default capacity holding `KEYS` keys whose lifetimes
5//! outlast the run, then asks nothing more of it. Once a second it checks
6//! whether `auth.snapshot` has been replaced, and every five minutes, and at
7//! the end, it prints the counts so far. On Linux it also prints what the
8//! process passed to `write` (`/proc/self/io`); `strace -f -c -e
9//! trace=fsync,fdatasync` around it counts the syncs.
10//!
11//! Run for an hour with
12//! `cargo run --release -p pb-mapper-auth --example snapshot_bench -- 3600`.
13
14use std::error::Error;
15use std::time::{Duration, Instant, SystemTime};
16
17use pb_mapper_auth::{
18    ADMIN_KEY_ID, AuthConfig, AuthRuntime, DEFAULT_MAX_TEMP_KEY_TTL, DEFAULT_TEMP_KEY_CAPACITY,
19    LegacyProtocolPolicy,
20};
21use pb_mapper_core::test_support::{TEST_ADMIN_KEY_BYTES, TempPath};
22
23type BenchResult<T> = Result<T, Box<dyn Error + Send + Sync>>;
24
25/// The keys the store holds.
26const KEYS: usize = 100;
27/// How often the counts are printed.
28const REPORT_EVERY: Duration = Duration::from_secs(5 * 60);
29
30/// `wchar` and `syscw` from `/proc/self/io`: bytes passed to write calls,
31/// and how many there were.
32#[cfg(target_os = "linux")]
33fn written() -> Option<(u64, u64)> {
34    let io = std::fs::read_to_string("/proc/self/io").ok()?;
35    let field = |name: &str| {
36        io.lines()
37            .find_map(|line| line.strip_prefix(name)?.trim().parse::<u64>().ok())
38    };
39    Some((field("wchar:")?, field("syscw:")?))
40}
41
42#[cfg(not(target_os = "linux"))]
43fn written() -> Option<(u64, u64)> {
44    None
45}
46
47struct Counts {
48    rewrites: u64,
49    snapshot_bytes: u64,
50    written_at_start: Option<(u64, u64)>,
51}
52
53impl Counts {
54    fn report(&self, elapsed: Duration) {
55        let mut line = format!(
56            "case=idle elapsed_s={} rewrites={} snapshot_bytes={}",
57            elapsed.as_secs(),
58            self.rewrites,
59            self.snapshot_bytes
60        );
61        if let (Some((wchar, syscw)), Some((wchar0, syscw0))) = (written(), self.written_at_start) {
62            line.push_str(&format!(
63                " write_bytes={} write_calls={}",
64                wchar - wchar0,
65                syscw - syscw0
66            ));
67        }
68        println!("{line}");
69    }
70}
71
72#[tokio::main]
73async fn main() -> BenchResult<()> {
74    let seconds = std::env::args()
75        .nth(1)
76        .map(|seconds| seconds.parse::<u64>())
77        .transpose()?
78        .unwrap_or(3600);
79    let state_dir = TempPath::new("snapshot-bench");
80    let config = AuthConfig {
81        state_dir: state_dir.to_path_buf(),
82        max_temporary_keys: DEFAULT_TEMP_KEY_CAPACITY,
83        max_temporary_key_ttl: DEFAULT_MAX_TEMP_KEY_TTL,
84        legacy_protocol: LegacyProtocolPolicy::Deny,
85    };
86    let runtime = AuthRuntime::start(TEST_ADMIN_KEY_BYTES, config).await?;
87    let admin = runtime.authenticate_presented(ADMIN_KEY_ID, &TEST_ADMIN_KEY_BYTES)?;
88    for _ in 0..KEYS {
89        runtime
90            .issue(&admin, DEFAULT_MAX_TEMP_KEY_TTL, None)
91            .await?;
92    }
93
94    let snapshot = state_dir.join("auth.snapshot");
95    let version = || -> Option<(SystemTime, u64)> {
96        let metadata = std::fs::metadata(&snapshot).ok()?;
97        Some((metadata.modified().ok()?, metadata.len()))
98    };
99    let mut counts = Counts {
100        rewrites: 0,
101        snapshot_bytes: 0,
102        written_at_start: written(),
103    };
104    let mut seen = version();
105    let start = Instant::now();
106    // For telling the idle hours apart in a trace of the run.
107    let since_epoch = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
108    println!("# idle from unix_ms={}", since_epoch.as_millis());
109    let end = start + Duration::from_secs(seconds);
110    let mut next_report = start + REPORT_EVERY;
111    let mut second = tokio::time::interval(Duration::from_secs(1));
112    while Instant::now() < end {
113        second.tick().await;
114        let now = version();
115        if now != seen {
116            counts.rewrites += 1;
117            counts.snapshot_bytes += now.map_or(0, |(_, len)| len);
118            seen = now;
119        }
120        if Instant::now() >= next_report {
121            counts.report(start.elapsed());
122            next_report += REPORT_EVERY;
123        }
124    }
125    counts.report(start.elapsed());
126
127    drop(admin);
128    runtime.shutdown_actor().await;
129    Ok(())
130}