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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
//! Async support for metrics
//!
//! Provides async-aware metric recording with zero-cost abstractions
use crate::Timer;
use std::borrow::Cow;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Instant;
/// Async timer guard that records on drop
pub struct AsyncTimerGuard<'a> {
timer: &'a Timer,
start: Instant,
recorded: bool,
}
impl<'a> AsyncTimerGuard<'a> {
/// Creates a new `AsyncTimerGuard` for the given timer, starting timing immediately.
#[inline]
pub fn new(timer: &'a Timer) -> Self {
Self {
timer,
start: Instant::now(),
recorded: false,
}
}
/// Returns the elapsed time since the guard was created.
#[inline]
pub fn elapsed(&self) -> std::time::Duration {
self.start.elapsed()
}
/// Stops the timer and records the elapsed time if not already recorded.
#[inline]
pub fn stop(mut self) {
if !self.recorded {
self.timer.record(self.start.elapsed());
self.recorded = true;
}
}
}
impl<'a> Drop for AsyncTimerGuard<'a> {
#[inline]
fn drop(&mut self) {
if !self.recorded {
self.timer.record(self.start.elapsed());
}
}
}
/// Extension trait for async timer operations
pub trait AsyncTimerExt {
/// Start an async-aware timer
fn start_async(&self) -> AsyncTimerGuard<'_>;
/// Time an async function
fn time_async<F, Fut, T>(&self, f: F) -> TimedFuture<'_, Fut>
where
F: FnOnce() -> Fut,
Fut: Future<Output = T>;
}
impl AsyncTimerExt for Timer {
#[inline]
fn start_async(&self) -> AsyncTimerGuard<'_> {
AsyncTimerGuard::new(self)
}
#[inline]
fn time_async<F, Fut, T>(&self, f: F) -> TimedFuture<'_, Fut>
where
F: FnOnce() -> Fut,
Fut: Future<Output = T>,
{
TimedFuture {
timer: self,
future: f(),
start: Some(Instant::now()),
}
}
}
/// Future wrapper that times execution
pub struct TimedFuture<'a, F> {
timer: &'a Timer,
future: F,
start: Option<Instant>,
}
impl<'a, F, T> Future for TimedFuture<'a, F>
where
F: Future<Output = T>,
{
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
// SAFETY: `TimedFuture` is `!Unpin`. We project through the outer
// `Pin<&mut TimedFuture>` to access its fields. The `future` field is
// structurally pinned — once `TimedFuture` is pinned, `future` is
// guaranteed to stay at the same memory address.
let this = unsafe { self.get_unchecked_mut() };
// SAFETY: `this.future` is structurally pinned (see above). Projecting
// to `Pin<&mut F>` is sound because we never move `future` out of `this`.
let future = unsafe { Pin::new_unchecked(&mut this.future) };
match future.poll(cx) {
Poll::Ready(result) => {
if let Some(start) = this.start.take() {
this.timer.record(start.elapsed());
}
Poll::Ready(result)
}
Poll::Pending => Poll::Pending,
}
}
}
/// Batched metric updates for async contexts
pub struct AsyncMetricBatch {
updates: Vec<MetricUpdate>,
}
enum MetricUpdate {
CounterInc { name: Cow<'static, str>, value: u64 },
GaugeSet { name: Cow<'static, str>, value: f64 },
TimerRecord { name: Cow<'static, str>, nanos: u64 },
RateTick { name: Cow<'static, str> },
}
impl AsyncMetricBatch {
/// Create new batch
pub fn new() -> Self {
Self {
updates: Vec::with_capacity(64),
}
}
}
impl Default for AsyncMetricBatch {
fn default() -> Self {
Self::new()
}
}
impl AsyncMetricBatch {
/// Add counter increment
///
/// `name` accepts both `&'static str` (string literals) and owned
/// `String`s via `impl Into<Cow<'static, str>>` — runtime-derived names
/// no longer require `Box::leak`.
#[inline]
pub fn counter_inc(&mut self, name: impl Into<Cow<'static, str>>, value: u64) {
self.updates.push(MetricUpdate::CounterInc {
name: name.into(),
value,
});
}
/// Add gauge set
///
/// `name` accepts both `&'static str` and owned `String`s — see
/// [`Self::counter_inc`] for details.
#[inline]
pub fn gauge_set(&mut self, name: impl Into<Cow<'static, str>>, value: f64) {
self.updates.push(MetricUpdate::GaugeSet {
name: name.into(),
value,
});
}
/// Add timer recording
///
/// `name` accepts both `&'static str` and owned `String`s — see
/// [`Self::counter_inc`] for details.
#[inline]
pub fn timer_record(&mut self, name: impl Into<Cow<'static, str>>, nanos: u64) {
self.updates.push(MetricUpdate::TimerRecord {
name: name.into(),
nanos,
});
}
/// Add rate tick
///
/// `name` accepts both `&'static str` and owned `String`s — see
/// [`Self::counter_inc`] for details.
#[inline]
pub fn rate_tick(&mut self, name: impl Into<Cow<'static, str>>) {
self.updates
.push(MetricUpdate::RateTick { name: name.into() });
}
/// Flush all updates to metrics
pub fn flush(self, metrics: &crate::MetricsCore) {
for update in self.updates {
match update {
MetricUpdate::CounterInc { name, value } => {
metrics.counter(&name).add(value);
}
MetricUpdate::GaugeSet { name, value } => {
metrics.gauge(&name).set(value);
}
MetricUpdate::TimerRecord { name, nanos } => {
metrics.timer(&name).record_ns(nanos);
}
MetricUpdate::RateTick { name } => {
metrics.rate(&name).tick();
}
}
}
}
/// Check if batch is empty
#[inline]
pub fn is_empty(&self) -> bool {
self.updates.is_empty()
}
/// Get number of pending updates
#[inline]
pub fn len(&self) -> usize {
self.updates.len()
}
}
/// Async-aware metrics batcher with automatic background flushing.
///
/// Accumulates metric updates and flushes them in batches, either when
/// `max_batch_size` is reached or on the configured `flush_interval`.
/// Requires the `async` feature.
#[cfg(feature = "async")]
pub struct AsyncMetricsBatcher {
batch: tokio::sync::Mutex<AsyncMetricBatch>,
flush_interval: std::time::Duration,
max_batch_size: usize,
}
#[cfg(feature = "async")]
impl AsyncMetricsBatcher {
/// Create a new batcher with the given flush interval and maximum batch size.
pub fn new(flush_interval: std::time::Duration, max_batch_size: usize) -> Self {
Self {
batch: tokio::sync::Mutex::new(AsyncMetricBatch::new()),
flush_interval,
max_batch_size,
}
}
/// Enqueue a metric update; flushes the batch in the background if
/// `max_batch_size` is reached.
pub async fn record(&self, update: impl FnOnce(&mut AsyncMetricBatch)) {
let mut batch = self.batch.lock().await;
update(&mut batch);
if batch.len() >= self.max_batch_size {
let batch = std::mem::take(&mut *batch);
// Flush in background
tokio::spawn(async move {
batch.flush(crate::metrics());
});
}
}
/// Spawn a Tokio task that flushes the batch on the configured interval.
///
/// The caller must hold an `Arc<Self>` for the task to keep the batcher alive.
pub fn start_flusher(self: std::sync::Arc<Self>) {
tokio::spawn(async move {
let mut interval = tokio::time::interval(self.flush_interval);
loop {
interval.tick().await;
let batch = {
let mut guard = self.batch.lock().await;
if guard.is_empty() {
continue;
}
std::mem::take(&mut *guard)
};
batch.flush(crate::metrics());
}
});
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_async_timer_guard() {
let timer = Timer::new();
{
let _guard = timer.start_async();
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert_eq!(timer.count(), 1);
assert!(timer.average() >= std::time::Duration::from_millis(9));
}
#[test]
fn test_metric_batch() {
let mut batch = AsyncMetricBatch::new();
batch.counter_inc("test", 5);
batch.gauge_set("test", 42.5);
batch.timer_record("test", 1000);
batch.rate_tick("test");
assert_eq!(batch.len(), 4);
assert!(!batch.is_empty());
let metrics = crate::MetricsCore::new();
batch.flush(&metrics);
assert_eq!(metrics.counter("test").get(), 5);
assert_eq!(metrics.gauge("test").get(), 42.5);
assert_eq!(metrics.timer("test").count(), 1);
metrics.rate("test").tick_n(1); // Simulate a tick
}
#[test]
fn test_async_timer_guard_elapsed_and_stop() {
let timer = Timer::new();
let guard = timer.start_async();
// Exercise elapsed path
let _elapsed = guard.elapsed();
// Exercise explicit stop path
guard.stop();
assert_eq!(timer.count(), 1);
}
// Manually poll a TimedFuture that is immediately ready to cover the Ready branch
#[test]
fn test_timed_future_manual_poll_ready() {
let timer = Timer::new();
// Create a future that is immediately ready without needing an async runtime
let mut timed = timer.time_async(|| async { 7 });
// Build a no-op waker/context to poll manually
fn dummy_raw_waker() -> std::task::RawWaker {
fn clone(_: *const ()) -> std::task::RawWaker {
dummy_raw_waker()
}
fn wake(_: *const ()) {}
fn wake_by_ref(_: *const ()) {}
fn drop(_: *const ()) {}
const VTABLE: std::task::RawWakerVTable =
std::task::RawWakerVTable::new(clone, wake, wake_by_ref, drop);
std::task::RawWaker::new(std::ptr::null(), &VTABLE)
}
// SAFETY: `dummy_raw_waker` builds a no-op `RawWaker` whose vtable
// functions are all no-ops and the data pointer is always null. The
// waker is only used within this test to drive a single synchronous poll.
let waker = unsafe { std::task::Waker::from_raw(dummy_raw_waker()) };
let mut cx = std::task::Context::from_waker(&waker);
// SAFETY: `timed` is a local variable that is not moved for the
// remainder of this test function. Pinning it here satisfies the
// `Future::poll` contract.
let mut pinned = unsafe { std::pin::Pin::new_unchecked(&mut timed) };
match std::future::Future::poll(pinned.as_mut(), &mut cx) {
std::task::Poll::Ready(v) => assert_eq!(v, 7),
std::task::Poll::Pending => panic!("future should be immediately ready"),
}
// Ensure the timer recorded the elapsed time on Ready
assert_eq!(timer.count(), 1);
}
#[cfg(feature = "async")]
#[tokio::test]
async fn test_timed_future() {
let timer = Timer::new();
let result = timer
.time_async(|| async {
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
42
})
.await;
assert_eq!(result, 42);
assert_eq!(timer.count(), 1);
assert!(timer.average() >= std::time::Duration::from_millis(9));
}
}