hick-trace 0.1.0

Tracing-or-noop diagnostic macro shim and backend-agnostic stats/metrics primitives for the hick mDNS stack.
Documentation
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Tracing-or-noop diagnostic macro shim and backend-agnostic stats/metrics
//! primitives for the hick mDNS stack.
//!
//! # Macros
//!
//! The five macros `trace!`, `debug!`, `info!`, `warn!`, and `error!` are
//! always available as `hick_trace::<name>!(...)`. When the `tracing` Cargo
//! feature is enabled they delegate to the real [`tracing`] crate; otherwise
//! they discard every argument without emitting code.
//!
//! # `stats` / `metrics` feature
//!
//! Enabling `stats` unlocks [`stats::Stats`] and [`stats::StatsSnapshot`]: a
//! set of atomic counters and gauges that are `no_std`-safe. Enabling
//! `metrics` additionally forwards every counter/gauge update to the
//! [`metrics`] facade (requires `std`).

#![cfg_attr(not(feature = "metrics"), no_std)]

// ── Tracing shim ────────────────────────────────────────────────────────────

#[cfg(feature = "tracing")]
pub use tracing::{debug, debug_span, error, info, info_span, trace, trace_span, warn};

/// Token-consuming no-op for all five diagnostic macros when `tracing` is
/// disabled. Every argument expression is type-checked but **never executed**:
/// each value is referenced inside an `if false { }` block, which the compiler
/// eliminates entirely while still seeing the expression as "used" (no
/// `unused_variables` warning, no side effects, no alloc, no panics).
///
/// # Supported forms
///
/// | Form | Example |
/// |------|---------|
/// | Positional format string | `debug!("n={}", n)` |
/// | `key = value` | `debug!(x = val, "msg")` |
/// | `key = %value` (Display) | `debug!(x = %val, "msg")` |
/// | `key = ?value` (Debug) | `debug!(x = ?val, "msg")` |
/// | Bare `%value` / `?value` | `debug!(%val)` |
/// | Bare `ident` shorthand | `debug!(x, "msg")` |
/// | `target: "t", ...` prefix | `debug!(target: "t", x = 1, "m")` |
///
/// # Unsupported forms
///
/// The following `tracing` forms are deliberately **not** supported:
/// `name: "..."`, `parent: span`, dotted field names (`a.b`), and
/// string-literal field keys (`"k" = v`). The codebase stays within the
/// subset above; any violation is caught as a compile error in the default
/// (no-tracing) build.
///
/// # Implementation note
///
/// Each value expression `$val` expands to `if false { let _ = &$val; }`.
/// The compiler eliminates the dead branch during MIR building, so there is
/// zero runtime cost. A plain `let _ = &$val;` (the previous approach)
/// evaluated the expression to produce the reference even though it was
/// discarded, causing side effects (allocs, panics, counter bumps) to run
/// in disabled builds.
#[doc(hidden)]
#[cfg(not(feature = "tracing"))]
#[macro_export]
macro_rules! __hick_trace_noop {
  (target: $tgt:expr, $($rest:tt)*) => {
    { if false { let _ = &$tgt; } $crate::__hick_trace_noop!($($rest)*) }
  };

  ($key:ident = %$val:expr, $($rest:tt)*) => {
    { if false { let _ = &$val; } $crate::__hick_trace_noop!($($rest)*) }
  };
  ($key:ident = %$val:expr) => {
    { if false { let _ = &$val; } }
  };

  ($key:ident = ?$val:expr, $($rest:tt)*) => {
    { if false { let _ = &$val; } $crate::__hick_trace_noop!($($rest)*) }
  };
  ($key:ident = ?$val:expr) => {
    { if false { let _ = &$val; } }
  };

  ($key:ident = $val:expr, $($rest:tt)*) => {
    { if false { let _ = &$val; } $crate::__hick_trace_noop!($($rest)*) }
  };
  ($key:ident = $val:expr) => {
    { if false { let _ = &$val; } }
  };

  // Matches BEFORE the format-string literal arm so that a bare ident that
  // is NOT a string literal is consumed correctly.
  ($key:ident, $($rest:tt)*) => {
    { if false { let _ = &$key; } $crate::__hick_trace_noop!($($rest)*) }
  };
  ($key:ident) => {
    { if false { let _ = &$key; } }
  };

  // ── Bare `%value` ────────────────────────────────────────────────────────
  (%$val:expr, $($rest:tt)*) => {
    { if false { let _ = &$val; } $crate::__hick_trace_noop!($($rest)*) }
  };
  (%$val:expr) => {
    { if false { let _ = &$val; } }
  };

  (?$val:expr, $($rest:tt)*) => {
    { if false { let _ = &$val; } $crate::__hick_trace_noop!($($rest)*) }
  };
  (?$val:expr) => {
    { if false { let _ = &$val; } }
  };

  ($fmt:literal $(, $arg:expr)* $(,)?) => {
    { if false { let _ = ::core::format_args!($fmt $(, $arg)*); } }
  };

  () => {{}};
}

#[cfg(not(feature = "tracing"))]
pub use __hick_trace_noop as trace;
#[cfg(not(feature = "tracing"))]
pub use __hick_trace_noop as debug;
#[cfg(not(feature = "tracing"))]
pub use __hick_trace_noop as info;
#[cfg(not(feature = "tracing"))]
pub use __hick_trace_noop as warn;
#[cfg(not(feature = "tracing"))]
pub use __hick_trace_noop as error;

/// No-op span returned when the `tracing` feature is disabled.
///
/// Implements `.entered()` and `.enter()` so that
/// `hick_trace::info_span!(...).entered()` compiles in both tracing and
/// no-tracing builds.
#[cfg(not(feature = "tracing"))]
#[derive(Debug)]
pub struct NoopSpan;

#[cfg(not(feature = "tracing"))]
impl NoopSpan {
  /// Enters the span (no-op). Returns `self` so it acts as a drop-guard.
  #[inline]
  pub fn entered(self) -> Self {
    self
  }
  /// Borrows the span and returns a new no-op guard (matches tracing's API).
  #[inline]
  pub fn enter(&self) -> Self {
    NoopSpan
  }
}

/// Token-consuming no-op for span macros when `tracing` is disabled.
/// Returns a [`NoopSpan`] so callers may use `.entered()` / `.enter()`
/// without compile errors. Uses the same field-consuming grammar as
/// [`__hick_trace_noop`] so variables passed as span fields are not flagged
/// as unused.
#[doc(hidden)]
#[cfg(not(feature = "tracing"))]
#[macro_export]
macro_rules! __hick_trace_noop_span {
  // Strip target prefix.
  (target: $tgt:expr, $($rest:tt)*) => {
    { if false { let _ = &$tgt; } $crate::__hick_trace_noop_span!($($rest)*) }
  };

  // Span name only (the required first argument after an optional target).
  // Any remaining tokens are field key=value pairs — consume them via the
  // diagnostic no-op and return the NoopSpan.
  ($name:literal, $($fields:tt)*) => {
    { $crate::__hick_trace_noop!($($fields)*); $crate::NoopSpan }
  };
  ($name:literal) => {
    $crate::NoopSpan
  };

  // Fallback: consume everything, return NoopSpan.
  ($($tt:tt)*) => {
    { $crate::__hick_trace_noop!($($tt)*); $crate::NoopSpan }
  };
}

#[cfg(not(feature = "tracing"))]
pub use __hick_trace_noop_span as trace_span;
#[cfg(not(feature = "tracing"))]
pub use __hick_trace_noop_span as debug_span;
#[cfg(not(feature = "tracing"))]
pub use __hick_trace_noop_span as info_span;

#[cfg(feature = "stats")]
pub mod stats {
  //! Backend-agnostic atomic counters and gauges for the hick mDNS stack.
  //!
  //! [`Stats`] owns one atomic counter per counter and gauge. All loads and
  //! stores use `Relaxed` ordering (sufficient for monotone counters where
  //! precise cross-thread ordering is not required).
  //!
  //! On targets that have native 64-bit atomics (`target_has_atomic = "64"`)
  //! [`core::sync::atomic::AtomicU64`] is used directly. On 32-bit embedded
  //! targets (e.g. `thumbv7em-none-eabihf`) [`portable_atomic::AtomicU64`]
  //! provides the same API via software emulation.
  //!
  //! When the `metrics` Cargo feature is also enabled, every counter increment
  //! and gauge update additionally forwards the value to the [`metrics`] facade.

  #[cfg(target_has_atomic = "64")]
  use core::sync::atomic::{AtomicU64, Ordering::Relaxed};
  #[cfg(not(target_has_atomic = "64"))]
  use portable_atomic::{AtomicU64, Ordering::Relaxed};

  macro_rules! declare_counters {
    ($($field:ident => $metric:literal),* $(,)?) => {
      $(
        #[inline]
        pub fn $field(&self, by: u64) {
          self.$field.fetch_add(by, Relaxed);
          #[cfg(feature = "metrics")]
          ::metrics::counter!($metric).increment(by);
        }
      )*
    };
  }

  macro_rules! declare_gauges {
    ($(
      $field:ident => $metric:literal :
        incr = $incr:ident,
        decr = $decr:ident,
        set  = $set:ident
    ),* $(,)?) => {
      $(
        #[inline]
        pub fn $incr(&self, by: u64) {
          self.$field.fetch_add(by, Relaxed);
          #[cfg(feature = "metrics")]
          ::metrics::gauge!($metric).increment(by as f64);
        }

        #[inline]
        pub fn $decr(&self, by: u64) {
          self.$field.fetch_sub(by, Relaxed);
          #[cfg(feature = "metrics")]
          ::metrics::gauge!($metric).decrement(by as f64);
        }

        /// Store an absolute value into this gauge.
        ///
        /// Note: values above 2^53 lose precision when forwarded to the
        /// `f64` metrics gauge.
        #[inline]
        pub fn $set(&self, v: u64) {
          self.$field.store(v, Relaxed);
          #[cfg(feature = "metrics")]
          ::metrics::gauge!($metric).set(v as f64);
        }
      )*
    };
  }

  /// Atomic counters and gauges for a single mDNS stack instance.
  ///
  /// Construct via [`Stats::default()`]; all fields start at zero.
  #[derive(Default, Debug)]
  pub struct Stats {
    // ── Counters ──────────────────────────────────────────────────────────
    packets_rx: AtomicU64,
    packets_tx: AtomicU64,
    bytes_rx: AtomicU64,
    bytes_tx: AtomicU64,
    packets_dropped: AtomicU64,
    parse_errors: AtomicU64,
    send_errors: AtomicU64,
    questions_rx: AtomicU64,
    answers_rx: AtomicU64,
    answers_collected: AtomicU64,
    answers_suppressed_kas: AtomicU64,
    duplicate_questions_suppressed: AtomicU64,
    responses_tx: AtomicU64,
    probes_tx: AtomicU64,
    announcements_tx: AtomicU64,
    goodbyes_tx: AtomicU64,
    conflicts: AtomicU64,
    renames: AtomicU64,
    cache_inserts: AtomicU64,
    cache_refreshes: AtomicU64,
    cache_evictions: AtomicU64,
    cache_expirations: AtomicU64,
    queries_started: AtomicU64,
    queries_done: AtomicU64,
    queries_timeout: AtomicU64,
    services_registered: AtomicU64,
    services_established: AtomicU64,
    // ── Gauges ────────────────────────────────────────────────────────────
    cache_size: AtomicU64,
    queries_active: AtomicU64,
    services_active: AtomicU64,
  }

  impl Stats {
    declare_counters! {
      packets_rx => "mdns_packets_rx",
      packets_tx => "mdns_packets_tx",
      bytes_rx => "mdns_bytes_rx",
      bytes_tx => "mdns_bytes_tx",
      packets_dropped => "mdns_packets_dropped",
      parse_errors => "mdns_parse_errors",
      send_errors => "mdns_send_errors",
      questions_rx => "mdns_questions_rx",
      answers_rx => "mdns_answers_rx",
      answers_collected => "mdns_answers_collected",
      answers_suppressed_kas => "mdns_answers_suppressed_kas",
      duplicate_questions_suppressed => "mdns_duplicate_questions_suppressed",
      responses_tx => "mdns_responses_tx",
      probes_tx => "mdns_probes_tx",
      announcements_tx => "mdns_announcements_tx",
      goodbyes_tx => "mdns_goodbyes_tx",
      conflicts => "mdns_conflicts",
      renames => "mdns_renames",
      cache_inserts => "mdns_cache_inserts",
      cache_refreshes => "mdns_cache_refreshes",
      cache_evictions => "mdns_cache_evictions",
      cache_expirations => "mdns_cache_expirations",
      queries_started => "mdns_queries_started",
      queries_done => "mdns_queries_done",
      queries_timeout => "mdns_queries_timeout",
      services_registered => "mdns_services_registered",
      services_established => "mdns_services_established",
    }

    declare_gauges! {
      cache_size => "mdns_cache_size" :
        incr = incr_cache_size,
        decr = decr_cache_size,
        set  = set_cache_size,
      queries_active => "mdns_queries_active" :
        incr = incr_queries_active,
        decr = decr_queries_active,
        set  = set_queries_active,
      services_active => "mdns_services_active" :
        incr = incr_services_active,
        decr = decr_services_active,
        set  = set_services_active,
    }

    /// Load a consistent snapshot of every counter and gauge.
    ///
    /// Each field is loaded independently with Relaxed ordering; the snapshot
    /// is not guaranteed to reflect a single instant in time but is sufficient
    /// for periodic reporting.
    pub fn snapshot(&self) -> StatsSnapshot {
      StatsSnapshot {
        packets_rx: self.packets_rx.load(Relaxed),
        packets_tx: self.packets_tx.load(Relaxed),
        bytes_rx: self.bytes_rx.load(Relaxed),
        bytes_tx: self.bytes_tx.load(Relaxed),
        packets_dropped: self.packets_dropped.load(Relaxed),
        parse_errors: self.parse_errors.load(Relaxed),
        send_errors: self.send_errors.load(Relaxed),
        questions_rx: self.questions_rx.load(Relaxed),
        answers_rx: self.answers_rx.load(Relaxed),
        answers_collected: self.answers_collected.load(Relaxed),
        answers_suppressed_kas: self.answers_suppressed_kas.load(Relaxed),
        duplicate_questions_suppressed: self.duplicate_questions_suppressed.load(Relaxed),
        responses_tx: self.responses_tx.load(Relaxed),
        probes_tx: self.probes_tx.load(Relaxed),
        announcements_tx: self.announcements_tx.load(Relaxed),
        goodbyes_tx: self.goodbyes_tx.load(Relaxed),
        conflicts: self.conflicts.load(Relaxed),
        renames: self.renames.load(Relaxed),
        cache_inserts: self.cache_inserts.load(Relaxed),
        cache_refreshes: self.cache_refreshes.load(Relaxed),
        cache_evictions: self.cache_evictions.load(Relaxed),
        cache_expirations: self.cache_expirations.load(Relaxed),
        queries_started: self.queries_started.load(Relaxed),
        queries_done: self.queries_done.load(Relaxed),
        queries_timeout: self.queries_timeout.load(Relaxed),
        services_registered: self.services_registered.load(Relaxed),
        services_established: self.services_established.load(Relaxed),
        cache_size: self.cache_size.load(Relaxed),
        queries_active: self.queries_active.load(Relaxed),
        services_active: self.services_active.load(Relaxed),
      }
    }
  }

  /// Point-in-time snapshot of every [`Stats`] counter and gauge.
  #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
  pub struct StatsSnapshot {
    // Counters
    pub packets_rx: u64,
    pub packets_tx: u64,
    pub bytes_rx: u64,
    pub bytes_tx: u64,
    pub packets_dropped: u64,
    pub parse_errors: u64,
    pub send_errors: u64,
    pub questions_rx: u64,
    pub answers_rx: u64,
    pub answers_collected: u64,
    pub answers_suppressed_kas: u64,
    pub duplicate_questions_suppressed: u64,
    pub responses_tx: u64,
    pub probes_tx: u64,
    pub announcements_tx: u64,
    pub goodbyes_tx: u64,
    pub conflicts: u64,
    pub renames: u64,
    pub cache_inserts: u64,
    pub cache_refreshes: u64,
    pub cache_evictions: u64,
    pub cache_expirations: u64,
    pub queries_started: u64,
    pub queries_done: u64,
    pub queries_timeout: u64,
    pub services_registered: u64,
    pub services_established: u64,
    // Gauges
    pub cache_size: u64,
    pub queries_active: u64,
    pub services_active: u64,
  }
}

#[cfg(test)]
mod tests;