Skip to main content

miden_node_tracing/
attribute.rs

1use std::fmt::{self, Display, Formatter};
2use std::path::{Path, PathBuf};
3use std::time::Duration;
4
5use miden_protocol::Word;
6use miden_protocol::account::{AccountId, AccountIdPrefix, StorageMapKey, StorageSlotName};
7use miden_protocol::batch::BatchId;
8use miden_protocol::block::BlockNumber;
9use miden_protocol::note::{NoteId, Nullifier};
10use miden_protocol::transaction::TransactionId;
11use tracing::Value;
12
13const BOOLEAN_FIELD_NAMES: &[&str] = &[
14    "account.updated",
15    "funding_service.remote_prover",
16    "note.erased",
17    "note_transport.inserted",
18    "note_transport.has_more",
19    "note.id_resolved",
20    "panic",
21    "request.include_mmr_proof",
22    "request.include_proof",
23    "rpc.authentication.configured",
24];
25
26const NUMBER_FIELD_NAMES: &[&str] = &[
27    "account.id.length",
28    "account.index",
29    "asset.amount",
30    "asset.balance",
31    "asset.collected",
32    "asset.reserve",
33    "batch.expiration_height",
34    "batch.expires_at",
35    "batch.reference_block.number",
36    "batch.size",
37    "block.from",
38    "block.number",
39    "block.protocol.version",
40    "deposit.count",
41    "block.size",
42    "block.timestamp",
43    "block_range.from",
44    "block_range.to",
45    "counter.failures.consecutive",
46    "counter.latency.timeout_ms",
47    "counter.value.expected",
48    "counter.value.observed",
49    "counter.value.target",
50    "current_client_block_height",
51    "cutoff_block",
52    "db.account_state_forest.size",
53    "db.account_tree.size",
54    "db.block_store.size",
55    "db.nullifier_tree.size",
56    "db.sqlite.connection_pool_size",
57    "db.sqlite.size",
58    "db.sqlite.wal.size",
59    "dice_roll",
60    "failure_rate",
61    "fee.verification_base_fee",
62    "funding_service.max_amount",
63    "funding_service.max_deposits_per_tx",
64    "funding_service.max_notes_per_tx",
65    "funding_service.tx_expiration_delta",
66    "inputs_size",
67    "mempool.accounts",
68    "mempool.batches.proposed",
69    "mempool.batches.proven",
70    "mempool.nullifiers",
71    "mempool.output_notes",
72    "mempool.transactions.unbatched",
73    "mempool.transactions.uncommitted",
74    "note.after_block_num",
75    "note.committed",
76    "note.count",
77    "note.tag",
78    "note_transport.payload_bytes",
79    "note_transport.returned",
80    "note_transport.cursor.sequence",
81    "note_transport.cursor.nonce",
82    "note_transport.deleted",
83    "note_transport.retained_bytes",
84    "ntx_builder.max_concurrent_txs",
85    "ntx_builder.max_cycles",
86    "ntx_builder.tx_expiration_delta",
87    "port",
88    "pow.hash",
89    "pow.nonce",
90    "pow.target",
91    "pow.target.leading_zero_bits",
92    "prefix_len",
93    "proof_size",
94    "prover.capacity",
95    "prover.port",
96    "prover.proof_type.raw",
97    "reference_block.number",
98    "retry.attempt",
99    "snapshot.block_num",
100    "snapshots.lag_blocks",
101    "snapshots.live",
102    "subscription.idle_ms",
103    "subscription.stall_timeout_ms",
104    "sync.block_gap",
105    "sync.ready_threshold",
106    "sync.upstream_block",
107    "tip.number",
108    "tip.stale_duration_secs",
109    "transaction.expiration_delta",
110    "transaction.expires_at",
111    "transaction.reference_block.number",
112    "transaction.submitted_at",
113    "validator.proving_input_retention_blocks",
114    "worker.status.raw",
115    "workers.active",
116    "workers.capacity",
117];
118
119const STRING_FIELD_NAMES: &[&str] = &[
120    "account.id",
121    "account.storage.kind",
122    "account.storage.map.entry.operation",
123    "account.storage.operation",
124    "admin.listen",
125    "asset.symbol",
126    "batch.interval",
127    "block.interval",
128    "dependency.endpoint",
129    "dependency.name",
130    "funding_service.listen",
131    "funding_service.poll_interval",
132    "genesis.source",
133    "genesis.source.kind",
134    "grpc.timeout",
135    "http.timeout",
136    "internal.listen",
137    "mempool.removal.reason",
138    "network_monitor.listen",
139    "node.role",
140    "note.execution_cycles",
141    "ntx_builder.endpoint",
142    "ntx_builder.idle_timeout",
143    "ntx_builder.listen",
144    "operation.name",
145    "path",
146    "pow.challenge.prefix",
147    "prover",
148    "prover.kind",
149    "prover.timeout",
150    "reason",
151    "request.kind",
152    "rpc.endpoint",
153    "rpc.listen",
154    "rpc.timeout",
155    "sequencer.endpoint",
156    "service.name",
157    "service.readiness.reason",
158    "service.version",
159    "shutdown.signal",
160    "sync.block_source.endpoint",
161    "task.name",
162    "tracing.filter",
163    "tracing.output",
164    "transaction.id",
165    "transaction.input_notes",
166    "transaction.output_notes",
167    "tx_prover.endpoint",
168    "tx_prover.timeout",
169    "validator.admin_listen",
170    "validator.endpoints",
171    "validator.listen",
172    "validator.signer",
173    "worker.name",
174];
175
176/// Converts a value into its canonical tracing attribute representation.
177///
178/// Values passed to the Miden tracing span and event macros must implement this trait.
179/// Implementations decide the allowed scalar field names, the attribute's primitive type, and its
180/// formatting, allowing tracing macros to use one name and representation consistently at every
181/// recording site. Collection implementations derive their field names by appending `s` to these
182/// scalar names.
183pub trait RecordAttribute {
184    /// Scalar field names associated with this value's type.
185    const FIELD_NAMES: &'static [&'static str];
186
187    /// Whether the final component of each field name must have an `s` suffix.
188    const PLURALIZE_FIELD_NAMES: bool = false;
189
190    /// Returns the value that is passed to `tracing`.
191    fn record_attribute(&self) -> impl Value + '_;
192}
193
194/// Returns whether `field_name` occurs in `field_names`.
195///
196/// This is public because it is referenced by the tracing proc macros. Callers should use the
197/// macros rather than invoking it directly.
198#[doc(hidden)]
199pub const fn field_name_allowed(field_names: &[&str], field_name: &str, pluralize: bool) -> bool {
200    let mut index = 0;
201    while index < field_names.len() {
202        let allowed = if pluralize {
203            str_eq_with_s_suffix(field_names[index], field_name)
204        } else {
205            str_eq(field_names[index], field_name)
206        };
207        if allowed {
208            return true;
209        }
210        index += 1;
211    }
212    false
213}
214
215const fn str_eq_with_s_suffix(singular: &str, plural: &str) -> bool {
216    let singular = singular.as_bytes();
217    let plural = plural.as_bytes();
218    if plural.len() != singular.len() + 1 || plural[singular.len()] != b's' {
219        return false;
220    }
221
222    let mut index = 0;
223    while index < singular.len() {
224        if singular[index] != plural[index] {
225            return false;
226        }
227        index += 1;
228    }
229    true
230}
231
232const fn str_eq(left: &str, right: &str) -> bool {
233    let left = left.as_bytes();
234    let right = right.as_bytes();
235    if left.len() != right.len() {
236        return false;
237    }
238
239    let mut index = 0;
240    while index < left.len() {
241        if left[index] != right[index] {
242            return false;
243        }
244        index += 1;
245    }
246    true
247}
248
249/// Converts an approved attribute into a `tracing` value.
250///
251/// This is public because it is referenced by the tracing proc macros. Callers should use the
252/// macros rather than invoking it directly.
253#[doc(hidden)]
254pub fn record_attribute<T: RecordAttribute + ?Sized>(value: &T) -> impl Value + '_ {
255    value.record_attribute()
256}
257
258macro_rules! impl_scalar_attribute {
259    ($field_names:expr; $($ty:ty),* $(,)?) => {
260        $(
261            impl RecordAttribute for $ty {
262                const FIELD_NAMES: &'static [&'static str] = $field_names;
263
264                fn record_attribute(&self) -> impl Value + '_ {
265                    *self
266                }
267            }
268        )*
269    };
270}
271
272impl_scalar_attribute!(BOOLEAN_FIELD_NAMES; bool);
273impl_scalar_attribute!(
274    NUMBER_FIELD_NAMES;
275    f32,
276    f64,
277    i8,
278    i16,
279    i32,
280    i64,
281    i128,
282    isize,
283    u8,
284    u16,
285    u64,
286    u128,
287    usize,
288);
289impl_scalar_attribute!(NUMBER_FIELD_NAMES; u32);
290
291/// Durations are recorded as whole milliseconds in a `u64`, saturating at `u64::MAX`.
292///
293/// Every allowed field name ends with `ms` so the recorded unit is visible on the query side.
294impl RecordAttribute for Duration {
295    const FIELD_NAMES: &'static [&'static str] = &[
296        "retry.delay_ms",
297        "shutdown.grace_period_ms",
298        "snapshots.oldest_superseded_for_ms",
299        "timeout.ms",
300    ];
301
302    fn record_attribute(&self) -> impl Value + '_ {
303        u64::try_from(self.as_millis()).unwrap_or(u64::MAX)
304    }
305}
306
307impl RecordAttribute for str {
308    const FIELD_NAMES: &'static [&'static str] = STRING_FIELD_NAMES;
309
310    fn record_attribute(&self) -> impl Value + '_ {
311        self
312    }
313}
314
315impl RecordAttribute for String {
316    const FIELD_NAMES: &'static [&'static str] = <str as RecordAttribute>::FIELD_NAMES;
317
318    fn record_attribute(&self) -> impl Value + '_ {
319        self.as_str()
320    }
321}
322
323impl<T: RecordAttribute + ?Sized> RecordAttribute for &T {
324    const FIELD_NAMES: &'static [&'static str] = T::FIELD_NAMES;
325    const PLURALIZE_FIELD_NAMES: bool = T::PLURALIZE_FIELD_NAMES;
326
327    fn record_attribute(&self) -> impl Value + '_ {
328        (*self).record_attribute()
329    }
330}
331
332impl<T: RecordAttribute> RecordAttribute for Option<T> {
333    const FIELD_NAMES: &'static [&'static str] = T::FIELD_NAMES;
334    const PLURALIZE_FIELD_NAMES: bool = T::PLURALIZE_FIELD_NAMES;
335
336    fn record_attribute(&self) -> impl Value + '_ {
337        self.as_ref().map(RecordAttribute::record_attribute)
338    }
339}
340
341impl RecordAttribute for Path {
342    const FIELD_NAMES: &'static [&'static str] =
343        &["account.file", "data.directory", "genesis.file", "path"];
344
345    fn record_attribute(&self) -> impl Value + '_ {
346        tracing::field::display(self.display())
347    }
348}
349
350impl RecordAttribute for PathBuf {
351    const FIELD_NAMES: &'static [&'static str] = <Path as RecordAttribute>::FIELD_NAMES;
352
353    fn record_attribute(&self) -> impl Value + '_ {
354        self.as_path().record_attribute()
355    }
356}
357
358impl RecordAttribute for BlockNumber {
359    const FIELD_NAMES: &'static [&'static str] = &[
360        "batch.expiration_height",
361        "batch.expires_at",
362        "batch.reference_block.number",
363        "block.from",
364        "block.number",
365        "block_range.from",
366        "block_range.to",
367        "cutoff_block",
368        "current_client_block_height",
369        "note.after_block_num",
370        "reference_block.number",
371        "snapshot.block_num",
372        "sync.upstream_block",
373        "tip.number",
374        "transaction.expires_at",
375        "transaction.reference_block.number",
376        "transaction.submitted_at",
377    ];
378
379    fn record_attribute(&self) -> impl Value + '_ {
380        self.as_u64()
381    }
382}
383
384macro_rules! impl_display_attribute {
385    ($ty:ty, $field_names:expr $(,)?) => {
386        impl RecordAttribute for $ty {
387            const FIELD_NAMES: &'static [&'static str] = $field_names;
388
389            fn record_attribute(&self) -> impl Value + '_ {
390                tracing::field::display(self)
391            }
392        }
393    };
394}
395
396impl_display_attribute!(
397    AccountId,
398    &[
399        "account.id",
400        "asset.faucet_id",
401        "counter.account.id.new",
402        "counter.account.id.old",
403        "note.sender",
404        "wallet.account.id.new",
405        "wallet.account.id.old",
406    ],
407);
408impl_display_attribute!(AccountIdPrefix, &["account.id.network_prefix"]);
409impl_display_attribute!(StorageMapKey, &["account.storage.map.key"]);
410impl_display_attribute!(StorageSlotName, &["account.storage.slot"]);
411impl_display_attribute!(BatchId, &["batch.id", "block.batch.id"]);
412impl_display_attribute!(NoteId, &["note.id"]);
413impl_display_attribute!(Nullifier, &["note.nullifier"]);
414impl_display_attribute!(TransactionId, &["block.transaction.id", "transaction.id"]);
415impl_display_attribute!(
416    Word,
417    &[
418        "account.final_state.commitment",
419        "account.initial_state.commitment",
420        "account.storage.value",
421        "batch.reference_block.commitment",
422        "block.commitment",
423        "block.commitments.account",
424        "block.commitments.chain",
425        "block.commitments.kernel",
426        "block.commitments.note",
427        "block.commitments.nullifier",
428        "block.commitments.transaction",
429        "block.prev_block_commitment",
430        "block.sub_commitment",
431        "genesis.commitment",
432        "script.root",
433        "transaction.reference_block.commitment",
434    ],
435);
436
437/// Formats a slice as one string-valued tracing attribute.
438///
439/// This is not an OpenTelemetry array: `tracing::Value` has no array representation, so the `OTel`
440/// tracing layer receives the formatted list as a string.
441struct AttributeList<'a, T>(&'a [T]);
442
443impl<T: Display> Display for AttributeList<'_, T> {
444    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
445        let mut values = self.0.iter();
446        let Some(first) = values.next() else {
447            return f.write_str("None");
448        };
449
450        write!(f, "[{first}")?;
451        for value in values {
452            write!(f, ", {value}")?;
453        }
454        f.write_str("]")
455    }
456}
457
458impl<T: Display + RecordAttribute> RecordAttribute for [T] {
459    const FIELD_NAMES: &'static [&'static str] = T::FIELD_NAMES;
460    const PLURALIZE_FIELD_NAMES: bool = true;
461
462    fn record_attribute(&self) -> impl Value + '_ {
463        tracing::field::display(AttributeList(self))
464    }
465}
466
467impl<T: Display + RecordAttribute, const N: usize> RecordAttribute for [T; N] {
468    const FIELD_NAMES: &'static [&'static str] = T::FIELD_NAMES;
469    const PLURALIZE_FIELD_NAMES: bool = true;
470
471    fn record_attribute(&self) -> impl Value + '_ {
472        self.as_slice().record_attribute()
473    }
474}
475
476impl<T: Display + RecordAttribute> RecordAttribute for Vec<T> {
477    const FIELD_NAMES: &'static [&'static str] = T::FIELD_NAMES;
478    const PLURALIZE_FIELD_NAMES: bool = true;
479
480    fn record_attribute(&self) -> impl Value + '_ {
481        self.as_slice().record_attribute()
482    }
483}
484
485#[cfg(test)]
486mod tests {
487    use miden_protocol::account::AccountId;
488
489    use super::{AttributeList, RecordAttribute, field_name_allowed};
490
491    #[test]
492    fn lists_use_the_canonical_format() {
493        assert_eq!(AttributeList::<u32>(&[]).to_string(), "None");
494        assert_eq!(AttributeList(&[1, 2, 3]).to_string(), "[1, 2, 3]");
495    }
496
497    #[test]
498    fn references_are_approved_when_the_referenced_type_is_approved() {
499        fn assert_record_attribute(_: &impl RecordAttribute) {}
500
501        let value = "attribute";
502        assert_record_attribute(&value);
503        assert_record_attribute(&&value);
504        assert_record_attribute(&Some(value));
505        assert_record_attribute(&None::<&str>);
506    }
507
508    #[test]
509    fn field_names_are_specific_to_the_attribute_type() {
510        assert!(field_name_allowed(
511            AccountId::FIELD_NAMES,
512            "account.id",
513            AccountId::PLURALIZE_FIELD_NAMES,
514        ));
515        assert!(!field_name_allowed(
516            AccountId::FIELD_NAMES,
517            "account.ids",
518            AccountId::PLURALIZE_FIELD_NAMES,
519        ));
520        assert!(field_name_allowed(
521            <[AccountId]>::FIELD_NAMES,
522            "account.ids",
523            <[AccountId]>::PLURALIZE_FIELD_NAMES,
524        ));
525        assert!(!field_name_allowed(
526            <[AccountId]>::FIELD_NAMES,
527            "account.id",
528            <[AccountId]>::PLURALIZE_FIELD_NAMES,
529        ));
530    }
531}