Skip to main content

kevy_embedded/
metric.rs

1//! Optional push-style metric callback. In-process embed mode has no metrics
2//! endpoint, so persistence events (AOF replay on startup, AOF rewrite/
3//! compaction) are pushed to a caller-supplied sink — wire it to Prometheus,
4//! a log line, a counter, whatever. Wire it via [`crate::Config::with_metric_sink`].
5
6use std::sync::Arc;
7
8/// A persistence event worth observing. More variants may be added; match
9/// non-exhaustively (`_ => {}`) to stay forward-compatible.
10#[derive(Debug, Clone)]
11#[non_exhaustive]
12pub enum KevyMetric {
13    /// AOF replay finished on startup. `bytes` is the AOF size replayed.
14    /// Fires once per `Store::open`, totals summed across all shards.
15    Replay {
16        /// Commands replayed from the AOF(s).
17        commands: u64,
18        /// Size in bytes of the AOF file(s) replayed (measured before replay).
19        bytes: u64,
20        /// Wall-clock time of the whole startup replay, in milliseconds.
21        elapsed_ms: u64,
22    },
23    /// An AOF rewrite (compaction) completed. `before_bytes - after_bytes` is
24    /// the space reclaimed. Fires once per rewritten shard.
25    Rewrite {
26        /// Keys written into the compacted AOF.
27        keys: u64,
28        /// AOF size in bytes before the rewrite.
29        before_bytes: u64,
30        /// AOF size in bytes after the rewrite (the compacted log).
31        after_bytes: u64,
32        /// Wall-clock time of this shard's rewrite, in milliseconds.
33        elapsed_ms: u64,
34    },
35}
36
37/// Cloneable handle to the caller's metric callback. Cheap `Arc` clone; the
38/// callback runs synchronously on whichever thread emits the event (the reaper
39/// thread for background rewrites, the opening thread for replay), so keep it
40/// fast / non-blocking.
41#[derive(Clone)]
42pub(crate) struct MetricSink(Arc<dyn Fn(KevyMetric) + Send + Sync>);
43
44impl MetricSink {
45    pub(crate) fn new(f: impl Fn(KevyMetric) + Send + Sync + 'static) -> Self {
46        MetricSink(Arc::new(f))
47    }
48
49    pub(crate) fn emit(&self, m: KevyMetric) {
50        (self.0)(m);
51    }
52}
53
54impl std::fmt::Debug for MetricSink {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        f.write_str("MetricSink(<fn>)")
57    }
58}