Skip to content
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(transactions): Adding support for transaction (re)naming rules #1695

Merged
merged 17 commits into from
Dec 20, 2022
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
- Parse string as number to handle a release bug. ([#1637](https://github.com/getsentry/relay/pull/1637))
- Expand Profiling's discard reasons. ([#1661](https://github.com/getsentry/relay/pull/1661), [#1685](https://github.com/getsentry/relay/pull/1685))
- Allow to rate limit profiles on top of transactions. ([#1681](https://github.com/getsentry/relay/pull/1681))
- Support transaction naming rules. The rules will be currently applied to transactions where the transaction source set to `url`. ([#1695](https://github.com/getsentry/relay/pull/1695))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
- Support transaction naming rules. The rules will be currently applied to transactions where the transaction source set to `url`. ([#1695](https://github.com/getsentry/relay/pull/1695))
- Support transaction naming rules. ([#1695](https://github.com/getsentry/relay/pull/1695))

I've mentioned this somewhere in a comment below: let's not focus this PR on having the source set to url. This is the default use case and the only one we currently support, but that's defined in sentry and not in relay. In fact, if the code is a bit generalized we could already be supporting more sources out of the box.


## 22.11.0

Expand Down
1 change: 1 addition & 0 deletions relay-cabi/src/processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ pub unsafe extern "C" fn relay_store_normalizer_normalize_event(
breakdowns_config: None, // only supported in relay
normalize_user_agent: config.normalize_user_agent,
normalize_transaction_name: false, // only supported in relay
tx_name_rules: &[], // only supported in relay
is_renormalize: config.is_renormalize.unwrap_or(false),
};
light_normalize_event(&mut event, &light_normalization_config)?;
Expand Down
151 changes: 132 additions & 19 deletions relay-common/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,45 +6,110 @@ use regex::Regex;

use crate::macros::impl_str_serde;

/// A simple glob matcher.
///
/// Supported are `?` for a single char, `*` for all but a slash and
/// `**` to match with slashes.
#[derive(Clone)]
pub struct Glob {
value: String,
pattern: Regex,
/// Glob options is used to configure the behaviour underlying regex.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I find this sentence difficult to understand, and without the example below I've not been able to. I suggest the following but feel free to modify it to a different one.

Suggested change
/// Glob options is used to configure the behaviour underlying regex.
/// Glob options represent the underlying regex emulating the globs.

#[derive(Debug)]
struct GlobPatternOpts<'g> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I would like to give this struct a more descriptive name but I don't have one. Maybe something like GlobPatternGroups or GlobPatternBuildingBlocks?

star: &'g str,
double_star: &'g str,
question_mark: &'g str,
}

impl Glob {
/// Creates a new glob from a string.
pub fn new(glob: &str) -> Glob {
let mut pattern = String::with_capacity(glob.len() + 100);
/// `GlobBuilder` provides the posibility to fine tune the final [`Glob`], mainly what capture
/// groups will be enabled in the underlying regex.
#[derive(Debug)]
pub struct GlobBuilder<'g> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe all this glob builder logic belongs to a different PR -- the complexity is enough to be on its own; it's easy to make mistakes when regexes, globs and custom logic is involved; and it makes reviewing the core functionality this PR is introducing more complicated.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no much logic, just a simple addition to make sure that existing or better to say, required rule application cane be done, and this happens only in replace_captures function. The rest is just a helper code.

value: &'g str,
opts: GlobPatternOpts<'g>,
}

impl<'g> GlobBuilder<'g> {
/// Create a new builder with all the captures enabled by default.
pub fn new(value: &'g str) -> Self {
let opts = GlobPatternOpts {
star: "([^/]*?)",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why the ? in star here? The ? tries to find as less matching groups as possible, so in /abc/ the non-null groups are a, b, and c. We're interested in a matching group of abc, and we accomplish that by removing ?.

Am I missing something?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This regex will match everything expect /.

double_star: "(.*?)",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the double star, the ? doesn't make any difference in this case. However, do we need it? I'm really not sure if I'm missing something.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this also supports proper globs, when you can have the glob like /foo/bar/**/this there ** matches any number of slashes and stuff in between.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that these three patterns already exist on master branch, they were just copied to a different location:

"?" => pattern.push_str("(.)"),
"**" => pattern.push_str("(.*?)"),
"*" => pattern.push_str("([^/]*?)"),

question_mark: "(.)",
Comment on lines +29 to +31
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fantastic idea of surrounding the regexes with parenthesis!

};
Self { value, opts }
}

/// Enable capture groups for `*` in the pattern.
pub fn capture_star(mut self, enable: bool) -> Self {
if !enable {
self.opts.star = "(?:[^/]*?)";
}
self
}

/// Enable capture groups for `**` in the pattern.
pub fn capture_double_star(mut self, enable: bool) -> Self {
if !enable {
self.opts.double_star = "(?:.*?)";
}
self
}

/// Enable capture groups for `?` in the pattern.
pub fn capture_question_mark(mut self, enable: bool) -> Self {
if !enable {
self.opts.question_mark = "(?:.)";
}
self
}

/// Create a new [`Glob`] from this builder.
pub fn build(self) -> Glob {
let mut pattern = String::with_capacity(&self.value.len() + 100);
let mut last = 0;

pattern.push('^');

static GLOB_RE: OnceCell<Regex> = OnceCell::new();
let regex = GLOB_RE.get_or_init(|| Regex::new(r#"\?|\*\*|\*"#).unwrap());

for m in regex.find_iter(glob) {
pattern.push_str(&regex::escape(&glob[last..m.start()]));
for m in regex.find_iter(self.value) {
pattern.push_str(&regex::escape(&self.value[last..m.start()]));
match m.as_str() {
"?" => pattern.push_str("(.)"),
"**" => pattern.push_str("(.*?)"),
"*" => pattern.push_str("([^/]*?)"),
"?" => pattern.push_str(self.opts.question_mark),
"**" => pattern.push_str(self.opts.double_star),
"*" => pattern.push_str(self.opts.star),
_ => {}
}
last = m.end();
}
pattern.push_str(&regex::escape(&glob[last..]));
pattern.push_str(&regex::escape(&self.value[last..]));
pattern.push('$');

Glob {
value: glob.to_string(),
value: self.value.to_owned(),
pattern: Regex::new(&pattern).unwrap(),
}
}
}

/// A simple glob matcher.
///
/// Supported are `?` for a single char, `*` for all but a slash and
/// `**` to match with slashes.
#[derive(Clone)]
pub struct Glob {
value: String,
pattern: Regex,
}

impl Glob {
/// Creates the [`GlobBuilder`], which can be fine-tunned using helper methods.
pub fn builder(glob: &'_ str) -> GlobBuilder {
GlobBuilder::new(glob)
}

/// Creates a new glob from a string.
///
/// All the glob patterns (wildcards) are enabled in the captures, and can be returned by
/// `matches` function.
pub fn new(glob: &str) -> Glob {
GlobBuilder::new(glob).build()
}

/// Returns the pattern as str.
pub fn pattern(&self) -> &str {
Expand All @@ -56,6 +121,26 @@ impl Glob {
self.pattern.is_match(value)
}

/// Currently support replacing only all `*` in the input string with provided replacement.
/// If no match is found, then a copy of the string is returned unchanged.
pub fn apply(&self, input: &str, replacement: &str) -> String {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit

Suggested change
pub fn apply(&self, input: &str, replacement: &str) -> String {
pub fn replace_captures(&self, input: &str, replacement: &str) -> String {

let mut output = String::new();
let mut current = 0;

for caps in self.pattern.captures_iter(input) {
// Create the iter on subcaptures and ignore the first capture, since this is always
// the entire string.
for cap in caps.iter().flatten().skip(1) {
output.push_str(&input[current..cap.start()]);
output.push_str(replacement);
current = cap.end();
}
}

output.push_str(&input[current..]);
output
}

/// Checks if the value matches and returns the wildcard matches.
pub fn matches<'t>(&self, value: &'t str) -> Option<Vec<&'t str>> {
self.pattern.captures(value).map(|caps| {
Expand All @@ -67,6 +152,14 @@ impl Glob {
}
}

impl PartialEq for Glob {
fn eq(&self, other: &Self) -> bool {
self.value == other.value
}
}

impl Eq for Glob {}

impl str::FromStr for Glob {
type Err = ();

Expand Down Expand Up @@ -167,6 +260,26 @@ mod tests {
let g = Glob::new("api/**/store/");
assert!(g.is_match("api/some/stuff/here/store/"));
assert!(g.is_match("api/some/store/"));

let g = Glob::new("/api/*/stuff/**");
assert!(g.is_match("/api/some/stuff/here/store/"));
assert!(!g.is_match("/api/some/store/"));
}

#[test]
fn test_glob_replace() {
let g = Glob::builder("/foo/*/bar/**")
.capture_star(true)
.capture_double_star(false)
.capture_question_mark(false)
.build();

assert_eq!(
g.apply("/foo/some/bar/here/store", "*"),
"/foo/*/bar/here/store"
);
assert_eq!(g.apply("/foo/testing/bar/", "*"), "/foo/*/bar/");
assert_eq!(g.apply("/foo/testing/1/", "*"), "/foo/testing/1/");
}

#[test]
Expand Down
9 changes: 8 additions & 1 deletion relay-general/src/protocol/transaction.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

use crate::processor::ProcessValue;
use crate::protocol::Timestamp;
use crate::types::{Annotated, Empty, ErrorKind, FromValue, IntoValue, SkipSerialization, Value};

/// Describes how the name of the transaction was determined.
#[derive(Clone, Debug, Eq, PartialEq)]
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lol TIL kebab-case, I didn't know there was a name for this. It's made my day 😂

#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "jsonschema", schemars(rename_all = "kebab-case"))]
pub enum TransactionSource {
Expand All @@ -20,6 +23,8 @@ pub enum TransactionSource {
View,
/// Named after a software component, such as a function or class name.
Component,
/// The transaction name was updated to remove high cardinality parts.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably a nit -- a "sanitized" transaction name doesn't necessarily require getting high cardinality parts removed. Currently, we are only going to support the removal feature, but let's not limit ourselves to that.

Suggested change
/// The transaction name was updated to remove high cardinality parts.
/// The transaction name was updated to reduce the name cardinality.

Sanitized,
/// Name of a background task (e.g. a Celery task).
Task,
/// This is the default value set by Relay for legacy SDKs.
Expand All @@ -37,6 +42,7 @@ impl TransactionSource {
Self::Route => "route",
Self::View => "view",
Self::Component => "component",
Self::Sanitized => "sanitized",
Self::Task => "task",
Self::Unknown => "unknown",
Self::Other(ref s) => s,
Expand All @@ -54,6 +60,7 @@ impl FromStr for TransactionSource {
"route" => Ok(Self::Route),
"view" => Ok(Self::View),
"component" => Ok(Self::Component),
"sanitized" => Ok(Self::Sanitized),
"task" => Ok(Self::Task),
"unknown" => Ok(Self::Unknown),
s => Ok(Self::Other(s.to_owned())),
Expand Down
9 changes: 6 additions & 3 deletions relay-general/src/store/normalize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use smallvec::SmallVec;

use relay_common::{DurationUnit, FractionUnit, MetricUnit};

use super::{schema, transactions, BreakdownsConfig};
use super::{schema, transactions, BreakdownsConfig, TransactionNameRule};
use crate::processor::{MaxChars, ProcessValue, ProcessingState, Processor};
use crate::protocol::{
self, AsPair, Breadcrumb, ClientSdkInfo, Context, Contexts, DebugImage, Event, EventId,
Expand Down Expand Up @@ -664,6 +664,7 @@ pub struct LightNormalizationConfig<'a> {
pub breakdowns_config: Option<&'a BreakdownsConfig>,
pub normalize_user_agent: Option<bool>,
pub normalize_transaction_name: bool,
pub tx_name_rules: &'a [TransactionNameRule],
pub is_renormalize: bool,
}

Expand All @@ -680,8 +681,10 @@ pub fn light_normalize_event(
// (internally noops for non-transaction events).
// TODO: Parts of this processor should probably be a filter so we
// can revert some changes to ProcessingAction
let mut transactions_processor =
transactions::TransactionsProcessor::new(config.normalize_transaction_name);
let mut transactions_processor = transactions::TransactionsProcessor::new(
config.normalize_transaction_name,
config.tx_name_rules,
);
transactions_processor.process_event(event, meta, ProcessingState::root())?;

// Check for required and non-empty values
Expand Down
5 changes: 5 additions & 0 deletions relay-general/src/store/transactions/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
mod processor;
mod rules;

pub use processor::*;
pub use rules::*;
Loading