micromegas_tracing_proc_macros/lib.rs
1//! Procedural macros for instrumenting Rust functions with tracing spans.
2//!
3//! This crate provides `#[span_fn]` and `#[log_fn]` attribute macros that automatically
4//! inject instrumentation into functions. These macros are the primary way to instrument
5//! async code in micromegas.
6//!
7//! # Quick Start
8//!
9//! ```rust,ignore
10//! use micromegas_tracing::prelude::*;
11//!
12//! #[span_fn]
13//! async fn fetch_user(id: u64) -> User {
14//! // This async function is automatically instrumented
15//! database.get_user(id).await
16//! }
17//!
18//! #[span_fn]
19//! fn compute_hash(data: &[u8]) -> Hash {
20//! // Sync functions work too
21//! hasher.hash(data)
22//! }
23//! ```
24//!
25//! # Why use `#[span_fn]`?
26//!
27//! The `#[span_fn]` macro solves a fundamental challenge in async Rust: tracking execution
28//! time across `.await` points. When an async function awaits, it yields control and may
29//! resume on a different thread. `#[span_fn]` wraps your async code in an `InstrumentedFuture`
30//! that correctly tracks wall-clock time even across these suspension points.
31//!
32//! For sync functions, it creates a scope-based span that measures the function's execution.
33//!
34//! # Import
35//!
36//! These macros are re-exported through the tracing prelude:
37//!
38//! ```rust,ignore
39//! use micromegas_tracing::prelude::*;
40//! ```
41
42// crate-specific lint exceptions:
43//#![allow()]
44
45mod log_impl;
46
47use proc_macro::TokenStream;
48use proc_macro2::Ident;
49use quote::{ToTokens, quote};
50use syn::{
51 Expr, ItemFn, LitStr, ReturnType, Token, Type, TypePath,
52 parse::{Parse, ParseStream, Result},
53 parse_macro_input, parse_quote,
54};
55
56enum PropKey {
57 Ident(Ident),
58 Str(LitStr),
59}
60
61impl Parse for PropKey {
62 fn parse(input: ParseStream<'_>) -> Result<Self> {
63 if input.peek(LitStr) {
64 Ok(Self::Str(input.parse()?))
65 } else {
66 Ok(Self::Ident(input.parse()?))
67 }
68 }
69}
70
71impl ToTokens for PropKey {
72 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
73 match self {
74 Self::Ident(ident) => ident.to_tokens(tokens),
75 Self::Str(lit) => lit.to_tokens(tokens),
76 }
77 }
78}
79
80struct TraceArgs {
81 alternative_name: Option<LitStr>,
82 properties: Vec<(PropKey, Expr)>,
83}
84
85impl Parse for TraceArgs {
86 fn parse(input: ParseStream<'_>) -> Result<Self> {
87 let mut alternative_name = None;
88 // A leading string literal followed by `=` is a property key, not the name.
89 if input.peek(LitStr) && !input.peek2(Token![=]) {
90 alternative_name = Some(input.parse()?);
91 if !input.is_empty() {
92 input.parse::<Token![,]>()?;
93 }
94 }
95 let mut properties = Vec::new();
96 while !input.is_empty() {
97 let key: PropKey = input.parse()?;
98 input.parse::<Token![=]>()?;
99 let value: Expr = input.parse()?;
100 properties.push((key, value));
101 if !input.is_empty() {
102 input.parse::<Token![,]>()?;
103 }
104 }
105 Ok(Self {
106 alternative_name,
107 properties,
108 })
109 }
110}
111
112/// Check if the function returns a Future (indicating it's an async trait method)
113fn returns_future(function: &ItemFn) -> bool {
114 match &function.sig.output {
115 ReturnType::Type(_, ty) => is_future_type(ty),
116 ReturnType::Default => false,
117 }
118}
119
120/// Check if a type is a Future type (Pin<Box<dyn Future>> or impl Future)
121fn is_future_type(ty: &Type) -> bool {
122 match ty {
123 // Check for Pin<Box<dyn Future<...>>>
124 Type::Path(TypePath { path, .. }) => {
125 if let Some(last_segment) = path.segments.last()
126 && last_segment.ident == "Pin"
127 {
128 // This is the pattern async-trait generates
129 return true;
130 }
131 false
132 }
133 // Check for impl Future<...>
134 Type::ImplTrait(impl_trait) => impl_trait.bounds.iter().any(|bound| {
135 if let syn::TypeParamBound::Trait(trait_bound) = bound
136 && let Some(segment) = trait_bound.path.segments.last()
137 {
138 return segment.ident == "Future";
139 }
140 false
141 }),
142 _ => false,
143 }
144}
145
146/// Picks the property-carrying `span_fn_future!` form only when properties exist, so functions
147/// without properties keep the static-descriptor expansion unchanged.
148fn instrument_future(
149 name: &str,
150 fut: proc_macro2::TokenStream,
151 props: &[proc_macro2::TokenStream],
152) -> proc_macro2::TokenStream {
153 if props.is_empty() {
154 quote! {
155 {
156 static_span_desc!(_SCOPE_DESC, concat!(module_path!(), "::", #name));
157 InstrumentedFuture::new(#fut, &_SCOPE_DESC)
158 }
159 }
160 } else {
161 quote! {
162 span_fn_future!(concat!(module_path!(), "::", #name), #fut, #(#props),*)
163 }
164 }
165}
166
167/// Instruments a function with automatic span tracing.
168///
169/// This is the primary macro for instrumenting both sync and async functions in micromegas.
170/// It automatically detects the function type and applies the appropriate instrumentation.
171///
172/// # Supported Function Types
173///
174/// - **Sync functions**: Wrapped with `span_scope!` for scope-based timing
175/// - **Async functions**: Wrapped with `InstrumentedFuture` for accurate async timing
176/// - **Async trait methods**: Works with `#[async_trait]` - place `#[span_fn]` after `#[async_trait]`
177///
178/// # Basic Usage
179///
180/// ```rust,ignore
181/// use micromegas_tracing::prelude::*;
182///
183/// // Async function - tracks time across .await points
184/// #[span_fn]
185/// async fn process_request(req: Request) -> Response {
186/// let data = fetch_data(req.id).await;
187/// transform(data).await
188/// }
189///
190/// // Sync function - tracks wall-clock execution time
191/// #[span_fn]
192/// fn calculate_checksum(data: &[u8]) -> u32 {
193/// data.iter().fold(0u32, |acc, &b| acc.wrapping_add(b as u32))
194/// }
195/// ```
196///
197/// # Custom Span Names
198///
199/// By default, the span name is the function name prefixed with the module path.
200/// You can override this with a custom name:
201///
202/// ```rust,ignore
203/// #[span_fn("custom_operation_name")]
204/// async fn internal_impl() {
205/// // Span will be named "module::path::custom_operation_name"
206/// }
207/// ```
208///
209/// # Span Properties
210///
211/// `key = expr` pairs attach properties to the span. Each value is any expression whose type
212/// implements `Display`; it is evaluated once when the function is called, so it can reference
213/// the arguments (borrowed, not moved), and is recorded on the span's end event. A key is an
214/// identifier or a string literal, and a leading string literal followed by a comma is still the
215/// custom name:
216///
217/// ```rust,ignore
218/// #[span_fn(view = view.get_view_set_name())]
219/// async fn materialize(view: Arc<dyn View>) -> Result<()> {
220/// Ok(())
221/// }
222///
223/// #[span_fn("lookup", id = id, "http.method" = "GET")]
224/// fn find(id: u32) -> Option<Row> {
225/// None
226/// }
227/// ```
228///
229/// # With Async Traits
230///
231/// When using `#[async_trait]`, place `#[span_fn]` on the method *after* the
232/// `#[async_trait]` attribute on the impl block:
233///
234/// ```rust,ignore
235/// use async_trait::async_trait;
236/// use micromegas_tracing::prelude::*;
237///
238/// #[async_trait]
239/// trait DataService {
240/// async fn fetch(&self, id: u64) -> Data;
241/// }
242///
243/// #[async_trait]
244/// impl DataService for MyService {
245/// #[span_fn]
246/// async fn fetch(&self, id: u64) -> Data {
247/// self.db.query(id).await
248/// }
249/// }
250/// ```
251///
252/// `#[async_trait]` renames arguments that are not plain identifiers (for example destructuring
253/// patterns) to `__argN` in the outer signature, so span properties can only use `self` and
254/// arguments bound to plain identifiers.
255///
256/// # How It Works
257///
258/// For **async functions**, the macro:
259/// 1. Removes the `async` keyword
260/// 2. Changes the return type to `impl Future<Output = T>`
261/// 3. Wraps the body in an `InstrumentedFuture` that tracks timing
262///
263/// For **sync functions**, the macro:
264/// 1. Inserts a `span_scope!` call at the start of the function
265/// 2. The span automatically closes when the function returns
266///
267/// # Performance
268///
269/// The overhead is approximately 40ns per span (20ns per event, with a span
270/// recording both begin and end). This makes it suitable for high-frequency
271/// instrumentation. Spans are collected in thread-local storage and batched
272/// for efficient transmission.
273///
274/// # See Also
275///
276/// - [`log_fn`] - For simple function entry logging without timing
277/// - `span_scope!` - For manual scope-based spans within a function
278/// - `span_async_named!` - For manual async spans with dynamic names
279#[proc_macro_attribute]
280pub fn span_fn(args: TokenStream, input: TokenStream) -> TokenStream {
281 let args = parse_macro_input!(args as TraceArgs);
282 let mut function = parse_macro_input!(input as ItemFn);
283
284 let function_name = args
285 .alternative_name
286 .map_or(function.sig.ident.to_string(), |n| n.value());
287 let props: Vec<_> = args
288 .properties
289 .iter()
290 .map(|(key, value)| quote! { #key = %(#value) })
291 .collect();
292 let has_props = !props.is_empty();
293
294 if returns_future(&function) {
295 // Case 1: Async trait method (after #[async_trait] transformation)
296 // Function returns Pin<Box<dyn Future<Output = T>>> and has no async keyword
297 let stmts = &function.block.stmts;
298
299 // Extract and instrument the async block from Box::pin(async move { ... })
300 if stmts.len() == 1
301 && let syn::Stmt::Expr(syn::Expr::Call(call_expr), _) = &stmts[0]
302 && call_expr.args.len() == 1
303 {
304 let async_block = &call_expr.args[0];
305
306 let instrumented = instrument_future(&function_name, quote! { #async_block }, &props);
307 function.block = parse_quote! {
308 {
309 Box::pin(#instrumented)
310 }
311 };
312 } else {
313 // For complex async functions that don't match the simple Box::pin pattern,
314 // wrap the entire body in an async block and instrument it
315 let original_block = &function.block;
316 let instrumented = instrument_future(
317 &function_name,
318 quote! { async move #original_block },
319 &props,
320 );
321 function.block = parse_quote! {
322 {
323 Box::pin(#instrumented)
324 }
325 };
326 }
327 } else if function.sig.asyncness.is_some() {
328 // Case 2: Regular async function
329 let original_block = &function.block;
330 let output_type = match &function.sig.output {
331 syn::ReturnType::Type(_, ty) => quote! { #ty },
332 syn::ReturnType::Default => quote! { () },
333 };
334
335 // Remove async and change return type to impl Future
336 function.sig.asyncness = None;
337 function.sig.output = parse_quote! { -> impl std::future::Future<Output = #output_type> };
338 let instrumented = instrument_future(
339 &function_name,
340 quote! { async move #original_block },
341 &props,
342 );
343 function.block = parse_quote! {
344 {
345 #instrumented
346 }
347 };
348 } else {
349 // Case 3: Regular sync function
350 let guard_stmt: syn::Stmt = if has_props {
351 parse_quote! {
352 let __span_fn_guard = span_scope!(
353 name = concat!(module_path!(), "::", #function_name),
354 #(#props),*
355 );
356 }
357 } else {
358 parse_quote! {
359 span_scope!(_METADATA_FUNC, concat!(module_path!(), "::", #function_name));
360 }
361 };
362 function.block.stmts.insert(0, guard_stmt);
363 }
364
365 TokenStream::from(quote! {
366 #function
367 })
368}
369
370/// Logs function entry with the function name.
371///
372/// This macro injects a `trace!` call at the start of the function, logging
373/// the function name. Unlike [`span_fn`], it does not measure execution time
374/// or track function exit.
375///
376/// # Usage
377///
378/// ```rust,ignore
379/// use micromegas_tracing::prelude::*;
380///
381/// #[log_fn]
382/// fn handle_event(event: Event) {
383/// // Logs "handle_event" at trace level when called
384/// process(event);
385/// }
386/// ```
387///
388/// # When to Use
389///
390/// Use `log_fn` when you only need to know that a function was called, without
391/// timing data. Note that log entries are typically more expensive than span
392/// events, so for performance instrumentation prefer [`span_fn`].
393///
394/// `log_fn` is useful when you want function calls to appear in the log stream
395/// rather than the spans/traces stream.
396#[proc_macro_attribute]
397pub fn log_fn(args: TokenStream, input: TokenStream) -> TokenStream {
398 assert!(args.is_empty());
399 let mut function = parse_macro_input!(input as ItemFn);
400 let function_name = function.sig.ident.to_string();
401
402 function.block.stmts.insert(
403 0,
404 parse_quote! {
405 trace!(#function_name);
406 },
407 );
408 TokenStream::from(quote! {
409 #function
410 })
411}
412
413/// Expansion of the log macros. Not for direct use: `macros.rs` feeds it the property
414/// accumulators of its muncher and the format tokens.
415#[doc(hidden)]
416#[proc_macro]
417pub fn __log_impl(input: TokenStream) -> TokenStream {
418 log_impl::expand(input.into()).into()
419}