fix(core): support regex global flag in urlMatches#2560
fix(core): support regex global flag in urlMatches#2560vmarchaud merged 2 commits intoopen-telemetry:mainfrom
Conversation
|
can you be more specific about the bug you are trying to fix ? as this was already changed in past |
const { isUrlIgnored } = require('@opentelemetry/core');
const ignoredUrls = [/test/g];
console.log(isUrlIgnored('test.com', ignoredUrls));
console.log(isUrlIgnored('test.com', ignoredUrls));
console.log(isUrlIgnored('test.com', ignoredUrls));
console.log(isUrlIgnored('test.com', ignoredUrls));
console.log(isUrlIgnored('test.com', ignoredUrls));
console.log(isUrlIgnored('test.com', ignoredUrls));Output true
false
true
false
true
false |
Codecov Report
@@ Coverage Diff @@
## main #2560 +/- ##
==========================================
- Coverage 93.09% 93.07% -0.02%
==========================================
Files 140 140
Lines 5172 5172
Branches 1111 1111
==========================================
- Hits 4815 4814 -1
- Misses 357 358 +1
|
dyladan
left a comment
There was a problem hiding this comment.
Thanks for the example. I'm curious, can you explain why it is broken with the old implementation? From what I see it should work just fine unless I am misunderstanding .test function.
It's broken because it's nondeterministic. Functions like this should be pure without any side effects. |
|
Right I get that it's nondeterministic, but why is it nondeterministic? Nothing in the old implementation would have made me think it wasn't deterministic. export function urlMatches(url: string, urlToMatch: string | RegExp): boolean {
if (typeof urlToMatch === 'string') { // this branch seems obviously deterministic
return url === urlToMatch;
} else { // this branch is `RegExp.prototype.test(url: string)` which I would also think is deterministic
return urlToMatch.test(url);
}
} |
The reason is that the I agree It is very unexpected. The top 3 in JS is this one followed by |
RegExp with global flag is problematic when the rx is persisted. A common place for this bug to appear is in options.
Example:
The above example will ignore the first request but not the second one.
Short description of the changes
!!str.match(rx)instead ofrx.test(str)solves the issue.Match is a tiny bit slower than test. If test is preferred the alternative solution is to
rx.lastIndex = 0after each test.Type of change
Please delete options that are not relevant.
How Has This Been Tested?
Reproduced by adding a test to
url.tests.tsTry this to verify
Output
Checklist: