Skip to content

Commit

Permalink
Detect if on is called by once
Browse files Browse the repository at this point in the history
  • Loading branch information
dyladan committed Aug 1, 2022
1 parent ff2d24f commit c7fe03c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ All notable changes to this project will be documented in this file.

### :bug: (Bug Fix)

* fix(context-async-hooks): Ensure listeners added using `once` can be removed using `removeListener`
[#3124](https://github.com/open-telemetry/opentelemetry-js/pulls/3124)

### :books: (Refine Doc)

### :house: (Internal)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ implements ContextManager {
// patch methods that add a listener to propagate context
ADD_LISTENER_METHODS.forEach(methodName => {
if (ee[methodName] === undefined) return;
ee[methodName] = this._patchAddListener(ee, ee[methodName], context);
ee[methodName] = this._patchAddListener(ee, ee[methodName], methodName, context);
});
// patch methods that remove a listener
if (typeof ee.removeListener === 'function') {
Expand Down Expand Up @@ -173,10 +173,15 @@ implements ContextManager {
private _patchAddListener(
ee: EventEmitter,
original: Function,
name: string,
context: Context
) {
const contextManager = this;
return function (this: never, event: string, listener: Func<void>) {
let active = contextManager.active();
if (active.getValue(contextManager._inOnce)) {
return original.call(this, event, listener);
}
let map = contextManager._getPatchMap(ee);
if (map === undefined) {
map = contextManager._createPatchMap(ee);
Expand All @@ -189,7 +194,12 @@ implements ContextManager {
const patchedListener = contextManager.bind(context, listener);
// store a weak reference of the user listener to ours
listeners.set(listener, patchedListener);
return original.call(this, event, patchedListener);
if (name === 'once') {
active = active.setValue(contextManager._inOnce, true)
}
return contextManager.with(active, () => {
return original.call(this, event, patchedListener);
});
};
}

Expand All @@ -204,4 +214,5 @@ implements ContextManager {
}

private readonly _kOtListeners = Symbol('OtListeners');
private readonly _inOnce = Symbol('OpenTelemetry once detection');
}

0 comments on commit c7fe03c

Please sign in to comment.