1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
//! The push-style half of the metric surface: [`KevyMetric`] events and
//! the sink that carries them (child module via `#[path]`, split from
//! `metric.rs` for the 500-LOC house rule; behaviour unchanged).
use std::sync::Arc;
/// A persistence event worth observing. More variants may be added; match
/// non-exhaustively (`_ => {}`) to stay forward-compatible.
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use kevy_embedded::{Config, KevyMetric, Store};
///
/// let dir = kevy_tmpdir::TmpDir::new("metric-enum-doc");
/// let seen = Arc::new(Mutex::new(Vec::new()));
/// let sink = Arc::clone(&seen);
/// let cfg = Config::default()
/// .with_persist(dir.path())
/// .with_metric_sink(move |m| sink.lock().unwrap().push(m));
/// let s = Store::open(cfg)?;
/// s.set(b"k", b"v")?;
/// s.rewrite_aof()?;
/// let seen = seen.lock().unwrap();
/// assert!(matches!(seen[0], KevyMetric::Replay { .. }));
/// assert!(matches!(seen[1], KevyMetric::Rewrite { keys: 1, .. }));
/// # Ok::<(), kevy_embedded::KevyError>(())
/// ```
#[cfg(feature = "persist")]
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum KevyMetric {
/// AOF replay finished on startup. `bytes` is the AOF size replayed.
/// Fires once per `Store::open`, totals summed across all shards.
///
/// ```
/// # use std::sync::{Arc, Mutex};
/// # use kevy_embedded::{AppendFsync, Config, KevyMetric, Store};
/// # let dir = kevy_tmpdir::TmpDir::new("metric-doc");
/// # let seen = Arc::new(Mutex::new(Vec::new()));
/// # let cfg = || {
/// # let sink = Arc::clone(&seen);
/// # Config::default()
/// # .with_persist(dir.path())
/// # .with_appendfsync(AppendFsync::Always)
/// # .with_metric_sink(move |m| sink.lock().unwrap().push(m))
/// # };
/// # let s = Store::open(cfg())?;
/// # s.set(b"a", b"1")?;
/// # s.set(b"b", b"2")?;
/// # drop(s);
/// # let s = Store::open(cfg())?;
/// let events = seen.lock().unwrap();
/// let Some(KevyMetric::Replay { commands, dropped_bytes, corrupt, .. }) = events.last().cloned() else {
/// panic!("the reopen reports its replay")
/// };
/// assert_eq!((commands, dropped_bytes, corrupt), (2, 0, false));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
Replay {
/// Commands replayed from the AOF(s).
///
/// ```
/// # use std::sync::{Arc, Mutex};
/// # use kevy_embedded::{AppendFsync, Config, KevyMetric, Store};
/// # let dir = kevy_tmpdir::TmpDir::new("metric-doc");
/// # let seen = Arc::new(Mutex::new(Vec::new()));
/// # let cfg = || {
/// # let sink = Arc::clone(&seen);
/// # Config::default()
/// # .with_persist(dir.path())
/// # .with_appendfsync(AppendFsync::Always)
/// # .with_metric_sink(move |m| sink.lock().unwrap().push(m))
/// # };
/// # let s = Store::open(cfg())?;
/// # s.set(b"a", b"1")?;
/// # s.set(b"b", b"2")?;
/// # drop(s);
/// # let s = Store::open(cfg())?;
/// let events = seen.lock().unwrap();
/// let Some(KevyMetric::Replay { commands, .. }) = events.last().cloned() else {
/// panic!("the reopen reports its replay")
/// };
/// assert_eq!(commands, 2); // the two SETs of the first open
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
commands: u64,
/// Size in bytes of the AOF file(s) replayed (measured before replay).
///
/// ```
/// # use std::sync::{Arc, Mutex};
/// # use kevy_embedded::{AppendFsync, Config, KevyMetric, Store};
/// # let dir = kevy_tmpdir::TmpDir::new("metric-doc");
/// # let seen = Arc::new(Mutex::new(Vec::new()));
/// # let cfg = || {
/// # let sink = Arc::clone(&seen);
/// # Config::default()
/// # .with_persist(dir.path())
/// # .with_appendfsync(AppendFsync::Always)
/// # .with_metric_sink(move |m| sink.lock().unwrap().push(m))
/// # };
/// # let s = Store::open(cfg())?;
/// # s.set(b"a", b"1")?;
/// # s.set(b"b", b"2")?;
/// # drop(s);
/// # let s = Store::open(cfg())?;
/// let events = seen.lock().unwrap();
/// let Some(KevyMetric::Replay { bytes, .. }) = events.last().cloned() else {
/// panic!("the reopen reports its replay")
/// };
/// assert_eq!(bytes, std::fs::metadata(dir.path().join("aof-0.aof"))?.len());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
bytes: u64,
/// Wall-clock time of the whole startup replay, in milliseconds.
///
/// ```
/// # use std::sync::{Arc, Mutex};
/// # use kevy_embedded::{AppendFsync, Config, KevyMetric, Store};
/// # let dir = kevy_tmpdir::TmpDir::new("metric-doc");
/// # let seen = Arc::new(Mutex::new(Vec::new()));
/// # let cfg = || {
/// # let sink = Arc::clone(&seen);
/// # Config::default()
/// # .with_persist(dir.path())
/// # .with_appendfsync(AppendFsync::Always)
/// # .with_metric_sink(move |m| sink.lock().unwrap().push(m))
/// # };
/// # let s = Store::open(cfg())?;
/// # s.set(b"a", b"1")?;
/// # s.set(b"b", b"2")?;
/// # drop(s);
/// # let s = Store::open(cfg())?;
/// let events = seen.lock().unwrap();
/// let Some(KevyMetric::Replay { elapsed_ms, .. }) = events.last().cloned() else {
/// panic!("the reopen reports its replay")
/// };
/// assert!(elapsed_ms < 60_000); // a two-record log replays at once
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
elapsed_ms: u64,
/// Bytes past the last replayable frame, summed across shards —
/// dropped from the live file (and quarantined). Non-zero means the
/// store recovered LESS than the file held: alert on this. A
/// 3-day production silent-loss incident was exactly this signal
/// living only in stderr.
///
/// ```
/// # use std::sync::{Arc, Mutex};
/// # use kevy_embedded::{AppendFsync, Config, KevyMetric, Store};
/// # let dir = kevy_tmpdir::TmpDir::new("metric-doc");
/// # let seen = Arc::new(Mutex::new(Vec::new()));
/// # let cfg = || {
/// # let sink = Arc::clone(&seen);
/// # Config::default()
/// # .with_persist(dir.path())
/// # .with_appendfsync(AppendFsync::Always)
/// # .with_metric_sink(move |m| sink.lock().unwrap().push(m))
/// # };
/// # let s = Store::open(cfg())?;
/// # s.set(b"a", b"1")?;
/// # s.set(b"b", b"2")?;
/// # drop(s);
/// # let s = Store::open(cfg())?;
/// let events = seen.lock().unwrap();
/// let Some(KevyMetric::Replay { dropped_bytes, .. }) = events.last().cloned() else {
/// panic!("the reopen reports its replay")
/// };
/// assert_eq!(dropped_bytes, 0); // a clean close leaves nothing to drop
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
dropped_bytes: u64,
/// True when any shard's replay stopped at a corrupt frame (vs a
/// clean end or a partial trailing frame).
///
/// ```
/// # use std::sync::{Arc, Mutex};
/// # use kevy_embedded::{AppendFsync, Config, KevyMetric, Store};
/// # let dir = kevy_tmpdir::TmpDir::new("metric-doc");
/// # let seen = Arc::new(Mutex::new(Vec::new()));
/// # let cfg = || {
/// # let sink = Arc::clone(&seen);
/// # Config::default()
/// # .with_persist(dir.path())
/// # .with_appendfsync(AppendFsync::Always)
/// # .with_metric_sink(move |m| sink.lock().unwrap().push(m))
/// # };
/// # let s = Store::open(cfg())?;
/// # s.set(b"a", b"1")?;
/// # s.set(b"b", b"2")?;
/// # drop(s);
/// # let s = Store::open(cfg())?;
/// let events = seen.lock().unwrap();
/// let Some(KevyMetric::Replay { corrupt, .. }) = events.last().cloned() else {
/// panic!("the reopen reports its replay")
/// };
/// assert!(!corrupt);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
corrupt: bool,
},
/// An AOF rewrite (compaction) completed. `before_bytes - after_bytes` is
/// the space reclaimed. Fires once per rewritten shard.
///
/// ```
/// # use std::sync::{Arc, Mutex};
/// # use kevy_embedded::{AppendFsync, Config, KevyMetric, Store};
/// # let dir = kevy_tmpdir::TmpDir::new("metric-doc");
/// # let seen = Arc::new(Mutex::new(Vec::new()));
/// # let cfg = || {
/// # let sink = Arc::clone(&seen);
/// # Config::default()
/// # .with_persist(dir.path())
/// # .with_appendfsync(AppendFsync::Always)
/// # .with_metric_sink(move |m| sink.lock().unwrap().push(m))
/// # };
/// # let s = Store::open(cfg())?;
/// for n in 0..100 {
/// s.set(b"counter", n.to_string().as_bytes())?;
/// }
/// s.rewrite_aof()?;
/// let events = seen.lock().unwrap();
/// let Some(KevyMetric::Rewrite { keys, before_bytes, after_bytes, .. }) = events.last().cloned() else {
/// panic!("the rewrite reports itself")
/// };
/// assert_eq!(keys, 1); // a hundred SETs of one key compact to one
/// assert!(after_bytes < before_bytes);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
Rewrite {
/// Keys written into the compacted AOF.
///
/// ```
/// # use std::sync::{Arc, Mutex};
/// # use kevy_embedded::{AppendFsync, Config, KevyMetric, Store};
/// # let dir = kevy_tmpdir::TmpDir::new("metric-doc");
/// # let seen = Arc::new(Mutex::new(Vec::new()));
/// # let cfg = || {
/// # let sink = Arc::clone(&seen);
/// # Config::default()
/// # .with_persist(dir.path())
/// # .with_appendfsync(AppendFsync::Always)
/// # .with_metric_sink(move |m| sink.lock().unwrap().push(m))
/// # };
/// # let s = Store::open(cfg())?;
/// for n in 0..100 {
/// s.set(b"counter", n.to_string().as_bytes())?;
/// }
/// s.rewrite_aof()?;
/// let events = seen.lock().unwrap();
/// let Some(KevyMetric::Rewrite { keys, .. }) = events.last().cloned() else {
/// panic!("the rewrite reports itself")
/// };
/// assert_eq!(keys, 1);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
keys: u64,
/// AOF size in bytes before the rewrite.
///
/// ```
/// # use std::sync::{Arc, Mutex};
/// # use kevy_embedded::{AppendFsync, Config, KevyMetric, Store};
/// # let dir = kevy_tmpdir::TmpDir::new("metric-doc");
/// # let seen = Arc::new(Mutex::new(Vec::new()));
/// # let cfg = || {
/// # let sink = Arc::clone(&seen);
/// # Config::default()
/// # .with_persist(dir.path())
/// # .with_appendfsync(AppendFsync::Always)
/// # .with_metric_sink(move |m| sink.lock().unwrap().push(m))
/// # };
/// # let s = Store::open(cfg())?;
/// for n in 0..100 {
/// s.set(b"counter", n.to_string().as_bytes())?;
/// }
/// s.rewrite_aof()?;
/// let events = seen.lock().unwrap();
/// let Some(KevyMetric::Rewrite { before_bytes, after_bytes, .. }) = events.last().cloned() else {
/// panic!("the rewrite reports itself")
/// };
/// assert!(before_bytes > after_bytes); // the hundred records before compaction
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
before_bytes: u64,
/// AOF size in bytes after the rewrite (the compacted log).
///
/// ```
/// # use std::sync::{Arc, Mutex};
/// # use kevy_embedded::{AppendFsync, Config, KevyMetric, Store};
/// # let dir = kevy_tmpdir::TmpDir::new("metric-doc");
/// # let seen = Arc::new(Mutex::new(Vec::new()));
/// # let cfg = || {
/// # let sink = Arc::clone(&seen);
/// # Config::default()
/// # .with_persist(dir.path())
/// # .with_appendfsync(AppendFsync::Always)
/// # .with_metric_sink(move |m| sink.lock().unwrap().push(m))
/// # };
/// # let s = Store::open(cfg())?;
/// for n in 0..100 {
/// s.set(b"counter", n.to_string().as_bytes())?;
/// }
/// s.rewrite_aof()?;
/// let events = seen.lock().unwrap();
/// let Some(KevyMetric::Rewrite { before_bytes, after_bytes, .. }) = events.last().cloned() else {
/// panic!("the rewrite reports itself")
/// };
/// assert!(after_bytes < before_bytes / 10); // one record where there were a hundred
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
after_bytes: u64,
/// Wall-clock time of this shard's rewrite, in milliseconds.
///
/// ```
/// # use std::sync::{Arc, Mutex};
/// # use kevy_embedded::{AppendFsync, Config, KevyMetric, Store};
/// # let dir = kevy_tmpdir::TmpDir::new("metric-doc");
/// # let seen = Arc::new(Mutex::new(Vec::new()));
/// # let cfg = || {
/// # let sink = Arc::clone(&seen);
/// # Config::default()
/// # .with_persist(dir.path())
/// # .with_appendfsync(AppendFsync::Always)
/// # .with_metric_sink(move |m| sink.lock().unwrap().push(m))
/// # };
/// # let s = Store::open(cfg())?;
/// for n in 0..100 {
/// s.set(b"counter", n.to_string().as_bytes())?;
/// }
/// s.rewrite_aof()?;
/// let events = seen.lock().unwrap();
/// let Some(KevyMetric::Rewrite { elapsed_ms, .. }) = events.last().cloned() else {
/// panic!("the rewrite reports itself")
/// };
/// assert!(elapsed_ms < 60_000);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
elapsed_ms: u64,
},
}
/// Cloneable handle to the caller's metric callback. Cheap `Arc` clone; the
/// callback runs synchronously on whichever thread emits the event (the reaper
/// thread for background rewrites, the opening thread for replay), so keep it
/// fast / non-blocking.
#[cfg(feature = "persist")]
#[derive(Clone)]
pub(crate) struct MetricSink(Arc<dyn Fn(KevyMetric) + Send + Sync>);
#[cfg(feature = "persist")]
impl MetricSink {
pub(crate) fn new(f: impl Fn(KevyMetric) + Send + Sync + 'static) -> Self {
MetricSink(Arc::new(f))
}
pub(crate) fn emit(&self, m: KevyMetric) {
(self.0)(m);
}
}
#[cfg(feature = "persist")]
impl std::fmt::Debug for MetricSink {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("MetricSink(<fn>)")
}
}