From f6c41f3d5e87cc61a8c04997aa5ede6a6c63c98f Mon Sep 17 00:00:00 2001 From: Sriramprabhu Sankaraguru Date: Tue, 23 Mar 2021 10:53:14 -0700 Subject: [PATCH 1/2] Make native metrics handle creation singleton Fixes #743 --- AutoCollection/NativePerformance.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/AutoCollection/NativePerformance.ts b/AutoCollection/NativePerformance.ts index 25a75014..a66c87e6 100644 --- a/AutoCollection/NativePerformance.ts +++ b/AutoCollection/NativePerformance.ts @@ -81,8 +81,10 @@ export class AutoCollectNativePerformance { if (this._isEnabled && AutoCollectNativePerformance._emitter) { // enable self AutoCollectNativePerformance._emitter.enable(true, collectionInterval); - this._handle = setInterval(() => this._trackNativeMetrics(), collectionInterval); - this._handle.unref(); + if (!this._handle) { + this._handle = setInterval(() => this._trackNativeMetrics(), collectionInterval); + this._handle.unref(); + } } else if (AutoCollectNativePerformance._emitter) { // disable self AutoCollectNativePerformance._emitter.enable(false); From fbdf91050ef6c19853a4dfa80d8494a3c8f4f026 Mon Sep 17 00:00:00 2001 From: Sriramprabhu Sankaraguru Date: Wed, 24 Mar 2021 17:33:39 -0700 Subject: [PATCH 2/2] Add tests for making native metrics handle creation singleton --- Tests/AutoCollection/NativePerformance.tests.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Tests/AutoCollection/NativePerformance.tests.ts b/Tests/AutoCollection/NativePerformance.tests.ts index b5b403b1..76490903 100644 --- a/Tests/AutoCollection/NativePerformance.tests.ts +++ b/Tests/AutoCollection/NativePerformance.tests.ts @@ -47,6 +47,19 @@ describe("AutoCollection/NativePerformance", () => { assert.ok(disposeSpy.calledOnce, "dispose is called when second instance is constructed"); }); + it("Calling enable multiple times shoud not create multiple timers", () => { + var client = new TelemetryClient("1aa11111-bbbb-1ccc-8ddd-eeeeffff3333"); + var native = new AutoCollectNativePerformance(client); + var setIntervalSpy = sinon.spy(global, "setInterval"); + + assert.ok(native); + assert.doesNotThrow(() => native.enable(true), "Does not throw when tryinig to enable"); + assert.doesNotThrow(() => native.enable(true), "Does not throw when trying to enable"); + assert.equal(setIntervalSpy.callCount, 1, "setInterval should be singleton"); + + setIntervalSpy.restore(); + }); + it("Calling enable when metrics are not available should fail gracefully", () => { var client = new TelemetryClient("1aa11111-bbbb-1ccc-8ddd-eeeeffff3333"); var native = new AutoCollectNativePerformance(client);