Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: isolate binding EventEmitter #1937

Merged
merged 6 commits into from
Feb 22, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,16 @@
import { ContextManager, Context } from '@opentelemetry/context-base';
import { EventEmitter } from 'events';

const kOtListeners = Symbol('OtListeners');

type Func<T> = (...args: unknown[]) => T;

type PatchedEventEmitter = {
/**
* Store a map for each event of all original listener and their "patched"
* version so when the listener is removed by the user, we remove the
* corresponding "patched" function.
*/
[kOtListeners]?: { [name: string]: WeakMap<Func<void>, Func<void>> };
} & EventEmitter;
/**
* Store a map for each event of all original listener and their "patched"
Flarna marked this conversation as resolved.
Show resolved Hide resolved
* version so when the listener is removed by the user, we remove the
Flarna marked this conversation as resolved.
Show resolved Hide resolved
* corresponding "patched" function.
*/
interface PatchMap {
[name: string]: WeakMap<Func<void>, Func<void>>;
}

const ADD_LISTENER_METHODS = [
'addListener' as const,
Expand Down Expand Up @@ -66,7 +64,7 @@ export abstract class AbstractAsyncHooksContextManager

private _bindFunction<T extends Function>(target: T, context: Context): T {
const manager = this;
const contextWrapper = function (this: {}, ...args: unknown[]) {
const contextWrapper = function (this: never, ...args: unknown[]) {
return manager.with(context, () => target.apply(this, args));
};
Object.defineProperty(contextWrapper, 'length', {
Expand All @@ -91,12 +89,12 @@ export abstract class AbstractAsyncHooksContextManager
* @param context the context we want to bind
*/
private _bindEventEmitter<T extends EventEmitter>(
target: T,
ee: T,
Flarna marked this conversation as resolved.
Show resolved Hide resolved
context: Context
): T {
const ee = (target as unknown) as PatchedEventEmitter;
if (ee[kOtListeners] !== undefined) return target;
ee[kOtListeners] = {};
const map = this._getPatchMap(ee);
if (map !== undefined) return ee;
this._createPatchMap(ee);

// patch methods that add a listener to propagate context
ADD_LISTENER_METHODS.forEach(methodName => {
Expand All @@ -117,7 +115,7 @@ export abstract class AbstractAsyncHooksContextManager
ee.removeAllListeners
);
}
return target;
return ee;
}

/**
Expand All @@ -126,9 +124,10 @@ export abstract class AbstractAsyncHooksContextManager
* @param ee EventEmitter instance
* @param original reference to the patched method
*/
private _patchRemoveListener(ee: PatchedEventEmitter, original: Function) {
return function (this: {}, event: string, listener: Func<void>) {
const events = ee[kOtListeners]?.[event];
private _patchRemoveListener(ee: EventEmitter, original: Function) {
const contextManager = this;
return function (this: never, event: string, listener: Func<void>) {
const events = contextManager._getPatchMap(ee)?.[event];
if (events === undefined) {
return original.call(this, event, listener);
}
Expand All @@ -143,13 +142,12 @@ export abstract class AbstractAsyncHooksContextManager
* @param ee EventEmitter instance
* @param original reference to the patched method
*/
private _patchRemoveAllListeners(
ee: PatchedEventEmitter,
original: Function
) {
return function (this: {}, event: string) {
if (ee[kOtListeners]?.[event] !== undefined) {
delete ee[kOtListeners]![event];
private _patchRemoveAllListeners(ee: EventEmitter, original: Function) {
const contextManager = this;
return function (this: never, event: string) {
const map = contextManager._getPatchMap(ee);
if (map?.[event] !== undefined) {
delete map[event];
}
return original.call(this, event);
};
Expand All @@ -163,22 +161,37 @@ export abstract class AbstractAsyncHooksContextManager
* @param [context] context to propagate when calling listeners
*/
private _patchAddListener(
ee: PatchedEventEmitter,
ee: EventEmitter,
original: Function,
context: Context
) {
const contextManager = this;
return function (this: {}, event: string, listener: Func<void>) {
if (ee[kOtListeners] === undefined) ee[kOtListeners] = {};
let listeners = ee[kOtListeners]![event];
return function (this: never, event: string, listener: Func<void>) {
let map = contextManager._getPatchMap(ee);
if (map === undefined) {
map = contextManager._createPatchMap(ee);
}
let listeners = map[event];
if (listeners === undefined) {
listeners = new WeakMap();
ee[kOtListeners]![event] = listeners;
map[event] = listeners;
}
const patchedListener = contextManager.bind(listener, context);
// store a weak reference of the user listener to ours
listeners.set(listener, patchedListener);
return original.call(this, event, patchedListener);
};
}

private _createPatchMap(ee: EventEmitter): PatchMap {
const map = {};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(ee as any)[this._kOtListeners] = map;
return map;
}
private _getPatchMap(ee: EventEmitter): PatchMap | undefined {
return (ee as never)[this._kOtListeners];
}

private readonly _kOtListeners = Symbol('OtListeners');
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export class AsyncLocalStorageContextManager extends AbstractAsyncHooksContextMa
...args: A
): ReturnType<F> {
const cb = thisArg == null ? fn : fn.bind(thisArg);
return this._asyncLocalStorage.run(context, cb as any, ...args);
return this._asyncLocalStorage.run(context, cb as never, ...args);
}

enable(): this {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ for (const contextManagerClass of [
| AsyncHooksContextManager
| AsyncLocalStorageContextManager;
const key1 = createContextKey('test key 1');
let otherContextManager:
| AsyncHooksContextManager
| AsyncLocalStorageContextManager;

before(function () {
if (
Expand All @@ -49,6 +52,7 @@ for (const contextManagerClass of [

afterEach(() => {
contextManager.disable();
otherContextManager?.disable();
});

describe('.enable()', () => {
Expand Down Expand Up @@ -416,6 +420,26 @@ for (const contextManagerClass of [
assert.strictEqual(patchedEe.listeners('test').length, 1);
patchedEe.emit('test');
});

it('should not influence other instances', () => {
const ee = new EventEmitter();
otherContextManager = new contextManagerClass();
otherContextManager.enable();

const context = ROOT_CONTEXT.setValue(key1, 2);
const otherContext = ROOT_CONTEXT.setValue(key1, 3);
const patchedEe = otherContextManager.bind(
Flarna marked this conversation as resolved.
Show resolved Hide resolved
contextManager.bind(ee, context),
otherContext
);
const handler = () => {
assert.deepStrictEqual(contextManager.active(), context);
assert.strictEqual(otherContextManager.active(), otherContext);
};

patchedEe.on('test', handler);
patchedEe.emit('test');
});
});
});
}