Skip to content

Commit

Permalink
Implement unregister method for probes
Browse files Browse the repository at this point in the history
Before this change, it was possible to disable a probe by
registering an empty probe with the same name, but this is neither
obvious nor documented. This commit adds a `probes.unregister()`
method that removes a probe in a more explicit manner.
  • Loading branch information
unflxw committed Jan 14, 2022
1 parent 434599b commit 6d1cfec
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
bump: "patch"
type: "add"
---

Implement unregister method for probes. You can now call the
`probes.unregister(name)` method to unregister a probe by name.
10 changes: 10 additions & 0 deletions packages/nodejs/src/__tests__/probes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,16 @@ describe("Probes", () => {
probes.register("test_metric", fn)
jest.runOnlyPendingTimers()
expect(fn).toHaveBeenCalled()
expect(probes.count).toEqual(1)
})

it("unregisters a probe", () => {
const fn = jest.fn()
probes.register("test_metric", fn)
probes.unregister("test_metric")
jest.runOnlyPendingTimers()
expect(fn).not.toHaveBeenCalled()
expect(probes.count).toEqual(0)
})

describe("v8 probe", () => {
Expand Down
5 changes: 5 additions & 0 deletions packages/nodejs/src/interfaces/probes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ export interface Probes {
*/
register(name: string, fn: () => void): this

/**
* Unregisters an existing minutely probe.
*/
unregister(name: string): this

/**
* Unregisters all probes and clears the timers.
*/
Expand Down
13 changes: 13 additions & 0 deletions packages/nodejs/src/probes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,25 @@ export class BaseProbes extends EventEmitter implements Probes {
return this.on(name, fn)
}

public unregister(name: string): this {
const timer = this.#timers.get(name)

if (typeof timer !== "undefined") {
clearInterval(timer)
this.#timers.delete(name)
this.removeAllListeners(name)
}

return this
}

/**
* Unregisters all probes and clears the timers.
*/
public clear(): this {
this.#timers.forEach(t => clearInterval(t))
this.#timers = new Map()
this.removeAllListeners()
return this
}
}

0 comments on commit 6d1cfec

Please sign in to comment.