From 5220f9be8a24e84121170b910bcda9860e79d5d3 Mon Sep 17 00:00:00 2001 From: Kelvin Jin Date: Mon, 29 Oct 2018 10:43:52 -0700 Subject: [PATCH] fix: allow sampling rate to be less than 1 (#896) --- src/tracing-policy.ts | 2 +- test/test-trace-policy.ts | 37 ++++++++++++++++++++++++++++++++----- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/src/tracing-policy.ts b/src/tracing-policy.ts index 9236950a9..cc8422abf 100644 --- a/src/tracing-policy.ts +++ b/src/tracing-policy.ts @@ -76,7 +76,7 @@ export class TracePolicy { * @param config Configuration for the TracePolicy instance. */ constructor(config: TracePolicyConfig) { - if (config.samplingRate >= 0 && config.samplingRate < 1) { + if (config.samplingRate === 0) { this.sampler = {shouldTrace: () => true}; } else if (config.samplingRate < 0) { this.sampler = {shouldTrace: () => false}; diff --git a/test/test-trace-policy.ts b/test/test-trace-policy.ts index e2aa08e7e..a9e2e0a07 100644 --- a/test/test-trace-policy.ts +++ b/test/test-trace-policy.ts @@ -35,14 +35,17 @@ describe('TracePolicy', () => { }); describe('Sampling', () => { - const tracesPerSecond = [10, 50, 150, 200, 500, 1000]; - for (const expected of tracesPerSecond) { - it(`should throttle traces when samplingRate = ` + expected, () => { + const NUM_SECONDS = 10; + const testCases = [0.1, 0.5, 1, 10, 50, 150, 200, 500, 1000]; + for (const testCase of testCases) { + it(`should throttle traces when samplingRate = ` + testCase, () => { const policy = - new TracePolicy({samplingRate: expected, ignoreUrls: []}); + new TracePolicy({samplingRate: testCase, ignoreUrls: []}); + const expected = NUM_SECONDS * testCase; let actual = 0; const start = Date.now(); - for (let timestamp = start; timestamp < start + 1000; timestamp++) { + for (let timestamp = start; timestamp < start + 1000 * NUM_SECONDS; + timestamp++) { if (policy.shouldTrace({timestamp, url: ''})) { actual++; } @@ -55,5 +58,29 @@ describe('TracePolicy', () => { `Expected close to (>=0.8*) ${expected} traced but got ${actual}`); }); } + + it('should always sample when samplingRate = 0', () => { + const policy = new TracePolicy({samplingRate: 0, ignoreUrls: []}); + let numSamples = 0; + const start = Date.now(); + for (let timestamp = start; timestamp < start + 1000; timestamp++) { + if (policy.shouldTrace({timestamp, url: ''})) { + numSamples++; + } + } + assert.strictEqual(numSamples, 1000); + }); + + it('should never sample when samplingRate < 0', () => { + const policy = new TracePolicy({samplingRate: -1, ignoreUrls: []}); + let numSamples = 0; + const start = Date.now(); + for (let timestamp = start; timestamp < start + 1000; timestamp++) { + if (policy.shouldTrace({timestamp, url: ''})) { + numSamples++; + } + } + assert.strictEqual(numSamples, 0); + }); }); });