Skip to content
This repository was archived by the owner on Jan 21, 2026. It is now read-only.

Commit 5220f9b

Browse files
authored
fix: allow sampling rate to be less than 1 (#896)
1 parent b56926a commit 5220f9b

2 files changed

Lines changed: 33 additions & 6 deletions

File tree

src/tracing-policy.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ export class TracePolicy {
7676
* @param config Configuration for the TracePolicy instance.
7777
*/
7878
constructor(config: TracePolicyConfig) {
79-
if (config.samplingRate >= 0 && config.samplingRate < 1) {
79+
if (config.samplingRate === 0) {
8080
this.sampler = {shouldTrace: () => true};
8181
} else if (config.samplingRate < 0) {
8282
this.sampler = {shouldTrace: () => false};

test/test-trace-policy.ts

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,17 @@ describe('TracePolicy', () => {
3535
});
3636

3737
describe('Sampling', () => {
38-
const tracesPerSecond = [10, 50, 150, 200, 500, 1000];
39-
for (const expected of tracesPerSecond) {
40-
it(`should throttle traces when samplingRate = ` + expected, () => {
38+
const NUM_SECONDS = 10;
39+
const testCases = [0.1, 0.5, 1, 10, 50, 150, 200, 500, 1000];
40+
for (const testCase of testCases) {
41+
it(`should throttle traces when samplingRate = ` + testCase, () => {
4142
const policy =
42-
new TracePolicy({samplingRate: expected, ignoreUrls: []});
43+
new TracePolicy({samplingRate: testCase, ignoreUrls: []});
44+
const expected = NUM_SECONDS * testCase;
4345
let actual = 0;
4446
const start = Date.now();
45-
for (let timestamp = start; timestamp < start + 1000; timestamp++) {
47+
for (let timestamp = start; timestamp < start + 1000 * NUM_SECONDS;
48+
timestamp++) {
4649
if (policy.shouldTrace({timestamp, url: ''})) {
4750
actual++;
4851
}
@@ -55,5 +58,29 @@ describe('TracePolicy', () => {
5558
`Expected close to (>=0.8*) ${expected} traced but got ${actual}`);
5659
});
5760
}
61+
62+
it('should always sample when samplingRate = 0', () => {
63+
const policy = new TracePolicy({samplingRate: 0, ignoreUrls: []});
64+
let numSamples = 0;
65+
const start = Date.now();
66+
for (let timestamp = start; timestamp < start + 1000; timestamp++) {
67+
if (policy.shouldTrace({timestamp, url: ''})) {
68+
numSamples++;
69+
}
70+
}
71+
assert.strictEqual(numSamples, 1000);
72+
});
73+
74+
it('should never sample when samplingRate < 0', () => {
75+
const policy = new TracePolicy({samplingRate: -1, ignoreUrls: []});
76+
let numSamples = 0;
77+
const start = Date.now();
78+
for (let timestamp = start; timestamp < start + 1000; timestamp++) {
79+
if (policy.shouldTrace({timestamp, url: ''})) {
80+
numSamples++;
81+
}
82+
}
83+
assert.strictEqual(numSamples, 0);
84+
});
5885
});
5986
});

0 commit comments

Comments
 (0)