-
Notifications
You must be signed in to change notification settings - Fork 804
/
AsyncHooksScopeManager.ts
242 lines (223 loc) · 7.38 KB
/
AsyncHooksScopeManager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/*!
* Copyright 2019, OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ScopeManager } from '@opentelemetry/scope-base';
import * as asyncHooks from 'async_hooks';
import { EventEmitter } from 'events';
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.
*/
__ot_listeners?: { [name: string]: WeakMap<Func<void>, Func<void>> };
} & EventEmitter;
const ADD_LISTENER_METHODS = [
'addListener' as 'addListener',
'on' as 'on',
'once' as 'once',
'prependListener' as 'prependListener',
'prependOnceListener' as 'prependOnceListener',
];
export class AsyncHooksScopeManager implements ScopeManager {
private _asyncHook: asyncHooks.AsyncHook;
private _scopes: { [uid: number]: unknown } = Object.create(null);
constructor() {
this._asyncHook = asyncHooks.createHook({
init: this._init.bind(this),
destroy: this._destroy.bind(this),
promiseResolve: this._destroy.bind(this),
});
}
active(): unknown {
return this._scopes[asyncHooks.executionAsyncId()] || undefined;
}
with<T extends (...args: unknown[]) => ReturnType<T>>(
scope: unknown,
fn: T
): ReturnType<T> {
const uid = asyncHooks.executionAsyncId();
const oldScope = this._scopes[uid];
this._scopes[uid] = scope;
try {
return fn();
} catch (err) {
throw err;
} finally {
if (oldScope === undefined) {
this._destroy(uid);
} else {
this._scopes[uid] = oldScope;
}
}
}
bind<T>(target: T, scope?: unknown): T {
// if no specific scope to propagate is given, we use the current one
if (scope === undefined) {
scope = this.active();
}
if (target instanceof EventEmitter) {
return this._bindEventEmitter(target, scope);
} else if (typeof target === 'function') {
return this._bindFunction(target, scope);
}
return target;
}
enable(): this {
this._asyncHook.enable();
return this;
}
disable(): this {
this._asyncHook.disable();
this._scopes = {};
return this;
}
private _bindFunction<T extends Function>(target: T, scope?: unknown): T {
const manager = this;
const contextWrapper = function(this: {}, ...args: unknown[]) {
return manager.with(scope, () => target.apply(this, args));
};
Object.defineProperty(contextWrapper, 'length', {
enumerable: false,
configurable: true,
writable: false,
value: target.length,
});
/**
* It isn't possible to tell Typescript that contextWrapper is the same as T
* so we forced to cast as any here.
*/
// tslint:disable-next-line:no-any
return contextWrapper as any;
}
/**
* By default, EventEmitter call their callback with their scope, which we do
* not want, instead we will bind a specific scope to all callbacks that
* go through it.
* @param target EventEmitter a instance of EventEmitter to patch
* @param scope the scope we want to bind
*/
private _bindEventEmitter<T extends EventEmitter>(
target: T,
scope?: unknown
): T {
const ee = (target as unknown) as PatchedEventEmitter;
if (ee.__ot_listeners !== undefined) return target;
ee.__ot_listeners = {};
// patch methods that add a listener to propagate scope
ADD_LISTENER_METHODS.forEach(methodName => {
if (ee[methodName] === undefined) return;
ee[methodName] = this._patchAddListener(ee, ee[methodName], scope);
});
// patch methods that remove a listener
if (typeof ee.removeListener === 'function') {
ee.removeListener = this._patchRemoveListener(ee, ee.removeListener);
}
if (typeof ee.off === 'function') {
ee.off = this._patchRemoveListener(ee, ee.off);
}
// patch method that remove all listeners
if (typeof ee.removeAllListeners === 'function') {
ee.removeAllListeners = this._patchRemoveAllListeners(
ee,
ee.removeAllListeners
);
}
return target;
}
/**
* Patch methods that remove a given listener so that we match the "patched"
* version of that listener (the one that propagate context).
* @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>) {
if (
ee.__ot_listeners === undefined ||
ee.__ot_listeners[event] === undefined
) {
return original.call(this, event, listener);
}
const events = ee.__ot_listeners[event];
const patchedListener = events.get(listener);
return original.call(this, event, patchedListener || listener);
};
}
/**
* Patch methods that remove all listeners so we remove our
* internal references for a given event.
* @param ee EventEmitter instance
* @param original reference to the patched method
*/
private _patchRemoveAllListeners(
ee: PatchedEventEmitter,
original: Function
) {
return function(this: {}, event: string) {
if (
ee.__ot_listeners === undefined ||
ee.__ot_listeners[event] === undefined
) {
return original.call(this, event);
}
delete ee.__ot_listeners[event];
return original.call(this, event);
};
}
/**
* Patch methods on an event emitter instance that can add listeners so we
* can force them to propagate a given context.
* @param ee EventEmitter instance
* @param original reference to the patched method
* @param [scope] scope to propagate when calling listeners
*/
private _patchAddListener(
ee: PatchedEventEmitter,
original: Function,
scope?: unknown
) {
const scopeManager = this;
return function(this: {}, event: string, listener: Func<void>) {
if (ee.__ot_listeners === undefined) ee.__ot_listeners = {};
let listeners = ee.__ot_listeners[event];
if (listeners === undefined) {
listeners = new WeakMap();
ee.__ot_listeners[event] = listeners;
}
const patchedListener = scopeManager.bind(listener, scope);
// store a weak reference of the user listener to ours
listeners.set(listener, patchedListener);
return original.call(this, event, patchedListener);
};
}
/**
* Init hook will be called when userland create a async scope, setting the
* scope as the current one if it exist.
* @param uid id of the async scope
*/
private _init(uid: number) {
this._scopes[uid] = this._scopes[asyncHooks.executionAsyncId()];
}
/**
* Destroy hook will be called when a given scope is no longer used so we can
* remove its attached scope.
* @param uid uid of the async scope
*/
private _destroy(uid: number) {
delete this._scopes[uid];
}
}