|
| 1 | +// Copyright 2025 RisingWave Labs |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +//! Procedural attributes for await-tree instrumentation. |
| 16 | +
|
| 17 | +use proc_macro::TokenStream; |
| 18 | +use quote::quote; |
| 19 | +use syn::{parse_macro_input, Ident, ItemFn, Token}; |
| 20 | + |
| 21 | +/// Parse the attribute arguments to extract method calls and format args |
| 22 | +struct InstrumentArgs { |
| 23 | + method_calls: Vec<Ident>, |
| 24 | + format_args: Option<proc_macro2::TokenStream>, |
| 25 | +} |
| 26 | + |
| 27 | +impl syn::parse::Parse for InstrumentArgs { |
| 28 | + fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { |
| 29 | + let mut method_calls = Vec::new(); |
| 30 | + let mut format_args = None; |
| 31 | + |
| 32 | + // Parse identifiers first (these will become method calls) |
| 33 | + while input.peek(Ident) { |
| 34 | + // Look ahead to see if this looks like a method call identifier |
| 35 | + let fork = input.fork(); |
| 36 | + let ident: Ident = fork.parse()?; |
| 37 | + |
| 38 | + // Check if the next token after the identifier is a comma or end |
| 39 | + // If it's something else (like a parenthesis or string), treat as format args |
| 40 | + if fork.peek(Token![,]) || fork.is_empty() { |
| 41 | + // This is a method call identifier |
| 42 | + input.parse::<Ident>()?; // consume the identifier |
| 43 | + method_calls.push(ident); |
| 44 | + if input.peek(Token![,]) { |
| 45 | + input.parse::<Token![,]>()?; |
| 46 | + } |
| 47 | + } else { |
| 48 | + // This looks like the start of format arguments |
| 49 | + break; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + // Parse remaining tokens as format arguments |
| 54 | + if !input.is_empty() { |
| 55 | + let remaining: proc_macro2::TokenStream = input.parse()?; |
| 56 | + format_args = Some(remaining); |
| 57 | + } |
| 58 | + |
| 59 | + Ok(InstrumentArgs { |
| 60 | + method_calls, |
| 61 | + format_args, |
| 62 | + }) |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +/// Instruments an async function with await-tree spans. |
| 67 | +/// |
| 68 | +/// This attribute macro transforms an async function to automatically create |
| 69 | +/// an await-tree span and instrument the function's execution. |
| 70 | +/// |
| 71 | +/// # Usage |
| 72 | +/// |
| 73 | +/// ```rust,ignore |
| 74 | +/// #[await_tree::instrument("span_name({})", arg1)] |
| 75 | +/// async fn foo(arg1: i32, arg2: String) { |
| 76 | +/// // function body |
| 77 | +/// } |
| 78 | +/// ``` |
| 79 | +/// |
| 80 | +/// With keywords: |
| 81 | +/// |
| 82 | +/// ```rust,ignore |
| 83 | +/// #[await_tree::instrument(long_running, verbose, "span_name({})", arg1)] |
| 84 | +/// async fn foo(arg1: i32, arg2: String) { |
| 85 | +/// // function body |
| 86 | +/// } |
| 87 | +/// ``` |
| 88 | +/// |
| 89 | +/// The above will be expanded to: |
| 90 | +/// |
| 91 | +/// ```rust,ignore |
| 92 | +/// async fn foo(arg1: i32, arg2: String) { |
| 93 | +/// let span = await_tree::span!("span_name({})", arg1).long_running().verbose(); |
| 94 | +/// let fut = async move { |
| 95 | +/// // original function body |
| 96 | +/// }; |
| 97 | +/// fut.instrument_await(span).await |
| 98 | +/// } |
| 99 | +/// ``` |
| 100 | +/// |
| 101 | +/// # Arguments |
| 102 | +/// |
| 103 | +/// The macro accepts format arguments similar to `format!` or `println!`: |
| 104 | +/// - The first argument is the format string |
| 105 | +/// - Subsequent arguments are the values to be formatted |
| 106 | +/// |
| 107 | +/// The format arguments are passed directly to the `await_tree::span!` macro |
| 108 | +/// without any parsing or modification. |
| 109 | +#[proc_macro_attribute] |
| 110 | +pub fn instrument(args: TokenStream, input: TokenStream) -> TokenStream { |
| 111 | + let input_fn = parse_macro_input!(input as ItemFn); |
| 112 | + |
| 113 | + // Validate that this is an async function |
| 114 | + if input_fn.sig.asyncness.is_none() { |
| 115 | + return syn::Error::new_spanned( |
| 116 | + &input_fn.sig.fn_token, |
| 117 | + "the `instrument` attribute can only be applied to async functions", |
| 118 | + ) |
| 119 | + .to_compile_error() |
| 120 | + .into(); |
| 121 | + } |
| 122 | + |
| 123 | + // Parse the arguments |
| 124 | + let parsed_args = if args.is_empty() { |
| 125 | + InstrumentArgs { |
| 126 | + method_calls: Vec::new(), |
| 127 | + format_args: None, |
| 128 | + } |
| 129 | + } else { |
| 130 | + match syn::parse::<InstrumentArgs>(args) { |
| 131 | + Ok(args) => args, |
| 132 | + Err(e) => return e.to_compile_error().into(), |
| 133 | + } |
| 134 | + }; |
| 135 | + |
| 136 | + // Extract the span format arguments |
| 137 | + let span_args = if let Some(format_args) = parsed_args.format_args { |
| 138 | + quote! { #format_args } |
| 139 | + } else { |
| 140 | + // If no format arguments provided, use the function name as span |
| 141 | + let fn_name = &input_fn.sig.ident; |
| 142 | + quote! { stringify!(#fn_name) } |
| 143 | + }; |
| 144 | + |
| 145 | + // Build span creation with method calls |
| 146 | + let mut span_creation = quote! { ::await_tree::span!(#span_args) }; |
| 147 | + |
| 148 | + // Chain all method calls |
| 149 | + for method_name in parsed_args.method_calls { |
| 150 | + span_creation = quote! { #span_creation.#method_name() }; |
| 151 | + } |
| 152 | + |
| 153 | + // Extract function components |
| 154 | + let fn_vis = &input_fn.vis; |
| 155 | + let fn_sig = &input_fn.sig; |
| 156 | + let fn_block = &input_fn.block; |
| 157 | + let fn_attrs = &input_fn.attrs; |
| 158 | + |
| 159 | + // Generate the instrumented function |
| 160 | + let result = quote! { |
| 161 | + #(#fn_attrs)* |
| 162 | + #fn_vis #fn_sig { |
| 163 | + use ::await_tree::SpanExt as _; |
| 164 | + let __at_span: ::await_tree::Span = #span_creation; |
| 165 | + let __at_fut = async move #fn_block; |
| 166 | + ::await_tree::InstrumentAwait::instrument_await(__at_fut, __at_span).await |
| 167 | + } |
| 168 | + }; |
| 169 | + |
| 170 | + result.into() |
| 171 | +} |
0 commit comments