-
Notifications
You must be signed in to change notification settings - Fork 1.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(pruner, metrics): skip
attribute for metrics derive macro
#4069
Merged
+156
−76
Merged
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
5c9c7b5
feat(pruner, metrics): skip attribute
shekhirin b9eb769
fix parsing
shekhirin 22fe8f0
simplify field extraction
shekhirin bf37faf
give variables names
shekhirin 73c0ff1
revert to unnamed variables, default keyword is occupied and i don't …
shekhirin 857a3a7
add skipped fields to tests
shekhirin 04cb464
Merge remote-tracking branch 'origin/main' into alexey/metrics-derive…
shekhirin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,8 +2,8 @@ use once_cell::sync::Lazy; | |
use quote::{quote, ToTokens}; | ||
use regex::Regex; | ||
use syn::{ | ||
punctuated::Punctuated, Attribute, Data, DeriveInput, Error, Expr, Lit, LitBool, LitStr, | ||
MetaNameValue, Result, Token, | ||
punctuated::Punctuated, Attribute, Data, DeriveInput, Error, Expr, Field, Lit, LitBool, LitStr, | ||
Meta, MetaNameValue, Result, Token, | ||
}; | ||
|
||
use crate::{metric::Metric, with_attrs::WithAttrs}; | ||
|
@@ -17,6 +17,19 @@ static METRIC_NAME_RE: Lazy<Regex> = | |
/// Supported metrics separators | ||
const SUPPORTED_SEPARATORS: &[&str] = &[".", "_", ":"]; | ||
|
||
enum MetricField<'a> { | ||
Included(Metric<'a>), | ||
Skipped(&'a Field), | ||
} | ||
|
||
impl<'a> MetricField<'a> { | ||
fn field(&self) -> &'a Field { | ||
match self { | ||
MetricField::Included(Metric { field, .. }) | MetricField::Skipped(field) => field, | ||
} | ||
} | ||
} | ||
|
||
pub(crate) fn derive(node: &DeriveInput) -> Result<proc_macro2::TokenStream> { | ||
let ty = &node.ident; | ||
let vis = &node.vis; | ||
|
@@ -36,32 +49,55 @@ pub(crate) fn derive(node: &DeriveInput) -> Result<proc_macro2::TokenStream> { | |
let (defaults, labeled_defaults, describes): (Vec<_>, Vec<_>, Vec<_>) = metric_fields | ||
.iter() | ||
.map(|metric| { | ||
let field_name = &metric.field.ident; | ||
let metric_name = | ||
format!("{}{}{}", scope.value(), metrics_attr.separator(), metric.name()); | ||
let registrar = metric.register_stmt()?; | ||
let describe = metric.describe_stmt()?; | ||
let description = &metric.description; | ||
Ok(( | ||
quote! { | ||
#field_name: #registrar(#metric_name), | ||
}, | ||
quote! { | ||
#field_name: #registrar(#metric_name, labels.clone()), | ||
}, | ||
quote! { | ||
#describe(#metric_name, #description); | ||
}, | ||
)) | ||
let field_name = &metric.field().ident; | ||
match metric { | ||
MetricField::Included(metric) => { | ||
let metric_name = format!( | ||
"{}{}{}", | ||
scope.value(), | ||
metrics_attr.separator(), | ||
metric.name() | ||
); | ||
let registrar = metric.register_stmt()?; | ||
let describe = metric.describe_stmt()?; | ||
let description = &metric.description; | ||
Ok(( | ||
quote! { | ||
#field_name: #registrar(#metric_name), | ||
}, | ||
quote! { | ||
#field_name: #registrar(#metric_name, labels.clone()), | ||
}, | ||
Some(quote! { | ||
#describe(#metric_name, #description); | ||
}), | ||
)) | ||
} | ||
MetricField::Skipped(_) => Ok(( | ||
quote! { | ||
#field_name: Default::default(), | ||
}, | ||
quote! { | ||
#field_name: Default::default(), | ||
}, | ||
None, | ||
)), | ||
} | ||
}) | ||
.collect::<Result<Vec<_>>>()? | ||
.into_iter() | ||
.fold((vec![], vec![], vec![]), |mut acc, x| { | ||
acc.0.push(x.0); | ||
acc.1.push(x.1); | ||
acc.2.push(x.2); | ||
acc | ||
}); | ||
.fold( | ||
(vec![], vec![], vec![]), | ||
|(mut defaults, mut labeled_defaults, mut describes), | ||
(default, labeled_default, describe)| { | ||
defaults.push(default); | ||
labeled_defaults.push(labeled_default); | ||
if let Some(describe) = describe { | ||
describes.push(describe); | ||
} | ||
(defaults, labeled_defaults, describes) | ||
}, | ||
); | ||
|
||
quote! { | ||
impl Default for #ty { | ||
|
@@ -93,37 +129,56 @@ pub(crate) fn derive(node: &DeriveInput) -> Result<proc_macro2::TokenStream> { | |
let (defaults, labeled_defaults, describes): (Vec<_>, Vec<_>, Vec<_>) = metric_fields | ||
.iter() | ||
.map(|metric| { | ||
let name = metric.name(); | ||
let separator = metrics_attr.separator(); | ||
let metric_name = quote! { | ||
format!("{}{}{}", scope, #separator, #name) | ||
}; | ||
let field_name = &metric.field.ident; | ||
|
||
let registrar = metric.register_stmt()?; | ||
let describe = metric.describe_stmt()?; | ||
let description = &metric.description; | ||
|
||
Ok(( | ||
quote! { | ||
#field_name: #registrar(#metric_name), | ||
}, | ||
quote! { | ||
#field_name: #registrar(#metric_name, labels.clone()), | ||
}, | ||
quote! { | ||
#describe(#metric_name, #description); | ||
}, | ||
)) | ||
let field_name = &metric.field().ident; | ||
match metric { | ||
MetricField::Included(metric) => { | ||
let name = metric.name(); | ||
let separator = metrics_attr.separator(); | ||
let metric_name = quote! { | ||
format!("{}{}{}", scope, #separator, #name) | ||
}; | ||
|
||
let registrar = metric.register_stmt()?; | ||
let describe = metric.describe_stmt()?; | ||
let description = &metric.description; | ||
|
||
Ok(( | ||
quote! { | ||
#field_name: #registrar(#metric_name), | ||
}, | ||
quote! { | ||
#field_name: #registrar(#metric_name, labels.clone()), | ||
}, | ||
Some(quote! { | ||
#describe(#metric_name, #description); | ||
}), | ||
)) | ||
} | ||
MetricField::Skipped(_) => Ok(( | ||
quote! { | ||
#field_name: Default::default(), | ||
}, | ||
quote! { | ||
#field_name: Default::default(), | ||
}, | ||
None, | ||
)), | ||
} | ||
}) | ||
.collect::<Result<Vec<_>>>()? | ||
.into_iter() | ||
.fold((vec![], vec![], vec![]), |mut acc, x| { | ||
acc.0.push(x.0); | ||
acc.1.push(x.1); | ||
acc.2.push(x.2); | ||
acc | ||
}); | ||
.fold( | ||
(vec![], vec![], vec![]), | ||
|(mut defaults, mut labeled_defaults, mut describes), | ||
(default, labeled_default, describe)| { | ||
defaults.push(default); | ||
labeled_defaults.push(labeled_default); | ||
if let Some(describe) = describe { | ||
describes.push(describe); | ||
} | ||
(defaults, labeled_defaults, describes) | ||
}, | ||
); | ||
|
||
quote! { | ||
impl #ty { | ||
|
@@ -246,40 +301,57 @@ fn parse_metrics_attr(node: &DeriveInput) -> Result<MetricsAttr> { | |
Ok(MetricsAttr { scope, separator }) | ||
} | ||
|
||
fn parse_metric_fields(node: &DeriveInput) -> Result<Vec<Metric<'_>>> { | ||
fn parse_metric_fields(node: &DeriveInput) -> Result<Vec<MetricField<'_>>> { | ||
let Data::Struct(ref data) = node.data else { | ||
return Err(Error::new_spanned(node, "Only structs are supported.")) | ||
}; | ||
|
||
let mut metrics = Vec::with_capacity(data.fields.len()); | ||
for field in data.fields.iter() { | ||
let (mut describe, mut rename) = (None, None); | ||
let (mut describe, mut rename, mut skip) = (None, None, false); | ||
if let Some(metric_attr) = parse_single_attr(field, "metric")? { | ||
let parsed = metric_attr | ||
.parse_args_with(Punctuated::<MetaNameValue, Token![,]>::parse_terminated)?; | ||
for kv in parsed { | ||
let lit = match kv.value { | ||
Expr::Lit(ref expr) => &expr.lit, | ||
_ => continue, | ||
}; | ||
if kv.path.is_ident("describe") { | ||
if describe.is_some() { | ||
return Err(Error::new_spanned(kv, "Duplicate `describe` value provided.")) | ||
} | ||
describe = Some(parse_str_lit(lit)?); | ||
} else if kv.path.is_ident("rename") { | ||
if rename.is_some() { | ||
return Err(Error::new_spanned(kv, "Duplicate `rename` value provided.")) | ||
let parsed = | ||
metric_attr.parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)?; | ||
for meta in parsed { | ||
match meta { | ||
Meta::Path(path) if path.is_ident("skip") => skip = true, | ||
Meta::NameValue(kv) => { | ||
let lit = match kv.value { | ||
Expr::Lit(ref expr) => &expr.lit, | ||
_ => continue, | ||
Comment on lines
+309
to
+313
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. simple |
||
}; | ||
if kv.path.is_ident("describe") { | ||
if describe.is_some() { | ||
return Err(Error::new_spanned( | ||
kv, | ||
"Duplicate `describe` value provided.", | ||
)) | ||
} | ||
describe = Some(parse_str_lit(lit)?); | ||
} else if kv.path.is_ident("rename") { | ||
if rename.is_some() { | ||
return Err(Error::new_spanned( | ||
kv, | ||
"Duplicate `rename` value provided.", | ||
)) | ||
} | ||
let rename_lit = parse_str_lit(lit)?; | ||
validate_metric_name(&rename_lit)?; | ||
rename = Some(rename_lit) | ||
} else { | ||
return Err(Error::new_spanned(kv, "Unsupported attribute entry.")) | ||
} | ||
} | ||
let rename_lit = parse_str_lit(lit)?; | ||
validate_metric_name(&rename_lit)?; | ||
rename = Some(rename_lit) | ||
} else { | ||
return Err(Error::new_spanned(kv, "Unsupported attribute entry.")) | ||
_ => return Err(Error::new_spanned(meta, "Unsupported attribute entry.")), | ||
} | ||
} | ||
} | ||
|
||
if skip { | ||
metrics.push(MetricField::Skipped(field)); | ||
continue | ||
} | ||
|
||
let description = match describe { | ||
Some(lit_str) => lit_str.value(), | ||
// Parse docs only if `describe` attribute was not provided | ||
|
@@ -294,7 +366,7 @@ fn parse_metric_fields(node: &DeriveInput) -> Result<Vec<Metric<'_>>> { | |
}, | ||
}; | ||
|
||
metrics.push(Metric::new(field, description, rename)); | ||
metrics.push(MetricField::Included(Metric::new(field, description, rename))); | ||
} | ||
|
||
Ok(metrics) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
let's avoid using keywords as var names
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ah, didn't know it's a keyword from nightly feature, fixed